title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to define important text using HTML5 ? - GeeksforGeeks
27 May, 2020 In this article, we define an important text by using the <strong> tag in HTML. It is the parsed tag and used to show the importance of the text. It reflects the text as bold. Syntax: <strong> Contents... </strong> Example 1: <!DOCTYPE html><html> <head> <title> How to define important text in HTML? </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> How to define important text using HTML5? </h2> <strong> Welcome to GeeksforGeeks! </strong></body> </html> Output: Example 2: <!DOCTYPE html><html> <head> <title> How to define important text in HTML? </title> <style> body { text-align: center; } h1 { color: green; } .gfg { font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2 class="gfg"> How to define important text using HTML5? </h2> <div class="gfg"> Welcome to GeeksforGeeks! </div></body> </html> Output: Supported Browsers: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc HTML5 CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS How to set space between the flexbox ? Form validation using jQuery Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26621, "s": 26593, "text": "\n27 May, 2020" }, { "code": null, "e": 26797, "s": 26621, "text": "In this article, we define an important text by using the <strong> tag in HTML. It is the parsed tag and used to show the importance of the text. It reflects the text as bold." }, { "code": null, "e": 26805, "s": 26797, "text": "Syntax:" }, { "code": null, "e": 26836, "s": 26805, "text": "<strong> Contents... </strong>" }, { "code": null, "e": 26847, "s": 26836, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to define important text in HTML? </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> How to define important text using HTML5? </h2> <strong> Welcome to GeeksforGeeks! </strong></body> </html>", "e": 27271, "s": 26847, "text": null }, { "code": null, "e": 27279, "s": 27271, "text": "Output:" }, { "code": null, "e": 27290, "s": 27279, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to define important text in HTML? </title> <style> body { text-align: center; } h1 { color: green; } .gfg { font-weight: bold; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2 class=\"gfg\"> How to define important text using HTML5? </h2> <div class=\"gfg\"> Welcome to GeeksforGeeks! </div></body> </html> ", "e": 27801, "s": 27290, "text": null }, { "code": null, "e": 27809, "s": 27801, "text": "Output:" }, { "code": null, "e": 27829, "s": 27809, "text": "Supported Browsers:" }, { "code": null, "e": 27843, "s": 27829, "text": "Google Chrome" }, { "code": null, "e": 27861, "s": 27843, "text": "Internet Explorer" }, { "code": null, "e": 27869, "s": 27861, "text": "Firefox" }, { "code": null, "e": 27875, "s": 27869, "text": "Opera" }, { "code": null, "e": 27882, "s": 27875, "text": "Safari" }, { "code": null, "e": 28019, "s": 27882, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 28028, "s": 28019, "text": "CSS-Misc" }, { "code": null, "e": 28038, "s": 28028, "text": "HTML-Misc" }, { "code": null, "e": 28044, "s": 28038, "text": "HTML5" }, { "code": null, "e": 28048, "s": 28044, "text": "CSS" }, { "code": null, "e": 28053, "s": 28048, "text": "HTML" }, { "code": null, "e": 28070, "s": 28053, "text": "Web Technologies" }, { "code": null, "e": 28097, "s": 28070, "text": "Web technologies Questions" }, { "code": null, "e": 28102, "s": 28097, "text": "HTML" }, { "code": null, "e": 28200, "s": 28102, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28237, "s": 28200, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28276, "s": 28237, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 28305, "s": 28276, "text": "Form validation using jQuery" }, { "code": null, "e": 28347, "s": 28305, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 28382, "s": 28347, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 28442, "s": 28382, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28495, "s": 28442, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 28556, "s": 28495, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28580, "s": 28556, "text": "REST API (Introduction)" } ]
Allow only alphabets in column in SQL Server - GeeksforGeeks
30 Aug, 2021 There may occur some situations when data in column should only be in alphabets, for example: Name column in details table. If user try to input other than alphabets, it will give error. To allow only alphabets in a column check constraint can be applied over column. To get information about Constraints and Check Constraints, refer below article links: SQL | Constraints SQL | CHECK Constraint Syntax: CONSTRAINT (Constraint_Name) CHECK ( BOOLEAN EXPRESSION) Example 1: In this example, constraints are applied on ADDRESS column to check if value inserted in ADDRESS column consist of only alphabets or not. The value inserted in ADDRESS column consists of only alphabets and thus it works fine and does not show any error. The condition NOT LIKE %[^A-Z]% checks is input values are alphabets or not. Output: Example 2: In this example, constraints are applied on ADDRESS column to check if entered value consist of only alphabets or not. The value inserted in ADDRESS column consists of alphabets and integer and thus it shows error. The ADDRESS “GEEKS1” is responsible for error. Output: ruhelaa48 SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL using Python How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25513, "s": 25485, "text": "\n30 Aug, 2021" }, { "code": null, "e": 25870, "s": 25513, "text": "There may occur some situations when data in column should only be in alphabets, for example: Name column in details table. If user try to input other than alphabets, it will give error. To allow only alphabets in a column check constraint can be applied over column. To get information about Constraints and Check Constraints, refer below article links: " }, { "code": null, "e": 25888, "s": 25870, "text": "SQL | Constraints" }, { "code": null, "e": 25911, "s": 25888, "text": "SQL | CHECK Constraint" }, { "code": null, "e": 25921, "s": 25911, "text": "Syntax: " }, { "code": null, "e": 25979, "s": 25921, "text": "CONSTRAINT (Constraint_Name) \nCHECK ( BOOLEAN EXPRESSION)" }, { "code": null, "e": 26323, "s": 25979, "text": "Example 1: In this example, constraints are applied on ADDRESS column to check if value inserted in ADDRESS column consist of only alphabets or not. The value inserted in ADDRESS column consists of only alphabets and thus it works fine and does not show any error. The condition NOT LIKE %[^A-Z]% checks is input values are alphabets or not. " }, { "code": null, "e": 26333, "s": 26323, "text": "Output: " }, { "code": null, "e": 26608, "s": 26333, "text": "Example 2: In this example, constraints are applied on ADDRESS column to check if entered value consist of only alphabets or not. The value inserted in ADDRESS column consists of alphabets and integer and thus it shows error. The ADDRESS “GEEKS1” is responsible for error. " }, { "code": null, "e": 26618, "s": 26608, "text": "Output: " }, { "code": null, "e": 26630, "s": 26620, "text": "ruhelaa48" }, { "code": null, "e": 26641, "s": 26630, "text": "SQL-Server" }, { "code": null, "e": 26645, "s": 26641, "text": "SQL" }, { "code": null, "e": 26649, "s": 26645, "text": "SQL" }, { "code": null, "e": 26747, "s": 26649, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26813, "s": 26747, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 26828, "s": 26813, "text": "SQL | Subquery" }, { "code": null, "e": 26885, "s": 26828, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 26917, "s": 26885, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 26995, "s": 26917, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 27031, "s": 26995, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 27048, "s": 27031, "text": "SQL using Python" }, { "code": null, "e": 27114, "s": 27048, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 27176, "s": 27114, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
Check if the given vectors are at equilibrium or not - GeeksforGeeks
08 Sep, 2021 Given the x, y and z coordinates of three vectors, the task is to check if they are at equilibrium or not.Examples: Input: x1 = -2, y1 = 1, z1 = 0, x2 = 5, y2 = 0, z2 = 5, x3 = -3, y3 = -1, z3 = -5 Output: The vectors are at equilibrium.Input: x1 = 2, y1 = -17, z1 = 0, x2 = 5, y2 = 1, z2 = -5, x3 = 4, y3 = 2, z3 = -4 Output: The vectors are not at equilibrium. When Three vectors are at equilibrium Approach: Three vectors are at equilibrium when the results of those three vectors is a Null vector, i.e. it has no magnitude and direction. Resultant of three vectors is equal to the vector sum of the vectors. The resultant vector is Null when, ∑x = 0, ∑y = 0 and ∑ z = 0. Thus we can say that when the said condition satisfies then the vectors are at equilibrium and otherwise not. C++ Java Python 3 C# PHP Javascript // CPP program to check the equilibrium of three vectors#include <bits/stdc++.h>using namespace std; // Function to check the equilibrium of three vectorsbool checkEquilibrium(int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3){ // summing the x coordinates int resx = x1 + x2 + x3; // summing the y coordinates int resy = y1 + y2 + y3; // summing the z coordinates int resz = z1 + z2 + z3; // Checking the condition for equilibrium if (resx == 0 and resy == 0 and resz == 0) return true; else return false;} // Driver codeint main(){ int x1 = -2, y1 = -7, z1 = -9, x2 = 5, y2 = -14, z2 = 14, x3 = -3, y3 = 21, z3 = -5; // Checking for equilibrium if (checkEquilibrium(x1, y1, z1, x2, y2, z2, x3, y3, z3)) cout << "The vectors are at equilibrium."; else cout << "The vectors are not at equilibrium."; return 0;} // Java program to check the equilibrium of three vectors public class GFG { // Function to check the equilibrium of three vectors static boolean checkEquilibrium(int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { // summing the x coordinates int resx = x1 + x2 + x3; // summing the y coordinates int resy = y1 + y2 + y3; // summing the z coordinates int resz = z1 + z2 + z3; // Checking the condition for equilibrium if (resx == 0 & resy == 0 & resz == 0) return true; else return false; } // Driver code public static void main(String args[]) { int x1 = -2, y1 = -7, z1 = -9, x2 = 5, y2 = -14, z2 = 14, x3 = -3, y3 = 21, z3 = -5; // Checking for equilibrium if (checkEquilibrium(x1, y1, z1, x2, y2, z2, x3, y3, z3)) System.out.println("The vectors are at equilibrium."); else System.out.println("The vectors are not at equilibrium."); } }// This code is contributed by ANKITRAI1 # Python 3 program to check the# equilibrium of three vectors # Function to check the equilibrium# of three vectorsdef checkEquilibrium(x1, y1, z1, x2, y2, z2, x3, y3, z3) : # summing the x coordinates resx = x1 + x2 + x3 # summing the y coordinates resy = y1 + y2 + y3 # summing the z coordinates resz = z1 + z2 + z3 # Checking the condition for equilibrium if (resx == 0 and resy == 0 and resz == 0): return True else: return False # Driver codex1 = -2; y1 = -7; z1 = -9x2 = 5; y2 = -14; z2 = 14x3 = -3; y3 = 21; z3 = -5 # Checking for equilibriumif (checkEquilibrium(x1, y1, z1, x2, y2, z2, x3, y3, z3)): print("The vectors are at equilibrium.") else: print("The vectors are not at equilibrium.") # This code is contributed# by Akanksha Rai // C# program to check the equilibrium// of three vectorsclass GFG{ // Function to check the equilibrium// of three vectorsstatic bool checkEquilibrium(int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3){ // summing the x coordinates int resx = x1 + x2 + x3; // summing the y coordinates int resy = y1 + y2 + y3; // summing the z coordinates int resz = z1 + z2 + z3; // Checking the condition for equilibrium if (resx == 0 & resy == 0 & resz == 0) return true; else return false;} // Driver codepublic static void Main(){ int x1 = -2, y1 = -7, z1 = -9, x2 = 5, y2 = -14, z2 = 14, x3 = -3, y3 = 21, z3 = -5; // Checking for equilibrium if (checkEquilibrium(x1, y1, z1, x2, y2, z2, x3, y3, z3)) System.Console.WriteLine("The vectors are " + "at equilibrium."); else System.Console.WriteLine("The vectors are not " + "at equilibrium."); }} // This code is contributed by mits <?php// PHP program to check the equilibrium// of three vectors // Function to check the equilibrium// of three vectorsfunction checkEquilibrium($x1, $y1, $z1, $x2, $y2, $z2, $x3, $y3, $z3){ // summing the x coordinates $resx = $x1 + $x2 + $x3; // summing the y coordinates $resy = $y1 + $y2 + $y3; // summing the z coordinates $resz = $z1 + $z2 + $z3; // Checking the condition // for equilibrium if ($resx == 0 and $resy == 0 and $resz == 0) return true; else return false;} // Driver code$x1 = -2; $y1 = -7; $z1 = -9;$x2 = 5; $y2 = -14; $z2 = 14;$x3 = -3; $y3 = 21; $z3 = -5; // Checking for equilibriumif (checkEquilibrium($x1, $y1, $z1, $x2, $y2, $z2, $x3, $y3, $z3)) echo "The vectors are at equilibrium.";else echo "The vectors are not at equilibrium."; // This code is contributed by akt_mit?> <script> // Javascript program to check the// equilibrium of three vectors // Function to check the equilibrium// of three vectorsfunction checkEquilibrium(x1, y1, z1, x2, y2, z2, x3, y3, z3){ // Summing the x coordinates var resx = x1 + x2 + x3; // Summing the y coordinates var resy = y1 + y2 + y3; // Summing the z coordinates var resz = z1 + z2 + z3; // Checking the condition for equilibrium if (resx == 0 & resy == 0 & resz == 0) return true; else return false;} // Driver Codevar x1 = -2, y1 = -7, z1 = -9, x2 = 5, y2 = -14, z2 = 14, x3 = -3, y3 = 21, z3 = -5; // Checking for equilibriumif (checkEquilibrium(x1, y1, z1, x2, y2, z2, x3, y3, z3)) document.write("The vectors are at equilibrium.");else document.write("The vectors are not at equilibrium."); // This code is contributed by Kirti </script> The vectors are at equilibrium. ankthon Mithun Kumar jit_t Akanksha_Rai Kirti_Mangal avtarkumar719 Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Haversine formula to find distance between two points on a sphere Program to find slope of a line Program to find line passing through 2 Points Equation of circle when three points on the circle are given Maximum Manhattan distance between a distinct pair from N coordinates Program for Fibonacci numbers Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) C++ Data Types Coin Change | DP-7
[ { "code": null, "e": 26561, "s": 26533, "text": "\n08 Sep, 2021" }, { "code": null, "e": 26679, "s": 26561, "text": "Given the x, y and z coordinates of three vectors, the task is to check if they are at equilibrium or not.Examples: " }, { "code": null, "e": 26926, "s": 26679, "text": "Input: x1 = -2, y1 = 1, z1 = 0, x2 = 5, y2 = 0, z2 = 5, x3 = -3, y3 = -1, z3 = -5 Output: The vectors are at equilibrium.Input: x1 = 2, y1 = -17, z1 = 0, x2 = 5, y2 = 1, z2 = -5, x3 = 4, y3 = 2, z3 = -4 Output: The vectors are not at equilibrium." }, { "code": null, "e": 26968, "s": 26928, "text": "When Three vectors are at equilibrium " }, { "code": null, "e": 27353, "s": 26968, "text": "Approach: Three vectors are at equilibrium when the results of those three vectors is a Null vector, i.e. it has no magnitude and direction. Resultant of three vectors is equal to the vector sum of the vectors. The resultant vector is Null when, ∑x = 0, ∑y = 0 and ∑ z = 0. Thus we can say that when the said condition satisfies then the vectors are at equilibrium and otherwise not. " }, { "code": null, "e": 27357, "s": 27353, "text": "C++" }, { "code": null, "e": 27362, "s": 27357, "text": "Java" }, { "code": null, "e": 27371, "s": 27362, "text": "Python 3" }, { "code": null, "e": 27374, "s": 27371, "text": "C#" }, { "code": null, "e": 27378, "s": 27374, "text": "PHP" }, { "code": null, "e": 27389, "s": 27378, "text": "Javascript" }, { "code": "// CPP program to check the equilibrium of three vectors#include <bits/stdc++.h>using namespace std; // Function to check the equilibrium of three vectorsbool checkEquilibrium(int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3){ // summing the x coordinates int resx = x1 + x2 + x3; // summing the y coordinates int resy = y1 + y2 + y3; // summing the z coordinates int resz = z1 + z2 + z3; // Checking the condition for equilibrium if (resx == 0 and resy == 0 and resz == 0) return true; else return false;} // Driver codeint main(){ int x1 = -2, y1 = -7, z1 = -9, x2 = 5, y2 = -14, z2 = 14, x3 = -3, y3 = 21, z3 = -5; // Checking for equilibrium if (checkEquilibrium(x1, y1, z1, x2, y2, z2, x3, y3, z3)) cout << \"The vectors are at equilibrium.\"; else cout << \"The vectors are not at equilibrium.\"; return 0;}", "e": 28324, "s": 27389, "text": null }, { "code": "// Java program to check the equilibrium of three vectors public class GFG { // Function to check the equilibrium of three vectors static boolean checkEquilibrium(int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3) { // summing the x coordinates int resx = x1 + x2 + x3; // summing the y coordinates int resy = y1 + y2 + y3; // summing the z coordinates int resz = z1 + z2 + z3; // Checking the condition for equilibrium if (resx == 0 & resy == 0 & resz == 0) return true; else return false; } // Driver code public static void main(String args[]) { int x1 = -2, y1 = -7, z1 = -9, x2 = 5, y2 = -14, z2 = 14, x3 = -3, y3 = 21, z3 = -5; // Checking for equilibrium if (checkEquilibrium(x1, y1, z1, x2, y2, z2, x3, y3, z3)) System.out.println(\"The vectors are at equilibrium.\"); else System.out.println(\"The vectors are not at equilibrium.\"); } }// This code is contributed by ANKITRAI1", "e": 29511, "s": 28324, "text": null }, { "code": "# Python 3 program to check the# equilibrium of three vectors # Function to check the equilibrium# of three vectorsdef checkEquilibrium(x1, y1, z1, x2, y2, z2, x3, y3, z3) : # summing the x coordinates resx = x1 + x2 + x3 # summing the y coordinates resy = y1 + y2 + y3 # summing the z coordinates resz = z1 + z2 + z3 # Checking the condition for equilibrium if (resx == 0 and resy == 0 and resz == 0): return True else: return False # Driver codex1 = -2; y1 = -7; z1 = -9x2 = 5; y2 = -14; z2 = 14x3 = -3; y3 = 21; z3 = -5 # Checking for equilibriumif (checkEquilibrium(x1, y1, z1, x2, y2, z2, x3, y3, z3)): print(\"The vectors are at equilibrium.\") else: print(\"The vectors are not at equilibrium.\") # This code is contributed# by Akanksha Rai", "e": 30388, "s": 29511, "text": null }, { "code": "// C# program to check the equilibrium// of three vectorsclass GFG{ // Function to check the equilibrium// of three vectorsstatic bool checkEquilibrium(int x1, int y1, int z1, int x2, int y2, int z2, int x3, int y3, int z3){ // summing the x coordinates int resx = x1 + x2 + x3; // summing the y coordinates int resy = y1 + y2 + y3; // summing the z coordinates int resz = z1 + z2 + z3; // Checking the condition for equilibrium if (resx == 0 & resy == 0 & resz == 0) return true; else return false;} // Driver codepublic static void Main(){ int x1 = -2, y1 = -7, z1 = -9, x2 = 5, y2 = -14, z2 = 14, x3 = -3, y3 = 21, z3 = -5; // Checking for equilibrium if (checkEquilibrium(x1, y1, z1, x2, y2, z2, x3, y3, z3)) System.Console.WriteLine(\"The vectors are \" + \"at equilibrium.\"); else System.Console.WriteLine(\"The vectors are not \" + \"at equilibrium.\"); }} // This code is contributed by mits", "e": 31517, "s": 30388, "text": null }, { "code": "<?php// PHP program to check the equilibrium// of three vectors // Function to check the equilibrium// of three vectorsfunction checkEquilibrium($x1, $y1, $z1, $x2, $y2, $z2, $x3, $y3, $z3){ // summing the x coordinates $resx = $x1 + $x2 + $x3; // summing the y coordinates $resy = $y1 + $y2 + $y3; // summing the z coordinates $resz = $z1 + $z2 + $z3; // Checking the condition // for equilibrium if ($resx == 0 and $resy == 0 and $resz == 0) return true; else return false;} // Driver code$x1 = -2; $y1 = -7; $z1 = -9;$x2 = 5; $y2 = -14; $z2 = 14;$x3 = -3; $y3 = 21; $z3 = -5; // Checking for equilibriumif (checkEquilibrium($x1, $y1, $z1, $x2, $y2, $z2, $x3, $y3, $z3)) echo \"The vectors are at equilibrium.\";else echo \"The vectors are not at equilibrium.\"; // This code is contributed by akt_mit?>", "e": 32481, "s": 31517, "text": null }, { "code": "<script> // Javascript program to check the// equilibrium of three vectors // Function to check the equilibrium// of three vectorsfunction checkEquilibrium(x1, y1, z1, x2, y2, z2, x3, y3, z3){ // Summing the x coordinates var resx = x1 + x2 + x3; // Summing the y coordinates var resy = y1 + y2 + y3; // Summing the z coordinates var resz = z1 + z2 + z3; // Checking the condition for equilibrium if (resx == 0 & resy == 0 & resz == 0) return true; else return false;} // Driver Codevar x1 = -2, y1 = -7, z1 = -9, x2 = 5, y2 = -14, z2 = 14, x3 = -3, y3 = 21, z3 = -5; // Checking for equilibriumif (checkEquilibrium(x1, y1, z1, x2, y2, z2, x3, y3, z3)) document.write(\"The vectors are at equilibrium.\");else document.write(\"The vectors are not at equilibrium.\"); // This code is contributed by Kirti </script>", "e": 33395, "s": 32481, "text": null }, { "code": null, "e": 33427, "s": 33395, "text": "The vectors are at equilibrium." }, { "code": null, "e": 33437, "s": 33429, "text": "ankthon" }, { "code": null, "e": 33450, "s": 33437, "text": "Mithun Kumar" }, { "code": null, "e": 33456, "s": 33450, "text": "jit_t" }, { "code": null, "e": 33469, "s": 33456, "text": "Akanksha_Rai" }, { "code": null, "e": 33482, "s": 33469, "text": "Kirti_Mangal" }, { "code": null, "e": 33496, "s": 33482, "text": "avtarkumar719" }, { "code": null, "e": 33506, "s": 33496, "text": "Geometric" }, { "code": null, "e": 33519, "s": 33506, "text": "Mathematical" }, { "code": null, "e": 33532, "s": 33519, "text": "Mathematical" }, { "code": null, "e": 33542, "s": 33532, "text": "Geometric" }, { "code": null, "e": 33640, "s": 33542, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33706, "s": 33640, "text": "Haversine formula to find distance between two points on a sphere" }, { "code": null, "e": 33738, "s": 33706, "text": "Program to find slope of a line" }, { "code": null, "e": 33784, "s": 33738, "text": "Program to find line passing through 2 Points" }, { "code": null, "e": 33845, "s": 33784, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 33915, "s": 33845, "text": "Maximum Manhattan distance between a distinct pair from N coordinates" }, { "code": null, "e": 33945, "s": 33915, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 34005, "s": 33945, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34048, "s": 34005, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 34063, "s": 34048, "text": "C++ Data Types" } ]
PostgreSQL - EXTRACT Function - GeeksforGeeks
07 Oct, 2021 The PostgreSQL EXTRACT() function is used to query for field associated with date and time such as a year, month, and day from a date/time value. Syntax: EXTRACT(field FROM source) Let’s analyze the above syntax: In the above syntax the field argument is used to specify fields that is to be extracted from the date/time value. The source is generally either a TIMESTAMP type or an INTERVAL type. Depending upon the values passed the type is set. For instance, if we pass a DATE value, the function adapt to a TIMESTAMP type value. Example 1: The below statement extracts year from a timestamp: SELECT EXTRACT(YEAR FROM TIMESTAMP '2020-12-31 13:30:15'); Output: Example 2: The below statement extracts the quarter from a timestamp: SELECT EXTRACT(QUARTER FROM TIMESTAMP '2020-12-31 13:30:15'); Output: Example 3: The below statement extracts month from a timestamp: SELECT EXTRACT(MONTH FROM TIMESTAMP '2020-12-31 13:30:15'); Output: ruhelaa48 PostgreSQL-Date-function PostgreSQL-function PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. PostgreSQL - Psql commands PostgreSQL - Change Column Type PostgreSQL - For Loops PostgreSQL - Function Returning A Table PostgreSQL - Create Auto-increment Column using SERIAL PostgreSQL - CREATE PROCEDURE PostgreSQL - ARRAY_AGG() Function PostgreSQL - DROP INDEX PostgreSQL - Copy Table PostgreSQL - Identity Column
[ { "code": null, "e": 29271, "s": 29243, "text": "\n07 Oct, 2021" }, { "code": null, "e": 29417, "s": 29271, "text": "The PostgreSQL EXTRACT() function is used to query for field associated with date and time such as a year, month, and day from a date/time value." }, { "code": null, "e": 29452, "s": 29417, "text": "Syntax: EXTRACT(field FROM source)" }, { "code": null, "e": 29484, "s": 29452, "text": "Let’s analyze the above syntax:" }, { "code": null, "e": 29599, "s": 29484, "text": "In the above syntax the field argument is used to specify fields that is to be extracted from the date/time value." }, { "code": null, "e": 29803, "s": 29599, "text": "The source is generally either a TIMESTAMP type or an INTERVAL type. Depending upon the values passed the type is set. For instance, if we pass a DATE value, the function adapt to a TIMESTAMP type value." }, { "code": null, "e": 29814, "s": 29803, "text": "Example 1:" }, { "code": null, "e": 29866, "s": 29814, "text": "The below statement extracts year from a timestamp:" }, { "code": null, "e": 29925, "s": 29866, "text": "SELECT EXTRACT(YEAR FROM TIMESTAMP '2020-12-31 13:30:15');" }, { "code": null, "e": 29933, "s": 29925, "text": "Output:" }, { "code": null, "e": 29944, "s": 29933, "text": "Example 2:" }, { "code": null, "e": 30003, "s": 29944, "text": "The below statement extracts the quarter from a timestamp:" }, { "code": null, "e": 30065, "s": 30003, "text": "SELECT EXTRACT(QUARTER FROM TIMESTAMP '2020-12-31 13:30:15');" }, { "code": null, "e": 30073, "s": 30065, "text": "Output:" }, { "code": null, "e": 30084, "s": 30073, "text": "Example 3:" }, { "code": null, "e": 30137, "s": 30084, "text": "The below statement extracts month from a timestamp:" }, { "code": null, "e": 30197, "s": 30137, "text": "SELECT EXTRACT(MONTH FROM TIMESTAMP '2020-12-31 13:30:15');" }, { "code": null, "e": 30205, "s": 30197, "text": "Output:" }, { "code": null, "e": 30215, "s": 30205, "text": "ruhelaa48" }, { "code": null, "e": 30240, "s": 30215, "text": "PostgreSQL-Date-function" }, { "code": null, "e": 30260, "s": 30240, "text": "PostgreSQL-function" }, { "code": null, "e": 30271, "s": 30260, "text": "PostgreSQL" }, { "code": null, "e": 30369, "s": 30271, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30396, "s": 30369, "text": "PostgreSQL - Psql commands" }, { "code": null, "e": 30428, "s": 30396, "text": "PostgreSQL - Change Column Type" }, { "code": null, "e": 30451, "s": 30428, "text": "PostgreSQL - For Loops" }, { "code": null, "e": 30491, "s": 30451, "text": "PostgreSQL - Function Returning A Table" }, { "code": null, "e": 30546, "s": 30491, "text": "PostgreSQL - Create Auto-increment Column using SERIAL" }, { "code": null, "e": 30576, "s": 30546, "text": "PostgreSQL - CREATE PROCEDURE" }, { "code": null, "e": 30610, "s": 30576, "text": "PostgreSQL - ARRAY_AGG() Function" }, { "code": null, "e": 30634, "s": 30610, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 30658, "s": 30634, "text": "PostgreSQL - Copy Table" } ]
Prefetch_related and select_related functions in django - GeeksforGeeks
23 Oct, 2020 In Django, select_related and prefetch_related are designed to stop the deluge of database queries that are caused by accessing related objects.In this article we will see how it reduces number of queries and make program much faster. select_related() “follows” foreign-key relationships, selecting additional related-object data when it executes its query. prefetch_related() does a separate lookup for each relationship, and does the “joining” in Python. One uses select_related when the object that you’re going to be selecting is a single object, so OneToOneField or a ForeignKey. You use prefetch_related when you’re going to get a “set” of things, so ManyToManyFields as you stated or reverse ForeignKeys. Just to clarify what I mean by “reverse ForeignKeys” . Example to illustrate the concept of Prefetch_related and select_related – The above classification might be not so clear let see an example : class A(models.Model): pass class B(models.Model): a = ForeignKey(ModelA) # Forward ForeignKey relationshipA.objects.select_related('a').all() # Reverse ForeignKey relationshipA.objects.prefetch_related('modelb_set').all() select_related obtains all data at one time through multi-table join Association query, and improves performance by reducing the number of database queries. It uses JOIN statements of SQL to optimize and improve performance by reducing the number of SQL queries.The latter is to solve the problem in the SQL query through JOIN statement. However, for many-to-many relationships, it is not wise to use SQL statements to solve them, because the tables obtained by JOIN will be very long, which will lead to the increase of running time and memory occupation of SQL statements. The solution to prefetch_related() is to query each table separately and then use Python to handle their relationship! Here are some examples : Models.py reads as follows: from django.db import models class Province(models.Model): name = models.CharField(max_length = 10) def __unicode__(self): return self.name class City(models.Model): name = models.CharField(max_length = 5) province = models.ForeignKey(Province) def __unicode__(self): return self.name class Person(models.Model): firstname = models.CharField(max_length = 10) lastname = models.CharField(max_length = 10) visitation = models.ManyToManyField(City, related_name = "visitor") hometown = models.ForeignKey(City, related_name = "birth") living = models.ForeignKey(City, related_name = "citizen") def __unicode__(self): return self.firstname + self.lastname select_related – we use the select_related() function: >>> citys = City.objects.select_related().all() >>> for c in citys: ... print c.province ... There is only one SQL query, which obviously greatly reduces the number of SQL queries: SELECT `Optimize_city`.`id`, `Optimize_city`.`name`, `Optimize_city`.`province_id`, `Optimize_province`.`id`, `Optimize_province`.`name` FROM`Optimize_city` INNER JOIN `Optimize_province` ON (`Optimize_city`.`province_id`=`Optimize_province`.`id`); prefetch_related – Here we can see that Django uses INNER JOIN. I would like to clear one thing that Optimize is a name of our app. If we want to get all the city names of Hubei, we can do this: > HB=Province.objects.prefetch_related('city_set').get(name__iexact=u"Hubei Province") >>> for city in hb.city_set.all(): ... city.name ... Triggered SQL queries: SELECT `Optimize_province`.`id`, `Optimize_province`.`name` FROM `Optimize_province` WHERE `Optimize_province', `name `LIKE'Hubei Province'; SELECT `Optimize_city`.`id`, `Optimize_city`.`name`, `Optimize_city`.`province_id` FROM `Optimize_city` WHERE `Optimize_city`.`province_id` IN (1); As we can see, prefetch is implemented using the IN statement. In this way, when there are too many objects in QuerySet, performance problems may arise depending on the characteristics of the database. Python Django Python Framework Python Web Technologies 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 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": 25653, "s": 25625, "text": "\n23 Oct, 2020" }, { "code": null, "e": 25890, "s": 25653, "text": " In Django, select_related and prefetch_related are designed to stop the deluge of database queries that are caused by accessing related objects.In this article we will see how it reduces number of queries and make program much faster. " }, { "code": null, "e": 26013, "s": 25890, "text": "select_related() “follows” foreign-key relationships, selecting additional related-object data when it executes its query." }, { "code": null, "e": 26112, "s": 26013, "text": "prefetch_related() does a separate lookup for each relationship, and does the “joining” in Python." }, { "code": null, "e": 26423, "s": 26112, "text": "One uses select_related when the object that you’re going to be selecting is a single object, so OneToOneField or a ForeignKey. You use prefetch_related when you’re going to get a “set” of things, so ManyToManyFields as you stated or reverse ForeignKeys. Just to clarify what I mean by “reverse ForeignKeys” . " }, { "code": null, "e": 26498, "s": 26423, "text": "Example to illustrate the concept of Prefetch_related and select_related –" }, { "code": null, "e": 26566, "s": 26498, "text": "The above classification might be not so clear let see an example :" }, { "code": "class A(models.Model): pass class B(models.Model): a = ForeignKey(ModelA) # Forward ForeignKey relationshipA.objects.select_related('a').all() # Reverse ForeignKey relationshipA.objects.prefetch_related('modelb_set').all() ", "e": 26799, "s": 26566, "text": null }, { "code": null, "e": 27493, "s": 26799, "text": "select_related obtains all data at one time through multi-table join Association query, and improves performance by reducing the number of database queries. It uses JOIN statements of SQL to optimize and improve performance by reducing the number of SQL queries.The latter is to solve the problem in the SQL query through JOIN statement. However, for many-to-many relationships, it is not wise to use SQL statements to solve them, because the tables obtained by JOIN will be very long, which will lead to the increase of running time and memory occupation of SQL statements. The solution to prefetch_related() is to query each table separately and then use Python to handle their relationship!" }, { "code": null, "e": 27518, "s": 27493, "text": "Here are some examples :" }, { "code": null, "e": 27546, "s": 27518, "text": "Models.py reads as follows:" }, { "code": "from django.db import models class Province(models.Model): name = models.CharField(max_length = 10) def __unicode__(self): return self.name class City(models.Model): name = models.CharField(max_length = 5) province = models.ForeignKey(Province) def __unicode__(self): return self.name class Person(models.Model): firstname = models.CharField(max_length = 10) lastname = models.CharField(max_length = 10) visitation = models.ManyToManyField(City, related_name = \"visitor\") hometown = models.ForeignKey(City, related_name = \"birth\") living = models.ForeignKey(City, related_name = \"citizen\") def __unicode__(self): return self.firstname + self.lastname", "e": 28240, "s": 27546, "text": null }, { "code": null, "e": 28257, "s": 28240, "text": "select_related –" }, { "code": null, "e": 28296, "s": 28257, "text": " we use the select_related() function:" }, { "code": null, "e": 28391, "s": 28296, "text": ">>> citys = City.objects.select_related().all()\n>>> for c in citys:\n... print c.province\n..." }, { "code": null, "e": 28479, "s": 28391, "text": "There is only one SQL query, which obviously greatly reduces the number of SQL queries:" }, { "code": null, "e": 28728, "s": 28479, "text": "SELECT `Optimize_city`.`id`, `Optimize_city`.`name`,\n`Optimize_city`.`province_id`, `Optimize_province`.`id`, `Optimize_province`.`name`\nFROM`Optimize_city`\nINNER JOIN `Optimize_province` ON\n(`Optimize_city`.`province_id`=`Optimize_province`.`id`);" }, { "code": null, "e": 28747, "s": 28728, "text": "prefetch_related –" }, { "code": null, "e": 28923, "s": 28747, "text": "Here we can see that Django uses INNER JOIN. I would like to clear one thing that Optimize is a name of our app. If we want to get all the city names of Hubei, we can do this:" }, { "code": null, "e": 29065, "s": 28923, "text": "> HB=Province.objects.prefetch_related('city_set').get(name__iexact=u\"Hubei Province\")\n>>> for city in hb.city_set.all():\n... city.name\n..." }, { "code": null, "e": 29088, "s": 29065, "text": "Triggered SQL queries:" }, { "code": null, "e": 29378, "s": 29088, "text": "SELECT `Optimize_province`.`id`, `Optimize_province`.`name`\nFROM `Optimize_province`\nWHERE `Optimize_province', `name `LIKE'Hubei Province';\n\nSELECT `Optimize_city`.`id`, `Optimize_city`.`name`, `Optimize_city`.`province_id`\nFROM `Optimize_city`\nWHERE `Optimize_city`.`province_id` IN (1);" }, { "code": null, "e": 29580, "s": 29378, "text": "As we can see, prefetch is implemented using the IN statement. In this way, when there are too many objects in QuerySet, performance problems may arise depending on the characteristics of the database." }, { "code": null, "e": 29594, "s": 29580, "text": "Python Django" }, { "code": null, "e": 29611, "s": 29594, "text": "Python Framework" }, { "code": null, "e": 29618, "s": 29611, "text": "Python" }, { "code": null, "e": 29635, "s": 29618, "text": "Web Technologies" }, { "code": null, "e": 29733, "s": 29635, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29751, "s": 29733, "text": "Python Dictionary" }, { "code": null, "e": 29786, "s": 29751, "text": "Read a file line by line in Python" }, { "code": null, "e": 29818, "s": 29786, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29840, "s": 29818, "text": "Enumerate() in Python" }, { "code": null, "e": 29882, "s": 29840, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29922, "s": 29882, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29955, "s": 29922, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30000, "s": 29955, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30043, "s": 30000, "text": "How to fetch data from an API in ReactJS ?" } ]
What does dollar sign ($) means in jQuery ? - GeeksforGeeks
19 Jul, 2021 The $ sign is nothing but an identifier of jQuery() function. Instead of writing jQuery we simply write $ which is the same as jQuery() function. A $ with a selector specifies that it is a jQuery selector. It is given a shorter identifier as $ just to reduce the time for writing larger syntax. It contains all the functions that are used by a jQuery object such as animate(), hide(), show(), css() and many more. Moreover, in terms of memory, $ is better than jQuery because $ takes a byte and jQuery takes 6 bytes which have the same functionality. Syntax: $('selector').action(); Example 1: A simple illustration to show jQuery and $ have the same functionality. HTML !DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Including jQuery --> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"> </script></head> <body> <script> console.log($===jQuery) </script></body> </html> Output: true Note: $(‘p’) and jQuery(‘p’) have the same meaning, and they return the same objects. Example 2: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Including jQuery --> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"> </script></head> <body> <p> This is a paragraph</p> <script> var p = $('p').text(); var x = jQuery('p').text() console.log(p); console.log(x); </script></body></html> Output: We can even change the $ by using jQuery noConflict() function because there may be chances when we are using other technologies which may have different meaning, in such cases we can have our customized identifier for jQuery using noConflict() method. Syntax: var new_identifier = jQuery.noConflict(); Example 3: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Including jQuery --> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"> </script></head> <body> <p> This is a paragraph</p> <script> var dollar = jQuery.noConflict(); // We can use dollar instead of $ by // using jQuery noConflict() method var x = dollar('p').text() console.log(x); </script></body> </html> Output: This is a paragraph jQuery-Questions Picked JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show and Hide div elements using radio buttons? How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method jQuery | removeAttr() with Examples How to get the value in an input text box using jQuery ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26954, "s": 26926, "text": "\n19 Jul, 2021" }, { "code": null, "e": 27017, "s": 26954, "text": "The $ sign is nothing but an identifier of jQuery() function. " }, { "code": null, "e": 27507, "s": 27017, "text": "Instead of writing jQuery we simply write $ which is the same as jQuery() function. A $ with a selector specifies that it is a jQuery selector. It is given a shorter identifier as $ just to reduce the time for writing larger syntax. It contains all the functions that are used by a jQuery object such as animate(), hide(), show(), css() and many more. Moreover, in terms of memory, $ is better than jQuery because $ takes a byte and jQuery takes 6 bytes which have the same functionality. " }, { "code": null, "e": 27515, "s": 27507, "text": "Syntax:" }, { "code": null, "e": 27539, "s": 27515, "text": "$('selector').action();" }, { "code": null, "e": 27622, "s": 27539, "text": "Example 1: A simple illustration to show jQuery and $ have the same functionality." }, { "code": null, "e": 27627, "s": 27622, "text": "HTML" }, { "code": "!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <!-- Including jQuery --> <script src=\"https://code.jquery.com/jquery-3.6.0.min.js\" integrity=\"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=\" crossorigin=\"anonymous\"> </script></head> <body> <script> console.log($===jQuery) </script></body> </html>", "e": 28142, "s": 27627, "text": null }, { "code": null, "e": 28150, "s": 28142, "text": "Output:" }, { "code": null, "e": 28155, "s": 28150, "text": "true" }, { "code": null, "e": 28241, "s": 28155, "text": "Note: $(‘p’) and jQuery(‘p’) have the same meaning, and they return the same objects." }, { "code": null, "e": 28252, "s": 28241, "text": "Example 2:" }, { "code": null, "e": 28257, "s": 28252, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <!-- Including jQuery --> <script src=\"https://code.jquery.com/jquery-3.6.0.min.js\" integrity=\"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=\" crossorigin=\"anonymous\"> </script></head> <body> <p> This is a paragraph</p> <script> var p = $('p').text(); var x = jQuery('p').text() console.log(p); console.log(x); </script></body></html>", "e": 28871, "s": 28257, "text": null }, { "code": null, "e": 28879, "s": 28871, "text": "Output:" }, { "code": null, "e": 29132, "s": 28879, "text": "We can even change the $ by using jQuery noConflict() function because there may be chances when we are using other technologies which may have different meaning, in such cases we can have our customized identifier for jQuery using noConflict() method." }, { "code": null, "e": 29140, "s": 29132, "text": "Syntax:" }, { "code": null, "e": 29182, "s": 29140, "text": "var new_identifier = jQuery.noConflict();" }, { "code": null, "e": 29193, "s": 29182, "text": "Example 3:" }, { "code": null, "e": 29198, "s": 29193, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <!-- Including jQuery --> <script src=\"https://code.jquery.com/jquery-3.6.0.min.js\" integrity=\"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=\" crossorigin=\"anonymous\"> </script></head> <body> <p> This is a paragraph</p> <script> var dollar = jQuery.noConflict(); // We can use dollar instead of $ by // using jQuery noConflict() method var x = dollar('p').text() console.log(x); </script></body> </html>", "e": 29895, "s": 29198, "text": null }, { "code": null, "e": 29903, "s": 29895, "text": "Output:" }, { "code": null, "e": 29923, "s": 29903, "text": "This is a paragraph" }, { "code": null, "e": 29940, "s": 29923, "text": "jQuery-Questions" }, { "code": null, "e": 29947, "s": 29940, "text": "Picked" }, { "code": null, "e": 29954, "s": 29947, "text": "JQuery" }, { "code": null, "e": 29971, "s": 29954, "text": "Web Technologies" }, { "code": null, "e": 30069, "s": 29971, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30124, "s": 30069, "text": "How to Show and Hide div elements using radio buttons?" }, { "code": null, "e": 30197, "s": 30124, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 30220, "s": 30197, "text": "jQuery | ajax() Method" }, { "code": null, "e": 30256, "s": 30220, "text": "jQuery | removeAttr() with Examples" }, { "code": null, "e": 30313, "s": 30256, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 30353, "s": 30313, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30386, "s": 30353, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30431, "s": 30386, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30474, "s": 30431, "text": "How to fetch data from an API in ReactJS ?" } ]
Python | Add Logging to a Python Script - GeeksforGeeks
12 Jun, 2019 In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follow work) hostname = 'www.python.org' item = 'spam' filename = 'data.csv' mode = 'r' # Example logging calls (insert into your program) logging.critical('Host %s unknown', hostname) logging.error("Couldn't find %r", item) logging.warning('Feature is deprecated') logging.info('Opening file %r, mode = %r', filename, mode) logging.debug('Got here') if __name__ == '__main__':main() The five logging calls (critical(), error(), warning(), info(), debug()) represent different severity levels in decreasing order. The level argument to basicConfig() is a filter. All messages issued at a level lower than this setting will be ignored. The argument to each logging operation is a message string followed by zero or more arguments. When making the final log message, the % operator is used to format the message string using the supplied arguments. If you run the code above, the contents of the file app.log will be as follow – CRITICAL:root:Host www.python.org unknown ERROR:root:Could not find 'spam' To change the output or level of output, change the parameters to the basicConfig() call as in the code given below – Code #2 : logging.basicConfig( filename = 'app.log', level = logging.WARNING, format = '%(levelname)s:%(asctime)s:%(message)s') Output : CRITICAL:2012-11-20 12:27:13, 595:Host www.python.org unknown ERROR:2012-11-20 12:27:13, 595:Could not find 'spam' WARNING:2012-11-20 12:27:13, 595:Feature is deprecated The logging configuration is hardcoded directly into the program. To configure it from a configuration file, change the basicConfig() call to the following. Code #3 : import loggingimport logging.config def main(): # Configure the logging system logging.config.fileConfig('logconfig.ini') ... Now make a configuration file that looks like this – [loggers] keys=root [handlers] keys=defaultHandler [formatters] keys=defaultFormatter [logger_root] level=INFO handlers=defaultHandler qualname=root [handler_defaultHandler] class=FileHandler formatter=defaultFormatter args=('app.log', 'a') [formatter_defaultFormatter] format=%(levelname)s:%(name)s:%(message)s If you want to make changes to the configuration, you can simply edit the file as appropriate. Ignoring for the moment that there are about a million advanced configuration options for the logging module, this solution is quite sufficient for simple programs and scripts. Simply make sure to execute the basicConfig() call prior to making any logging calls, and the program will generate logging output. Reference: https://docs.python.org/3/howto/logging-cookbook.html python-utility 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": 26635, "s": 26607, "text": "\n12 Jun, 2019" }, { "code": null, "e": 26752, "s": 26635, "text": "In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files." }, { "code": null, "e": 26822, "s": 26752, "text": "Code #1 : Using the logging module to add logging to a simple program" }, { "code": "import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follow work) hostname = 'www.python.org' item = 'spam' filename = 'data.csv' mode = 'r' # Example logging calls (insert into your program) logging.critical('Host %s unknown', hostname) logging.error(\"Couldn't find %r\", item) logging.warning('Feature is deprecated') logging.info('Opening file %r, mode = %r', filename, mode) logging.debug('Got here') if __name__ == '__main__':main()", "e": 27444, "s": 26822, "text": null }, { "code": null, "e": 27574, "s": 27444, "text": "The five logging calls (critical(), error(), warning(), info(), debug()) represent different severity levels in decreasing order." }, { "code": null, "e": 27695, "s": 27574, "text": "The level argument to basicConfig() is a filter. All messages issued at a level lower than this setting will be ignored." }, { "code": null, "e": 27907, "s": 27695, "text": "The argument to each logging operation is a message string followed by zero or more arguments. When making the final log message, the % operator is used to format the message string using the supplied arguments." }, { "code": null, "e": 27987, "s": 27907, "text": "If you run the code above, the contents of the file app.log will be as follow –" }, { "code": null, "e": 28062, "s": 27987, "text": "CRITICAL:root:Host www.python.org unknown\nERROR:root:Could not find 'spam'" }, { "code": null, "e": 28180, "s": 28062, "text": "To change the output or level of output, change the parameters to the basicConfig() call as in the code given below –" }, { "code": null, "e": 28190, "s": 28180, "text": "Code #2 :" }, { "code": "logging.basicConfig( filename = 'app.log', level = logging.WARNING, format = '%(levelname)s:%(asctime)s:%(message)s')", "e": 28332, "s": 28190, "text": null }, { "code": null, "e": 28341, "s": 28332, "text": "Output :" }, { "code": null, "e": 28511, "s": 28341, "text": "CRITICAL:2012-11-20 12:27:13, 595:Host www.python.org unknown\nERROR:2012-11-20 12:27:13, 595:Could not find 'spam'\nWARNING:2012-11-20 12:27:13, 595:Feature is deprecated" }, { "code": null, "e": 28668, "s": 28511, "text": "The logging configuration is hardcoded directly into the program. To configure it from a configuration file, change the basicConfig() call to the following." }, { "code": null, "e": 28678, "s": 28668, "text": "Code #3 :" }, { "code": "import loggingimport logging.config def main(): # Configure the logging system logging.config.fileConfig('logconfig.ini') ...", "e": 28814, "s": 28678, "text": null }, { "code": null, "e": 28867, "s": 28814, "text": "Now make a configuration file that looks like this –" }, { "code": null, "e": 29185, "s": 28867, "text": "[loggers]\nkeys=root\n\n[handlers]\nkeys=defaultHandler\n\n[formatters]\nkeys=defaultFormatter\n\n[logger_root]\nlevel=INFO\nhandlers=defaultHandler\nqualname=root\n\n[handler_defaultHandler]\nclass=FileHandler\nformatter=defaultFormatter\nargs=('app.log', 'a')\n\n[formatter_defaultFormatter]\nformat=%(levelname)s:%(name)s:%(message)s\n" }, { "code": null, "e": 29280, "s": 29185, "text": "If you want to make changes to the configuration, you can simply edit the file as appropriate." }, { "code": null, "e": 29589, "s": 29280, "text": "Ignoring for the moment that there are about a million advanced configuration options for the logging module, this solution is quite sufficient for simple programs and scripts. Simply make sure to execute the basicConfig() call prior to making any logging calls, and the program will generate logging output." }, { "code": null, "e": 29655, "s": 29589, "text": " Reference: https://docs.python.org/3/howto/logging-cookbook.html" }, { "code": null, "e": 29670, "s": 29655, "text": "python-utility" }, { "code": null, "e": 29677, "s": 29670, "text": "Python" }, { "code": null, "e": 29775, "s": 29677, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29793, "s": 29775, "text": "Python Dictionary" }, { "code": null, "e": 29828, "s": 29793, "text": "Read a file line by line in Python" }, { "code": null, "e": 29860, "s": 29828, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29882, "s": 29860, "text": "Enumerate() in Python" }, { "code": null, "e": 29924, "s": 29882, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29954, "s": 29924, "text": "Iterate over a list in Python" }, { "code": null, "e": 29980, "s": 29954, "text": "Python String | replace()" }, { "code": null, "e": 30009, "s": 29980, "text": "*args and **kwargs in Python" }, { "code": null, "e": 30053, "s": 30009, "text": "Reading and Writing to text files in Python" } ]
How to set the Margin between the CheckBox controls in C#? - GeeksforGeeks
27 Sep, 2021 The CheckBox control is the part of windows form which is used to take input from the user. Or in other words, CheckBox control allows us to select single or multiple elements from the given list. In CheckBox, you are allowed to set the space between two or more CheckBox controls using the Margin Property of the CheckBox. It makes your CheckBox more attractive. In Windows form, you can set this property in two different ways: 1. Design-Time: It is the simplest way to set the Margin property of a CheckBox using the following steps: Step 1: Create a windows form as shown in the below image: Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the CheckBox control from the ToolBox and drop it on the windows form. You can place CheckBox anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the CheckBox control to set the space between two or more CheckBox controls using the Margin property. Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the Margin property of a CheckBox programmatically using the following syntax: public System.Windows.Forms.Padding Margin { get; set; } Here, the Padding is used to represent the space between CheckBox controls. Following steps are used to set the Margin property of the CheckBox: Step 1: Create a checkbox using the CheckBox() constructor provided by the CheckBox class. // Creating checkbox CheckBox Mycheckbox = new CheckBox(); Step 2: After creating CheckBox, set the Margin property of the CheckBox provided by the CheckBox class. // Set the Margin property of the CheckBox Mycheckbox.Margin = new Padding(6, 6, 6, 6); Step 3: And last add this checkbox control to form using Add() method. // Add this checkbox to form this.Controls.Add(Mycheckbox); Example: C# using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp5 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Text = "Select Gender:"; l.Location = new Point(233, 111); // Adding label to form this.Controls.Add(l); // Creating and setting the properties of CheckBox CheckBox Mycheckbox = new CheckBox(); Mycheckbox.Height = 50; Mycheckbox.Width = 100; Mycheckbox.Location = new Point(229, 136); Mycheckbox.Text = "Male"; Mycheckbox.Margin = new Padding(6, 6, 6, 6); // Adding checkbox to form this.Controls.Add(Mycheckbox); // Creating and setting the properties of CheckBox CheckBox Mycheckbox1 = new CheckBox(); Mycheckbox1.Height = 50; Mycheckbox1.Width = 100; Mycheckbox1.Location = new Point(230, 174); Mycheckbox1.Text = "Female"; // Adding checkbox to form this.Controls.Add(Mycheckbox1); }}} Output: sagartomar9927 CSharp-Windows-Forms-Namespace 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# C# | Constructors Extension Method in C# Introduction to .NET Framework C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method
[ { "code": null, "e": 25315, "s": 25287, "text": "\n27 Sep, 2021" }, { "code": null, "e": 25745, "s": 25315, "text": "The CheckBox control is the part of windows form which is used to take input from the user. Or in other words, CheckBox control allows us to select single or multiple elements from the given list. In CheckBox, you are allowed to set the space between two or more CheckBox controls using the Margin Property of the CheckBox. It makes your CheckBox more attractive. In Windows form, you can set this property in two different ways:" }, { "code": null, "e": 25853, "s": 25745, "text": "1. Design-Time: It is the simplest way to set the Margin property of a CheckBox using the following steps: " }, { "code": null, "e": 25971, "s": 25853, "text": "Step 1: Create a windows form as shown in the below image: Visual Studio -> File -> New -> Project -> WindowsFormApp " }, { "code": null, "e": 26132, "s": 25971, "text": "Step 2: Drag the CheckBox control from the ToolBox and drop it on the windows form. You can place CheckBox anywhere on the windows form according to your need. " }, { "code": null, "e": 26297, "s": 26132, "text": "Step 3: After drag and drop you will go to the properties of the CheckBox control to set the space between two or more CheckBox controls using the Margin property. " }, { "code": null, "e": 26306, "s": 26297, "text": "Output: " }, { "code": null, "e": 26477, "s": 26306, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the Margin property of a CheckBox programmatically using the following syntax:" }, { "code": null, "e": 26534, "s": 26477, "text": "public System.Windows.Forms.Padding Margin { get; set; }" }, { "code": null, "e": 26680, "s": 26534, "text": "Here, the Padding is used to represent the space between CheckBox controls. Following steps are used to set the Margin property of the CheckBox: " }, { "code": null, "e": 26771, "s": 26680, "text": "Step 1: Create a checkbox using the CheckBox() constructor provided by the CheckBox class." }, { "code": null, "e": 26830, "s": 26771, "text": "// Creating checkbox\nCheckBox Mycheckbox = new CheckBox();" }, { "code": null, "e": 26935, "s": 26830, "text": "Step 2: After creating CheckBox, set the Margin property of the CheckBox provided by the CheckBox class." }, { "code": null, "e": 27023, "s": 26935, "text": "// Set the Margin property of the CheckBox\nMycheckbox.Margin = new Padding(6, 6, 6, 6);" }, { "code": null, "e": 27095, "s": 27023, "text": "Step 3: And last add this checkbox control to form using Add() method. " }, { "code": null, "e": 27155, "s": 27095, "text": "// Add this checkbox to form\nthis.Controls.Add(Mycheckbox);" }, { "code": null, "e": 27164, "s": 27155, "text": "Example:" }, { "code": null, "e": 27167, "s": 27164, "text": "C#" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp5 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.Text = \"Select Gender:\"; l.Location = new Point(233, 111); // Adding label to form this.Controls.Add(l); // Creating and setting the properties of CheckBox CheckBox Mycheckbox = new CheckBox(); Mycheckbox.Height = 50; Mycheckbox.Width = 100; Mycheckbox.Location = new Point(229, 136); Mycheckbox.Text = \"Male\"; Mycheckbox.Margin = new Padding(6, 6, 6, 6); // Adding checkbox to form this.Controls.Add(Mycheckbox); // Creating and setting the properties of CheckBox CheckBox Mycheckbox1 = new CheckBox(); Mycheckbox1.Height = 50; Mycheckbox1.Width = 100; Mycheckbox1.Location = new Point(230, 174); Mycheckbox1.Text = \"Female\"; // Adding checkbox to form this.Controls.Add(Mycheckbox1); }}}", "e": 28490, "s": 27167, "text": null }, { "code": null, "e": 28499, "s": 28490, "text": "Output: " }, { "code": null, "e": 28516, "s": 28501, "text": "sagartomar9927" }, { "code": null, "e": 28547, "s": 28516, "text": "CSharp-Windows-Forms-Namespace" }, { "code": null, "e": 28550, "s": 28547, "text": "C#" }, { "code": null, "e": 28648, "s": 28550, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28676, "s": 28648, "text": "C# Dictionary with examples" }, { "code": null, "e": 28691, "s": 28676, "text": "C# | Delegates" }, { "code": null, "e": 28714, "s": 28691, "text": "C# | Method Overriding" }, { "code": null, "e": 28736, "s": 28714, "text": "C# | Abstract Classes" }, { "code": null, "e": 28782, "s": 28736, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28800, "s": 28782, "text": "C# | Constructors" }, { "code": null, "e": 28823, "s": 28800, "text": "Extension Method in C#" }, { "code": null, "e": 28854, "s": 28823, "text": "Introduction to .NET Framework" }, { "code": null, "e": 28894, "s": 28854, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
Interfaces in Golang - GeeksforGeeks
20 Nov, 2019 Go language interfaces are different from other languages. In Go language, the interface is a custom type that is used to specify a set of one or more method signatures and the interface is abstract, so you are not allowed to create an instance of the interface. But you are allowed to create a variable of an interface type and this variable can be assigned with a concrete type value that has the methods the interface requires. Or in other words, the interface is a collection of methods as well as it is a custom type. In Go language, you can create an interface using the following syntax: type interface_name interface{ // Method signatures } For Example: // Creating an interface type myinterface interface{ // Methods fun1() int fun2() float64 } Here the interface name is enclosed between the type and interface keywords and the method signatures enclosed in between the curly braces. In the Go language, it is necessary to implement all the methods declared in the interface for implementing an interface. The go language interfaces are implemented implicitly. And it does not contain any specific keyword to implement an interface just like other languages. As shown in the below example: Example: // Golang program illustrates how// to implement an interfacepackage main import "fmt" // Creating an interfacetype tank interface { // Methods Tarea() float64 Volume() float64} type myvalue struct { radius float64 height float64} // Implementing methods of// the tank interfacefunc (m myvalue) Tarea() float64 { return 2*m.radius*m.height + 2*3.14*m.radius*m.radius} func (m myvalue) Volume() float64 { return 3.14 * m.radius * m.radius * m.height} // Main Methodfunc main() { // Accessing elements of // the tank interface var t tank t = myvalue{10, 14} fmt.Println("Area of tank :", t.Tarea()) fmt.Println("Volume of tank:", t.Volume())} Output: Area of tank : 908 Volume of tank: 4396 The zero value of the interface is nil. When an interface contains zero methods, such types of interface is known as the empty interface. So, all the types implement the empty interface.Syntax:interface{} Syntax: interface{} Interface Types: The interface is of two types one is static and another one is dynamic type. The static type is the interface itself, for example, tank in the below example. But interface does not have a static value so it always points to the dynamic values.A variable of the interface type containing the value of the Type which implements the interface, so the value of that Type is known as dynamic value and the type is the dynamic type. It is also known as concrete value and concrete type.Example:// Go program to illustrate the concept// of dynamic values and typespackage main import "fmt" // Creating an interfacetype tank interface { // Methods Tarea() float64 Volume() float64} func main() { var t tank fmt.Println("Value of the tank interface is: ", t) fmt.Printf("Type of the tank interface is: %T ", t)}Output:Value of the tank interface is: <nil> Type of the tank interface is: <nil> Here, in the above example, we have an interface named as a tank. In this example,fmt.Println(“Value of the tank interface is: “, t) statement returns the dynamic value of the interface and fmt.Printf(“Type of the tank interface is: %T “, t) statement returns the dynamic type, i.e nil because here the interface does not know who is implementing it. Example: // Go program to illustrate the concept// of dynamic values and typespackage main import "fmt" // Creating an interfacetype tank interface { // Methods Tarea() float64 Volume() float64} func main() { var t tank fmt.Println("Value of the tank interface is: ", t) fmt.Printf("Type of the tank interface is: %T ", t)} Output: Value of the tank interface is: <nil> Type of the tank interface is: <nil> Here, in the above example, we have an interface named as a tank. In this example,fmt.Println(“Value of the tank interface is: “, t) statement returns the dynamic value of the interface and fmt.Printf(“Type of the tank interface is: %T “, t) statement returns the dynamic type, i.e nil because here the interface does not know who is implementing it. Type Assertions: In Go language, type assertion is an operation applied to the value of the interface. Or in other words, type assertion is a process to extract the values of the interface.Syntax:a.(T)Here, a is the value or the expression of the interface and T is the type also known as asserted type. The type assertion is used to check that the dynamic type of its operand will match the asserted type or not. If the T is of concrete type, then the type assertion checks the given dynamic type of a is equal to the T, here if the checking proceeds successfully, then the type assertion returns the dynamic value of a. Or if the checking fails, then the operation will panics. If the T is of an interface type, then the type assertion checks the given dynamic type of a satisfies T, here if the checking proceeds successfully, then the dynamic value is not extracted.Example:// Go program to illustrate// the type assertionpackage main import "fmt" func myfun(a interface{}) { // Extracting the value of a val := a.(string) fmt.Println("Value: ", val)}func main() { var val interface { } = "GeeksforGeeks" myfun(val)}Output:Value: GeeksforGeeksIn the above example if we change this val := a.(string) statement into val := a.(int), then the program panic. So to overcome this problem we use the following syntax:value, ok := a.(T)Here if the type of the a is equal to T, then the value contains the dynamic value of the a and ok will set to true. And if the type of the a is not equal to T, then ok set to false and value contain zero value, and the program does not panic. As shown in the below program:Example:// Go program to illustrate type assertionpackage main import "fmt" func myfun(a interface{}) { value, ok := a.(float64) fmt.Println(value, ok)}func main() { var a1 interface { } = 98.09 myfun(a1) var a2 interface { } = "GeeksforGeeks" myfun(a2)}Output:98.09 true 0 false Syntax: a.(T) Here, a is the value or the expression of the interface and T is the type also known as asserted type. The type assertion is used to check that the dynamic type of its operand will match the asserted type or not. If the T is of concrete type, then the type assertion checks the given dynamic type of a is equal to the T, here if the checking proceeds successfully, then the type assertion returns the dynamic value of a. Or if the checking fails, then the operation will panics. If the T is of an interface type, then the type assertion checks the given dynamic type of a satisfies T, here if the checking proceeds successfully, then the dynamic value is not extracted. Example: // Go program to illustrate// the type assertionpackage main import "fmt" func myfun(a interface{}) { // Extracting the value of a val := a.(string) fmt.Println("Value: ", val)}func main() { var val interface { } = "GeeksforGeeks" myfun(val)} Output: Value: GeeksforGeeks In the above example if we change this val := a.(string) statement into val := a.(int), then the program panic. So to overcome this problem we use the following syntax: value, ok := a.(T) Here if the type of the a is equal to T, then the value contains the dynamic value of the a and ok will set to true. And if the type of the a is not equal to T, then ok set to false and value contain zero value, and the program does not panic. As shown in the below program: Example: // Go program to illustrate type assertionpackage main import "fmt" func myfun(a interface{}) { value, ok := a.(float64) fmt.Println(value, ok)}func main() { var a1 interface { } = 98.09 myfun(a1) var a2 interface { } = "GeeksforGeeks" myfun(a2)} Output: 98.09 true 0 false Type Switch: In Go interface, type switch is used to compare the concrete type of an interface with the multiple types provide in the case statements. It is similar to type assertion with only one difference, i.e, case specifies types, not the values. You can also compare a type to the interface type. As shown in the below example:Example:// Go program to illustrate type switchpackage main import "fmt" func myfun(a interface{}) { // Using type switch switch a.(type) { case int: fmt.Println("Type: int, Value:", a.(int)) case string: fmt.Println("\nType: string, Value: ", a.(string)) case float64: fmt.Println("\nType: float64, Value: ", a.(float64)) default: fmt.Println("\nType not found") }} // Main methodfunc main() { myfun("GeeksforGeeks") myfun(67.9) myfun(true)}Output:Type: string, Value: GeeksforGeeks Type: float64, Value: 67.9 Type not found Example: // Go program to illustrate type switchpackage main import "fmt" func myfun(a interface{}) { // Using type switch switch a.(type) { case int: fmt.Println("Type: int, Value:", a.(int)) case string: fmt.Println("\nType: string, Value: ", a.(string)) case float64: fmt.Println("\nType: float64, Value: ", a.(float64)) default: fmt.Println("\nType not found") }} // Main methodfunc main() { myfun("GeeksforGeeks") myfun(67.9) myfun(true)} Output: Type: string, Value: GeeksforGeeks Type: float64, Value: 67.9 Type not found Use of Interface: You can use interface when in methods or functions you want to pass different types of argument in them just like Println () function. Or you can also use interface when multiple types implement same interface. Golang Golang-Interfaces Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to concatenate two strings in Golang time.Sleep() Function in Golang With Examples strings.Contains Function in Golang with Examples Time Formatting in Golang strings.Replace() Function in Golang With Examples 6 Best Books to Learn Go Programming Language How to Split a String in Golang? fmt.Sprintf() Function in Golang With Examples Different ways to compare Strings in Golang
[ { "code": null, "e": 24393, "s": 24365, "text": "\n20 Nov, 2019" }, { "code": null, "e": 24916, "s": 24393, "text": "Go language interfaces are different from other languages. In Go language, the interface is a custom type that is used to specify a set of one or more method signatures and the interface is abstract, so you are not allowed to create an instance of the interface. But you are allowed to create a variable of an interface type and this variable can be assigned with a concrete type value that has the methods the interface requires. Or in other words, the interface is a collection of methods as well as it is a custom type." }, { "code": null, "e": 24988, "s": 24916, "text": "In Go language, you can create an interface using the following syntax:" }, { "code": null, "e": 25045, "s": 24988, "text": "type interface_name interface{\n\n// Method signatures\n\n}\n" }, { "code": null, "e": 25058, "s": 25045, "text": "For Example:" }, { "code": null, "e": 25152, "s": 25058, "text": "// Creating an interface\ntype myinterface interface{\n\n// Methods\nfun1() int\nfun2() float64\n}\n" }, { "code": null, "e": 25292, "s": 25152, "text": "Here the interface name is enclosed between the type and interface keywords and the method signatures enclosed in between the curly braces." }, { "code": null, "e": 25598, "s": 25292, "text": "In the Go language, it is necessary to implement all the methods declared in the interface for implementing an interface. The go language interfaces are implemented implicitly. And it does not contain any specific keyword to implement an interface just like other languages. As shown in the below example:" }, { "code": null, "e": 25607, "s": 25598, "text": "Example:" }, { "code": "// Golang program illustrates how// to implement an interfacepackage main import \"fmt\" // Creating an interfacetype tank interface { // Methods Tarea() float64 Volume() float64} type myvalue struct { radius float64 height float64} // Implementing methods of// the tank interfacefunc (m myvalue) Tarea() float64 { return 2*m.radius*m.height + 2*3.14*m.radius*m.radius} func (m myvalue) Volume() float64 { return 3.14 * m.radius * m.radius * m.height} // Main Methodfunc main() { // Accessing elements of // the tank interface var t tank t = myvalue{10, 14} fmt.Println(\"Area of tank :\", t.Tarea()) fmt.Println(\"Volume of tank:\", t.Volume())}", "e": 26308, "s": 25607, "text": null }, { "code": null, "e": 26316, "s": 26308, "text": "Output:" }, { "code": null, "e": 26357, "s": 26316, "text": "Area of tank : 908\nVolume of tank: 4396\n" }, { "code": null, "e": 26397, "s": 26357, "text": "The zero value of the interface is nil." }, { "code": null, "e": 26562, "s": 26397, "text": "When an interface contains zero methods, such types of interface is known as the empty interface. So, all the types implement the empty interface.Syntax:interface{}" }, { "code": null, "e": 26570, "s": 26562, "text": "Syntax:" }, { "code": null, "e": 26582, "s": 26570, "text": "interface{}" }, { "code": null, "e": 27861, "s": 26582, "text": "Interface Types: The interface is of two types one is static and another one is dynamic type. The static type is the interface itself, for example, tank in the below example. But interface does not have a static value so it always points to the dynamic values.A variable of the interface type containing the value of the Type which implements the interface, so the value of that Type is known as dynamic value and the type is the dynamic type. It is also known as concrete value and concrete type.Example:// Go program to illustrate the concept// of dynamic values and typespackage main import \"fmt\" // Creating an interfacetype tank interface { // Methods Tarea() float64 Volume() float64} func main() { var t tank fmt.Println(\"Value of the tank interface is: \", t) fmt.Printf(\"Type of the tank interface is: %T \", t)}Output:Value of the tank interface is: <nil>\nType of the tank interface is: <nil> \nHere, in the above example, we have an interface named as a tank. In this example,fmt.Println(“Value of the tank interface is: “, t) statement returns the dynamic value of the interface and fmt.Printf(“Type of the tank interface is: %T “, t) statement returns the dynamic type, i.e nil because here the interface does not know who is implementing it." }, { "code": null, "e": 27870, "s": 27861, "text": "Example:" }, { "code": "// Go program to illustrate the concept// of dynamic values and typespackage main import \"fmt\" // Creating an interfacetype tank interface { // Methods Tarea() float64 Volume() float64} func main() { var t tank fmt.Println(\"Value of the tank interface is: \", t) fmt.Printf(\"Type of the tank interface is: %T \", t)}", "e": 28210, "s": 27870, "text": null }, { "code": null, "e": 28218, "s": 28210, "text": "Output:" }, { "code": null, "e": 28296, "s": 28218, "text": "Value of the tank interface is: <nil>\nType of the tank interface is: <nil> \n" }, { "code": null, "e": 28647, "s": 28296, "text": "Here, in the above example, we have an interface named as a tank. In this example,fmt.Println(“Value of the tank interface is: “, t) statement returns the dynamic value of the interface and fmt.Printf(“Type of the tank interface is: %T “, t) statement returns the dynamic type, i.e nil because here the interface does not know who is implementing it." }, { "code": null, "e": 30600, "s": 28647, "text": "Type Assertions: In Go language, type assertion is an operation applied to the value of the interface. Or in other words, type assertion is a process to extract the values of the interface.Syntax:a.(T)Here, a is the value or the expression of the interface and T is the type also known as asserted type. The type assertion is used to check that the dynamic type of its operand will match the asserted type or not. If the T is of concrete type, then the type assertion checks the given dynamic type of a is equal to the T, here if the checking proceeds successfully, then the type assertion returns the dynamic value of a. Or if the checking fails, then the operation will panics. If the T is of an interface type, then the type assertion checks the given dynamic type of a satisfies T, here if the checking proceeds successfully, then the dynamic value is not extracted.Example:// Go program to illustrate// the type assertionpackage main import \"fmt\" func myfun(a interface{}) { // Extracting the value of a val := a.(string) fmt.Println(\"Value: \", val)}func main() { var val interface { } = \"GeeksforGeeks\" myfun(val)}Output:Value: GeeksforGeeksIn the above example if we change this val := a.(string) statement into val := a.(int), then the program panic. So to overcome this problem we use the following syntax:value, ok := a.(T)Here if the type of the a is equal to T, then the value contains the dynamic value of the a and ok will set to true. And if the type of the a is not equal to T, then ok set to false and value contain zero value, and the program does not panic. As shown in the below program:Example:// Go program to illustrate type assertionpackage main import \"fmt\" func myfun(a interface{}) { value, ok := a.(float64) fmt.Println(value, ok)}func main() { var a1 interface { } = 98.09 myfun(a1) var a2 interface { } = \"GeeksforGeeks\" myfun(a2)}Output:98.09 true\n0 false\n" }, { "code": null, "e": 30608, "s": 30600, "text": "Syntax:" }, { "code": null, "e": 30614, "s": 30608, "text": "a.(T)" }, { "code": null, "e": 31284, "s": 30614, "text": "Here, a is the value or the expression of the interface and T is the type also known as asserted type. The type assertion is used to check that the dynamic type of its operand will match the asserted type or not. If the T is of concrete type, then the type assertion checks the given dynamic type of a is equal to the T, here if the checking proceeds successfully, then the type assertion returns the dynamic value of a. Or if the checking fails, then the operation will panics. If the T is of an interface type, then the type assertion checks the given dynamic type of a satisfies T, here if the checking proceeds successfully, then the dynamic value is not extracted." }, { "code": null, "e": 31293, "s": 31284, "text": "Example:" }, { "code": "// Go program to illustrate// the type assertionpackage main import \"fmt\" func myfun(a interface{}) { // Extracting the value of a val := a.(string) fmt.Println(\"Value: \", val)}func main() { var val interface { } = \"GeeksforGeeks\" myfun(val)}", "e": 31566, "s": 31293, "text": null }, { "code": null, "e": 31574, "s": 31566, "text": "Output:" }, { "code": null, "e": 31596, "s": 31574, "text": "Value: GeeksforGeeks" }, { "code": null, "e": 31765, "s": 31596, "text": "In the above example if we change this val := a.(string) statement into val := a.(int), then the program panic. So to overcome this problem we use the following syntax:" }, { "code": null, "e": 31784, "s": 31765, "text": "value, ok := a.(T)" }, { "code": null, "e": 32059, "s": 31784, "text": "Here if the type of the a is equal to T, then the value contains the dynamic value of the a and ok will set to true. And if the type of the a is not equal to T, then ok set to false and value contain zero value, and the program does not panic. As shown in the below program:" }, { "code": null, "e": 32068, "s": 32059, "text": "Example:" }, { "code": "// Go program to illustrate type assertionpackage main import \"fmt\" func myfun(a interface{}) { value, ok := a.(float64) fmt.Println(value, ok)}func main() { var a1 interface { } = 98.09 myfun(a1) var a2 interface { } = \"GeeksforGeeks\" myfun(a2)}", "e": 32349, "s": 32068, "text": null }, { "code": null, "e": 32357, "s": 32349, "text": "Output:" }, { "code": null, "e": 32377, "s": 32357, "text": "98.09 true\n0 false\n" }, { "code": null, "e": 33308, "s": 32377, "text": "Type Switch: In Go interface, type switch is used to compare the concrete type of an interface with the multiple types provide in the case statements. It is similar to type assertion with only one difference, i.e, case specifies types, not the values. You can also compare a type to the interface type. As shown in the below example:Example:// Go program to illustrate type switchpackage main import \"fmt\" func myfun(a interface{}) { // Using type switch switch a.(type) { case int: fmt.Println(\"Type: int, Value:\", a.(int)) case string: fmt.Println(\"\\nType: string, Value: \", a.(string)) case float64: fmt.Println(\"\\nType: float64, Value: \", a.(float64)) default: fmt.Println(\"\\nType not found\") }} // Main methodfunc main() { myfun(\"GeeksforGeeks\") myfun(67.9) myfun(true)}Output:Type: string, Value: GeeksforGeeks\n\nType: float64, Value: 67.9\n\nType not found\n" }, { "code": null, "e": 33317, "s": 33308, "text": "Example:" }, { "code": "// Go program to illustrate type switchpackage main import \"fmt\" func myfun(a interface{}) { // Using type switch switch a.(type) { case int: fmt.Println(\"Type: int, Value:\", a.(int)) case string: fmt.Println(\"\\nType: string, Value: \", a.(string)) case float64: fmt.Println(\"\\nType: float64, Value: \", a.(float64)) default: fmt.Println(\"\\nType not found\") }} // Main methodfunc main() { myfun(\"GeeksforGeeks\") myfun(67.9) myfun(true)}", "e": 33819, "s": 33317, "text": null }, { "code": null, "e": 33827, "s": 33819, "text": "Output:" }, { "code": null, "e": 33909, "s": 33827, "text": "Type: string, Value: GeeksforGeeks\n\nType: float64, Value: 67.9\n\nType not found\n" }, { "code": null, "e": 34138, "s": 33909, "text": "Use of Interface: You can use interface when in methods or functions you want to pass different types of argument in them just like Println () function. Or you can also use interface when multiple types implement same interface." }, { "code": null, "e": 34145, "s": 34138, "text": "Golang" }, { "code": null, "e": 34163, "s": 34145, "text": "Golang-Interfaces" }, { "code": null, "e": 34175, "s": 34163, "text": "Go Language" }, { "code": null, "e": 34273, "s": 34175, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34325, "s": 34273, "text": "Different ways to concatenate two strings in Golang" }, { "code": null, "e": 34371, "s": 34325, "text": "time.Sleep() Function in Golang With Examples" }, { "code": null, "e": 34421, "s": 34371, "text": "strings.Contains Function in Golang with Examples" }, { "code": null, "e": 34447, "s": 34421, "text": "Time Formatting in Golang" }, { "code": null, "e": 34498, "s": 34447, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 34544, "s": 34498, "text": "6 Best Books to Learn Go Programming Language" }, { "code": null, "e": 34577, "s": 34544, "text": "How to Split a String in Golang?" }, { "code": null, "e": 34624, "s": 34577, "text": "fmt.Sprintf() Function in Golang With Examples" } ]
numpy.arcsin() in Python - GeeksforGeeks
29 Nov, 2018 numpy.arcsin(x[, out]) = ufunc ‘arcsin’) : This mathematical function helps user to calculate inverse sine for all x(being the array elements). Parameters : array : [array_like]elements are in radians. out : [array_like]array of same shape as x. Return : An array with inverse sine of x for all x i.e. array elements. The values are in the closed interval [-pi/2, pi/2]. Code #1 : Working # Python program explaining# arcsin() function import numpy as np in_array = [0, 1, 0.3, -1]print ("Input array : \n", in_array) arcsin_Values = np.arcsin(in_array)print ("\nInverse Sine values : \n", arcsin_Values) Output : Input array : [0, 1, 0.3, -1] Inverse Sine values : [ 0. 1.57079633 0.30469265 -1.57079633] Code #2 : Graphical representation # Python program showing# Graphical representation of # arcsin() function import numpy as npimport matplotlib.pyplot as plt in_array = np.linspace(-np.pi, np.pi, 12)out_array1 = np.sin(in_array)out_array2 = np.arcsin(in_array) print("in_array : ", in_array)print("\nout_array with sin : ", out_array1)print("\nout_arraywith arcsin : ", out_array1) # red for numpy.arcsin()plt.plot(in_array, out_array1, color = 'blue', marker = "*") plt.plot(in_array, out_array2, color = 'red', marker = "o") plt.title("blue : numpy.sin() \nred : numpy.arcsin()")plt.xlabel("X")plt.ylabel("Y")plt.show() Output : in_array : [-3.14159265 -2.57039399 -1.99919533 -1.42799666 -0.856798 -0.28559933 0.28559933 0.856798 1.42799666 1.99919533 2.57039399 3.14159265] out_array with sin : [ -1.22464680e-16 -5.40640817e-01 -9.09631995e-01 -9.89821442e-01 -7.55749574e-01 -2.81732557e-01 2.81732557e-01 7.55749574e-01 9.89821442e-01 9.09631995e-01 5.40640817e-01 1.22464680e-16] out_arraywith arcsin : [ -1.22464680e-16 -5.40640817e-01 -9.09631995e-01 -9.89821442e-01 -7.55749574e-01 -2.81732557e-01 2.81732557e-01 7.55749574e-01 9.89821442e-01 9.09631995e-01 5.40640817e-01 1.22464680e-16] RuntimeWarning: invalid value encountered in arcsin out_array2 = np.arcsin(in_array) References :https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.arcsin.html#numpy.arcsin. Python numpy-Mathematical Function 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 ? 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 Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n29 Nov, 2018" }, { "code": null, "e": 25681, "s": 25537, "text": "numpy.arcsin(x[, out]) = ufunc ‘arcsin’) : This mathematical function helps user to calculate inverse sine for all x(being the array elements)." }, { "code": null, "e": 25694, "s": 25681, "text": "Parameters :" }, { "code": null, "e": 25788, "s": 25694, "text": "array : [array_like]elements are in radians.\nout : [array_like]array of same shape as x.\n" }, { "code": null, "e": 25797, "s": 25788, "text": "Return :" }, { "code": null, "e": 25916, "s": 25797, "text": "An array with inverse sine of x\nfor all x i.e. array elements. \n\nThe values are in the closed interval [-pi/2, pi/2].\n" }, { "code": null, "e": 25935, "s": 25916, "text": " Code #1 : Working" }, { "code": "# Python program explaining# arcsin() function import numpy as np in_array = [0, 1, 0.3, -1]print (\"Input array : \\n\", in_array) arcsin_Values = np.arcsin(in_array)print (\"\\nInverse Sine values : \\n\", arcsin_Values)", "e": 26154, "s": 25935, "text": null }, { "code": null, "e": 26163, "s": 26154, "text": "Output :" }, { "code": null, "e": 26270, "s": 26163, "text": "Input array : \n [0, 1, 0.3, -1]\n\nInverse Sine values : \n [ 0. 1.57079633 0.30469265 -1.57079633]" }, { "code": null, "e": 26306, "s": 26270, "text": " Code #2 : Graphical representation" }, { "code": "# Python program showing# Graphical representation of # arcsin() function import numpy as npimport matplotlib.pyplot as plt in_array = np.linspace(-np.pi, np.pi, 12)out_array1 = np.sin(in_array)out_array2 = np.arcsin(in_array) print(\"in_array : \", in_array)print(\"\\nout_array with sin : \", out_array1)print(\"\\nout_arraywith arcsin : \", out_array1) # red for numpy.arcsin()plt.plot(in_array, out_array1, color = 'blue', marker = \"*\") plt.plot(in_array, out_array2, color = 'red', marker = \"o\") plt.title(\"blue : numpy.sin() \\nred : numpy.arcsin()\")plt.xlabel(\"X\")plt.ylabel(\"Y\")plt.show()", "e": 26946, "s": 26306, "text": null }, { "code": null, "e": 26955, "s": 26946, "text": "Output :" }, { "code": null, "e": 27666, "s": 26955, "text": "\nin_array : [-3.14159265 -2.57039399 -1.99919533 -1.42799666 -0.856798 -0.28559933\n 0.28559933 0.856798 1.42799666 1.99919533 2.57039399 3.14159265]\n\nout_array with sin : [ -1.22464680e-16 -5.40640817e-01 -9.09631995e-01 -9.89821442e-01\n -7.55749574e-01 -2.81732557e-01 2.81732557e-01 7.55749574e-01\n 9.89821442e-01 9.09631995e-01 5.40640817e-01 1.22464680e-16]\n\nout_arraywith arcsin : [ -1.22464680e-16 -5.40640817e-01 -9.09631995e-01 -9.89821442e-01\n -7.55749574e-01 -2.81732557e-01 2.81732557e-01 7.55749574e-01\n 9.89821442e-01 9.09631995e-01 5.40640817e-01 1.22464680e-16]\nRuntimeWarning: invalid value encountered in arcsin\n out_array2 = np.arcsin(in_array)" }, { "code": null, "e": 27767, "s": 27666, "text": "References :https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.arcsin.html#numpy.arcsin." }, { "code": null, "e": 27802, "s": 27767, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 27815, "s": 27802, "text": "Python-numpy" }, { "code": null, "e": 27822, "s": 27815, "text": "Python" }, { "code": null, "e": 27920, "s": 27822, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27952, "s": 27920, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27994, "s": 27952, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28036, "s": 27994, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28063, "s": 28036, "text": "Python Classes and Objects" }, { "code": null, "e": 28119, "s": 28063, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28158, "s": 28119, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28180, "s": 28158, "text": "Defaultdict in Python" }, { "code": null, "e": 28211, "s": 28180, "text": "Python | os.path.join() method" }, { "code": null, "e": 28240, "s": 28211, "text": "Create a directory in Python" } ]
Django - Admin Interface
Django provides a ready-to-use user interface for administrative activities. We all know how an admin interface is important for a web project. Django automatically generates admin UI based on your project models. The Admin interface depends on the django.countrib module. To have it working you need to make sure some modules are imported in the INSTALLED_APPS and MIDDLEWARE_CLASSES tuples of the myproject/settings.py file. For INSTALLED_APPS make sure you have − INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', ) For MIDDLEWARE_CLASSES − MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) Before launching your server, to access your Admin Interface, you need to initiate the database − $ python manage.py migrate syncdb will create necessary tables or collections depending on your db type, necessary for the admin interface to run. Even if you don't have a superuser, you will be prompted to create one. If you already have a superuser or have forgotten it, you can always create one using the following code − $ python manage.py createsuperuser Now to start the Admin Interface, we need to make sure we have configured a URL for our admin interface. Open the myproject/url.py and you should have something like − from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'myproject.views.home', name = 'home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), ) Now just run the server. $ python manage.py runserver And your admin interface is accessible at: http://127.0.0.1:8000/admin/ Once connected with your superuser account, you will see the following screen − That interface will let you administrate Django groups and users, and all registered models in your app. The interface gives you the ability to do at least the "CRUD" (Create, Read, Update, Delete) operations on your models. 39 Lectures 3.5 hours John Elder 36 Lectures 2.5 hours John Elder 28 Lectures 2 hours John Elder 20 Lectures 1 hours John Elder 35 Lectures 3 hours John Elder 79 Lectures 10 hours Rathan Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 2259, "s": 2045, "text": "Django provides a ready-to-use user interface for administrative activities. We all know how an admin interface is important for a web project. Django automatically generates admin UI based on your project models." }, { "code": null, "e": 2472, "s": 2259, "text": "The Admin interface depends on the django.countrib module. To have it working you need to make sure some modules are imported in the INSTALLED_APPS and MIDDLEWARE_CLASSES tuples of the myproject/settings.py file." }, { "code": null, "e": 2512, "s": 2472, "text": "For INSTALLED_APPS make sure you have −" }, { "code": null, "e": 2725, "s": 2512, "text": "INSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'myapp',\n)" }, { "code": null, "e": 2750, "s": 2725, "text": "For MIDDLEWARE_CLASSES −" }, { "code": null, "e": 3112, "s": 2750, "text": "MIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)" }, { "code": null, "e": 3210, "s": 3112, "text": "Before launching your server, to access your Admin Interface, you need to initiate the database −" }, { "code": null, "e": 3238, "s": 3210, "text": "$ python manage.py migrate\n" }, { "code": null, "e": 3430, "s": 3238, "text": "syncdb will create necessary tables or collections depending on your db type, necessary for the admin interface to run. Even if you don't have a superuser, you will be prompted to create one." }, { "code": null, "e": 3537, "s": 3430, "text": "If you already have a superuser or have forgotten it, you can always create one using the following code −" }, { "code": null, "e": 3573, "s": 3537, "text": "$ python manage.py createsuperuser\n" }, { "code": null, "e": 3741, "s": 3573, "text": "Now to start the Admin Interface, we need to make sure we have configured a URL for our admin interface. Open the myproject/url.py and you should have something like −" }, { "code": null, "e": 4039, "s": 3741, "text": "from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'myproject.views.home', name = 'home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n)" }, { "code": null, "e": 4064, "s": 4039, "text": "Now just run the server." }, { "code": null, "e": 4094, "s": 4064, "text": "$ python manage.py runserver\n" }, { "code": null, "e": 4166, "s": 4094, "text": "And your admin interface is accessible at: http://127.0.0.1:8000/admin/" }, { "code": null, "e": 4246, "s": 4166, "text": "Once connected with your superuser account, you will see the following screen −" }, { "code": null, "e": 4471, "s": 4246, "text": "That interface will let you administrate Django groups and users, and all registered models in your app. The interface gives you the ability to do at least the \"CRUD\" (Create, Read, Update, Delete) operations on your models." }, { "code": null, "e": 4506, "s": 4471, "text": "\n 39 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4518, "s": 4506, "text": " John Elder" }, { "code": null, "e": 4553, "s": 4518, "text": "\n 36 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4565, "s": 4553, "text": " John Elder" }, { "code": null, "e": 4598, "s": 4565, "text": "\n 28 Lectures \n 2 hours \n" }, { "code": null, "e": 4610, "s": 4598, "text": " John Elder" }, { "code": null, "e": 4643, "s": 4610, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 4655, "s": 4643, "text": " John Elder" }, { "code": null, "e": 4688, "s": 4655, "text": "\n 35 Lectures \n 3 hours \n" }, { "code": null, "e": 4700, "s": 4688, "text": " John Elder" }, { "code": null, "e": 4734, "s": 4700, "text": "\n 79 Lectures \n 10 hours \n" }, { "code": null, "e": 4748, "s": 4734, "text": " Rathan Kumar" }, { "code": null, "e": 4755, "s": 4748, "text": " Print" }, { "code": null, "e": 4766, "s": 4755, "text": " Add Notes" } ]
3D Wireframe plotting in Python using Matplotlib - GeeksforGeeks
03 Feb, 2022 To create static, animated and interactive visualizations of data, we use the Matplotlib module in Python. The below programs will depict 3D wireframe. visualization of data in Python. In-order to visualize data using 3D wireframe we require some modules from matplotlib, mpl_toolkits and numpy library. Example 1: Python3 # importing modulesfrom mpl_toolkits.mplot3d import axes3dfrom matplotlib import pyplot # creating the visualizationfig = pyplot.figure()wf = fig.add_subplot(111, projection='3d')x, y, z = axes3d.get_test_data(0.05)wf.plot_wireframe(x,y,z, rstride=2, cstride=2,color='green') # displaying the visualizationwf.set_title('Example 1')pyplot.show() Output: In the above program, a 3D wireframe is plotted using test values for coordinates.Example 2: Python3 # importing modulesfrom mpl_toolkits import mplot3dimport numpyfrom matplotlib import pyplot # assigning coordinates a = numpy.linspace(-5, 5, 25)b = numpy.linspace(-5, 5, 25)x, y = numpy.meshgrid(a, b)z = numpy.sin(numpy.sqrt(x**2 + y**2)) # creating the visualizationfig = pyplot.figure()wf = pyplot.axes(projection ='3d')wf.plot_wireframe(x, y, z, color ='green') # displaying the visualizationwf.set_title('Example 2')pyplot.show() Output: singghakshay rkbhola5 Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 30222, "s": 30194, "text": "\n03 Feb, 2022" }, { "code": null, "e": 30539, "s": 30222, "text": "To create static, animated and interactive visualizations of data, we use the Matplotlib module in Python. The below programs will depict 3D wireframe. visualization of data in Python. In-order to visualize data using 3D wireframe we require some modules from matplotlib, mpl_toolkits and numpy library. Example 1: " }, { "code": null, "e": 30547, "s": 30539, "text": "Python3" }, { "code": "# importing modulesfrom mpl_toolkits.mplot3d import axes3dfrom matplotlib import pyplot # creating the visualizationfig = pyplot.figure()wf = fig.add_subplot(111, projection='3d')x, y, z = axes3d.get_test_data(0.05)wf.plot_wireframe(x,y,z, rstride=2, cstride=2,color='green') # displaying the visualizationwf.set_title('Example 1')pyplot.show()", "e": 30911, "s": 30547, "text": null }, { "code": null, "e": 30921, "s": 30911, "text": "Output: " }, { "code": null, "e": 31016, "s": 30921, "text": "In the above program, a 3D wireframe is plotted using test values for coordinates.Example 2: " }, { "code": null, "e": 31024, "s": 31016, "text": "Python3" }, { "code": "# importing modulesfrom mpl_toolkits import mplot3dimport numpyfrom matplotlib import pyplot # assigning coordinates a = numpy.linspace(-5, 5, 25)b = numpy.linspace(-5, 5, 25)x, y = numpy.meshgrid(a, b)z = numpy.sin(numpy.sqrt(x**2 + y**2)) # creating the visualizationfig = pyplot.figure()wf = pyplot.axes(projection ='3d')wf.plot_wireframe(x, y, z, color ='green') # displaying the visualizationwf.set_title('Example 2')pyplot.show()", "e": 31462, "s": 31024, "text": null }, { "code": null, "e": 31472, "s": 31462, "text": "Output: " }, { "code": null, "e": 31487, "s": 31474, "text": "singghakshay" }, { "code": null, "e": 31496, "s": 31487, "text": "rkbhola5" }, { "code": null, "e": 31514, "s": 31496, "text": "Python-matplotlib" }, { "code": null, "e": 31521, "s": 31514, "text": "Python" }, { "code": null, "e": 31619, "s": 31521, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31628, "s": 31619, "text": "Comments" }, { "code": null, "e": 31641, "s": 31628, "text": "Old Comments" }, { "code": null, "e": 31669, "s": 31641, "text": "Read JSON file using Python" }, { "code": null, "e": 31719, "s": 31669, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 31741, "s": 31719, "text": "Python map() function" }, { "code": null, "e": 31785, "s": 31741, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 31803, "s": 31785, "text": "Python Dictionary" }, { "code": null, "e": 31826, "s": 31803, "text": "Taking input in Python" }, { "code": null, "e": 31861, "s": 31826, "text": "Read a file line by line in Python" }, { "code": null, "e": 31883, "s": 31861, "text": "Enumerate() in Python" }, { "code": null, "e": 31915, "s": 31883, "text": "How to Install PIP on Windows ?" } ]
Rotate a matrix by 90 degree in clockwise direction without using any extra space in C++
We are given a 2-D array that will be used to form a matrix pattern. The task is to rotate a matrix by 90 degrees in a clockwise direction such that the last row becomes the first column, second row becomes second column and first becomes third column and the challenge is that we don’t have to use any extra space. Input − int arr[row_col_size][row_col_size] = { { 5, 1, 4}, { 9, 16, 12 }, { 2, 8, 9}} Output − Rotation of a matrix by 90 degree in clockwise direction without using any extra space is: 2 9 5 8 16 1 9 12 4 Explanation − we are given a 2-D array of integer type. Now we will rotate a matrix by 90 degrees in a clockwise direction. Before rotation-: { { 5, 1, 4}, { 9, 16, 12 }, { 2, 8, 9}} After rotation-: 2 9 5 8 16 1 9 12 4 Input − int arr[row_col_size][row_col_size] = { { 2, 1, 9}, { 11, 6, 32 }, { 3, 7, 5}} Output − Rotation of a matrix by 90 degree in clockwise direction without using any extra space is: 2 9 5 8 16 1 9 12 4 Explanation − we are given a 2-D array of integer type. Now we will rotate a matrix by 90 degrees in a clockwise direction. Before rotation-: { { 2, 1, 9}, { 11, 6, 32 }, { 3, 7, 5}} After rotation-: 3 11 2 7 6 1 5 32 9 Input a 2-D integer array that will be treated as a matrix with row_col_size. Input a 2-D integer array that will be treated as a matrix with row_col_size. Pass the data to the function Rotate_ClockWise(arr). Pass the data to the function Rotate_ClockWise(arr). Inside the function Rotate_ClockWise(arr)Start loop FOR from i to 0 till i less than row_col_size/2.Inside the loop, start another loop FOR from j to 0 till j less than row_col_size - i - 1.Inside the loop, set ptr to arr[i][j], arr[i][j] to arr[row_col_size - 1 - j][i], arr[row_col_size - 1 - j][i] to arr[row_col_size - 1 - i][row_col_size - 1 - j], arr[row_col_size - 1 - i][row_col_size - 1 - j] to arr[j][row_col_size - 1 - i] and arr[j][row_col_size - 1 - i] to ptr. Inside the function Rotate_ClockWise(arr) Start loop FOR from i to 0 till i less than row_col_size/2. Start loop FOR from i to 0 till i less than row_col_size/2. Inside the loop, start another loop FOR from j to 0 till j less than row_col_size - i - 1. Inside the loop, start another loop FOR from j to 0 till j less than row_col_size - i - 1. Inside the loop, set ptr to arr[i][j], arr[i][j] to arr[row_col_size - 1 - j][i], arr[row_col_size - 1 - j][i] to arr[row_col_size - 1 - i][row_col_size - 1 - j], arr[row_col_size - 1 - i][row_col_size - 1 - j] to arr[j][row_col_size - 1 - i] and arr[j][row_col_size - 1 - i] to ptr. Inside the loop, set ptr to arr[i][j], arr[i][j] to arr[row_col_size - 1 - j][i], arr[row_col_size - 1 - j][i] to arr[row_col_size - 1 - i][row_col_size - 1 - j], arr[row_col_size - 1 - i][row_col_size - 1 - j] to arr[j][row_col_size - 1 - i] and arr[j][row_col_size - 1 - i] to ptr. Start loop FOR from i to 0 till i less than row_col_size. Inside the loop, start another loop FOR from j to 0 till j less than row_col_size; j++ and print arr[i][j]. Start loop FOR from i to 0 till i less than row_col_size. Inside the loop, start another loop FOR from j to 0 till j less than row_col_size; j++ and print arr[i][j]. Input a 2-D integer array that will be treated as a matrix with row_col_size. Input a 2-D integer array that will be treated as a matrix with row_col_size. Pass the data to the function Rotate_ClockWise(arr). Pass the data to the function Rotate_ClockWise(arr). Inside the function Rotate_ClockWise(arr)Start loop FOR from i to 0 till i less than row_col_size.Inside the loop, start another loop FOR from j to 0 till j less than row_col_size - i.Inside the loop, set ptr to arr[i][j], arr[i][j] to arr[row_col_size - 1 - j]arr[row_col_size - 1 - i] and [row_col_size - 1 - j] to arr[j][row_col_size - 1 - i] to ptr.Start loop FOR from i to 0 till i less than row_col_size / 2. Inside the loop, start another loop FOR from j to 0 till j less than row_col_size. Inside the loop, set ptr to arr[i][j], arr[i][j] to arr[row_col_size - 1 - i][j] and arr[row_col_size - 1 - i][j] to ptr Inside the function Rotate_ClockWise(arr) Start loop FOR from i to 0 till i less than row_col_size. Start loop FOR from i to 0 till i less than row_col_size. Inside the loop, start another loop FOR from j to 0 till j less than row_col_size - i. Inside the loop, start another loop FOR from j to 0 till j less than row_col_size - i. Inside the loop, set ptr to arr[i][j], arr[i][j] to arr[row_col_size - 1 - j]arr[row_col_size - 1 - i] and [row_col_size - 1 - j] to arr[j][row_col_size - 1 - i] to ptr. Inside the loop, set ptr to arr[i][j], arr[i][j] to arr[row_col_size - 1 - j]arr[row_col_size - 1 - i] and [row_col_size - 1 - j] to arr[j][row_col_size - 1 - i] to ptr. Start loop FOR from i to 0 till i less than row_col_size / 2. Inside the loop, start another loop FOR from j to 0 till j less than row_col_size. Inside the loop, set ptr to arr[i][j], arr[i][j] to arr[row_col_size - 1 - i][j] and arr[row_col_size - 1 - i][j] to ptr Start loop FOR from i to 0 till i less than row_col_size / 2. Inside the loop, start another loop FOR from j to 0 till j less than row_col_size. Inside the loop, set ptr to arr[i][j], arr[i][j] to arr[row_col_size - 1 - i][j] and arr[row_col_size - 1 - i][j] to ptr Start loop FOR from i to 0 till i less than row_col_size. Inside the loop, start another loop FOR from j to 0 till j less than row_col_size; j++ and print arr[i][j]. Start loop FOR from i to 0 till i less than row_col_size. Inside the loop, start another loop FOR from j to 0 till j less than row_col_size; j++ and print arr[i][j]. #include <bits/stdc++.h> using namespace std; #define row_col_size 3 void Rotate_ClockWise(int arr[row_col_size][row_col_size]){ for(int i = 0; i < row_col_size / 2; i++){ for(int j = i; j < row_col_size - i - 1; j++){ int ptr = arr[i][j]; arr[i][j] = arr[row_col_size - 1 - j][i]; arr[row_col_size - 1 - j][i] = arr[row_col_size - 1 - i][row_col_size - 1 - j]; arr[row_col_size - 1 - i][row_col_size - 1 - j] = arr[j][row_col_size - 1 - i]; arr[j][row_col_size - 1 - i] = ptr; } } } int main(){ int arr[row_col_size][row_col_size] = { { 5, 1, 4},{ 9, 16, 12 },{ 2, 8, 9}}; Rotate_ClockWise(arr); cout<<"Rotation of a matrix by 90 degree in clockwise direction without using any extra space is: \n"; for(int i = 0; i < row_col_size; i++){ for(int j = 0; j < row_col_size; j++){ cout << arr[i][j] << " "; } cout << '\n'; } return 0; } If we run the above code it will generate the following Output Rotation of a matrix by 90 degree in clockwise direction without using any extra space is: 2 9 5 8 16 1 9 12 4 #include <bits/stdc++.h> using namespace std; #define row_col_size 3 void Rotate_ClockWise(int arr[row_col_size][row_col_size]){ for(int i = 0; i < row_col_size; i++){ for(int j = 0; j < row_col_size - i; j++){ int ptr = arr[i][j]; arr[i][j] = arr[row_col_size - 1 - j][row_col_size - 1 - i]; arr[row_col_size - 1 - j][row_col_size - 1 - i] = ptr; } } for(int i = 0; i < row_col_size / 2; i++){ for(int j = 0; j < row_col_size; j++){ int ptr = arr[i][j]; arr[i][j] = arr[row_col_size - 1 - i][j]; arr[row_col_size - 1 - i][j] = ptr; } } } int main(){ int arr[row_col_size][row_col_size] = { { 5, 1, 4},{ 9, 16, 12 },{ 2, 8, 9}}; Rotate_ClockWise(arr); cout<<"Rotation of a matrix by 90 degree in clockwise direction without using any extra space is: \n"; for(int i = 0; i < row_col_size; i++){ for(int j = 0; j < row_col_size; j++){ cout << arr[i][j] << " "; } cout << '\n'; } return 0; } If we run the above code it will generate the following Output Rotation of a matrix by 90 degree in clockwise direction without using any extra space is: 2 9 5 8 16 1 9 12 4
[ { "code": null, "e": 1378, "s": 1062, "text": "We are given a 2-D array that will be used to form a matrix pattern. The task is to rotate a matrix by 90 degrees in a clockwise direction such that the last row becomes the first column, second row becomes second column and first becomes third column and the challenge is that we don’t\nhave to use any extra space." }, { "code": null, "e": 1386, "s": 1378, "text": "Input −" }, { "code": null, "e": 1471, "s": 1386, "text": "int arr[row_col_size][row_col_size] = { { 5, 1, 4},\n { 9, 16, 12 },\n { 2, 8, 9}}" }, { "code": null, "e": 1480, "s": 1471, "text": "Output −" }, { "code": null, "e": 1591, "s": 1480, "text": "Rotation of a matrix by 90 degree in clockwise direction without using any extra space is:\n2 9 5\n8 16 1\n9 12 4" }, { "code": null, "e": 1715, "s": 1591, "text": "Explanation − we are given a 2-D array of integer type. Now we will rotate a matrix by 90 degrees in a clockwise direction." }, { "code": null, "e": 1811, "s": 1715, "text": "Before rotation-:\n{ { 5, 1, 4},\n{ 9, 16, 12 },\n{ 2, 8, 9}}\nAfter rotation-:\n2 9 5\n8 16 1\n9 12 4" }, { "code": null, "e": 1821, "s": 1811, "text": "Input −" }, { "code": null, "e": 1906, "s": 1821, "text": "int arr[row_col_size][row_col_size] = { { 2, 1, 9},\n { 11, 6, 32 },\n { 3, 7, 5}}" }, { "code": null, "e": 1917, "s": 1906, "text": "Output −" }, { "code": null, "e": 2028, "s": 1917, "text": "Rotation of a matrix by 90 degree in clockwise direction without using any extra space is:\n2 9 5\n8 16 1\n9 12 4" }, { "code": null, "e": 2152, "s": 2028, "text": "Explanation − we are given a 2-D array of integer type. Now we will rotate a matrix by 90 degrees in a clockwise direction." }, { "code": null, "e": 2248, "s": 2152, "text": "Before rotation-:\n{ { 2, 1, 9},\n{ 11, 6, 32 },\n{ 3, 7, 5}}\nAfter rotation-:\n3 11 2\n7 6 1\n5 32 9" }, { "code": null, "e": 2326, "s": 2248, "text": "Input a 2-D integer array that will be treated as a matrix with row_col_size." }, { "code": null, "e": 2404, "s": 2326, "text": "Input a 2-D integer array that will be treated as a matrix with row_col_size." }, { "code": null, "e": 2457, "s": 2404, "text": "Pass the data to the function Rotate_ClockWise(arr)." }, { "code": null, "e": 2510, "s": 2457, "text": "Pass the data to the function Rotate_ClockWise(arr)." }, { "code": null, "e": 2984, "s": 2510, "text": "Inside the function Rotate_ClockWise(arr)Start loop FOR from i to 0 till i less than row_col_size/2.Inside the loop, start another loop FOR from j to 0 till j less than row_col_size - i - 1.Inside the loop, set ptr to arr[i][j], arr[i][j] to arr[row_col_size - 1 - j][i], arr[row_col_size - 1 - j][i] to arr[row_col_size - 1 - i][row_col_size - 1 - j], arr[row_col_size - 1 - i][row_col_size - 1 - j] to arr[j][row_col_size - 1 - i] and arr[j][row_col_size - 1 - i] to ptr." }, { "code": null, "e": 3026, "s": 2984, "text": "Inside the function Rotate_ClockWise(arr)" }, { "code": null, "e": 3086, "s": 3026, "text": "Start loop FOR from i to 0 till i less than row_col_size/2." }, { "code": null, "e": 3146, "s": 3086, "text": "Start loop FOR from i to 0 till i less than row_col_size/2." }, { "code": null, "e": 3237, "s": 3146, "text": "Inside the loop, start another loop FOR from j to 0 till j less than row_col_size - i - 1." }, { "code": null, "e": 3328, "s": 3237, "text": "Inside the loop, start another loop FOR from j to 0 till j less than row_col_size - i - 1." }, { "code": null, "e": 3612, "s": 3328, "text": "Inside the loop, set ptr to arr[i][j], arr[i][j] to arr[row_col_size - 1 - j][i], arr[row_col_size - 1 - j][i] to arr[row_col_size - 1 - i][row_col_size - 1 - j], arr[row_col_size - 1 - i][row_col_size - 1 - j] to arr[j][row_col_size - 1 - i] and arr[j][row_col_size - 1 - i] to ptr." }, { "code": null, "e": 3896, "s": 3612, "text": "Inside the loop, set ptr to arr[i][j], arr[i][j] to arr[row_col_size - 1 - j][i], arr[row_col_size - 1 - j][i] to arr[row_col_size - 1 - i][row_col_size - 1 - j], arr[row_col_size - 1 - i][row_col_size - 1 - j] to arr[j][row_col_size - 1 - i] and arr[j][row_col_size - 1 - i] to ptr." }, { "code": null, "e": 4062, "s": 3896, "text": "Start loop FOR from i to 0 till i less than row_col_size. Inside the loop, start another loop FOR from j to 0 till j less than row_col_size; j++ and print arr[i][j]." }, { "code": null, "e": 4228, "s": 4062, "text": "Start loop FOR from i to 0 till i less than row_col_size. Inside the loop, start another loop FOR from j to 0 till j less than row_col_size; j++ and print arr[i][j]." }, { "code": null, "e": 4306, "s": 4228, "text": "Input a 2-D integer array that will be treated as a matrix with row_col_size." }, { "code": null, "e": 4384, "s": 4306, "text": "Input a 2-D integer array that will be treated as a matrix with row_col_size." }, { "code": null, "e": 4437, "s": 4384, "text": "Pass the data to the function Rotate_ClockWise(arr)." }, { "code": null, "e": 4490, "s": 4437, "text": "Pass the data to the function Rotate_ClockWise(arr)." }, { "code": null, "e": 5109, "s": 4490, "text": "Inside the function Rotate_ClockWise(arr)Start loop FOR from i to 0 till i less than row_col_size.Inside the loop, start another loop FOR from j to 0 till j less than row_col_size - i.Inside the loop, set ptr to arr[i][j], arr[i][j] to arr[row_col_size - 1 - j]arr[row_col_size - 1 - i] and [row_col_size - 1 - j] to arr[j][row_col_size - 1 - i] to ptr.Start loop FOR from i to 0 till i less than row_col_size / 2. Inside the loop, start another loop FOR from j to 0 till j less than row_col_size. Inside the loop, set ptr to arr[i][j], arr[i][j] to arr[row_col_size - 1 - i][j] and arr[row_col_size - 1 - i][j] to ptr" }, { "code": null, "e": 5151, "s": 5109, "text": "Inside the function Rotate_ClockWise(arr)" }, { "code": null, "e": 5209, "s": 5151, "text": "Start loop FOR from i to 0 till i less than row_col_size." }, { "code": null, "e": 5267, "s": 5209, "text": "Start loop FOR from i to 0 till i less than row_col_size." }, { "code": null, "e": 5354, "s": 5267, "text": "Inside the loop, start another loop FOR from j to 0 till j less than row_col_size - i." }, { "code": null, "e": 5441, "s": 5354, "text": "Inside the loop, start another loop FOR from j to 0 till j less than row_col_size - i." }, { "code": null, "e": 5611, "s": 5441, "text": "Inside the loop, set ptr to arr[i][j], arr[i][j] to arr[row_col_size - 1 - j]arr[row_col_size - 1 - i] and [row_col_size - 1 - j] to arr[j][row_col_size - 1 - i] to ptr." }, { "code": null, "e": 5781, "s": 5611, "text": "Inside the loop, set ptr to arr[i][j], arr[i][j] to arr[row_col_size - 1 - j]arr[row_col_size - 1 - i] and [row_col_size - 1 - j] to arr[j][row_col_size - 1 - i] to ptr." }, { "code": null, "e": 6047, "s": 5781, "text": "Start loop FOR from i to 0 till i less than row_col_size / 2. Inside the loop, start another loop FOR from j to 0 till j less than row_col_size. Inside the loop, set ptr to arr[i][j], arr[i][j] to arr[row_col_size - 1 - i][j] and arr[row_col_size - 1 - i][j] to ptr" }, { "code": null, "e": 6313, "s": 6047, "text": "Start loop FOR from i to 0 till i less than row_col_size / 2. Inside the loop, start another loop FOR from j to 0 till j less than row_col_size. Inside the loop, set ptr to arr[i][j], arr[i][j] to arr[row_col_size - 1 - i][j] and arr[row_col_size - 1 - i][j] to ptr" }, { "code": null, "e": 6479, "s": 6313, "text": "Start loop FOR from i to 0 till i less than row_col_size. Inside the loop, start another loop FOR from j to 0 till j less than row_col_size; j++ and print arr[i][j]." }, { "code": null, "e": 6645, "s": 6479, "text": "Start loop FOR from i to 0 till i less than row_col_size. Inside the loop, start another loop FOR from j to 0 till j less than row_col_size; j++ and print arr[i][j]." }, { "code": null, "e": 7588, "s": 6645, "text": "#include <bits/stdc++.h>\nusing namespace std;\n#define row_col_size 3\nvoid Rotate_ClockWise(int arr[row_col_size][row_col_size]){\n for(int i = 0; i < row_col_size / 2; i++){\n for(int j = i; j < row_col_size - i - 1; j++){\n int ptr = arr[i][j];\n arr[i][j] = arr[row_col_size - 1 - j][i];\n arr[row_col_size - 1 - j][i] = arr[row_col_size - 1 - i][row_col_size - 1 - j];\n arr[row_col_size - 1 - i][row_col_size - 1 - j] = arr[j][row_col_size - 1 - i];\n arr[j][row_col_size - 1 - i] = ptr;\n }\n }\n}\nint main(){\n int arr[row_col_size][row_col_size] = { { 5, 1, 4},{ 9, 16, 12 },{ 2, 8, 9}};\n Rotate_ClockWise(arr);\n cout<<\"Rotation of a matrix by 90 degree in clockwise direction without using any extra space is: \\n\";\n for(int i = 0; i < row_col_size; i++){\n for(int j = 0; j < row_col_size; j++){\n cout << arr[i][j] << \" \";\n }\n cout << '\\n';\n }\n return 0;\n}" }, { "code": null, "e": 7651, "s": 7588, "text": "If we run the above code it will generate the following Output" }, { "code": null, "e": 7762, "s": 7651, "text": "Rotation of a matrix by 90 degree in clockwise direction without using any extra space is:\n2 9 5\n8 16 1\n9 12 4" }, { "code": null, "e": 8786, "s": 7762, "text": "#include <bits/stdc++.h>\nusing namespace std;\n#define row_col_size 3\nvoid Rotate_ClockWise(int arr[row_col_size][row_col_size]){\n for(int i = 0; i < row_col_size; i++){\n for(int j = 0; j < row_col_size - i; j++){\n int ptr = arr[i][j];\n arr[i][j] = arr[row_col_size - 1 - j][row_col_size - 1 - i];\n arr[row_col_size - 1 - j][row_col_size - 1 - i] = ptr;\n }\n }\n for(int i = 0; i < row_col_size / 2; i++){\n for(int j = 0; j < row_col_size; j++){\n int ptr = arr[i][j];\n arr[i][j] = arr[row_col_size - 1 - i][j];\n arr[row_col_size - 1 - i][j] = ptr;\n }\n }\n}\nint main(){\n int arr[row_col_size][row_col_size] = { { 5, 1, 4},{ 9, 16, 12 },{ 2, 8, 9}};\n Rotate_ClockWise(arr);\n cout<<\"Rotation of a matrix by 90 degree in clockwise direction without using any extra space is: \\n\";\n for(int i = 0; i < row_col_size; i++){\n for(int j = 0; j < row_col_size; j++){\n cout << arr[i][j] << \" \";\n }\n cout << '\\n';\n }\n return 0;\n}" }, { "code": null, "e": 8849, "s": 8786, "text": "If we run the above code it will generate the following Output" }, { "code": null, "e": 8960, "s": 8849, "text": "Rotation of a matrix by 90 degree in clockwise direction without using any extra space is:\n2 9 5\n8 16 1\n9 12 4" } ]
Why Char[] array is more secure (store sensitive data) than String in Java?
Both String and Char[] array are used to store the textual data but choosing one over the other is more difficult. Maybe we can get the idea from the immutability of String why char[] array is preferred over String for storing sensitive information data like password, SSN, etc. Using the plain string is a much higher chance of accidentally printing the password to logs or some other insecure places where char[] array is less vulnerable. Since String is immutable, there is no method defined that allow us to change or overwrite the content of the string. This feature makes string objects unstable for storing secure information such as passwords, SSN, etc. We should always store the secure information in char[] array rather than String. Since String is immutable if we store the password as plain text it will be available in memory until the garbage collector cleans it. Since string used String Constant Pool (SCP) for re-usability of a string, there will be a pretty chance that it will remain in memory for a long duration. Since anyone who has access to memory dump can easily find the password in plain text that's another reason should use encrypt password than plain text. If we notice in Java Swing applications, there is a method of JPasswordField getPassword() which return char[] and the deprecated method getText() which return the password in plain text. So java itself recommending to use the get password() method. Another reason for storing a password in char[] array, because char[] can be sanitized, for example, after usage one can override a clear password with junk, while String is immutable in Java. Live Demo public class SecureInfoData { public static void main(String args[]) { String pwd = "string_pass_word"; System.out.println("String Password is: " + pwd); char charPwd[] = "char_pass_word".toCharArray(); System.out.println("Character Password is: " + charPwd); } } String Password is: string_pass_word Character Password is: [C@6d06d69c
[ { "code": null, "e": 1341, "s": 1062, "text": "Both String and Char[] array are used to store the textual data but choosing one over the other is more difficult. Maybe we can get the idea from the immutability of String why char[] array is preferred over String for storing sensitive information data like password, SSN, etc." }, { "code": null, "e": 1503, "s": 1341, "text": "Using the plain string is a much higher chance of accidentally printing the password to logs or some other insecure places where char[] array is less vulnerable." }, { "code": null, "e": 1806, "s": 1503, "text": "Since String is immutable, there is no method defined that allow us to change or overwrite the content of the string. This feature makes string objects unstable for storing secure information such as passwords, SSN, etc. We should always store the secure information in char[] array rather than String." }, { "code": null, "e": 2250, "s": 1806, "text": "Since String is immutable if we store the password as plain text it will be available in memory until the garbage\ncollector cleans it. Since string used String Constant Pool (SCP) for re-usability of a string, there will be a pretty chance that it will remain in memory for a long duration. Since anyone who has access to memory dump can easily find the password in plain text that's another reason should use encrypt\npassword than plain text." }, { "code": null, "e": 2500, "s": 2250, "text": "If we notice in Java Swing applications, there is a method of JPasswordField\ngetPassword() which return char[] and the deprecated method getText() which return the password in plain text. So java itself recommending to use the get password() method." }, { "code": null, "e": 2693, "s": 2500, "text": "Another reason for storing a password in char[] array, because char[] can be sanitized, for example, after usage one can override a clear password with junk, while String is immutable in Java." }, { "code": null, "e": 2704, "s": 2693, "text": " Live Demo" }, { "code": null, "e": 2998, "s": 2704, "text": "public class SecureInfoData {\n public static void main(String args[]) {\n String pwd = \"string_pass_word\";\n System.out.println(\"String Password is: \" + pwd);\n char charPwd[] = \"char_pass_word\".toCharArray();\n System.out.println(\"Character Password is: \" + charPwd);\n }\n}" }, { "code": null, "e": 3070, "s": 2998, "text": "String Password is: string_pass_word\nCharacter Password is: [C@6d06d69c" } ]
TypeScript - Array concat()
concat() method returns a new array comprised of this array joined with two or more arrays. array.concat(value1, value2, ..., valueN); valueN − Arrays and/or values to concatenate to the resulting array. Returns a new array. var alpha = ["a", "b", "c"]; var numeric = [1, 2, 3]; var alphaNumeric = alpha.concat(numeric); console.log("alphaNumeric : " + alphaNumeric ); On compiling, it will generate the same code in JavaScript. Its output is as follows − alphaNumeric : a,b,c,1,2,3 45 Lectures 4 hours Antonio Papa 41 Lectures 7 hours Haider Malik 60 Lectures 2.5 hours Skillbakerystudios 77 Lectures 8 hours Sean Bradley 77 Lectures 3.5 hours TELCOMA Global 19 Lectures 3 hours Christopher Frewin Print Add Notes Bookmark this page
[ { "code": null, "e": 2140, "s": 2048, "text": "concat() method returns a new array comprised of this array joined with two or more arrays." }, { "code": null, "e": 2184, "s": 2140, "text": "array.concat(value1, value2, ..., valueN);\n" }, { "code": null, "e": 2253, "s": 2184, "text": "valueN − Arrays and/or values to concatenate to the resulting array." }, { "code": null, "e": 2274, "s": 2253, "text": "Returns a new array." }, { "code": null, "e": 2422, "s": 2274, "text": "var alpha = [\"a\", \"b\", \"c\"]; \nvar numeric = [1, 2, 3];\n\nvar alphaNumeric = alpha.concat(numeric); \nconsole.log(\"alphaNumeric : \" + alphaNumeric );\n" }, { "code": null, "e": 2482, "s": 2422, "text": "On compiling, it will generate the same code in JavaScript." }, { "code": null, "e": 2509, "s": 2482, "text": "Its output is as follows −" }, { "code": null, "e": 2537, "s": 2509, "text": "alphaNumeric : a,b,c,1,2,3\n" }, { "code": null, "e": 2570, "s": 2537, "text": "\n 45 Lectures \n 4 hours \n" }, { "code": null, "e": 2584, "s": 2570, "text": " Antonio Papa" }, { "code": null, "e": 2617, "s": 2584, "text": "\n 41 Lectures \n 7 hours \n" }, { "code": null, "e": 2631, "s": 2617, "text": " Haider Malik" }, { "code": null, "e": 2666, "s": 2631, "text": "\n 60 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2686, "s": 2666, "text": " Skillbakerystudios" }, { "code": null, "e": 2719, "s": 2686, "text": "\n 77 Lectures \n 8 hours \n" }, { "code": null, "e": 2733, "s": 2719, "text": " Sean Bradley" }, { "code": null, "e": 2768, "s": 2733, "text": "\n 77 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2784, "s": 2768, "text": " TELCOMA Global" }, { "code": null, "e": 2817, "s": 2784, "text": "\n 19 Lectures \n 3 hours \n" }, { "code": null, "e": 2837, "s": 2817, "text": " Christopher Frewin" }, { "code": null, "e": 2844, "s": 2837, "text": " Print" }, { "code": null, "e": 2855, "s": 2844, "text": " Add Notes" } ]
Ant - Creating JAR files
The next logical step after compiling your java source files, is to build the java archive, i.e., the Java Archive (JAR) file. Creating JAR files with Ant is quite easy with the jar task. The commonly used attributes of the jar task are as follows − basedir The base directory for the output JAR file. By default, this is set to the base directory of the project. compress Advises Ant to compress the file as it creates the JAR file. keepcompression While the compress attribute is applicable to the individual files, the keepcompression attribute does the same thing, but it applies to the entire archive. destfile The name of the output JAR file. duplicate Advises Ant on what to do when duplicate files are found. You could add, preserve, or fail the duplicate files. excludes Advises Ant to not include these comma separated list of files in the package. excludesfile Same as above, except the exclude files are specified using a pattern. inlcudes Inverse of excludes. includesfile Inverse of excludesfile. update Advises Ant to overwrite files in the already built JAR file. Continuing our Hello World Fax Application project, let us add a new target to produce the jar files. But before that, let us consider the jar task given below. <jar destfile="${web.dir}/lib/util.jar" basedir="${build.dir}/classes" includes="faxapp/util/**" excludes="**/Test.class" /> Here, the web.dir property points to the path of the web source files. In our case, this is where the util.jar will be placed. The build.dir property in this example, points to the build folder, where the class files for the util.jar can be found. In this example, we create a jar file called util.jar using the classes from the faxapp.util.* package. However, we are excluding the classes that end with the name Test. The output jar file will be placed in the web application lib folder. If we want to make the util.jar an executable jar file, we need to add the manifest with the Main-Class meta attribute. Therefore, the above example will be updated as follows − <jar destfile="${web.dir}/lib/util.jar" basedir="${build.dir}/classes" includes="faxapp/util/**" excludes="**/Test.class" class="ts" <manifest class="ts" <attribute name="Main-Class" value="com.tutorialspoint.util.FaxUtil"/> </manifest class="ts" </jar class="ts" To execute the jar task, wrap it inside a target, most commonly, the build or package target, and execute them. <target name="build-jar" class="ts" <jar destfile="${web.dir}/lib/util.jar" basedir="${build.dir}/classes" includes="faxapp/util/**" excludes="**/Test.class" class="ts" <manifest class="ts" <attribute name="Main-Class" value="com.tutorialspoint.util.FaxUtil"/> </manifest class="ts" </jar class="ts" </target class="ts" Running Ant on this file creates the util.jar file for us. The following outcome is the result of running the Ant file − C:\ class="ts"ant build-jar Buildfile: C:\build.xml BUILD SUCCESSFUL Total time: 1.3 seconds The util.jar file is now placed in the output folder. 20 Lectures 2 hours Deepti Trivedi 19 Lectures 2.5 hours Deepti Trivedi 139 Lectures 14 hours Er. Himanshu Vasishta 30 Lectures 1.5 hours Pushpendu Mondal 65 Lectures 6.5 hours Ridhi Arora 10 Lectures 2 hours Manish Gupta Print Add Notes Bookmark this page
[ { "code": null, "e": 2285, "s": 2097, "text": "The next logical step after compiling your java source files, is to build the java archive, i.e., the Java Archive (JAR) file. Creating JAR files with Ant is quite easy with the jar task." }, { "code": null, "e": 2347, "s": 2285, "text": "The commonly used attributes of the jar task are as follows −" }, { "code": null, "e": 2355, "s": 2347, "text": "basedir" }, { "code": null, "e": 2461, "s": 2355, "text": "The base directory for the output JAR file. By default, this is set to the base directory of the project." }, { "code": null, "e": 2470, "s": 2461, "text": "compress" }, { "code": null, "e": 2531, "s": 2470, "text": "Advises Ant to compress the file as it creates the JAR file." }, { "code": null, "e": 2547, "s": 2531, "text": "keepcompression" }, { "code": null, "e": 2704, "s": 2547, "text": "While the compress attribute is applicable to the individual files, the keepcompression attribute does the same thing, but it applies to the entire archive." }, { "code": null, "e": 2713, "s": 2704, "text": "destfile" }, { "code": null, "e": 2746, "s": 2713, "text": "The name of the output JAR file." }, { "code": null, "e": 2756, "s": 2746, "text": "duplicate" }, { "code": null, "e": 2868, "s": 2756, "text": "Advises Ant on what to do when duplicate files are found. You could add, preserve, or fail the duplicate files." }, { "code": null, "e": 2877, "s": 2868, "text": "excludes" }, { "code": null, "e": 2956, "s": 2877, "text": "Advises Ant to not include these comma separated list of files in the package." }, { "code": null, "e": 2969, "s": 2956, "text": "excludesfile" }, { "code": null, "e": 3040, "s": 2969, "text": "Same as above, except the exclude files are specified using a pattern." }, { "code": null, "e": 3049, "s": 3040, "text": "inlcudes" }, { "code": null, "e": 3070, "s": 3049, "text": "Inverse of excludes." }, { "code": null, "e": 3083, "s": 3070, "text": "includesfile" }, { "code": null, "e": 3108, "s": 3083, "text": "Inverse of excludesfile." }, { "code": null, "e": 3115, "s": 3108, "text": "update" }, { "code": null, "e": 3177, "s": 3115, "text": "Advises Ant to overwrite files in the already built JAR file." }, { "code": null, "e": 3279, "s": 3177, "text": "Continuing our Hello World Fax Application project, let us add a new target to produce the jar files." }, { "code": null, "e": 3338, "s": 3279, "text": "But before that, let us consider the jar task given below." }, { "code": null, "e": 3472, "s": 3338, "text": "<jar destfile=\"${web.dir}/lib/util.jar\"\n basedir=\"${build.dir}/classes\"\n includes=\"faxapp/util/**\"\n excludes=\"**/Test.class\"\n/>" }, { "code": null, "e": 3599, "s": 3472, "text": "Here, the web.dir property points to the path of the web source files. In our case, this is where the util.jar will be placed." }, { "code": null, "e": 3720, "s": 3599, "text": "The build.dir property in this example, points to the build folder, where the class files for the util.jar can be found." }, { "code": null, "e": 3961, "s": 3720, "text": "In this example, we create a jar file called util.jar using the classes from the faxapp.util.* package. However, we are excluding the classes that end with the name Test. The output jar file will be placed in the web application lib folder." }, { "code": null, "e": 4081, "s": 3961, "text": "If we want to make the util.jar an executable jar file, we need to add the manifest with the Main-Class meta attribute." }, { "code": null, "e": 4139, "s": 4081, "text": "Therefore, the above example will be updated as follows −" }, { "code": null, "e": 4424, "s": 4139, "text": "<jar destfile=\"${web.dir}/lib/util.jar\"\n basedir=\"${build.dir}/classes\"\n includes=\"faxapp/util/**\"\n excludes=\"**/Test.class\" class=\"ts\"\n <manifest class=\"ts\"\n <attribute name=\"Main-Class\" value=\"com.tutorialspoint.util.FaxUtil\"/>\n </manifest class=\"ts\"\n</jar class=\"ts\"" }, { "code": null, "e": 4536, "s": 4424, "text": "To execute the jar task, wrap it inside a target, most commonly, the build or package target, and execute them." }, { "code": null, "e": 4877, "s": 4536, "text": "<target name=\"build-jar\" class=\"ts\"\n<jar destfile=\"${web.dir}/lib/util.jar\"\n basedir=\"${build.dir}/classes\"\n includes=\"faxapp/util/**\"\n excludes=\"**/Test.class\" class=\"ts\"\n <manifest class=\"ts\"\n <attribute name=\"Main-Class\" value=\"com.tutorialspoint.util.FaxUtil\"/>\n </manifest class=\"ts\"\n</jar class=\"ts\"\n</target class=\"ts\"" }, { "code": null, "e": 4936, "s": 4877, "text": "Running Ant on this file creates the util.jar file for us." }, { "code": null, "e": 4998, "s": 4936, "text": "The following outcome is the result of running the Ant file −" }, { "code": null, "e": 5092, "s": 4998, "text": "C:\\ class=\"ts\"ant build-jar\nBuildfile: C:\\build.xml\n\nBUILD SUCCESSFUL\nTotal time: 1.3 seconds" }, { "code": null, "e": 5146, "s": 5092, "text": "The util.jar file is now placed in the output folder." }, { "code": null, "e": 5179, "s": 5146, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 5195, "s": 5179, "text": " Deepti Trivedi" }, { "code": null, "e": 5230, "s": 5195, "text": "\n 19 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5246, "s": 5230, "text": " Deepti Trivedi" }, { "code": null, "e": 5281, "s": 5246, "text": "\n 139 Lectures \n 14 hours \n" }, { "code": null, "e": 5304, "s": 5281, "text": " Er. Himanshu Vasishta" }, { "code": null, "e": 5339, "s": 5304, "text": "\n 30 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5357, "s": 5339, "text": " Pushpendu Mondal" }, { "code": null, "e": 5392, "s": 5357, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 5405, "s": 5392, "text": " Ridhi Arora" }, { "code": null, "e": 5438, "s": 5405, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 5452, "s": 5438, "text": " Manish Gupta" }, { "code": null, "e": 5459, "s": 5452, "text": " Print" }, { "code": null, "e": 5470, "s": 5459, "text": " Add Notes" } ]
How to perform Friedman test in R?
To perform Friedman test in R, we can follow the below steps − First of all, create a matrix. Then, use friedman.test function to perform the Friedman test. Let's create a data matrix as shown below − Live Demo First<-sample(1:100,20) Second<-sample(1:100,20) Third<-sample(1:100,20) Fourth<-sample(1:100,20) Period<-matrix(c(First,Second,Third,Fourth),byrow=FALSE,nrow=20) Period On executing, the above script generates the below output(this output will vary on your system due to randomization) − [,1] [,2] [,3] [,4] [1,] 56 19 61 100 [2,] 16 1 89 82 [3,] 34 18 13 13 [4,] 85 85 35 55 [5,] 10 29 42 79 [6,] 99 52 11 92 [7,] 27 42 87 86 [8,] 42 26 6 63 [9,] 19 3 90 16 [10,] 48 80 93 4 [11,] 89 43 94 52 [12,] 46 62 54 30 [13,] 61 68 57 71 [14,] 5 2 64 64 [15,] 15 93 45 91 [16,] 86 61 28 36 [17,] 66 53 84 28 [18,] 80 90 73 33 [19,] 18 23 7 24 [20,] 26 73 95 2 Using friedman.test function to perform the test on data in Period − Live Demo First<-sample(1:100,20) Second<-sample(1:100,20) Third<-sample(1:100,20) Fourth<-sample(1:100,20) Period<-matrix(c(First,Second,Third,Fourth),byrow=FALSE,nrow=20) friedman.test(Period) Friedman rank sum test data: Period Friedman chi-squared = 0.19797, df = 3, p-value = 0.9779 Create the matrix Let's create a data matrix as shown below − Live Demo Jan<-round(rnorm(20),2) Feb<-round(rnorm(20),2) Mar<-round(rnorm(20),2) Apr<-round(rnorm(20),2) May<-round(rnorm(20),2) Time<-matrix(c(Jan,Feb,Mar,Apr,May),byrow=FALSE,nrow=20) Time On executing, the above script generates the below output(this output will vary on your system due to randomization) − [,1] [,2] [,3] [,4] [,5] [1,] 1.30 -1.21 -0.26 0.94 1.19 [2,] 1.14 -0.77 -1.54 0.67 1.77 [3,] 0.18 -0.50 0.72 0.76 -1.58 [4,] 1.51 0.13 2.71 0.51 0.62 [5,] -1.10 0.09 0.47 0.25 0.26 [6,] 1.31 0.51 -1.79 -1.67 0.32 [7,] 0.00 0.59 0.20 0.55 -0.20 [8,] 1.25 -0.91 -1.34 1.33 0.07 [9,] -0.19 -1.39 0.09 -2.08 -1.63 [10,] 0.66 1.17 -0.66 -0.02 -0.07 [11,] 0.05 -1.31 0.55 0.68 0.97 [12,] 1.57 -2.80 1.00 -1.55 -1.90 [13,] -0.67 0.29 0.60 2.28 1.34 [14,] 0.43 -3.66 -0.23 0.41 0.69 [15,] -0.56 0.11 0.60 1.09 -1.34 [16,] 1.87 0.48 0.49 -1.00 0.91 [17,] 1.01 0.64 0.74 -0.88 1.20 [18,] 0.90 -0.43 -0.61 0.27 0.10 [19,] 1.98 -0.54 1.02 0.89 -0.52 [20,] 0.11 -1.29 2.31 -0.18 1.41 Using friedman.test function to perform the test on data in Period − Live Demo Jan<-round(rnorm(20),2) Feb<-round(rnorm(20),2) Mar<-round(rnorm(20),2) Apr<-round(rnorm(20),2) May<-round(rnorm(20),2) Time<-matrix(c(Jan,Feb,Mar,Apr,May),byrow=FALSE,nrow=20) friedman.test(Time) Friedman rank sum test data: Time Friedman chi-squared = 8.92, df = 4, p-value = 0.06313
[ { "code": null, "e": 1125, "s": 1062, "text": "To perform Friedman test in R, we can follow the below steps −" }, { "code": null, "e": 1156, "s": 1125, "text": "First of all, create a matrix." }, { "code": null, "e": 1219, "s": 1156, "text": "Then, use friedman.test function to perform the Friedman test." }, { "code": null, "e": 1263, "s": 1219, "text": "Let's create a data matrix as shown below −" }, { "code": null, "e": 1274, "s": 1263, "text": " Live Demo" }, { "code": null, "e": 1444, "s": 1274, "text": "First<-sample(1:100,20)\nSecond<-sample(1:100,20)\nThird<-sample(1:100,20)\nFourth<-sample(1:100,20)\nPeriod<-matrix(c(First,Second,Third,Fourth),byrow=FALSE,nrow=20)\nPeriod" }, { "code": null, "e": 1563, "s": 1444, "text": "On executing, the above script generates the below output(this output will vary on your system due to randomization) −" }, { "code": null, "e": 2042, "s": 1563, "text": " [,1] [,2] [,3] [,4]\n[1,] 56 19 61 100\n[2,] 16 1 89 82\n[3,] 34 18 13 13\n[4,] 85 85 35 55\n[5,] 10 29 42 79\n[6,] 99 52 11 92\n[7,] 27 42 87 86\n[8,] 42 26 6 63\n[9,] 19 3 90 16\n[10,] 48 80 93 4\n[11,] 89 43 94 52\n[12,] 46 62 54 30\n[13,] 61 68 57 71\n[14,] 5 2 64 64\n[15,] 15 93 45 91\n[16,] 86 61 28 36\n[17,] 66 53 84 28\n[18,] 80 90 73 33\n[19,] 18 23 7 24\n[20,] 26 73 95 2" }, { "code": null, "e": 2111, "s": 2042, "text": "Using friedman.test function to perform the test on data in Period −" }, { "code": null, "e": 2122, "s": 2111, "text": " Live Demo" }, { "code": null, "e": 2307, "s": 2122, "text": "First<-sample(1:100,20)\nSecond<-sample(1:100,20)\nThird<-sample(1:100,20)\nFourth<-sample(1:100,20)\nPeriod<-matrix(c(First,Second,Third,Fourth),byrow=FALSE,nrow=20)\nfriedman.test(Period)" }, { "code": null, "e": 2400, "s": 2307, "text": "Friedman rank sum test\ndata: Period\nFriedman chi-squared = 0.19797, df = 3, p-value = 0.9779" }, { "code": null, "e": 2418, "s": 2400, "text": "Create the matrix" }, { "code": null, "e": 2462, "s": 2418, "text": "Let's create a data matrix as shown below −" }, { "code": null, "e": 2473, "s": 2462, "text": " Live Demo" }, { "code": null, "e": 2655, "s": 2473, "text": "Jan<-round(rnorm(20),2)\nFeb<-round(rnorm(20),2)\nMar<-round(rnorm(20),2)\nApr<-round(rnorm(20),2)\nMay<-round(rnorm(20),2)\nTime<-matrix(c(Jan,Feb,Mar,Apr,May),byrow=FALSE,nrow=20)\nTime" }, { "code": null, "e": 2774, "s": 2655, "text": "On executing, the above script generates the below output(this output will vary on your system due to randomization) −" }, { "code": null, "e": 3450, "s": 2774, "text": " [,1] [,2] [,3] [,4] [,5]\n[1,] 1.30 -1.21 -0.26 0.94 1.19\n[2,] 1.14 -0.77 -1.54 0.67 1.77\n[3,] 0.18 -0.50 0.72 0.76 -1.58\n[4,] 1.51 0.13 2.71 0.51 0.62\n[5,] -1.10 0.09 0.47 0.25 0.26\n[6,] 1.31 0.51 -1.79 -1.67 0.32\n[7,] 0.00 0.59 0.20 0.55 -0.20\n[8,] 1.25 -0.91 -1.34 1.33 0.07\n[9,] -0.19 -1.39 0.09 -2.08 -1.63\n[10,] 0.66 1.17 -0.66 -0.02 -0.07\n[11,] 0.05 -1.31 0.55 0.68 0.97\n[12,] 1.57 -2.80 1.00 -1.55 -1.90\n[13,] -0.67 0.29 0.60 2.28 1.34\n[14,] 0.43 -3.66 -0.23 0.41 0.69\n[15,] -0.56 0.11 0.60 1.09 -1.34\n[16,] 1.87 0.48 0.49 -1.00 0.91\n[17,] 1.01 0.64 0.74 -0.88 1.20\n[18,] 0.90 -0.43 -0.61 0.27 0.10\n[19,] 1.98 -0.54 1.02 0.89 -0.52\n[20,] 0.11 -1.29 2.31 -0.18 1.41" }, { "code": null, "e": 3519, "s": 3450, "text": "Using friedman.test function to perform the test on data in Period −" }, { "code": null, "e": 3530, "s": 3519, "text": " Live Demo" }, { "code": null, "e": 3727, "s": 3530, "text": "Jan<-round(rnorm(20),2)\nFeb<-round(rnorm(20),2)\nMar<-round(rnorm(20),2)\nApr<-round(rnorm(20),2)\nMay<-round(rnorm(20),2)\nTime<-matrix(c(Jan,Feb,Mar,Apr,May),byrow=FALSE,nrow=20)\nfriedman.test(Time)" }, { "code": null, "e": 3816, "s": 3727, "text": "Friedman rank sum test\ndata: Time\nFriedman chi-squared = 8.92, df = 4, p-value = 0.06313" } ]
How to change the Certificate's friendly name using PowerShell?
Suppose we know the Thumbprint of the certificate then we can use the below command to update or change the certificate's friendly name. $cert = Get-ChildItem ` -Path Cert:\LocalMachine\My\43E6035D120EBE9ECE8100E8F38B85A9F1C1140F $cert.FriendlyName = "mysitecert" The above command will update the certificate-friendly name to "mysitecert". If you don't know the thumbprint or how to retrieve it, you can use different properties like Subject name, friendly name, etc. $cert = Get-ChildItem -path ` Cert:\LocalMachine\My\` | where{$_.Subject -eq "CN=mysite.local"} $cert.FriendlyName = "mysitecert"
[ { "code": null, "e": 1199, "s": 1062, "text": "Suppose we know the Thumbprint of the certificate then we can use the below command to update or change the certificate's friendly name." }, { "code": null, "e": 1295, "s": 1199, "text": "$cert = Get-ChildItem `\n -Path Cert:\\LocalMachine\\My\\43E6035D120EBE9ECE8100E8F38B85A9F1C1140F" }, { "code": null, "e": 1329, "s": 1295, "text": "$cert.FriendlyName = \"mysitecert\"" }, { "code": null, "e": 1534, "s": 1329, "text": "The above command will update the certificate-friendly name to \"mysitecert\". If you don't know the thumbprint or how to retrieve it, you can use different properties like Subject name, friendly name, etc." }, { "code": null, "e": 1637, "s": 1534, "text": "$cert = Get-ChildItem -path `\n Cert:\\LocalMachine\\My\\`\n | where{$_.Subject -eq \"CN=mysite.local\"}" }, { "code": null, "e": 1671, "s": 1637, "text": "$cert.FriendlyName = \"mysitecert\"" } ]
Python - Convert Lists into Similar key value lists - GeeksforGeeks
29 Aug, 2020 Given two lists, one of key and other values, convert it to dictionary with list values, if keys map to different values on basis of index, add in its value list. Input : test_list1 = [5, 6, 6, 6], test_list2 = [8, 3, 2, 9]Output : {5: [8], 6: [3, 2, 9]}Explanation : Elements with index 6 in corresponding list, are mapped to 6. Input : test_list1 = [6, 6, 6, 6], test_list2 = [8, 3, 2, 9]Output : {6: [8, 3, 2, 9]}Explanation : All mapped to single number. Method #1 : Using zip() + loop This is one of the ways in which this task can be performed. In this, we perform mapping the keys to required values using zip() and loop is used to perform iteration of keys. Python3 # Python3 code to demonstrate working of # Convert Lists into Similar key value lists# Using loop + zip() # initializing liststest_list1 = [5, 6, 6, 4, 5, 6] test_list2 = [8, 3, 2, 9, 10, 4] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # creating a mesh of keys with empty values listres = {key: [] for key in test_list1} # loop to iterate through keys and valuesfor key, val in zip(test_list1, test_list2): res[key].append(val) # printing result print("The mapped dictionary : " + str(res)) The original list 1 is : [5, 6, 6, 4, 5, 6] The original list 2 is : [8, 3, 2, 9, 10, 4] The mapped dictionary : {5: [8, 10], 6: [3, 2, 4], 4: [9]} Method #2 : Using defaultdict() + list comprehension + zip() The combination of above functions can be used to solve this problem. In this, we perform task as one liner and defaultdict() is used to preassign values with empty lists. Python3 # Python3 code to demonstrate working of # Convert Lists into Similar key value lists# Using defaultdict() + list comprehension + zip()from collections import defaultdict # initializing liststest_list1 = [5, 6, 6, 4, 5, 6] test_list2 = [8, 3, 2, 9, 10, 4] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # creating a mesh of keys using defaultdictres = defaultdict(list)[res[key].append(val) for key, val in zip(test_list1, test_list2)] # printing result print("The mapped dictionary : " + str(dict(res))) The original list 1 is : [5, 6, 6, 4, 5, 6] The original list 2 is : [8, 3, 2, 9, 10, 4] The mapped dictionary : {5: [8, 10], 6: [3, 2, 4], 4: [9]} Python dictionary-programs Python list-programs Python Python Programs 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 ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 24307, "s": 24279, "text": "\n29 Aug, 2020" }, { "code": null, "e": 24470, "s": 24307, "text": "Given two lists, one of key and other values, convert it to dictionary with list values, if keys map to different values on basis of index, add in its value list." }, { "code": null, "e": 24637, "s": 24470, "text": "Input : test_list1 = [5, 6, 6, 6], test_list2 = [8, 3, 2, 9]Output : {5: [8], 6: [3, 2, 9]}Explanation : Elements with index 6 in corresponding list, are mapped to 6." }, { "code": null, "e": 24766, "s": 24637, "text": "Input : test_list1 = [6, 6, 6, 6], test_list2 = [8, 3, 2, 9]Output : {6: [8, 3, 2, 9]}Explanation : All mapped to single number." }, { "code": null, "e": 24797, "s": 24766, "text": "Method #1 : Using zip() + loop" }, { "code": null, "e": 24973, "s": 24797, "text": "This is one of the ways in which this task can be performed. In this, we perform mapping the keys to required values using zip() and loop is used to perform iteration of keys." }, { "code": null, "e": 24981, "s": 24973, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Convert Lists into Similar key value lists# Using loop + zip() # initializing liststest_list1 = [5, 6, 6, 4, 5, 6] test_list2 = [8, 3, 2, 9, 10, 4] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # creating a mesh of keys with empty values listres = {key: [] for key in test_list1} # loop to iterate through keys and valuesfor key, val in zip(test_list1, test_list2): res[key].append(val) # printing result print(\"The mapped dictionary : \" + str(res)) ", "e": 25567, "s": 24981, "text": null }, { "code": null, "e": 25716, "s": 25567, "text": "The original list 1 is : [5, 6, 6, 4, 5, 6]\nThe original list 2 is : [8, 3, 2, 9, 10, 4]\nThe mapped dictionary : {5: [8, 10], 6: [3, 2, 4], 4: [9]}\n" }, { "code": null, "e": 25777, "s": 25716, "text": "Method #2 : Using defaultdict() + list comprehension + zip()" }, { "code": null, "e": 25949, "s": 25777, "text": "The combination of above functions can be used to solve this problem. In this, we perform task as one liner and defaultdict() is used to preassign values with empty lists." }, { "code": null, "e": 25957, "s": 25949, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Convert Lists into Similar key value lists# Using defaultdict() + list comprehension + zip()from collections import defaultdict # initializing liststest_list1 = [5, 6, 6, 4, 5, 6] test_list2 = [8, 3, 2, 9, 10, 4] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # creating a mesh of keys using defaultdictres = defaultdict(list)[res[key].append(val) for key, val in zip(test_list1, test_list2)] # printing result print(\"The mapped dictionary : \" + str(dict(res))) ", "e": 26550, "s": 25957, "text": null }, { "code": null, "e": 26699, "s": 26550, "text": "The original list 1 is : [5, 6, 6, 4, 5, 6]\nThe original list 2 is : [8, 3, 2, 9, 10, 4]\nThe mapped dictionary : {5: [8, 10], 6: [3, 2, 4], 4: [9]}\n" }, { "code": null, "e": 26726, "s": 26699, "text": "Python dictionary-programs" }, { "code": null, "e": 26747, "s": 26726, "text": "Python list-programs" }, { "code": null, "e": 26754, "s": 26747, "text": "Python" }, { "code": null, "e": 26770, "s": 26754, "text": "Python Programs" }, { "code": null, "e": 26868, "s": 26770, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26877, "s": 26868, "text": "Comments" }, { "code": null, "e": 26890, "s": 26877, "text": "Old Comments" }, { "code": null, "e": 26922, "s": 26890, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26944, "s": 26922, "text": "Enumerate() in Python" }, { "code": null, "e": 26986, "s": 26944, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27012, "s": 26986, "text": "Python String | replace()" }, { "code": null, "e": 27049, "s": 27012, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27071, "s": 27049, "text": "Defaultdict in Python" }, { "code": null, "e": 27117, "s": 27071, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27156, "s": 27117, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27194, "s": 27156, "text": "Python | Convert a list to dictionary" } ]
C Language | Set 10 - GeeksforGeeks
18 Feb, 2021 Following questions have been asked in GATE CS 2014 exam.1) Consider the following program in C language: C #include <stdio.h>main(){ int i; int *pi = &i; scanf("%d", pi); printf("%d\n", i+5);} Which one of the following statements is TRUE? (A) Compilation fails. (B) Execution results in a run-time error. (C) On execution, the value printed is 5 more than the address of variable i. (D) On execution, the value printed is 5 more than the integer value entered.Answer: (D) Explanation: There is no problem in the program as pi points to a valid location. Also, in scanf() we pass address of a variable and pi is an address.2) Consider the function func shown below: C int func(int num){ int count = 0; while (num) { count++; num >>= 1; } return (count);} The value returned by func(435)is __________.Answer: 9 Explanation: The function mainly returns position of Most significant bit in binary representation of n. The MSD in binary representation of 435 is 9th bit.3) Consider the C function given below. C int f(int j){ static int i = 50; int k; if (i == j) { printf("something"); k = f(i); return 0; } else return 0;} Which one of the following is TRUE? (A) The function returns 0 for all values of j. (B) The function prints the string something for all values of j. (C) The function returns 0 when j = 50. (D) The function will exhaust the runtime stack or run into an infinite loop when j = 50Answer: (D) Explanation: When j is 50, the function would call itself again and again as neither i nor j is changed inside the recursion.4) Consider the C function given below. Assume that the array listA contains n (> 0) elements, sorted in ascending order. C int ProcessArray(int *listA, int x, int n){ int i, j, k; i = 0; j = n-1; do{ k = (i+j)/2; if (x <= listA[k]) j = k-1; if (listA[k] <= x) i = k+1; } while (i <= j); if (listA[k] == x) return(k); else return -1;} Which one of the following statements about the function ProcessArray is CORRECT? (A) It will run into an infinite loop when x is not in listA. (B) It is an implementation of binary search. (C) It will always find the maximum element in listA. (D) It will return -1 even when x is present in listA.Answer: (B) Explanation: The program is a simple iterative C implementation of Binary Search. 5) Consider the following function C double f(double x){ if (abs(x*x - 3) < 0.01) return x; else return f(x/2 + 1.5/x);} Give a value q (to 2 decimals) such that f(q) will return q:_____.Answer: 1.732 Explanation: The main thing to note is the expression “abs(x*x – 3) < 0.01” inside the if condition. The function would return x when (x2 – 3 ) is close to 0 (smaller than 0.01) which means when x is close to square root of 3. Square root of 3 is 1.732.See following for complete solutions of all GATE CS 2014 papers GATE-CS-2014-(Set-1) GATE-CS-2014-(Set-2) GATE-CS-2014-(Set-3)Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above. dsaharia998 GATE-CS-2014 GATE-CS-C-Language MCQ Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Computer Networks | Set 2 Database Management Systems | Set 1 Computer Networks | Set 3 Computer Networks | Set 10 Computer Networks | Set 4 Output of C programs | Set 64 (Pointers) Practice questions on B and B+ Trees Data Structures and Algorithms | Set 31 Computer Networks | Set 11 Data Structures and Algorithms | Set 22
[ { "code": null, "e": 24010, "s": 23982, "text": "\n18 Feb, 2021" }, { "code": null, "e": 24118, "s": 24010, "text": "Following questions have been asked in GATE CS 2014 exam.1) Consider the following program in C language: " }, { "code": null, "e": 24120, "s": 24118, "text": "C" }, { "code": "#include <stdio.h>main(){ int i; int *pi = &i; scanf(\"%d\", pi); printf(\"%d\\n\", i+5);}", "e": 24218, "s": 24120, "text": null }, { "code": null, "e": 24693, "s": 24218, "text": "Which one of the following statements is TRUE? (A) Compilation fails. (B) Execution results in a run-time error. (C) On execution, the value printed is 5 more than the address of variable i. (D) On execution, the value printed is 5 more than the integer value entered.Answer: (D) Explanation: There is no problem in the program as pi points to a valid location. Also, in scanf() we pass address of a variable and pi is an address.2) Consider the function func shown below: " }, { "code": null, "e": 24695, "s": 24693, "text": "C" }, { "code": "int func(int num){ int count = 0; while (num) { count++; num >>= 1; } return (count);}", "e": 24811, "s": 24695, "text": null }, { "code": null, "e": 25064, "s": 24811, "text": "The value returned by func(435)is __________.Answer: 9 Explanation: The function mainly returns position of Most significant bit in binary representation of n. The MSD in binary representation of 435 is 9th bit.3) Consider the C function given below. " }, { "code": null, "e": 25066, "s": 25064, "text": "C" }, { "code": "int f(int j){ static int i = 50; int k; if (i == j) { printf(\"something\"); k = f(i); return 0; } else return 0;}", "e": 25194, "s": 25066, "text": null }, { "code": null, "e": 25733, "s": 25194, "text": "Which one of the following is TRUE? (A) The function returns 0 for all values of j. (B) The function prints the string something for all values of j. (C) The function returns 0 when j = 50. (D) The function will exhaust the runtime stack or run into an infinite loop when j = 50Answer: (D) Explanation: When j is 50, the function would call itself again and again as neither i nor j is changed inside the recursion.4) Consider the C function given below. Assume that the array listA contains n (> 0) elements, sorted in ascending order. " }, { "code": null, "e": 25735, "s": 25733, "text": "C" }, { "code": "int ProcessArray(int *listA, int x, int n){ int i, j, k; i = 0; j = n-1; do{ k = (i+j)/2; if (x <= listA[k]) j = k-1; if (listA[k] <= x) i = k+1; } while (i <= j); if (listA[k] == x) return(k); else return -1;}", "e": 26024, "s": 25735, "text": null }, { "code": null, "e": 26453, "s": 26024, "text": "Which one of the following statements about the function ProcessArray is CORRECT? (A) It will run into an infinite loop when x is not in listA. (B) It is an implementation of binary search. (C) It will always find the maximum element in listA. (D) It will return -1 even when x is present in listA.Answer: (B) Explanation: The program is a simple iterative C implementation of Binary Search. 5) Consider the following function " }, { "code": null, "e": 26455, "s": 26453, "text": "C" }, { "code": "double f(double x){ if (abs(x*x - 3) < 0.01) return x; else return f(x/2 + 1.5/x);}", "e": 26543, "s": 26455, "text": null }, { "code": null, "e": 27153, "s": 26543, "text": "Give a value q (to 2 decimals) such that f(q) will return q:_____.Answer: 1.732 Explanation: The main thing to note is the expression “abs(x*x – 3) < 0.01” inside the if condition. The function would return x when (x2 – 3 ) is close to 0 (smaller than 0.01) which means when x is close to square root of 3. Square root of 3 is 1.732.See following for complete solutions of all GATE CS 2014 papers GATE-CS-2014-(Set-1) GATE-CS-2014-(Set-2) GATE-CS-2014-(Set-3)Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above. " }, { "code": null, "e": 27165, "s": 27153, "text": "dsaharia998" }, { "code": null, "e": 27178, "s": 27165, "text": "GATE-CS-2014" }, { "code": null, "e": 27197, "s": 27178, "text": "GATE-CS-C-Language" }, { "code": null, "e": 27201, "s": 27197, "text": "MCQ" }, { "code": null, "e": 27299, "s": 27201, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27325, "s": 27299, "text": "Computer Networks | Set 2" }, { "code": null, "e": 27361, "s": 27325, "text": "Database Management Systems | Set 1" }, { "code": null, "e": 27387, "s": 27361, "text": "Computer Networks | Set 3" }, { "code": null, "e": 27414, "s": 27387, "text": "Computer Networks | Set 10" }, { "code": null, "e": 27440, "s": 27414, "text": "Computer Networks | Set 4" }, { "code": null, "e": 27481, "s": 27440, "text": "Output of C programs | Set 64 (Pointers)" }, { "code": null, "e": 27518, "s": 27481, "text": "Practice questions on B and B+ Trees" }, { "code": null, "e": 27558, "s": 27518, "text": "Data Structures and Algorithms | Set 31" }, { "code": null, "e": 27585, "s": 27558, "text": "Computer Networks | Set 11" } ]
How to add column to an existing table in PostgreSQL?
The syntax to add a new column to an existing table is quite straightforward. ALTER TABLE table_name ADD COLUMN column_name column_type column_constraint; Say you have existing table marks. An example is given below − Now, suppose you want to add a column named subject. You can do that using − ALTER TABLE marks ADD COLUMN subject VARCHAR; Now if you query the table again using, SELECT * from marks You will see the following output − Note that the values in the subject column are null because we have just created the column, not populated it. We can populate it using the UPDATE statements. The statement syntax is as follows − UPDATE table_name SET column_name = column_value WHERE condition For instance, if, in the above example, Yash has scored 42 marks in Maths, the UPDATE statement will look like this − UPDATE marks SET subject 'Maths' WHERE roll_no = 26 You could have also added the name=’Yash’ condition instead of roll_no=26. Now, if you query the table, you will see the following output − If you don’t add any condition in the UPDATE statement, the value of every row will be changed for that column. For instance, if I run the following query − UPDATE marks SET subject = 'Science' And then query the table, I’ll see the following output −
[ { "code": null, "e": 1140, "s": 1062, "text": "The syntax to add a new column to an existing table is quite straightforward." }, { "code": null, "e": 1217, "s": 1140, "text": "ALTER TABLE table_name\nADD COLUMN column_name column_type column_constraint;" }, { "code": null, "e": 1280, "s": 1217, "text": "Say you have existing table marks. An example is given below −" }, { "code": null, "e": 1357, "s": 1280, "text": "Now, suppose you want to add a column named subject. You can do that using −" }, { "code": null, "e": 1403, "s": 1357, "text": "ALTER TABLE marks\nADD COLUMN subject VARCHAR;" }, { "code": null, "e": 1443, "s": 1403, "text": "Now if you query the table again using," }, { "code": null, "e": 1463, "s": 1443, "text": "SELECT * from marks" }, { "code": null, "e": 1500, "s": 1463, "text": "You will see the following output −" }, { "code": null, "e": 1696, "s": 1500, "text": "Note that the values in the subject column are null because we have just created the column, not populated it. We can populate it using the UPDATE statements. The statement syntax is as follows −" }, { "code": null, "e": 1761, "s": 1696, "text": "UPDATE table_name\nSET column_name = column_value\nWHERE condition" }, { "code": null, "e": 1879, "s": 1761, "text": "For instance, if, in the above example, Yash has scored 42 marks in Maths, the UPDATE statement will look like this −" }, { "code": null, "e": 1931, "s": 1879, "text": "UPDATE marks\nSET subject 'Maths'\nWHERE roll_no = 26" }, { "code": null, "e": 2071, "s": 1931, "text": "You could have also added the name=’Yash’ condition instead of roll_no=26. Now, if you query the table, you will see the following output −" }, { "code": null, "e": 2228, "s": 2071, "text": "If you don’t add any condition in the UPDATE statement, the value of every row will be changed for that column. For instance, if I run the following query −" }, { "code": null, "e": 2265, "s": 2228, "text": "UPDATE marks\nSET subject = 'Science'" }, { "code": null, "e": 2323, "s": 2265, "text": "And then query the table, I’ll see the following output −" } ]
Rust - Slices
A slice is a pointer to a block of memory. Slices can be used to access portions of data stored in contiguous memory blocks. It can be used with data structures like arrays, vectors and strings. Slices use index numbers to access portions of data. The size of a slice is determined at runtime. Slices are pointers to the actual data. They are passed by reference to functions, which is also known as borrowing. For example, slices can be used to fetch a portion of a string value. A sliced string is a pointer to the actual string object. Therefore, we need to specify the starting and ending index of a String. Index starts from 0 just like arrays. let sliced_value = &data_structure[start_index..end_index] The minimum index value is 0 and the maximum index value is the size of the data structure. NOTE that the end_index will not be included in final string. The diagram below shows a sample string Tutorials, that has 9 characters. The index of the first character is 0 and that of the last character is 8. The following code fetches 5 characters from the string (starting from index 4). fn main() { let n1 = "Tutorials".to_string(); println!("length of string is {}",n1.len()); let c1 = &n1[4..9]; // fetches characters at 4,5,6,7, and 8 indexes println!("{}",c1); } length of string is 9 rials The main() function declares an array with 5 elements. It invokes the use_slice() function and passes to it a slice of three elements (points to the data array). The slices are passed by reference. The use_slice() function prints the value of the slice and its length. fn main(){ let data = [10,20,30,40,50]; use_slice(&data[1..4]); //this is effectively borrowing elements for a while } fn use_slice(slice:&[i32]) { // is taking a slice or borrowing a part of an array of i32s println!("length of slice is {:?}",slice.len()); println!("{:?}",slice); } length of slice is 3 [20, 30, 40] The &mut keyword can be used to mark a slice as mutable. fn main(){ let mut data = [10,20,30,40,50]; use_slice(&mut data[1..4]); // passes references of 20, 30 and 40 println!("{:?}",data); } fn use_slice(slice:&mut [i32]) { println!("length of slice is {:?}",slice.len()); println!("{:?}",slice); slice[0] = 1010; // replaces 20 with 1010 } length of slice is 3 [20, 30, 40] [10, 1010, 30, 40, 50] The above code passes a mutable slice to the use_slice() function. The function modifies the second element of the original array. 45 Lectures 4.5 hours Stone River ELearning 10 Lectures 33 mins Ken Burke Print Add Notes Bookmark this page
[ { "code": null, "e": 2381, "s": 2087, "text": "A slice is a pointer to a block of memory. Slices can be used to access portions of data stored in contiguous memory blocks. It can be used with data structures like arrays, vectors and strings. Slices use index numbers to access portions of data. The size of a slice is determined at runtime." }, { "code": null, "e": 2498, "s": 2381, "text": "Slices are pointers to the actual data. They are passed by reference to functions, which is also known as borrowing." }, { "code": null, "e": 2737, "s": 2498, "text": "For example, slices can be used to fetch a portion of a string value. A sliced string is a pointer to the actual string object. Therefore, we need to specify the starting and ending index of a String. Index starts from 0 just like arrays." }, { "code": null, "e": 2797, "s": 2737, "text": "let sliced_value = &data_structure[start_index..end_index]\n" }, { "code": null, "e": 2951, "s": 2797, "text": "The minimum index value is 0 and the maximum index value is the size of the data structure. NOTE that the end_index will not be included in final string." }, { "code": null, "e": 3100, "s": 2951, "text": "The diagram below shows a sample string Tutorials, that has 9 characters. The index of the first character is 0 and that of the last character is 8." }, { "code": null, "e": 3181, "s": 3100, "text": "The following code fetches 5 characters from the string (starting from index 4)." }, { "code": null, "e": 3381, "s": 3181, "text": "fn main() {\n let n1 = \"Tutorials\".to_string();\n println!(\"length of string is {}\",n1.len());\n let c1 = &n1[4..9]; \n \n // fetches characters at 4,5,6,7, and 8 indexes\n println!(\"{}\",c1);\n}" }, { "code": null, "e": 3410, "s": 3381, "text": "length of string is 9\nrials\n" }, { "code": null, "e": 3679, "s": 3410, "text": "The main() function declares an array with 5 elements. It invokes the use_slice() function and passes to it a slice of three elements (points to the data array). The slices are passed by reference. The use_slice() function prints the value of the slice and its length." }, { "code": null, "e": 3982, "s": 3679, "text": "fn main(){\n let data = [10,20,30,40,50];\n use_slice(&data[1..4]);\n //this is effectively borrowing elements for a while\n}\nfn use_slice(slice:&[i32]) { \n // is taking a slice or borrowing a part of an array of i32s\n println!(\"length of slice is {:?}\",slice.len());\n println!(\"{:?}\",slice);\n}" }, { "code": null, "e": 4017, "s": 3982, "text": "length of slice is 3\n[20, 30, 40]\n" }, { "code": null, "e": 4075, "s": 4017, "text": "The &mut keyword can be used to mark a slice as mutable." }, { "code": null, "e": 4385, "s": 4075, "text": "fn main(){\n let mut data = [10,20,30,40,50];\n use_slice(&mut data[1..4]);\n // passes references of \n 20, 30 and 40\n println!(\"{:?}\",data);\n}\nfn use_slice(slice:&mut [i32]) {\n println!(\"length of slice is {:?}\",slice.len());\n println!(\"{:?}\",slice);\n slice[0] = 1010; // replaces 20 with 1010\n}" }, { "code": null, "e": 4443, "s": 4385, "text": "length of slice is 3\n[20, 30, 40]\n[10, 1010, 30, 40, 50]\n" }, { "code": null, "e": 4574, "s": 4443, "text": "The above code passes a mutable slice to the use_slice() function. The function modifies the second element of the original array." }, { "code": null, "e": 4609, "s": 4574, "text": "\n 45 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4632, "s": 4609, "text": " Stone River ELearning" }, { "code": null, "e": 4664, "s": 4632, "text": "\n 10 Lectures \n 33 mins\n" }, { "code": null, "e": 4675, "s": 4664, "text": " Ken Burke" }, { "code": null, "e": 4682, "s": 4675, "text": " Print" }, { "code": null, "e": 4693, "s": 4682, "text": " Add Notes" } ]
Inter-Annotator Agreement (IAA). Pair-wise Cohen kappa and group Fleiss’... | by Louis de Bruijn | Towards Data Science
In this story, we’ll explore the Inter-Annotator Agreement (IAA), a measure of how well multiple annotators can make the same annotation decision for a certain category. Supervised Natural Language Processing algorithms use a labeled dataset, that is often annotated by humans. An example would be the annotation scheme for my master’s thesis, where tweets were labeled as either abusive or non-abusive. IAA shows you how clear your annotation guidelines are, how uniformly your annotators understood it, and how reproducible the annotation task is. It is a vital part of both the validation and reproducibility of classification results. Accuracy and F1 score don’t take into account the expected chance agreements that are likely to occur when people annotate instances. The measures taking expected chance agreement into account: Cohen’s κ: two annotators annotating each instance with a category Fleiss’ κ: each instance was annotated n times with a category This story covers best practices for annotations and explores the two IAA metrics for qualitative annotations: Cohen and Fleiss’ kappa. Cohen kappa is calculated between a pair of annotators and Fleiss’ kappa over a group of multiple annotators. Supervised learning is the machine learning task of learning a function that maps an input to an output based on example input-output pairs. It infers this function from labeled training data consisting of a set of training examples. When annotating data it is preferable to have multiple annotators annotate the same training instances to validate the labels. When multiple annotators annotate the same portion of the data we’re able to compute the inter-observer agreement or IAA. For my master’s thesis, I worked with 44 Bachelor students, divided over 11 groups. Each individual annotated 100 unique tweets and 50 overlapping tweets that the other three group members also annotated. This resulted in 50 annotated tweets by four different annotators and 400 tweets by a single annotator. Cohen’s kappa coefficient (κ) is a statistic to measure the reliability between annotators for qualitative (categorical) items. It is a more robust measure than simple percent agreement calculations, as κ takes into account the possibility of the agreement occurring by chance. It is a pairwise reliability measure between two annotators. Cohen’s kappa statistic is the agreement between two raters where Po is the relative observed agreement among raters (identical to the accuracy), and Pe is the hypothetical probability of chance agreement. Below you will find the programmatic implementation of this evaluation metric. Note that the annotations lists have to be ordered by the same index. ann1[0] and ann2[0] should represent the same annotated instance (tweet). Fleiss’ kappa is a statistical measure for assessing the reliability of agreement between a fixed number of raters when assigning categorical ratings to several items or classifying items. It is a generalization of Scott’s pi (π) evaluation metric for two annotators extended to multiple annotators. Whereas Scott’s pi and Cohen’s kappa work for only two raters, Fleiss’ kappa works for any number of raters giving categorical ratings, to a fixed number of items. In addition to that, not all raters are required to annotate all items. Thanks to Skylander86 for his contribution to the Fleiss kappa implementation in Python. I’ve simply duplicated his code and added comments to explain what is happening. If the raters are in complete agreement then κ = 1. If there is no agreement among the raters (other than what would be expected by chance) then κ ≤ 0. Cohen kappa has just two annotators, each annotator annotates every item. Cohen’s κ is more informative than Scott’s π due to the way the chance agreement is calculated: The latter uses one distribution for each rater while the former uses different distributions. Fleiss’ kappa is an extension of Scott’s π for two coders (not Cohen’s κ). Fleiss’ kappa can have any number of annotators, where every item is not necessarily annotated by each annotator! There are also implementations for Cohen and Fleiss’ kappa statistics available in the following packages, so you don’t have to write separate functions for them (even though it’s good practice!). import sklearnfrom sklearn.metrics import cohen_kappa_scoreimport statsmodelsfrom statsmodels.stats.inter_rater import fleiss_kappa Hopefully, this story showed you how to compute the IAA to validate your results and increase the reproducibility of your experiments! The full script can be found here.
[ { "code": null, "e": 451, "s": 47, "text": "In this story, we’ll explore the Inter-Annotator Agreement (IAA), a measure of how well multiple annotators can make the same annotation decision for a certain category. Supervised Natural Language Processing algorithms use a labeled dataset, that is often annotated by humans. An example would be the annotation scheme for my master’s thesis, where tweets were labeled as either abusive or non-abusive." }, { "code": null, "e": 686, "s": 451, "text": "IAA shows you how clear your annotation guidelines are, how uniformly your annotators understood it, and how reproducible the annotation task is. It is a vital part of both the validation and reproducibility of classification results." }, { "code": null, "e": 880, "s": 686, "text": "Accuracy and F1 score don’t take into account the expected chance agreements that are likely to occur when people annotate instances. The measures taking expected chance agreement into account:" }, { "code": null, "e": 947, "s": 880, "text": "Cohen’s κ: two annotators annotating each instance with a category" }, { "code": null, "e": 1010, "s": 947, "text": "Fleiss’ κ: each instance was annotated n times with a category" }, { "code": null, "e": 1256, "s": 1010, "text": "This story covers best practices for annotations and explores the two IAA metrics for qualitative annotations: Cohen and Fleiss’ kappa. Cohen kappa is calculated between a pair of annotators and Fleiss’ kappa over a group of multiple annotators." }, { "code": null, "e": 1490, "s": 1256, "text": "Supervised learning is the machine learning task of learning a function that maps an input to an output based on example input-output pairs. It infers this function from labeled training data consisting of a set of training examples." }, { "code": null, "e": 1739, "s": 1490, "text": "When annotating data it is preferable to have multiple annotators annotate the same training instances to validate the labels. When multiple annotators annotate the same portion of the data we’re able to compute the inter-observer agreement or IAA." }, { "code": null, "e": 2048, "s": 1739, "text": "For my master’s thesis, I worked with 44 Bachelor students, divided over 11 groups. Each individual annotated 100 unique tweets and 50 overlapping tweets that the other three group members also annotated. This resulted in 50 annotated tweets by four different annotators and 400 tweets by a single annotator." }, { "code": null, "e": 2387, "s": 2048, "text": "Cohen’s kappa coefficient (κ) is a statistic to measure the reliability between annotators for qualitative (categorical) items. It is a more robust measure than simple percent agreement calculations, as κ takes into account the possibility of the agreement occurring by chance. It is a pairwise reliability measure between two annotators." }, { "code": null, "e": 2672, "s": 2387, "text": "Cohen’s kappa statistic is the agreement between two raters where Po is the relative observed agreement among raters (identical to the accuracy), and Pe is the hypothetical probability of chance agreement. Below you will find the programmatic implementation of this evaluation metric." }, { "code": null, "e": 2816, "s": 2672, "text": "Note that the annotations lists have to be ordered by the same index. ann1[0] and ann2[0] should represent the same annotated instance (tweet)." }, { "code": null, "e": 3352, "s": 2816, "text": "Fleiss’ kappa is a statistical measure for assessing the reliability of agreement between a fixed number of raters when assigning categorical ratings to several items or classifying items. It is a generalization of Scott’s pi (π) evaluation metric for two annotators extended to multiple annotators. Whereas Scott’s pi and Cohen’s kappa work for only two raters, Fleiss’ kappa works for any number of raters giving categorical ratings, to a fixed number of items. In addition to that, not all raters are required to annotate all items." }, { "code": null, "e": 3522, "s": 3352, "text": "Thanks to Skylander86 for his contribution to the Fleiss kappa implementation in Python. I’ve simply duplicated his code and added comments to explain what is happening." }, { "code": null, "e": 3674, "s": 3522, "text": "If the raters are in complete agreement then κ = 1. If there is no agreement among the raters (other than what would be expected by chance) then κ ≤ 0." }, { "code": null, "e": 3748, "s": 3674, "text": "Cohen kappa has just two annotators, each annotator annotates every item." }, { "code": null, "e": 3939, "s": 3748, "text": "Cohen’s κ is more informative than Scott’s π due to the way the chance agreement is calculated: The latter uses one distribution for each rater while the former uses different distributions." }, { "code": null, "e": 4014, "s": 3939, "text": "Fleiss’ kappa is an extension of Scott’s π for two coders (not Cohen’s κ)." }, { "code": null, "e": 4128, "s": 4014, "text": "Fleiss’ kappa can have any number of annotators, where every item is not necessarily annotated by each annotator!" }, { "code": null, "e": 4325, "s": 4128, "text": "There are also implementations for Cohen and Fleiss’ kappa statistics available in the following packages, so you don’t have to write separate functions for them (even though it’s good practice!)." }, { "code": null, "e": 4457, "s": 4325, "text": "import sklearnfrom sklearn.metrics import cohen_kappa_scoreimport statsmodelsfrom statsmodels.stats.inter_rater import fleiss_kappa" } ]
How to create a new column with means of row values for each or some of the columns in an R data frame?
Comparison of columns of an R data frame can be done in many ways and one of the ways is having one or more columns of means. In this way, we can compare column of raw data with the column of means and also the column of means with another column of means. We can use apply function to create a new column with means of row values for each or some of the columns of an R data frame. Consider the below data frame x1 <-1:20 x2 <-1:20 x3 <-20:1 df <-data.frame(x1,x2,x3) df x1 x2 x3 1 1 1 20 2 2 2 19 3 3 3 18 4 4 4 17 5 5 5 16 6 6 6 15 7 7 7 14 8 8 8 13 9 9 9 12 10 10 10 11 11 11 11 10 12 12 12 9 13 13 13 8 14 14 14 7 15 15 15 6 16 16 16 5 17 17 17 4 18 18 18 3 19 19 19 2 20 20 20 1 We will create new column for the mean of all columns and for the mean of some columns − df$Means <-apply(df,1,mean) df x1 x2 x3 Means 1 1 1 20 7.333333 2 2 2 19 7.666667 3 3 3 18 8.000000 4 4 4 17 8.333333 5 5 5 16 8.666667 6 6 6 15 9.000000 7 7 7 14 9.333333 8 8 8 13 9.666667 9 9 9 12 10.000000 10 10 10 11 10.333333 11 11 11 10 10.666667 12 12 12 9 11.000000 13 13 13 8 11.333333 14 14 14 7 11.666667 15 15 15 6 12.000000 16 16 16 5 12.333333 17 17 17 4 12.666667 18 18 18 3 13.000000 19 19 19 2 13.333333 20 20 20 1 13.666667 df$Means_of_x1_and_x2 <-apply(df[,1:2],1,mean) df x1 x2 x3 Means Means_of_x1_and_x2 1 1 1 20 7.333333 1 2 2 2 19 7.666667 2 3 3 3 18 8.000000 3 4 4 4 17 8.333333 4 5 5 5 16 8.666667 5 6 6 6 15 9.000000 6 7 7 7 14 9.333333 7 8 8 8 13 9.666667 8 9 9 9 12 10.000000 9 10 10 10 11 10.333333 10 11 11 11 10 10.666667 11 12 12 12 9 11.000000 12 13 13 13 8 11.333333 13 14 14 14 7 11.666667 14 15 15 15 6 12.000000 15 16 16 16 5 12.333333 16 17 17 17 4 12.666667 17 18 18 18 3 13.000000 18 19 19 19 2 13.333333 19 20 20 20 1 13.666667 20 df$Means_of_x1_and_x3 <-apply(df[,1:3],1,mean) df x1 x2 x3 Means Means_of_x1_and_x2 Means_of_x1_and_x3 1 1 1 20 7.333333 1 7.333333 2 2 2 19 7.666667 2 7.666667 3 3 3 18 8.000000 3 8.000000 4 4 4 17 8.333333 4 8.333333 5 5 5 16 8.666667 5 8.666667 6 6 6 15 9.000000 6 9.000000 7 7 7 14 9.333333 7 9.333333 8 8 8 13 9.666667 8 9.666667 9 9 9 12 10.000000 9 10.000000 10 10 10 11 10.333333 10 10.333333 11 11 11 10 10.666667 11 10.666667 12 12 12 9 11.000000 12 11.000000 13 13 13 8 11.333333 13 11.333333 14 14 14 7 11.666667 14 11.666667 15 15 15 6 12.000000 15 12.000000 16 16 16 5 12.333333 16 12.333333 17 17 17 4 12.666667 17 12.666667 18 18 18 3 13.000000 18 13.000000 19 19 19 2 13.333333 19 13.333333 20 20 20 1 13.666667 20 13.666667 $Means_of_x2_and_x3 &klt;-apply(df[,2:3],1,mean) df x1 x2 x3 Means Means_of_x1_and_x2 Means_of_x1_and_x3 Means_of_x2_and_x3 1 1 1 20 7.333333 1 7.333333 10.5 2 2 2 19 7.666667 2 7.666667 10.5 3 3 3 18 8.000000 3 8.000000 10.5 4 4 4 17 8.333333 4 8.333333 10.5 5 5 5 16 8.666667 5 8.666667 10.5 6 6 6 15 9.000000 6 9.000000 10.5 7 7 7 14 9.333333 7 9.333333 10.5 8 8 8 13 9.666667 8 9.666667 10.5 9 9 9 12 10.000000 9 10.000000 10.5 10 10 10 11 10.333333 10 10.333333 10.5 11 11 11 10 10.666667 11 10.666667 10.5 12 12 12 9 11.000000 12 11.000000 10.5 13 13 13 8 11.333333 13 11.333333 10.5 14 14 14 7 11.666667 14 11.666667 10.5 15 15 15 6 12.000000 15 12.000000 10.5 16 16 16 5 12.333333 16 12.333333 10.5 17 17 17 4 12.666667 17 12.666667 10.5 18 18 18 3 13.000000 18 13.000000 10.5 19 19 19 2 13.333333 19 13.333333 10.5 20 20 20 1 13.666667 20 13.666667 10.5
[ { "code": null, "e": 1445, "s": 1062, "text": "Comparison of columns of an R data frame can be done in many ways and one of the ways is having one or more columns of means. In this way, we can compare column of raw data with the column of means and also the column of means with another column of means. We can use apply function to create a new column with means of row values for each or some of the columns of an R data frame." }, { "code": null, "e": 1475, "s": 1445, "text": "Consider the below data frame" }, { "code": null, "e": 1534, "s": 1475, "text": "x1 <-1:20\nx2 <-1:20\nx3 <-20:1\ndf <-data.frame(x1,x2,x3)\ndf" }, { "code": null, "e": 1747, "s": 1534, "text": "x1 x2 x3\n1 1 1 20\n2 2 2 19\n3 3 3 18\n4 4 4 17\n5 5 5 16\n6 6 6 15\n7 7 7 14\n8 8 8 13\n9 9 9 12\n10 10 10 11\n11 11 11 10\n12 12 12 9\n13 13 13 8\n14 14 14 7\n15 15 15 6\n16 16 16 5\n17 17 17 4\n18 18 18 3\n19 19 19 2\n20 20 20 1" }, { "code": null, "e": 1836, "s": 1747, "text": "We will create new column for the mean of all columns and for the mean of some columns −" }, { "code": null, "e": 1867, "s": 1836, "text": "df$Means <-apply(df,1,mean)\ndf" }, { "code": null, "e": 2278, "s": 1867, "text": "x1 x2 x3 Means\n1 1 1 20 7.333333\n2 2 2 19 7.666667\n3 3 3 18 8.000000\n4 4 4 17 8.333333\n5 5 5 16 8.666667\n6 6 6 15 9.000000\n7 7 7 14 9.333333\n8 8 8 13 9.666667\n9 9 9 12 10.000000\n10 10 10 11 10.333333\n11 11 11 10 10.666667\n12 12 12 9 11.000000\n13 13 13 8 11.333333\n14 14 14 7 11.666667\n15 15 15 6 12.000000\n16 16 16 5 12.333333\n17 17 17 4 12.666667\n18 18 18 3 13.000000\n19 19 19 2 13.333333\n20 20 20 1 13.666667" }, { "code": null, "e": 2328, "s": 2278, "text": "df$Means_of_x1_and_x2 <-apply(df[,1:2],1,mean)\ndf" }, { "code": null, "e": 2809, "s": 2328, "text": "x1 x2 x3 Means Means_of_x1_and_x2\n1 1 1 20 7.333333 1\n2 2 2 19 7.666667 2\n3 3 3 18 8.000000 3\n4 4 4 17 8.333333 4\n5 5 5 16 8.666667 5\n6 6 6 15 9.000000 6\n7 7 7 14 9.333333 7\n8 8 8 13 9.666667 8\n9 9 9 12 10.000000 9\n10 10 10 11 10.333333 10\n11 11 11 10 10.666667 11\n12 12 12 9 11.000000 12\n13 13 13 8 11.333333 13\n14 14 14 7 11.666667 14\n15 15 15 6 12.000000 15\n16 16 16 5 12.333333 16\n17 17 17 4 12.666667 17\n18 18 18 3 13.000000 18\n19 19 19 2 13.333333 19\n20 20 20 1 13.666667 20" }, { "code": null, "e": 2859, "s": 2809, "text": "df$Means_of_x1_and_x3 <-apply(df[,1:3],1,mean)\ndf" }, { "code": null, "e": 3551, "s": 2859, "text": "x1 x2 x3 Means Means_of_x1_and_x2 Means_of_x1_and_x3\n1 1 1 20 7.333333 1 7.333333\n2 2 2 19 7.666667 2 7.666667\n3 3 3 18 8.000000 3 8.000000\n4 4 4 17 8.333333 4 8.333333\n5 5 5 16 8.666667 5 8.666667\n6 6 6 15 9.000000 6 9.000000\n7 7 7 14 9.333333 7 9.333333\n8 8 8 13 9.666667 8 9.666667\n9 9 9 12 10.000000 9 10.000000\n10 10 10 11 10.333333 10 10.333333\n11 11 11 10 10.666667 11 10.666667\n12 12 12 9 11.000000 12 11.000000\n13 13 13 8 11.333333 13 11.333333\n14 14 14 7 11.666667 14 11.666667\n15 15 15 6 12.000000 15 12.000000\n16 16 16 5 12.333333 16 12.333333\n17 17 17 4 12.666667 17 12.666667\n18 18 18 3 13.000000 18 13.000000\n19 19 19 2 13.333333 19 13.333333\n20 20 20 1 13.666667 20 13.666667" }, { "code": null, "e": 3603, "s": 3551, "text": "$Means_of_x2_and_x3 &klt;-apply(df[,2:3],1,mean)\ndf" }, { "code": null, "e": 4414, "s": 3603, "text": "x1 x2 x3 Means Means_of_x1_and_x2 Means_of_x1_and_x3 Means_of_x2_and_x3\n1 1 1 20 7.333333 1 7.333333 10.5\n2 2 2 19 7.666667 2 7.666667 10.5\n3 3 3 18 8.000000 3 8.000000 10.5\n4 4 4 17 8.333333 4 8.333333 10.5\n5 5 5 16 8.666667 5 8.666667 10.5\n6 6 6 15 9.000000 6 9.000000 10.5\n7 7 7 14 9.333333 7 9.333333 10.5\n8 8 8 13 9.666667 8 9.666667 10.5\n9 9 9 12 10.000000 9 10.000000 10.5\n10 10 10 11 10.333333 10 10.333333 10.5\n11 11 11 10 10.666667 11 10.666667 10.5\n12 12 12 9 11.000000 12 11.000000 10.5\n13 13 13 8 11.333333 13 11.333333 10.5\n14 14 14 7 11.666667 14 11.666667 10.5\n15 15 15 6 12.000000 15 12.000000 10.5\n16 16 16 5 12.333333 16 12.333333 10.5\n17 17 17 4 12.666667 17 12.666667 10.5\n18 18 18 3 13.000000 18 13.000000 10.5\n19 19 19 2 13.333333 19 13.333333 10.5\n20 20 20 1 13.666667 20 13.666667 10.5" } ]
Using R to Merge the CSV Files in Code-Point Open Into One Massive File | by Jamie Whyte | Towards Data Science
If you have a dataset that you have postcodes for — eg customer data, or asset information, one of the most useful things you can do with it is put that data onto a map. To do that, each record needs to be geo-referenced. Ordnance Survey have an open dataset, called Code-Point Open, which you can get from their Open Data site. This dataset allows you to lookup postcodes in your own data to find their co-ordinates, so you can then put them on a map. The dataset from Ordnance Survey is contained in a zip file, and when you extract it, it consists of 120 csv files. This can be a pain in the backside to deal with, so I’m going to show how to use R (actually R Studio) to stick all these csv files together into one. There are other ways of doing this — manually (😱), writing a batch file, MS Visual Basic, etc, but this is an elegant and quick way to get it done. To start with, open up R Studio, and make a new project. Create a new folder in the project folder, and call it ‘temp’. You now need to copy the 120 csv files from Ordnance Survey into this folder. After this, in the R Studio console, we need to set the working directory of this project to that temp folder: setwd(‘temp/’) Then, we need to pass all the filenames of everything in that folder into a variable: filenames <- list.files(full.names=TRUE) This will go through the files in that folder, pick out the filenames, and pass them into the variable ‘filenames’. We’ll now use those file names to iterate through the files, extracting the data from each csv file, and combining it into one list (Note that this will take a few seconds to complete): All <- lapply(filenames,function(i){read.csv(i, header=FALSE, skip=4)}) This pushes the data into the variable 'All'. If we look in the ‘Environment’ tab, we can see that this is a ‘Large list’ containing 120 elements, and is 156Mb in size. To use the datasets, either to do matching in R, or to save as its own csv file, we need to turn it into a dataframe. To do this, we can run the following: df <- do.call(rbind.data.frame, All) To check the contents of the dataframe, we can use the head function to show the first few rows of data: head(df) Which give us this: This looks good (although it would probably be good practice to rename to columns to something more meaningful). V1 has the postcode, and V3 and V4 the British Co-ordinate System references. Finally, to save this big postcode list as a new csv file we can use write.csv: write.csv(df,”all_postcodes.csv”, row.names=FALSE) This will create a new (massive) csv file in the temp folder in the R Studio project folders. From here, you can either merge the postcode file with your own data to geo-reference it within R, or you can go and do vlookups in Excel. Note that this exercise works because each of the csv files has the same shape, in terms of the number of columns of data. This kind of process gets more complicated for different datasets. Here’s all the code in one go: setwd(‘temp/’)filenames <- list.files(full.names=TRUE)All <- lapply(filenames,function(i){read.csv(i, header=FALSE, skip=4)})df <- do.call(rbind.data.frame, All)write.csv(df,”all_postcodes.csv”, row.names=FALSE)
[ { "code": null, "e": 625, "s": 172, "text": "If you have a dataset that you have postcodes for — eg customer data, or asset information, one of the most useful things you can do with it is put that data onto a map. To do that, each record needs to be geo-referenced. Ordnance Survey have an open dataset, called Code-Point Open, which you can get from their Open Data site. This dataset allows you to lookup postcodes in your own data to find their co-ordinates, so you can then put them on a map." }, { "code": null, "e": 1040, "s": 625, "text": "The dataset from Ordnance Survey is contained in a zip file, and when you extract it, it consists of 120 csv files. This can be a pain in the backside to deal with, so I’m going to show how to use R (actually R Studio) to stick all these csv files together into one. There are other ways of doing this — manually (😱), writing a batch file, MS Visual Basic, etc, but this is an elegant and quick way to get it done." }, { "code": null, "e": 1238, "s": 1040, "text": "To start with, open up R Studio, and make a new project. Create a new folder in the project folder, and call it ‘temp’. You now need to copy the 120 csv files from Ordnance Survey into this folder." }, { "code": null, "e": 1349, "s": 1238, "text": "After this, in the R Studio console, we need to set the working directory of this project to that temp folder:" }, { "code": null, "e": 1364, "s": 1349, "text": "setwd(‘temp/’)" }, { "code": null, "e": 1450, "s": 1364, "text": "Then, we need to pass all the filenames of everything in that folder into a variable:" }, { "code": null, "e": 1491, "s": 1450, "text": "filenames <- list.files(full.names=TRUE)" }, { "code": null, "e": 1793, "s": 1491, "text": "This will go through the files in that folder, pick out the filenames, and pass them into the variable ‘filenames’. We’ll now use those file names to iterate through the files, extracting the data from each csv file, and combining it into one list (Note that this will take a few seconds to complete):" }, { "code": null, "e": 1865, "s": 1793, "text": "All <- lapply(filenames,function(i){read.csv(i, header=FALSE, skip=4)})" }, { "code": null, "e": 2034, "s": 1865, "text": "This pushes the data into the variable 'All'. If we look in the ‘Environment’ tab, we can see that this is a ‘Large list’ containing 120 elements, and is 156Mb in size." }, { "code": null, "e": 2190, "s": 2034, "text": "To use the datasets, either to do matching in R, or to save as its own csv file, we need to turn it into a dataframe. To do this, we can run the following:" }, { "code": null, "e": 2227, "s": 2190, "text": "df <- do.call(rbind.data.frame, All)" }, { "code": null, "e": 2332, "s": 2227, "text": "To check the contents of the dataframe, we can use the head function to show the first few rows of data:" }, { "code": null, "e": 2341, "s": 2332, "text": "head(df)" }, { "code": null, "e": 2361, "s": 2341, "text": "Which give us this:" }, { "code": null, "e": 2632, "s": 2361, "text": "This looks good (although it would probably be good practice to rename to columns to something more meaningful). V1 has the postcode, and V3 and V4 the British Co-ordinate System references. Finally, to save this big postcode list as a new csv file we can use write.csv:" }, { "code": null, "e": 2683, "s": 2632, "text": "write.csv(df,”all_postcodes.csv”, row.names=FALSE)" }, { "code": null, "e": 2916, "s": 2683, "text": "This will create a new (massive) csv file in the temp folder in the R Studio project folders. From here, you can either merge the postcode file with your own data to geo-reference it within R, or you can go and do vlookups in Excel." }, { "code": null, "e": 3106, "s": 2916, "text": "Note that this exercise works because each of the csv files has the same shape, in terms of the number of columns of data. This kind of process gets more complicated for different datasets." }, { "code": null, "e": 3137, "s": 3106, "text": "Here’s all the code in one go:" } ]
lp - Unix, Linux Command
lp: submits files for printing or alters a pending job.. lp -i request-ID [-c] [-m] [-p] [-s] [-w] [-d destination] [-f form-name] [-H special-handling] [-n number] [-o options] [-p pagenumbers] [-q priority-level] [-S character-set | print-wheel] [-t title] [-T content-Type [-r]] [-y mode-list] lp -i request-ID [-c] [-m] [-p] [-s] [-w] [-d destination] [-f form-name] [-H special-handling] [-n number] [-o options] [-p pagenumbers] [-q priority-level] [-S character-set | print-wheel] [-t title] [-T content-Type [-r]] [-y mode-list] lp command arranges for the files specified by the Files parameter and their associated information (called a request) to be printed by a line printer. If you do not specify a value for the Files parameter, the lp command accepts standard input. The file name - (dash) represents standard input and can be specified on the command line in addition to files. The lp command sends the requests in the order specified. If the job is submitted to a local print queue, the lp command displays the following to standard output: Job number is: nnn where nnn is the assigned job number. To suppress the job number use the -s flag. -H hh:mm -H hold -H immediate -H restart -H resume Example-1: To print the /etc/motd file on printer lp0 attached to device dlp0, enter: # lp /etc/motd Example-2: To print 30 copies of the /etc/motd file using a copy of the file, and to notify the user that the job is completed using mail, enter: # lp -c -m -n30 -dlp0:lpd0 /etc/motd Example-3: To print the /etc/motd file using backend flags -f and -a, with a job title of blah, enter: # lp -t"blah" -o -f -o -a /etc/motd Example-4: To queue the MyFile file and return the job number, enter: # lp myfile Example-5: To queue the MyFile file and suppress the job number, enter: # lp -s myfile Example-6: To Print the double-sided legal document filename to printer myprinter. # lp -d myprinter -o media=legal -o sides=two-sided-long-edge filename Example-7: Print document filename across 4 pages. # lp -d myprinter -o scaling=200 filename Example-8: Print a text file with 12 characters per inch, 8 lines per inch, and a 1 inch left margin. # lp -d myprinter -o cpi=12 -o lpi=8 -o page-left=72 filename 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10634, "s": 10577, "text": "lp: submits files for printing or alters a pending job.." }, { "code": null, "e": 10889, "s": 10634, "text": " lp -i request-ID [-c] [-m] [-p] [-s] [-w] [-d destination] [-f form-name] \n [-H special-handling] [-n number] [-o options] [-p pagenumbers] \n [-q priority-level] [-S character-set | print-wheel] [-t title] \n [-T content-Type [-r]] [-y mode-list]\n " }, { "code": null, "e": 11142, "s": 10889, "text": " lp -i request-ID [-c] [-m] [-p] [-s] [-w] [-d destination] [-f form-name] \n [-H special-handling] [-n number] [-o options] [-p pagenumbers] \n [-q priority-level] [-S character-set | print-wheel] [-t title] \n [-T content-Type [-r]] [-y mode-list]" }, { "code": null, "e": 11766, "s": 11142, "text": "lp command arranges for the files specified by the Files parameter and their associated information (called a request) to be printed by a line printer. If you do not specify a value for the Files parameter, the lp command accepts standard input. The file name - (dash) represents standard input and can be specified on the command line in addition to files. The lp command sends the requests in the order specified. If the job is submitted to a local print queue, the lp command displays the following to standard output:\nJob number is: nnn\nwhere nnn is the assigned job number. To suppress the job number use the -s flag.\n" }, { "code": null, "e": 11775, "s": 11766, "text": "-H hh:mm" }, { "code": null, "e": 11783, "s": 11775, "text": "-H hold" }, { "code": null, "e": 11796, "s": 11783, "text": "-H immediate" }, { "code": null, "e": 11807, "s": 11796, "text": "-H restart" }, { "code": null, "e": 11817, "s": 11807, "text": "-H resume" }, { "code": null, "e": 11828, "s": 11817, "text": "Example-1:" }, { "code": null, "e": 11903, "s": 11828, "text": "To print the /etc/motd file on printer lp0 attached to device dlp0, enter:" }, { "code": null, "e": 11919, "s": 11903, "text": "# lp /etc/motd " }, { "code": null, "e": 11930, "s": 11919, "text": "Example-2:" }, { "code": null, "e": 12065, "s": 11930, "text": "To print 30 copies of the /etc/motd file using a copy of the file, and to notify the user that the job is completed using mail, enter:" }, { "code": null, "e": 12107, "s": 12065, "text": "# lp -c -m -n30 -dlp0:lpd0 /etc/motd " }, { "code": null, "e": 12118, "s": 12107, "text": "Example-3:" }, { "code": null, "e": 12210, "s": 12118, "text": "To print the /etc/motd file using backend flags -f and -a, with a job title of blah, enter:" }, { "code": null, "e": 12250, "s": 12210, "text": "# lp -t\"blah\" -o -f -o -a /etc/motd " }, { "code": null, "e": 12261, "s": 12250, "text": "Example-4:" }, { "code": null, "e": 12320, "s": 12261, "text": "To queue the MyFile file and return the job number, enter:" }, { "code": null, "e": 12332, "s": 12320, "text": "# lp myfile" }, { "code": null, "e": 12343, "s": 12332, "text": "Example-5:" }, { "code": null, "e": 12404, "s": 12343, "text": "To queue the MyFile file and suppress the job number, enter:" }, { "code": null, "e": 12420, "s": 12404, "text": "# lp -s myfile" }, { "code": null, "e": 12431, "s": 12420, "text": "Example-6:" }, { "code": null, "e": 12503, "s": 12431, "text": "To Print the double-sided legal document filename to printer myprinter." }, { "code": null, "e": 12574, "s": 12503, "text": "# lp -d myprinter -o media=legal -o sides=two-sided-long-edge filename" }, { "code": null, "e": 12585, "s": 12574, "text": "Example-7:" }, { "code": null, "e": 12625, "s": 12585, "text": "Print document filename across 4 pages." }, { "code": null, "e": 12667, "s": 12625, "text": "# lp -d myprinter -o scaling=200 filename" }, { "code": null, "e": 12678, "s": 12667, "text": "Example-8:" }, { "code": null, "e": 12769, "s": 12678, "text": "Print a text file with 12 characters per inch, 8 lines per inch, and a 1 inch left margin." }, { "code": null, "e": 12831, "s": 12769, "text": "# lp -d myprinter -o cpi=12 -o lpi=8 -o page-left=72 filename" }, { "code": null, "e": 12866, "s": 12831, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 12894, "s": 12866, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 12928, "s": 12894, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12945, "s": 12928, "text": " Frahaan Hussain" }, { "code": null, "e": 12978, "s": 12945, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 12989, "s": 12978, "text": " Pradeep D" }, { "code": null, "e": 13024, "s": 12989, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 13040, "s": 13024, "text": " Musab Zayadneh" }, { "code": null, "e": 13073, "s": 13040, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 13085, "s": 13073, "text": " GUHARAJANM" }, { "code": null, "e": 13117, "s": 13085, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 13125, "s": 13117, "text": " Uplatz" }, { "code": null, "e": 13132, "s": 13125, "text": " Print" }, { "code": null, "e": 13143, "s": 13132, "text": " Add Notes" } ]
Practical Code Implementations of Feature Engineering for Machine Learning with Python | by Sole from Train in Data | Towards Data Science
According to a survey by Forbes, data scientists and machine learning engineers spend around 60% of their time preparing data for analysis and machine learning. A large chunk of that time is spent on feature engineering. Feature engineering is the process of taking a data set and constructing explanatory variables, or predictor features, that are then passed onto the prediction model to train a machine learning algorithm. It is a crucial step in all machine learning models, but can often be challenging and very time consuming. Feature engineering involves aspects such as imputing missing values, encoding categorical variables, transforming and discretizing numerical variables, removing or censoring outliers and scaling, among others. In the last few years, a growing number of open source Python libraries that support feature engineering techniques have started to emerge. Among these, the Featuretools library supports an exhaustive array of functions to work with transaction data and time series; the Category encoders library supports a comprehensive selection of methods to encode categorical variables; and the Scikit-learn and Feature-engine libraries support a wide range of transformations including imputation, categorical encoding, discretization, mathematical transformations and more (see Table 1 below for a snapshot summary). In the following sections of this blog post, we will cover brief practical code implementations and comparisons of some of the commonly available open-source feature engineering Python packages, including: Scikit-learn Feature-engine Category Encoders For more in depth knowledge and additional code recipes check out the course “Feature Engineering for Machine Learning” or the book “Python Feature Engineering Cookbook”. Many, if not most, feature engineering techniques learn parameters from the data. For example, to impute data with the mean, we derive the value from the training set. To encode categorical variables, we define mappings of strings to numbers from the training data as well. Among the mathematical transformations for example, the transformation of BoxCox also needs to learn the optimal exponent to transform data from the train set. As a result, open source Python packages need to have the functionality to first learn and store these parameters, and then retrieve them to transform incoming data. For this exact reason, in this blog, we will be focusing on Scikit-learn, Feature-engine and Category encoders, all of which have this functionality. We will not be discussing libraries such as pandas, which, while containing intrinsic methods to, say, impute missing data ( fillna() ), or map ( map() ) a variable value to some other value, does not contain the functionality to learn and perpetuate the necessary parameters. Scikit-learn, Feature-engine and Category encoders share the fit() and transform() functionality to learn parameters from data, and then transform the variables. The transformers from these libraries, that is, the ‘classes’ in technical terms, can all store the learned parameters within their attributes. Yet, there are some nuances and subtleties that are different across these packages in terms of i) their output, ii) whether they operate on the entire dataframe or on a slice, and iii) if they allow grid search of engineering methods. Feature engineering is performed ahead of training machine learning models. Often, we want to understand how these transformations affect the variable characteristics and their relationships with each other. Pandas is a great tool for data analysis and visualization, and thus, libraries that return pandas dataframes instead of NumPy arrays are inherently more data analysis “friendly”. Feature-engine and Category encoders return pandas dataframes, while Scikit-learn returns NumPy arrays instead. NumPy arrays are optimized for machine learning, as the library is generally more computationally efficient but are less suited for data visualization. The difference in data output type between the packages means that we may need to add another line of code or two to convert between the NumPy arrays and Pandas dataframes before inserting back into your workflow. Table 2 below summarizes these key differences between the three packages. Feature engineering techniques are usually applied to different variable subsets. For example, we would only impute variables that contain missing data, and not necessarily the entire data set. Also, there are imputation techniques more suited to numerical variables and those more suited to categorical variables. Similarly, we may also want to discretize a group of variables while transform mathematically another. Thus, the ability to select variables within the feature engineering transformer, or class, allows for an easier flow of the feature engineering pipeline. Feature-engine and Category encoders allow us to select which variables to transform within the transformer. On the other hand, Scikit-learn transformers will operate over the entire data set (Table 2); meaning we need to slice the dataframe into categorical and numerical or into the variable subgroups to which we will apply each technique before using Scikit-learn transformers, which we can do manually using pandas, or with help of Scikit-learn’s ColumnTransformer or Feature-engine’s SklearnWrapper. The beauty of using the latter, is that the output is a pandas dataframe! Sometimes, we may wonder which transformation technique returns the most predictive variable. For example, should we do equal-width or equal-frequency discretization? Should we impute with the mean, median or an arbitrary number? Should we transform with the logarithm or maybe some other mathematical function? Most Scikit-learn transformers are centralized, meaning that one transformer, or class, can carry out different transformations. For example, we can apply 3 discretization techniques by simply changing the parameters of the KBinsDiscretizer() class from Scikit-learn, whereas, Feature-engine presents 3 different transformers for discretization. The same holds true for imputation; by changing the parameters of SimpleImputer(), we can perform different imputation techniques with Scikit-learn, whereas Feature-engine has several transformers, each of which can perform at most 2 different imputation variations. This adds additional versatility to Scikit-learn transformers through allowing for GridSearch, giving itself an edge on the jack-of-all-trades time sensitive kind of applications such as Data Science competitions and hackathons. On the other hand, Feature-engine transformers offer a more general use-case, oriented more towards mainstream industry usage where their applications are much more streamlined. Through the rest of the blog, we will compare the implementation of missing data imputation, categorical encoding, mathematical transformation and discretization among Scikit-learn, Feature-engine and Category encoders whenever possible. Imputation is the process of replacing missing data in a column, or variable, with a probable value estimated by other available information in the data set, typically within the same variable. There are multiple missing data imputation techniques available, each of which serve different purposes. If you want to learn more about these techniques, their advantages and limitations and when we should use them, check out the course “Feature engineering for Machine Learning”. Here, we will compare their implementation with current open source libraries. Scikit-learn and Feature-engine offer a variety of transformers for data imputation for numerical and categorical variables. Each of these libraries come with their own subtle differences in implementation and output. We will be doing walkthroughs of a few of the imputation methods in the next few paragraphs and discussing a few of those differences below. As we discussed in the previous section, in terms of the output, Feature-engine returns the imputed data sets as pandas dataframes while Scikit-learn returns NumPy arrays. Now, depending on the stage of your data pre-processing workflow and your personal preferences, you could be dealing with either NumPy arrays or pandas dataframes, requiring you to add a line of code or two to convert between the two. Table 3 below summarizes the techniques supported by each package and the main takeaways of their advantages and shortcomings. Both libraries contain functionality for most common imputation techniques. Feature-engine can additionally do while Scikit-learn offers Multivariate imputation of chained equations in its functionality. As we mentioned previously, Feature-engine allows us to select the variables that we want to impute within each transformer, whereas Scikit-learn transformers will impute over the entire dataframe. Feature-engine transformers can also automatically identify between numerical and categorical, depending on the imputation technique we would like to apply. That way, we will not end up inadvertently adding a string when we impute numerical variables, or a number to categorical ones. The method for selecting the variables will become clearer when we demonstrate a walk-through in the next few paragraphs. Finally, in Table 3, we are reminded that the same Scikit-learn transformer, SimpleImputer(), can perform all imputation techniques just by adjusting the strategy and the fill_value parameters. Thus, giving us the freedom of performing a GridSearch of imputation techniques, as shown for example in the code implementation in Scikit-learn’s documentation. To compare the implementation of both libraries, we will first carry out median imputation followed by imputation by the most frequent category. For median imputation, which is only applicable to numerical variables, the Feature-engine library offers the MeanMedianImputer(), and Scikit-learn offers the SimpleImputer(). During implementation, Feature-engine’s MeanMedianImputer() automatically selects all numerical variables in the training data set, leaving out the categorical variables, whereas Scikit-learn’s SimpleImputer() transforms all variables in the data set and raises an error if there are categorical variables during the execution. Therefore, the SimpleImputer() may require an additional step for defining the specific set of numerical variables within the training data as compared to MeanMedianImputer(). The SimpleImputer() class also supports imputing categorical data represented as string values or pandas categorical, using the ‘most_frequent’ or ‘constant’ strategy. However, when using either of these imputation strategies, the transformation is automatically applied to both numerical and categorical variables, although they are almost exclusively intended to be used on categorical variables. In those cases, the numerical variables are re-cast as objects, which may not be ideal for our workflow. Feature-engine has a separate CategoricalImputer() transformer, which automatically selects the categorical variables for imputation if they are not specifically declared. In the next few sections, we will be covering a few of the categorical encoding techniques and walkthroughs. The 2 walkthroughs below will demonstrate median imputation of numerical variables. For the demonstrations, we use the house prices data set from Kaggle. In the walkthrough below, we can see the implementation of the MeanMedianImputer() using the median as the imputation method on predicting variables on both the test and train datasets. Mean imputation can be implemented similarly by simply replacing “median” with “mean” for imputation_method. import pandas as pdfrom sklearn.model_selection import train_test_splitfrom feature_engine.imputation import MeanMedianImputer # Load datasetdata = pd.read_csv('houseprice.csv') # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['Id', 'SalePrice'], axis=1), data['SalePrice'], test_size=0.3, random_state=0 ) # set up the imputermedian_imputer = MeanMedianImputer( imputation_method='median', variables=['LotFrontage', 'MasVnrArea'] ) # fit the imputermedian_imputer.fit(X_train) # transform the datatrain_t= median_imputer.transform(X_train)test_t= median_imputer.transform(X_test) Feature-engine returns the original dataframe, where only the applicable variables were modified. For more details visit the MeanMedianImputer() documentation. Similar to Feature-engine’s MeanMedianImputer(), the mean imputation method can also be used by specifying it in the strategy parameter within the SimpleImputer() class. import pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.impute import SimpleImputer # Load datasetdata = pd.read_csv('houseprice.csv') # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['Id', 'SalePrice'], axis=1), data['SalePrice'], test_size=0.3, random_state=0 ) # Set up the imputermedian_imputer = SimpleImputer(strategy='median') # fit the imputermedian_imputer.fit(X_train[['LotFrontage', 'MasVnrArea']]) # transform the dataX_train_t = median_imputer.transform( X_train[['LotFrontage', 'MasVnrArea']] )X_test_t = median_imputer.transform( X_test[['LotFrontage', 'MasVnrArea']] ) As we can see above, Scikit-learn requires that we slice the dataframe before or as we pass it onto the imputation function, whereas this step was not required for its Feature-engine counterpart. The return is a NumPy array with only the sliced data, which in this case is only the 2 numerical variables. This method applies to categorical variables and replaces missing data with the most frequent category (i.e., the mode), identified in the variables in the training set. The walkthroughs below will demonstrate the most frequent category imputation. The CategoricalImputer() replaces missing data in categorical variables by its mode if we set the imputation_method parameter to ‘frequent’. A list of variables can be declared, as is done below; otherwise, the imputer will automatically select all categorical variables in the training data set. import pandas as pdfrom sklearn.model_selection import train_test_splitfrom feature_engine.imputation import CategoricalImputer # Load datasetdata = pd.read_csv('houseprice.csv') # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['Id', 'SalePrice'], axis=1), data['SalePrice'], test_size=0.3, random_state=0 ) # set up the imputerimputer = CategoricalImputer( imputation_method=’frequent’, variables=['Alley', 'MasVnrType'] ) # fit the imputerimputer.fit(X_train) # transform the datatrain_t= imputer.transform(X_train)test_t= imputer.transform(X_test) We obtain a dataframe without missing data in the 2 indicated variables. The SimpleImputer() class is also used for frequent category imputation by using “most_frequent” as the imputation strategy. The categorical variables must, however, be explicitly declared in this case since the SimpleImputer()’s “most_frequent” imputation strategy will apply to both numerical and categorical variables if left unspecified. import pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.impute import SimpleImputer # Load datasetdata = pd.read_csv('houseprice.csv') # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['Id', 'SalePrice'], axis=1), data['SalePrice'], test_size=0.3, random_state=0 ) # set up the imputermode_imputer = SimpleImputer(strategy='most_frequent') # fit the imputermode_imputer.fit(X_train[['Alley', 'MasVnrType']]) # transform the dataX_train= mode_imputer.transform( X_train[['Alley', 'MasVnrType']] )X_test= mode_imputer.transform( X_test[['Alley', 'MasVnrType']] ) The output in this case is a Numpy array with 2 columns. We could instead assign the result to the original dataframe to replace the original column values. Machine learning models require input data in a numerical format, which necessitates categorically labelled variables to be converted to numerical values. The method of encoding we choose is completely data context and business problem driven; how we represent and engineer these features could have a major impact on the performance of the model. Scikit-learn, Feature-engine and Category encoders offer a wide range of categorical label encoders. All three offer the commonly used encoders such as One Hot Encoding and Ordinal Encoding, one that we will be demonstrating below. Feature-engine and Category encoders also offer target-based encoding methods such as target mean encoding and weight of evidence encoding. Feature-engine maintains its advantage of automatically detecting categorical variables that neither Scikit-learn nor Category encoders are capable of; albeit we could manually define the variables in the transformers for Category encoders, as well as in Feature-engine. Overall, Category encoders appear to be the front runner in this field of categorical encoding, offering the widest arsenal of encoding techniques. They were originally derived from a host of scientific publications, developed almost exclusively for categorical data encoding. Supporting both NumPy arrays and pandas dataframes input formats, the Category encoders transformers are fully compatible Scikit-learn functionality and can be used in pipelines in your existing scripts. In addition to the more commonly implemented encoders mentioned above, Category encoders also offer some special use-case encoders including Backward Difference, Helmert, Polynomial and Sum Coding, as well as a handful selection of experimental encoders such as LeaveOneOut, Binary and BaseN. In the following paragraphs, we will compare the implementation of Ordinal encoding among the 3 Python open source libraries. Also referred to as Label Encoding, Ordinal Encoding numerically labels the categories into the number of unique classes. For example, for a categorical variable with n number of unique categories, Ordinal Encoding will replace the categories by numerical digits from 0 to n-1. The inherent characteristic of Ordinal Encoding is that it assumes there is a relationship (some kind of order or hierarchy) between each of the unique classes. Given that Sickit-learn, Feature-engine, and Category encoders all offer ordinal encoding implementation — let’s review some of those demonstrations below. Feature-engine’s OrdinalEncoder() works only with categorical variables, where a list of variables can be indicated, or the encoder will automatically select all categorical variables in the train set. It replaces the categories by numbers, starting from 0 to n-1, where n is the number of different categories. If we select “arbitrary” as the encoding method, then the encoder will assign numbers in the sequence that the labels appear in the variable (i.e. first-come first-served). If “ordered” is selected, the encoder will assign numbers following the mean of the target value for that label. The labels for which the mean of the target is higher will get assigned the number 0, and those where the mean of the target is smallest will be assigned n-1. import pandas as pdfrom sklearn.model_selection import train_test_splitfrom feature_engine.encoding import OrdinalEncoder # Load datasetdef load_titanic(): data = pd.read_csv( 'https://www.openml.org/data/get_csv/16826755/phpMYEkMl' ) data = data.replace('?', np.nan) data['cabin'] = data['cabin'].astype(str).str[0] data['pclass'] = data['pclass'].astype('O') data['embarked'].fillna('C', inplace=True) return data data = load_titanic() # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['survived', 'name', 'ticket'], axis=1), data['survived'], test_size=0.3, random_state=0 ) # set up the encoderencoder = OrdinalEncoder( encoding_method='arbitrary', variables=['pclass', 'cabin', 'embarked'] ) # fit the encoderencoder.fit(X_train, y_train) # transform the datatrain_t= encoder.transform(X_train)test_t= encoder.transform(X_test) The output of the precedent code block returns the original pandas dataframe where the selected categorical variables were transformed. Scitkit-learn’s OrdinalEncoder() requires the input to be sliced for the categorical variables. During the encoding process, the numbers are simply assigned per the alphabetical order of the labels. import pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import OrdinalEncoder # Load datasetdef load_titanic(): data = pd.read_csv( 'https://www.openml.org/data/get_csv/16826755/phpMYEkMl' ) data = data.replace('?', np.nan) data['cabin'] = data['cabin'].astype(str).str[0] data['pclass'] = data['pclass'].astype('O') data['embarked'].fillna('C', inplace=True) return data data = load_titanic() # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['survived', 'name', 'ticket'], axis=1), data['survived'], test_size=0.3, random_state=0 )# set up the encoderencoder = OrdinalEncoder() # fit the encoderencoder.fit( X_train[['pclass', 'cabin', 'embarked']], y_train ) # transform the datatrain_t= encoder.transform( X_train[['pclass', 'cabin', 'embarked']] )test_t= encoder.transform( X_test[['pclass', 'cabin', 'embarked']] ) The output of the precedent code block is a NumPy array with (only) 3 columns. Category encoders’ OrdinalEncoder() allows us to specify the variables/columns as a parameter. An optional mapping dictionary can be passed as well, in cases where we have the knowledge that there is some true order to the classes themselves. Otherwise, the classes are assumed to have no true order and the numbers are assigned to the labels at random. import pandas as pdfrom sklearn.model_selection import train_test_splitfrom category_encoders.ordinal import OrdinalEncoder # Load datasetdef load_titanic(): data = pd.read_csv( 'https://www.openml.org/data/get_csv/16826755/phpMYEkMl' ) data = data.replace('?', np.nan) data['cabin'] = data['cabin'].astype(str).str[0] data['pclass'] = data['pclass'].astype('O') data['embarked'].fillna('C', inplace=True) return data data = load_titanic() # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['survived', 'name', 'ticket'], axis=1), data['survived'], test_size=0.3, random_state=0 ) # set up the encoderencoder = OrdinalEncoder(cols=['pclass', 'cabin', 'embarked']) # fit the encoderencoder.fit(X_train, y_train) # transform the datatrain_t= encoder.transform(X_train)test_t= encoder.transform(X_test) We transform numerical variables with various mathematical transformation functions e.g., logarithmic, power and reciprocal, with a general aim of obtaining a more “Gaussian”, or “Normal” looking distribution of the original variable(s). Scikit-learn offers the FunctionTransformer() which, in principle, can apply any function desired and defined by the user. It takes the function as an argument, either as a NumPy method, or as a lambda function. Through transformers such as LogTransformer() and ReciprocalTransformer(), Feature-engine, instead, supports mathematical transformations with individual specific transformers. When it comes to “automatic” transformations, both Scikit-learn and Feature-engine packages support Yeo-Johnson and Box Cox transformations. While Scikit-learn centralizes the transformations within the PowerTransformer() just by changing the ‘method’ argument, Feature-engine has 2 individual Yeo-Johnson and Box Cox transformers. The usual differences between the two libraries, as we discussed in earlier sections, translates onto transformations as well. Feature-engine outputs a pandas dataframe and automatically selects numerical variables or allows us to declare selected variables, while Scikit-learn applies the transformation to the entire dataframe and returns a NumPy array. Feature-engine returns an error if a transformation is not mathematically possible, for example log(0), or reciprocal of 0, while Scikit-learn will introduce NaNs instead, necessitating you to do a rationality check afterwards. In the next couple of paragraphs, we will compare the implementation of the logarithmic and BoxCox transformations between the packages. For the demonstrations, we use the house prices data set from Kaggle. Feature-engine’s LogTransformer() applies the natural logarithm or the base 10 logarithm to numerical variables. It only works with numerical non-negative values. If the variable contains a 0 or a negative value, the transformer will return an error. As with all Feature-engine’s transformer, this one also allows to select the variables to transform: A list of variables can be passed as an argument, or alternatively, the transformer will automatically select and transform all numerical variables. import pandas as pdfrom sklearn.model_selection import train_test_splitfrom feature_engine.transformation import LogTransformer # Load datasetdata = data = pd.read_csv('houseprice.csv') # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['Id', 'SalePrice'], axis=1), data['SalePrice'], test_size=0.3, random_state=0 ) # set up the variable transformertf = LogTransformer(variables = ['LotArea', 'GrLivArea']) # fit the transformertf.fit(X_train) # transform the datatrain_t = tf.transform(X_train)test_t = tf.transform(X_test) Scikit-learn applies the logarithmic transformation through its FunctionTransformer() by passing the logarithmic function as a NumPy method into the transformer, as shown below. import pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import FunctionTransformer # Load datasetdata = data = pd.read_csv('houseprice.csv') # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['Id', 'SalePrice'], axis=1), data['SalePrice'], test_size=0.3, random_state=0 ) # set up the variable transformertf = FunctionTransformer(np.log) # fit the transformertf.fit(X_train[['LotArea', 'GrLivArea']]) # transform the datatrain_t = tf.transform(X_train[['LotArea', 'GrLivArea']])test_t = tf.transform(X_test[['LotArea', 'GrLivArea']]) The Box Cox transformation is a method of transforming non-normal variables into a normal distribution shape, using a shift, or transformation parameter λ, to find out the best transformation. Normality is an important assumption for many statistical techniques; and if your data isn’t normally distributed, applying a Box Cox transformation allows you to run a broader number of tests. The BoxCoxTransformer() applies the Box Cox transformation to numerical variables and works only with non-negative variables. Similar to the other Feature-engine variable transformers, a list of variables can be passed as an argument, or it will automatically select and transform all numerical variables. import pandas as pdfrom sklearn.model_selection import train_test_splitfrom feature_engine.transformation import BoxCoxTransformer # Load datasetdata = data = pd.read_csv('houseprice.csv') # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['Id', 'SalePrice'], axis=1), data['SalePrice'], test_size=0.3, random_state=0 ) # set up the variable transformertf = BoxCoxTransformer(variables = ['LotArea', 'GrLivArea']) # fit the transformertf.fit(X_train) # transform the datatrain_t = tf.transform(X_train)test_t = tf.transform(X_test) The transformation implemented by this transformer is that of scipy.stats.boxcox and returned as a pandas dataframe. Scikit-learn offers both Box Cox and Yeo-Johnson transformation through its PowerTransformer(). Box Cox requires the input data to be strictly positive values. import pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import PowerTransformer # Load datasetdata = data = pd.read_csv('houseprice.csv') # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['Id', 'SalePrice'], axis=1), data['SalePrice'], test_size=0.3, random_state=0 ) # set up the variable transformertf = PowerTransformer(method=”box-cox”) # fit the transformertf.fit(X_train[['LotArea', 'GrLivArea']]) # transform the datatrain_t = tf.transform(X_train[['LotArea', 'GrLivArea']])test_t = tf.transform(X_test[['LotArea', 'GrLivArea']]) The optimal parameter for stabilizing variance and minimizing the skewness is estimated through maximum likelihood. As with all Scikit-learn transformers, the results are returned as a NumPy array. Discretization converts, or partitions, continuous numerical variables into discrete variables of contiguous intervals, or bins, that span across the full range of the variable values. Discretization is often implemented to improve the signal to noise ratio for a given variable and reduce the effects of outliers. The differences in output type and variable selection methods between the two packages, as we discussed earlier, remain valid for this transformation as well. One of the major differences between Scikit-learn and Feature-engine’s discretization offerings lies in the fact that Scikit-learn offers KBinsDiscretizer() as a centralized transformer through which we can do equal-width, equal-frequency, and k-means discretization allowing us to optimize the model through grid search of all techniques. Wherein with Feature-engine, we would need to do this manually given that they are offered as separate transformers — EqualFrequencyDiscretiser() and EqualWidthDiscretiser(). Additionally, Scikit-learn allows us to one hot encode the bins straightaway from the transformer, just by setting up the encoding parameter. For Feature-engine, if we wish to treat the bins as categories, we would need to set “return_object=True”, and then we can run any of the categorical encoders at the back end of the discretization transformer. In the following paragraphs, we will compare the implementation of equal frequency discretization between the packages. This type of discretization bins variables into a predefined number of contiguous intervals. The bin intervals are normally the percentiles. EqualFrequencyDiscretiser() sorts the numerical variable values into contiguous intervals of equal proportion of observations, where the interval limits are calculated according to the quantiles. This number of intervals, i.e., the number of quantiles in which the variable should be divided, is determined by the user. The transformer can return the variable as either numeric or object (default being numeric). Inherent to Feature-engine, a list of variables can be indicated, or the discretizer will automatically select all numerical variables in the train set. import pandas as pdfrom sklearn.model_selection import train_test_splitfrom feature_engine.discretisation import EqualFrequencyDiscretiser # Load datasetdata = data = pd.read_csv('houseprice.csv') # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['Id', 'SalePrice'], axis=1), data['SalePrice'], test_size=0.3, random_state=0 ) # set up the discretisation transformerdisc = EqualFrequencyDiscretiser( q=10, variables=['LotArea', 'GrLivArea'] ) # fit the transformerdisc.fit(X_train) # transform the datatrain_t = disc.transform(X_train)test_t = disc.transform(X_test) The EqualFrequencyDiscretiser() first finds the boundaries for the intervals or quantiles for each variable as it fits the data. Then it transforms the variables, by sorting the values into the intervals and returns the pandas dataframe. The Scikit-learn package can implement equal frequency discretization through its KBinsDiscretizer() transformer by setting the “strategy” parameter to “quantiles”. import pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import KBinsDiscretizer # Load datasetdata = data = pd.read_csv('houseprice.csv') # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['Id', 'SalePrice'], axis=1), data['SalePrice'], test_size=0.3, random_state=0 ) # set up the discretisation transformerdisc = KBinsDiscretizer(n_bins=10, strategy='quantile') # fit the transformerdisc.fit(X_train[['LotArea', 'GrLivArea']]) # transform the datatrain_t = disc.transform(X_train[['LotArea', 'GrLivArea']])test_t = disc.transform(X_test[['LotArea', 'GrLivArea']]) By default, the NumPy array output is one-hot encoded into a sparse matrix. This can be further configured, such as setting to an ordinal encoding method instead, with the “encode” parameter. Machine learning algorithms are sensitive to the range and distribution of variable data points where outliers, or anomalies, can deceive the model training process. They can often be the result of measurement/experimental errors or exceptional system conditions and therefore do not relay the statistical characteristic of the underlying system. Therefore, we must treat and manage outliers, by either capping them at maximum or minimum values or by removing them altogether, if using algorithms that are sensitive to them. Feature-engine exclusively offers outlier handling abilities through Winsorizer() by capping or censoring at maximum or minimum values of a variable at an arbitrary or derived value, and through OutlierTrimmer() by removing the outliers altogether from the data set. It can do so based on Gaussian approximation, the inter-quartile range proximity rule, or percentiles. Alongside the usual go-to library for most Natural Language Processing (NLP) needs — Natural Language Toolkit (NLTK), Scikit-learn also hosts a selected range of a few straightforward feature engineering vectorizers for NLP applications. This includes the TF-IDF vectorizer, HashingVectorizer(), as well as the Bags of Words vectorizer implemented through CountVectorizer(), each of which comes with stop word removal capabilities, adding to the versatility that Scikit-learn brings to feature engineering. For relational and transaction data, where there could be multiple transaction records for each specific entry, usually accompanied by a timestamp, Featuretools offers an exclusive robust framework geared towards automatic feature engineering. Featuretools uses Deep Feature Synthesis (DFS) to carefully select relevant data and engineer features automatically at the transaction level, with the ability the add a cut-off time for each time period and adding a secondary time index. We sure have covered a lot of ground in this article and hopefully were able to put forth a valuable comparison of all the major open source Python libraries for feature engineering. Once you get your hands dirty and try them out as well, you will have a much greater appreciation of the little nuances and advantages each of the packages brings to your pipeline. Featuretools, Category encoders, Scikit-learn, and Feature-engine — each of these libraries will help you streamline your data preparation pipelines in their own way. Feature engineering is an essential component in end-to-end data science and machine learning pipelines. It is meant to be an iterative process that every data scientist should master in order to optimize model performance — even simpler ones. It is a computationally expensive and time-consuming portion of your pipeline, and gaining those little efficiencies by knowing the advantages and edges of each package will definitely stack up through your workflow. Feature-engine: Python library for feature engineering Preprocessing data with Scikit-learn Feature Engineering for Machine Learning — Online Course Python Feature Engineering Cookbook — Book
[ { "code": null, "e": 393, "s": 172, "text": "According to a survey by Forbes, data scientists and machine learning engineers spend around 60% of their time preparing data for analysis and machine learning. A large chunk of that time is spent on feature engineering." }, { "code": null, "e": 705, "s": 393, "text": "Feature engineering is the process of taking a data set and constructing explanatory variables, or predictor features, that are then passed onto the prediction model to train a machine learning algorithm. It is a crucial step in all machine learning models, but can often be challenging and very time consuming." }, { "code": null, "e": 916, "s": 705, "text": "Feature engineering involves aspects such as imputing missing values, encoding categorical variables, transforming and discretizing numerical variables, removing or censoring outliers and scaling, among others." }, { "code": null, "e": 1524, "s": 916, "text": "In the last few years, a growing number of open source Python libraries that support feature engineering techniques have started to emerge. Among these, the Featuretools library supports an exhaustive array of functions to work with transaction data and time series; the Category encoders library supports a comprehensive selection of methods to encode categorical variables; and the Scikit-learn and Feature-engine libraries support a wide range of transformations including imputation, categorical encoding, discretization, mathematical transformations and more (see Table 1 below for a snapshot summary)." }, { "code": null, "e": 1730, "s": 1524, "text": "In the following sections of this blog post, we will cover brief practical code implementations and comparisons of some of the commonly available open-source feature engineering Python packages, including:" }, { "code": null, "e": 1743, "s": 1730, "text": "Scikit-learn" }, { "code": null, "e": 1758, "s": 1743, "text": "Feature-engine" }, { "code": null, "e": 1776, "s": 1758, "text": "Category Encoders" }, { "code": null, "e": 1947, "s": 1776, "text": "For more in depth knowledge and additional code recipes check out the course “Feature Engineering for Machine Learning” or the book “Python Feature Engineering Cookbook”." }, { "code": null, "e": 2547, "s": 1947, "text": "Many, if not most, feature engineering techniques learn parameters from the data. For example, to impute data with the mean, we derive the value from the training set. To encode categorical variables, we define mappings of strings to numbers from the training data as well. Among the mathematical transformations for example, the transformation of BoxCox also needs to learn the optimal exponent to transform data from the train set. As a result, open source Python packages need to have the functionality to first learn and store these parameters, and then retrieve them to transform incoming data." }, { "code": null, "e": 2974, "s": 2547, "text": "For this exact reason, in this blog, we will be focusing on Scikit-learn, Feature-engine and Category encoders, all of which have this functionality. We will not be discussing libraries such as pandas, which, while containing intrinsic methods to, say, impute missing data ( fillna() ), or map ( map() ) a variable value to some other value, does not contain the functionality to learn and perpetuate the necessary parameters." }, { "code": null, "e": 3516, "s": 2974, "text": "Scikit-learn, Feature-engine and Category encoders share the fit() and transform() functionality to learn parameters from data, and then transform the variables. The transformers from these libraries, that is, the ‘classes’ in technical terms, can all store the learned parameters within their attributes. Yet, there are some nuances and subtleties that are different across these packages in terms of i) their output, ii) whether they operate on the entire dataframe or on a slice, and iii) if they allow grid search of engineering methods." }, { "code": null, "e": 3904, "s": 3516, "text": "Feature engineering is performed ahead of training machine learning models. Often, we want to understand how these transformations affect the variable characteristics and their relationships with each other. Pandas is a great tool for data analysis and visualization, and thus, libraries that return pandas dataframes instead of NumPy arrays are inherently more data analysis “friendly”." }, { "code": null, "e": 4382, "s": 3904, "text": "Feature-engine and Category encoders return pandas dataframes, while Scikit-learn returns NumPy arrays instead. NumPy arrays are optimized for machine learning, as the library is generally more computationally efficient but are less suited for data visualization. The difference in data output type between the packages means that we may need to add another line of code or two to convert between the NumPy arrays and Pandas dataframes before inserting back into your workflow." }, { "code": null, "e": 4457, "s": 4382, "text": "Table 2 below summarizes these key differences between the three packages." }, { "code": null, "e": 5030, "s": 4457, "text": "Feature engineering techniques are usually applied to different variable subsets. For example, we would only impute variables that contain missing data, and not necessarily the entire data set. Also, there are imputation techniques more suited to numerical variables and those more suited to categorical variables. Similarly, we may also want to discretize a group of variables while transform mathematically another. Thus, the ability to select variables within the feature engineering transformer, or class, allows for an easier flow of the feature engineering pipeline." }, { "code": null, "e": 5610, "s": 5030, "text": "Feature-engine and Category encoders allow us to select which variables to transform within the transformer. On the other hand, Scikit-learn transformers will operate over the entire data set (Table 2); meaning we need to slice the dataframe into categorical and numerical or into the variable subgroups to which we will apply each technique before using Scikit-learn transformers, which we can do manually using pandas, or with help of Scikit-learn’s ColumnTransformer or Feature-engine’s SklearnWrapper. The beauty of using the latter, is that the output is a pandas dataframe!" }, { "code": null, "e": 5922, "s": 5610, "text": "Sometimes, we may wonder which transformation technique returns the most predictive variable. For example, should we do equal-width or equal-frequency discretization? Should we impute with the mean, median or an arbitrary number? Should we transform with the logarithm or maybe some other mathematical function?" }, { "code": null, "e": 6535, "s": 5922, "text": "Most Scikit-learn transformers are centralized, meaning that one transformer, or class, can carry out different transformations. For example, we can apply 3 discretization techniques by simply changing the parameters of the KBinsDiscretizer() class from Scikit-learn, whereas, Feature-engine presents 3 different transformers for discretization. The same holds true for imputation; by changing the parameters of SimpleImputer(), we can perform different imputation techniques with Scikit-learn, whereas Feature-engine has several transformers, each of which can perform at most 2 different imputation variations." }, { "code": null, "e": 6942, "s": 6535, "text": "This adds additional versatility to Scikit-learn transformers through allowing for GridSearch, giving itself an edge on the jack-of-all-trades time sensitive kind of applications such as Data Science competitions and hackathons. On the other hand, Feature-engine transformers offer a more general use-case, oriented more towards mainstream industry usage where their applications are much more streamlined." }, { "code": null, "e": 7180, "s": 6942, "text": "Through the rest of the blog, we will compare the implementation of missing data imputation, categorical encoding, mathematical transformation and discretization among Scikit-learn, Feature-engine and Category encoders whenever possible." }, { "code": null, "e": 7735, "s": 7180, "text": "Imputation is the process of replacing missing data in a column, or variable, with a probable value estimated by other available information in the data set, typically within the same variable. There are multiple missing data imputation techniques available, each of which serve different purposes. If you want to learn more about these techniques, their advantages and limitations and when we should use them, check out the course “Feature engineering for Machine Learning”. Here, we will compare their implementation with current open source libraries." }, { "code": null, "e": 8094, "s": 7735, "text": "Scikit-learn and Feature-engine offer a variety of transformers for data imputation for numerical and categorical variables. Each of these libraries come with their own subtle differences in implementation and output. We will be doing walkthroughs of a few of the imputation methods in the next few paragraphs and discussing a few of those differences below." }, { "code": null, "e": 8501, "s": 8094, "text": "As we discussed in the previous section, in terms of the output, Feature-engine returns the imputed data sets as pandas dataframes while Scikit-learn returns NumPy arrays. Now, depending on the stage of your data pre-processing workflow and your personal preferences, you could be dealing with either NumPy arrays or pandas dataframes, requiring you to add a line of code or two to convert between the two." }, { "code": null, "e": 8628, "s": 8501, "text": "Table 3 below summarizes the techniques supported by each package and the main takeaways of their advantages and shortcomings." }, { "code": null, "e": 8704, "s": 8628, "text": "Both libraries contain functionality for most common imputation techniques." }, { "code": null, "e": 8832, "s": 8704, "text": "Feature-engine can additionally do while Scikit-learn offers Multivariate imputation of chained equations in its functionality." }, { "code": null, "e": 9030, "s": 8832, "text": "As we mentioned previously, Feature-engine allows us to select the variables that we want to impute within each transformer, whereas Scikit-learn transformers will impute over the entire dataframe." }, { "code": null, "e": 9437, "s": 9030, "text": "Feature-engine transformers can also automatically identify between numerical and categorical, depending on the imputation technique we would like to apply. That way, we will not end up inadvertently adding a string when we impute numerical variables, or a number to categorical ones. The method for selecting the variables will become clearer when we demonstrate a walk-through in the next few paragraphs." }, { "code": null, "e": 9793, "s": 9437, "text": "Finally, in Table 3, we are reminded that the same Scikit-learn transformer, SimpleImputer(), can perform all imputation techniques just by adjusting the strategy and the fill_value parameters. Thus, giving us the freedom of performing a GridSearch of imputation techniques, as shown for example in the code implementation in Scikit-learn’s documentation." }, { "code": null, "e": 10114, "s": 9793, "text": "To compare the implementation of both libraries, we will first carry out median imputation followed by imputation by the most frequent category. For median imputation, which is only applicable to numerical variables, the Feature-engine library offers the MeanMedianImputer(), and Scikit-learn offers the SimpleImputer()." }, { "code": null, "e": 10618, "s": 10114, "text": "During implementation, Feature-engine’s MeanMedianImputer() automatically selects all numerical variables in the training data set, leaving out the categorical variables, whereas Scikit-learn’s SimpleImputer() transforms all variables in the data set and raises an error if there are categorical variables during the execution. Therefore, the SimpleImputer() may require an additional step for defining the specific set of numerical variables within the training data as compared to MeanMedianImputer()." }, { "code": null, "e": 11294, "s": 10618, "text": "The SimpleImputer() class also supports imputing categorical data represented as string values or pandas categorical, using the ‘most_frequent’ or ‘constant’ strategy. However, when using either of these imputation strategies, the transformation is automatically applied to both numerical and categorical variables, although they are almost exclusively intended to be used on categorical variables. In those cases, the numerical variables are re-cast as objects, which may not be ideal for our workflow. Feature-engine has a separate CategoricalImputer() transformer, which automatically selects the categorical variables for imputation if they are not specifically declared." }, { "code": null, "e": 11403, "s": 11294, "text": "In the next few sections, we will be covering a few of the categorical encoding techniques and walkthroughs." }, { "code": null, "e": 11557, "s": 11403, "text": "The 2 walkthroughs below will demonstrate median imputation of numerical variables. For the demonstrations, we use the house prices data set from Kaggle." }, { "code": null, "e": 11852, "s": 11557, "text": "In the walkthrough below, we can see the implementation of the MeanMedianImputer() using the median as the imputation method on predicting variables on both the test and train datasets. Mean imputation can be implemented similarly by simply replacing “median” with “mean” for imputation_method." }, { "code": null, "e": 12507, "s": 11852, "text": "import pandas as pdfrom sklearn.model_selection import train_test_splitfrom feature_engine.imputation import MeanMedianImputer # Load datasetdata = pd.read_csv('houseprice.csv') # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['Id', 'SalePrice'], axis=1), data['SalePrice'], test_size=0.3, random_state=0 ) # set up the imputermedian_imputer = MeanMedianImputer( imputation_method='median', variables=['LotFrontage', 'MasVnrArea'] ) # fit the imputermedian_imputer.fit(X_train) # transform the datatrain_t= median_imputer.transform(X_train)test_t= median_imputer.transform(X_test)" }, { "code": null, "e": 12667, "s": 12507, "text": "Feature-engine returns the original dataframe, where only the applicable variables were modified. For more details visit the MeanMedianImputer() documentation." }, { "code": null, "e": 12837, "s": 12667, "text": "Similar to Feature-engine’s MeanMedianImputer(), the mean imputation method can also be used by specifying it in the strategy parameter within the SimpleImputer() class." }, { "code": null, "e": 13527, "s": 12837, "text": "import pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.impute import SimpleImputer # Load datasetdata = pd.read_csv('houseprice.csv') # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['Id', 'SalePrice'], axis=1), data['SalePrice'], test_size=0.3, random_state=0 ) # Set up the imputermedian_imputer = SimpleImputer(strategy='median') # fit the imputermedian_imputer.fit(X_train[['LotFrontage', 'MasVnrArea']]) # transform the dataX_train_t = median_imputer.transform( X_train[['LotFrontage', 'MasVnrArea']] )X_test_t = median_imputer.transform( X_test[['LotFrontage', 'MasVnrArea']] )" }, { "code": null, "e": 13832, "s": 13527, "text": "As we can see above, Scikit-learn requires that we slice the dataframe before or as we pass it onto the imputation function, whereas this step was not required for its Feature-engine counterpart. The return is a NumPy array with only the sliced data, which in this case is only the 2 numerical variables." }, { "code": null, "e": 14081, "s": 13832, "text": "This method applies to categorical variables and replaces missing data with the most frequent category (i.e., the mode), identified in the variables in the training set. The walkthroughs below will demonstrate the most frequent category imputation." }, { "code": null, "e": 14378, "s": 14081, "text": "The CategoricalImputer() replaces missing data in categorical variables by its mode if we set the imputation_method parameter to ‘frequent’. A list of variables can be declared, as is done below; otherwise, the imputer will automatically select all categorical variables in the training data set." }, { "code": null, "e": 15003, "s": 14378, "text": "import pandas as pdfrom sklearn.model_selection import train_test_splitfrom feature_engine.imputation import CategoricalImputer # Load datasetdata = pd.read_csv('houseprice.csv') # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['Id', 'SalePrice'], axis=1), data['SalePrice'], test_size=0.3, random_state=0 ) # set up the imputerimputer = CategoricalImputer( imputation_method=’frequent’, variables=['Alley', 'MasVnrType'] ) # fit the imputerimputer.fit(X_train) # transform the datatrain_t= imputer.transform(X_train)test_t= imputer.transform(X_test)" }, { "code": null, "e": 15076, "s": 15003, "text": "We obtain a dataframe without missing data in the 2 indicated variables." }, { "code": null, "e": 15418, "s": 15076, "text": "The SimpleImputer() class is also used for frequent category imputation by using “most_frequent” as the imputation strategy. The categorical variables must, however, be explicitly declared in this case since the SimpleImputer()’s “most_frequent” imputation strategy will apply to both numerical and categorical variables if left unspecified." }, { "code": null, "e": 16083, "s": 15418, "text": "import pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.impute import SimpleImputer # Load datasetdata = pd.read_csv('houseprice.csv') # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['Id', 'SalePrice'], axis=1), data['SalePrice'], test_size=0.3, random_state=0 ) # set up the imputermode_imputer = SimpleImputer(strategy='most_frequent') # fit the imputermode_imputer.fit(X_train[['Alley', 'MasVnrType']]) # transform the dataX_train= mode_imputer.transform( X_train[['Alley', 'MasVnrType']] )X_test= mode_imputer.transform( X_test[['Alley', 'MasVnrType']] )" }, { "code": null, "e": 16240, "s": 16083, "text": "The output in this case is a Numpy array with 2 columns. We could instead assign the result to the original dataframe to replace the original column values." }, { "code": null, "e": 16588, "s": 16240, "text": "Machine learning models require input data in a numerical format, which necessitates categorically labelled variables to be converted to numerical values. The method of encoding we choose is completely data context and business problem driven; how we represent and engineer these features could have a major impact on the performance of the model." }, { "code": null, "e": 16960, "s": 16588, "text": "Scikit-learn, Feature-engine and Category encoders offer a wide range of categorical label encoders. All three offer the commonly used encoders such as One Hot Encoding and Ordinal Encoding, one that we will be demonstrating below. Feature-engine and Category encoders also offer target-based encoding methods such as target mean encoding and weight of evidence encoding." }, { "code": null, "e": 17231, "s": 16960, "text": "Feature-engine maintains its advantage of automatically detecting categorical variables that neither Scikit-learn nor Category encoders are capable of; albeit we could manually define the variables in the transformers for Category encoders, as well as in Feature-engine." }, { "code": null, "e": 17508, "s": 17231, "text": "Overall, Category encoders appear to be the front runner in this field of categorical encoding, offering the widest arsenal of encoding techniques. They were originally derived from a host of scientific publications, developed almost exclusively for categorical data encoding." }, { "code": null, "e": 18005, "s": 17508, "text": "Supporting both NumPy arrays and pandas dataframes input formats, the Category encoders transformers are fully compatible Scikit-learn functionality and can be used in pipelines in your existing scripts. In addition to the more commonly implemented encoders mentioned above, Category encoders also offer some special use-case encoders including Backward Difference, Helmert, Polynomial and Sum Coding, as well as a handful selection of experimental encoders such as LeaveOneOut, Binary and BaseN." }, { "code": null, "e": 18131, "s": 18005, "text": "In the following paragraphs, we will compare the implementation of Ordinal encoding among the 3 Python open source libraries." }, { "code": null, "e": 18409, "s": 18131, "text": "Also referred to as Label Encoding, Ordinal Encoding numerically labels the categories into the number of unique classes. For example, for a categorical variable with n number of unique categories, Ordinal Encoding will replace the categories by numerical digits from 0 to n-1." }, { "code": null, "e": 18726, "s": 18409, "text": "The inherent characteristic of Ordinal Encoding is that it assumes there is a relationship (some kind of order or hierarchy) between each of the unique classes. Given that Sickit-learn, Feature-engine, and Category encoders all offer ordinal encoding implementation — let’s review some of those demonstrations below." }, { "code": null, "e": 18928, "s": 18726, "text": "Feature-engine’s OrdinalEncoder() works only with categorical variables, where a list of variables can be indicated, or the encoder will automatically select all categorical variables in the train set." }, { "code": null, "e": 19483, "s": 18928, "text": "It replaces the categories by numbers, starting from 0 to n-1, where n is the number of different categories. If we select “arbitrary” as the encoding method, then the encoder will assign numbers in the sequence that the labels appear in the variable (i.e. first-come first-served). If “ordered” is selected, the encoder will assign numbers following the mean of the target value for that label. The labels for which the mean of the target is higher will get assigned the number 0, and those where the mean of the target is smallest will be assigned n-1." }, { "code": null, "e": 20418, "s": 19483, "text": "import pandas as pdfrom sklearn.model_selection import train_test_splitfrom feature_engine.encoding import OrdinalEncoder # Load datasetdef load_titanic(): data = pd.read_csv( 'https://www.openml.org/data/get_csv/16826755/phpMYEkMl' ) data = data.replace('?', np.nan) data['cabin'] = data['cabin'].astype(str).str[0] data['pclass'] = data['pclass'].astype('O') data['embarked'].fillna('C', inplace=True) return data data = load_titanic() # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['survived', 'name', 'ticket'], axis=1), data['survived'], test_size=0.3, random_state=0 ) # set up the encoderencoder = OrdinalEncoder( encoding_method='arbitrary', variables=['pclass', 'cabin', 'embarked'] ) # fit the encoderencoder.fit(X_train, y_train) # transform the datatrain_t= encoder.transform(X_train)test_t= encoder.transform(X_test)" }, { "code": null, "e": 20554, "s": 20418, "text": "The output of the precedent code block returns the original pandas dataframe where the selected categorical variables were transformed." }, { "code": null, "e": 20753, "s": 20554, "text": "Scitkit-learn’s OrdinalEncoder() requires the input to be sliced for the categorical variables. During the encoding process, the numbers are simply assigned per the alphabetical order of the labels." }, { "code": null, "e": 21730, "s": 20753, "text": "import pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import OrdinalEncoder # Load datasetdef load_titanic(): data = pd.read_csv( 'https://www.openml.org/data/get_csv/16826755/phpMYEkMl' ) data = data.replace('?', np.nan) data['cabin'] = data['cabin'].astype(str).str[0] data['pclass'] = data['pclass'].astype('O') data['embarked'].fillna('C', inplace=True) return data data = load_titanic() # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['survived', 'name', 'ticket'], axis=1), data['survived'], test_size=0.3, random_state=0 )# set up the encoderencoder = OrdinalEncoder() # fit the encoderencoder.fit( X_train[['pclass', 'cabin', 'embarked']], y_train ) # transform the datatrain_t= encoder.transform( X_train[['pclass', 'cabin', 'embarked']] )test_t= encoder.transform( X_test[['pclass', 'cabin', 'embarked']] )" }, { "code": null, "e": 21809, "s": 21730, "text": "The output of the precedent code block is a NumPy array with (only) 3 columns." }, { "code": null, "e": 22163, "s": 21809, "text": "Category encoders’ OrdinalEncoder() allows us to specify the variables/columns as a parameter. An optional mapping dictionary can be passed as well, in cases where we have the knowledge that there is some true order to the classes themselves. Otherwise, the classes are assumed to have no true order and the numbers are assigned to the labels at random." }, { "code": null, "e": 23055, "s": 22163, "text": "import pandas as pdfrom sklearn.model_selection import train_test_splitfrom category_encoders.ordinal import OrdinalEncoder # Load datasetdef load_titanic(): data = pd.read_csv( 'https://www.openml.org/data/get_csv/16826755/phpMYEkMl' ) data = data.replace('?', np.nan) data['cabin'] = data['cabin'].astype(str).str[0] data['pclass'] = data['pclass'].astype('O') data['embarked'].fillna('C', inplace=True) return data data = load_titanic() # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['survived', 'name', 'ticket'], axis=1), data['survived'], test_size=0.3, random_state=0 ) # set up the encoderencoder = OrdinalEncoder(cols=['pclass', 'cabin', 'embarked']) # fit the encoderencoder.fit(X_train, y_train) # transform the datatrain_t= encoder.transform(X_train)test_t= encoder.transform(X_test)" }, { "code": null, "e": 23293, "s": 23055, "text": "We transform numerical variables with various mathematical transformation functions e.g., logarithmic, power and reciprocal, with a general aim of obtaining a more “Gaussian”, or “Normal” looking distribution of the original variable(s)." }, { "code": null, "e": 23682, "s": 23293, "text": "Scikit-learn offers the FunctionTransformer() which, in principle, can apply any function desired and defined by the user. It takes the function as an argument, either as a NumPy method, or as a lambda function. Through transformers such as LogTransformer() and ReciprocalTransformer(), Feature-engine, instead, supports mathematical transformations with individual specific transformers." }, { "code": null, "e": 24014, "s": 23682, "text": "When it comes to “automatic” transformations, both Scikit-learn and Feature-engine packages support Yeo-Johnson and Box Cox transformations. While Scikit-learn centralizes the transformations within the PowerTransformer() just by changing the ‘method’ argument, Feature-engine has 2 individual Yeo-Johnson and Box Cox transformers." }, { "code": null, "e": 24370, "s": 24014, "text": "The usual differences between the two libraries, as we discussed in earlier sections, translates onto transformations as well. Feature-engine outputs a pandas dataframe and automatically selects numerical variables or allows us to declare selected variables, while Scikit-learn applies the transformation to the entire dataframe and returns a NumPy array." }, { "code": null, "e": 24598, "s": 24370, "text": "Feature-engine returns an error if a transformation is not mathematically possible, for example log(0), or reciprocal of 0, while Scikit-learn will introduce NaNs instead, necessitating you to do a rationality check afterwards." }, { "code": null, "e": 24805, "s": 24598, "text": "In the next couple of paragraphs, we will compare the implementation of the logarithmic and BoxCox transformations between the packages. For the demonstrations, we use the house prices data set from Kaggle." }, { "code": null, "e": 25056, "s": 24805, "text": "Feature-engine’s LogTransformer() applies the natural logarithm or the base 10 logarithm to numerical variables. It only works with numerical non-negative values. If the variable contains a 0 or a negative value, the transformer will return an error." }, { "code": null, "e": 25306, "s": 25056, "text": "As with all Feature-engine’s transformer, this one also allows to select the variables to transform: A list of variables can be passed as an argument, or alternatively, the transformer will automatically select and transform all numerical variables." }, { "code": null, "e": 25895, "s": 25306, "text": "import pandas as pdfrom sklearn.model_selection import train_test_splitfrom feature_engine.transformation import LogTransformer # Load datasetdata = data = pd.read_csv('houseprice.csv') # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['Id', 'SalePrice'], axis=1), data['SalePrice'], test_size=0.3, random_state=0 ) # set up the variable transformertf = LogTransformer(variables = ['LotArea', 'GrLivArea']) # fit the transformertf.fit(X_train) # transform the datatrain_t = tf.transform(X_train)test_t = tf.transform(X_test)" }, { "code": null, "e": 26073, "s": 25895, "text": "Scikit-learn applies the logarithmic transformation through its FunctionTransformer() by passing the logarithmic function as a NumPy method into the transformer, as shown below." }, { "code": null, "e": 26712, "s": 26073, "text": "import pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import FunctionTransformer # Load datasetdata = data = pd.read_csv('houseprice.csv') # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['Id', 'SalePrice'], axis=1), data['SalePrice'], test_size=0.3, random_state=0 ) # set up the variable transformertf = FunctionTransformer(np.log) # fit the transformertf.fit(X_train[['LotArea', 'GrLivArea']]) # transform the datatrain_t = tf.transform(X_train[['LotArea', 'GrLivArea']])test_t = tf.transform(X_test[['LotArea', 'GrLivArea']])" }, { "code": null, "e": 27099, "s": 26712, "text": "The Box Cox transformation is a method of transforming non-normal variables into a normal distribution shape, using a shift, or transformation parameter λ, to find out the best transformation. Normality is an important assumption for many statistical techniques; and if your data isn’t normally distributed, applying a Box Cox transformation allows you to run a broader number of tests." }, { "code": null, "e": 27405, "s": 27099, "text": "The BoxCoxTransformer() applies the Box Cox transformation to numerical variables and works only with non-negative variables. Similar to the other Feature-engine variable transformers, a list of variables can be passed as an argument, or it will automatically select and transform all numerical variables." }, { "code": null, "e": 28000, "s": 27405, "text": "import pandas as pdfrom sklearn.model_selection import train_test_splitfrom feature_engine.transformation import BoxCoxTransformer # Load datasetdata = data = pd.read_csv('houseprice.csv') # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['Id', 'SalePrice'], axis=1), data['SalePrice'], test_size=0.3, random_state=0 ) # set up the variable transformertf = BoxCoxTransformer(variables = ['LotArea', 'GrLivArea']) # fit the transformertf.fit(X_train) # transform the datatrain_t = tf.transform(X_train)test_t = tf.transform(X_test)" }, { "code": null, "e": 28117, "s": 28000, "text": "The transformation implemented by this transformer is that of scipy.stats.boxcox and returned as a pandas dataframe." }, { "code": null, "e": 28277, "s": 28117, "text": "Scikit-learn offers both Box Cox and Yeo-Johnson transformation through its PowerTransformer(). Box Cox requires the input data to be strictly positive values." }, { "code": null, "e": 28920, "s": 28277, "text": "import pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import PowerTransformer # Load datasetdata = data = pd.read_csv('houseprice.csv') # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['Id', 'SalePrice'], axis=1), data['SalePrice'], test_size=0.3, random_state=0 ) # set up the variable transformertf = PowerTransformer(method=”box-cox”) # fit the transformertf.fit(X_train[['LotArea', 'GrLivArea']]) # transform the datatrain_t = tf.transform(X_train[['LotArea', 'GrLivArea']])test_t = tf.transform(X_test[['LotArea', 'GrLivArea']])" }, { "code": null, "e": 29118, "s": 28920, "text": "The optimal parameter for stabilizing variance and minimizing the skewness is estimated through maximum likelihood. As with all Scikit-learn transformers, the results are returned as a NumPy array." }, { "code": null, "e": 29433, "s": 29118, "text": "Discretization converts, or partitions, continuous numerical variables into discrete variables of contiguous intervals, or bins, that span across the full range of the variable values. Discretization is often implemented to improve the signal to noise ratio for a given variable and reduce the effects of outliers." }, { "code": null, "e": 29592, "s": 29433, "text": "The differences in output type and variable selection methods between the two packages, as we discussed earlier, remain valid for this transformation as well." }, { "code": null, "e": 30107, "s": 29592, "text": "One of the major differences between Scikit-learn and Feature-engine’s discretization offerings lies in the fact that Scikit-learn offers KBinsDiscretizer() as a centralized transformer through which we can do equal-width, equal-frequency, and k-means discretization allowing us to optimize the model through grid search of all techniques. Wherein with Feature-engine, we would need to do this manually given that they are offered as separate transformers — EqualFrequencyDiscretiser() and EqualWidthDiscretiser()." }, { "code": null, "e": 30459, "s": 30107, "text": "Additionally, Scikit-learn allows us to one hot encode the bins straightaway from the transformer, just by setting up the encoding parameter. For Feature-engine, if we wish to treat the bins as categories, we would need to set “return_object=True”, and then we can run any of the categorical encoders at the back end of the discretization transformer." }, { "code": null, "e": 30579, "s": 30459, "text": "In the following paragraphs, we will compare the implementation of equal frequency discretization between the packages." }, { "code": null, "e": 30720, "s": 30579, "text": "This type of discretization bins variables into a predefined number of contiguous intervals. The bin intervals are normally the percentiles." }, { "code": null, "e": 30916, "s": 30720, "text": "EqualFrequencyDiscretiser() sorts the numerical variable values into contiguous intervals of equal proportion of observations, where the interval limits are calculated according to the quantiles." }, { "code": null, "e": 31133, "s": 30916, "text": "This number of intervals, i.e., the number of quantiles in which the variable should be divided, is determined by the user. The transformer can return the variable as either numeric or object (default being numeric)." }, { "code": null, "e": 31286, "s": 31133, "text": "Inherent to Feature-engine, a list of variables can be indicated, or the discretizer will automatically select all numerical variables in the train set." }, { "code": null, "e": 31926, "s": 31286, "text": "import pandas as pdfrom sklearn.model_selection import train_test_splitfrom feature_engine.discretisation import EqualFrequencyDiscretiser # Load datasetdata = data = pd.read_csv('houseprice.csv') # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['Id', 'SalePrice'], axis=1), data['SalePrice'], test_size=0.3, random_state=0 ) # set up the discretisation transformerdisc = EqualFrequencyDiscretiser( q=10, variables=['LotArea', 'GrLivArea'] ) # fit the transformerdisc.fit(X_train) # transform the datatrain_t = disc.transform(X_train)test_t = disc.transform(X_test)" }, { "code": null, "e": 32164, "s": 31926, "text": "The EqualFrequencyDiscretiser() first finds the boundaries for the intervals or quantiles for each variable as it fits the data. Then it transforms the variables, by sorting the values into the intervals and returns the pandas dataframe." }, { "code": null, "e": 32329, "s": 32164, "text": "The Scikit-learn package can implement equal frequency discretization through its KBinsDiscretizer() transformer by setting the “strategy” parameter to “quantiles”." }, { "code": null, "e": 33000, "s": 32329, "text": "import pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import KBinsDiscretizer # Load datasetdata = data = pd.read_csv('houseprice.csv') # Separate into train and test setsX_train, X_test, y_train, y_test = train_test_split( data.drop(['Id', 'SalePrice'], axis=1), data['SalePrice'], test_size=0.3, random_state=0 ) # set up the discretisation transformerdisc = KBinsDiscretizer(n_bins=10, strategy='quantile') # fit the transformerdisc.fit(X_train[['LotArea', 'GrLivArea']]) # transform the datatrain_t = disc.transform(X_train[['LotArea', 'GrLivArea']])test_t = disc.transform(X_test[['LotArea', 'GrLivArea']])" }, { "code": null, "e": 33192, "s": 33000, "text": "By default, the NumPy array output is one-hot encoded into a sparse matrix. This can be further configured, such as setting to an ordinal encoding method instead, with the “encode” parameter." }, { "code": null, "e": 33717, "s": 33192, "text": "Machine learning algorithms are sensitive to the range and distribution of variable data points where outliers, or anomalies, can deceive the model training process. They can often be the result of measurement/experimental errors or exceptional system conditions and therefore do not relay the statistical characteristic of the underlying system. Therefore, we must treat and manage outliers, by either capping them at maximum or minimum values or by removing them altogether, if using algorithms that are sensitive to them." }, { "code": null, "e": 34087, "s": 33717, "text": "Feature-engine exclusively offers outlier handling abilities through Winsorizer() by capping or censoring at maximum or minimum values of a variable at an arbitrary or derived value, and through OutlierTrimmer() by removing the outliers altogether from the data set. It can do so based on Gaussian approximation, the inter-quartile range proximity rule, or percentiles." }, { "code": null, "e": 34594, "s": 34087, "text": "Alongside the usual go-to library for most Natural Language Processing (NLP) needs — Natural Language Toolkit (NLTK), Scikit-learn also hosts a selected range of a few straightforward feature engineering vectorizers for NLP applications. This includes the TF-IDF vectorizer, HashingVectorizer(), as well as the Bags of Words vectorizer implemented through CountVectorizer(), each of which comes with stop word removal capabilities, adding to the versatility that Scikit-learn brings to feature engineering." }, { "code": null, "e": 34838, "s": 34594, "text": "For relational and transaction data, where there could be multiple transaction records for each specific entry, usually accompanied by a timestamp, Featuretools offers an exclusive robust framework geared towards automatic feature engineering." }, { "code": null, "e": 35077, "s": 34838, "text": "Featuretools uses Deep Feature Synthesis (DFS) to carefully select relevant data and engineer features automatically at the transaction level, with the ability the add a cut-off time for each time period and adding a secondary time index." }, { "code": null, "e": 35441, "s": 35077, "text": "We sure have covered a lot of ground in this article and hopefully were able to put forth a valuable comparison of all the major open source Python libraries for feature engineering. Once you get your hands dirty and try them out as well, you will have a much greater appreciation of the little nuances and advantages each of the packages brings to your pipeline." }, { "code": null, "e": 35608, "s": 35441, "text": "Featuretools, Category encoders, Scikit-learn, and Feature-engine — each of these libraries will help you streamline your data preparation pipelines in their own way." }, { "code": null, "e": 36069, "s": 35608, "text": "Feature engineering is an essential component in end-to-end data science and machine learning pipelines. It is meant to be an iterative process that every data scientist should master in order to optimize model performance — even simpler ones. It is a computationally expensive and time-consuming portion of your pipeline, and gaining those little efficiencies by knowing the advantages and edges of each package will definitely stack up through your workflow." }, { "code": null, "e": 36124, "s": 36069, "text": "Feature-engine: Python library for feature engineering" }, { "code": null, "e": 36161, "s": 36124, "text": "Preprocessing data with Scikit-learn" }, { "code": null, "e": 36218, "s": 36161, "text": "Feature Engineering for Machine Learning — Online Course" } ]
Microsoft Expression Web - Webpage Layout
In this chapter, we will be covering the basic layout of your webpages. Before creating our webpage layout, we need to think about our content and then design how we want to present that content, as it is the content that will be visible on our website. It is up to us how we present our content so that our viewers find our site and then stay to check it out. The layout will probably include the company logo or banner at the top, the navigation menu, a content area that may include multiple columns, and footer at the bottom of the page. Previously, developers used tables to achieve this look. Tables created group of boxes that were used to create rows and columns. Now, web designers use <div>s to form the boxes and CSS to place those boxes on the page. Following are some of the features of <div> tag. The <div> tag defines a division or a section in an HTML document and makes it easy to manage, style, and manipulate those divisions or sections. The <div> tag defines a division or a section in an HTML document and makes it easy to manage, style, and manipulate those divisions or sections. It is used to group block elements to format them with CSS. It is used to group block elements to format them with CSS. Browsers usually place a line break before and after the div element. Browsers usually place a line break before and after the div element. The <div> tag is a block-level element. The <div> tag is a block-level element. The <div> tag can contain almost any other element. The <div> tag can contain almost any other element. The <div> tag cannot be inside a <p> tag. The <div> tag cannot be inside a <p> tag. Let’s take a look at a simple example in which we will be using <div> </div> tags to create the various boxes and style rules. Step 1 − Open Expression Web and then the index.html page that we created in the previous chapter. Step 2 − As seen in the above screenshot, the Code View is highlighted by default. You can work in Code View or Design View, but you can also see the Split View which will open both Code View and Design View. So let’s select the Split View option. Step 3 − The body element defines the document's body. To style the <body> tag, we need to create a new style. First select the body tag in Design View and then click the New Style... in Apply Styles panel, which will open the New Style dialog. Here, you can define the different options for your style. Step 4 − The first step is to select the body from the Selector dropdown list and then select the Existing style sheet from “Define in” the dropdown list. From the URL, select the CSS file we have created in the previous chapter. On the left side, there is a Category list such as Font, Background, etc. and the current Font is highlighted. Set the Font-related information as per your requirements as shown in the above screenshot. Step 5 − Select the Background color you want. You can also select the image for your background by using the browser button. Once you are done with the Background, define your Borders if you want. Step 6 − Let’s select the double line option for the border and choose the width and color also from the dropdown lists. Once you are done with the style, then click Ok. Step 7 − Now you can see in the design view that the background color is changed to what we have selected. If you open the sample.css file, you will see that all the information is automatically stored in the CSS file. Step 8 − Go to the index.html page again and drag the <div> from the 'Toolbox' panel and drop it on your open page. Step 9 − Above the code view, you will see <body> and <div> tags, click the <div> tag and then in Apply Styles panel click on the New Style.... which will open the New Style dialog. Type “#container” in the Selector field. The hash mark # is an ID selector. From the “Define in” dropdown list, select the Existing style sheet and check the “Apply new style to document selection” option. Go to the Background category. Step 10 − Select the background color, let’s select white color and then go to the Box category. Step 11 − Define padding and margin and then go to the Position category Step 12 − Set the width to 90%. However, don’t specify the height as here we want that the container should expand when we enter the content. Click the OK button. Similarly, let’s add styles for Header, top navigation, left navigation, main content, and footer. Following is the code in sample.css style-sheet after adding all the above-mentioned styles. body { font-family: Calibri; font-size: medium; font-weight: normal; font-style: normal; font-variant: normal; text-transform: none; color: #0000FF; background-color: #CCFFFF; background-image: none; border: medium double #FF0000; } #container { background-color: #FFFFFF; padding: 8px; margin: 8px; width: 90%; } #header { background-color: #54B431; background-repeat: no-repeat; background-position: right center; height: 170px; } #top-nav { height: 50px; border-top: solid medium #006600; border-bottom: solid medium #006600; background-color: #FFFFFF; } #left-nav { margin: 20px 0px 10px 0px; width: 180px; float: left; border: thin dashed #006600; } #main-content { margin: 20px 10px 10px 200px; background-color: #CCFFCC; } #footer { border-top: 2px solid #006600; clear: both; padding: 10px 0px; text-align: center; } Following is the code in index.html file after adding all the <div> tags. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <meta content = "text/html; charset = utf-8" http-equiv = "Content-Type" /> <style type = "text/css"></style> <link href = "sample.css" rel = "stylesheet" type = "text/css" /> </head> <body> <div id = "container"> <div id = "header"></div> <div id = "top-nav"></div> <div id = "left-nav"></div> <div id = "main-content"></div> <div id = "footer"></div> </div> </body> </html> Your page layout in the design view will look as shown in the following screenshot. 16 Lectures 11.5 hours SHIVPRASAD KOIRALA 33 Lectures 3 hours Abhishek And Pukhraj 33 Lectures 5.5 hours Abhishek And Pukhraj 40 Lectures 6.5 hours Syed Raza 15 Lectures 2 hours Harshit Srivastava, Pranjal Srivastava 18 Lectures 1.5 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2450, "s": 2196, "text": "In this chapter, we will be covering the basic layout of your webpages. Before creating our webpage layout, we need to think about our content and then design how we want to present that content, as it is the content that will be visible on our website." }, { "code": null, "e": 2738, "s": 2450, "text": "It is up to us how we present our content so that our viewers find our site and then stay to check it out. The layout will probably include the company logo or banner at the top, the navigation menu, a content area that may include multiple columns, and footer at the bottom of the page." }, { "code": null, "e": 2958, "s": 2738, "text": "Previously, developers used tables to achieve this look. Tables created group of boxes that were used to create rows and columns. Now, web designers use <div>s to form the boxes and CSS to place those boxes on the page." }, { "code": null, "e": 3007, "s": 2958, "text": "Following are some of the features of <div> tag." }, { "code": null, "e": 3153, "s": 3007, "text": "The <div> tag defines a division or a section in an HTML document and makes it easy to manage, style, and manipulate those divisions or sections." }, { "code": null, "e": 3299, "s": 3153, "text": "The <div> tag defines a division or a section in an HTML document and makes it easy to manage, style, and manipulate those divisions or sections." }, { "code": null, "e": 3359, "s": 3299, "text": "It is used to group block elements to format them with CSS." }, { "code": null, "e": 3419, "s": 3359, "text": "It is used to group block elements to format them with CSS." }, { "code": null, "e": 3489, "s": 3419, "text": "Browsers usually place a line break before and after the div element." }, { "code": null, "e": 3559, "s": 3489, "text": "Browsers usually place a line break before and after the div element." }, { "code": null, "e": 3599, "s": 3559, "text": "The <div> tag is a block-level element." }, { "code": null, "e": 3639, "s": 3599, "text": "The <div> tag is a block-level element." }, { "code": null, "e": 3691, "s": 3639, "text": "The <div> tag can contain almost any other element." }, { "code": null, "e": 3743, "s": 3691, "text": "The <div> tag can contain almost any other element." }, { "code": null, "e": 3785, "s": 3743, "text": "The <div> tag cannot be inside a <p> tag." }, { "code": null, "e": 3827, "s": 3785, "text": "The <div> tag cannot be inside a <p> tag." }, { "code": null, "e": 3954, "s": 3827, "text": "Let’s take a look at a simple example in which we will be using <div> </div> tags to create the various boxes and style rules." }, { "code": null, "e": 4053, "s": 3954, "text": "Step 1 − Open Expression Web and then the index.html page that we created in the previous chapter." }, { "code": null, "e": 4301, "s": 4053, "text": "Step 2 − As seen in the above screenshot, the Code View is highlighted by default. You can work in Code View or Design View, but you can also see the Split View which will open both Code View and Design View. So let’s select the Split View option." }, { "code": null, "e": 4605, "s": 4301, "text": "Step 3 − The body element defines the document's body. To style the <body> tag, we need to create a new style. First select the body tag in Design View and then click the New Style... in Apply Styles panel, which will open the New Style dialog. Here, you can define the different options for your style." }, { "code": null, "e": 4835, "s": 4605, "text": "Step 4 − The first step is to select the body from the Selector dropdown list and then select the Existing style sheet from “Define in” the dropdown list. From the URL, select the CSS file we have created in the previous chapter." }, { "code": null, "e": 5038, "s": 4835, "text": "On the left side, there is a Category list such as Font, Background, etc. and the current Font is highlighted. Set the Font-related information as per your requirements as shown in the above screenshot." }, { "code": null, "e": 5236, "s": 5038, "text": "Step 5 − Select the Background color you want. You can also select the image for your background by using the browser button. Once you are done with the Background, define your Borders if you want." }, { "code": null, "e": 5406, "s": 5236, "text": "Step 6 − Let’s select the double line option for the border and choose the width and color also from the dropdown lists. Once you are done with the style, then click Ok." }, { "code": null, "e": 5625, "s": 5406, "text": "Step 7 − Now you can see in the design view that the background color is changed to what we have selected. If you open the sample.css file, you will see that all the information is automatically stored in the CSS file." }, { "code": null, "e": 5741, "s": 5625, "text": "Step 8 − Go to the index.html page again and drag the <div> from the 'Toolbox' panel and drop it on your open page." }, { "code": null, "e": 5923, "s": 5741, "text": "Step 9 − Above the code view, you will see <body> and <div> tags, click the <div> tag and then in Apply Styles panel click on the New Style.... which will open the New Style dialog." }, { "code": null, "e": 6160, "s": 5923, "text": "Type “#container” in the Selector field. The hash mark # is an ID selector. From the “Define in” dropdown list, select the Existing style sheet and check the “Apply new style to document selection” option. Go to the Background category." }, { "code": null, "e": 6257, "s": 6160, "text": "Step 10 − Select the background color, let’s select white color and then go to the Box category." }, { "code": null, "e": 6330, "s": 6257, "text": "Step 11 − Define padding and margin and then go to the Position category" }, { "code": null, "e": 6493, "s": 6330, "text": "Step 12 − Set the width to 90%. However, don’t specify the height as here we want that the container should expand when we enter the content. Click the OK button." }, { "code": null, "e": 6592, "s": 6493, "text": "Similarly, let’s add styles for Header, top navigation, left navigation, main content, and footer." }, { "code": null, "e": 6685, "s": 6592, "text": "Following is the code in sample.css style-sheet after adding all the above-mentioned styles." }, { "code": null, "e": 7682, "s": 6685, "text": "body { \n font-family: Calibri; \n font-size: medium; \n font-weight: normal; \n font-style: normal; \n font-variant: normal; \n text-transform: none; \n color: #0000FF; \n background-color: #CCFFFF; \n background-image: none; \n border: medium double #FF0000; \n} \n\n#container { \n background-color: #FFFFFF; \n padding: 8px; \n margin: 8px; \n width: 90%; \n} \n\n#header { \n background-color: #54B431; \n background-repeat: no-repeat; \n background-position: right center; \n height: 170px; \n} \n\n#top-nav { \n height: 50px; \n border-top: solid medium #006600; \n border-bottom: solid medium #006600; \n background-color: #FFFFFF; \n} \n\n#left-nav { \n margin: 20px 0px 10px 0px; \n width: 180px; \n float: left; \n border: thin dashed #006600; \n} \n\n#main-content { \n margin: 20px 10px 10px 200px; \n background-color: #CCFFCC; \n} \n\n#footer { \n border-top: 2px solid #006600; \n clear: both; \n padding: 10px 0px; \n text-align: center; \n} " }, { "code": null, "e": 7756, "s": 7682, "text": "Following is the code in index.html file after adding all the <div> tags." }, { "code": null, "e": 8418, "s": 7756, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> \n<html xmlns = \"http://www.w3.org/1999/xhtml\"> \n <head> \n <meta content = \"text/html; charset = utf-8\" http-equiv = \"Content-Type\" /> \n <style type = \"text/css\"></style> \n <link href = \"sample.css\" rel = \"stylesheet\" type = \"text/css\" /> \n </head> \n\n <body> \n <div id = \"container\"> \n <div id = \"header\"></div> \n <div id = \"top-nav\"></div> \n <div id = \"left-nav\"></div> \n <div id = \"main-content\"></div> \n <div id = \"footer\"></div> \n </div> \n </body> \n</html> " }, { "code": null, "e": 8502, "s": 8418, "text": "Your page layout in the design view will look as shown in the following screenshot." }, { "code": null, "e": 8538, "s": 8502, "text": "\n 16 Lectures \n 11.5 hours \n" }, { "code": null, "e": 8558, "s": 8538, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 8591, "s": 8558, "text": "\n 33 Lectures \n 3 hours \n" }, { "code": null, "e": 8613, "s": 8591, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 8648, "s": 8613, "text": "\n 33 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8670, "s": 8648, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 8705, "s": 8670, "text": "\n 40 Lectures \n 6.5 hours \n" }, { "code": null, "e": 8716, "s": 8705, "text": " Syed Raza" }, { "code": null, "e": 8749, "s": 8716, "text": "\n 15 Lectures \n 2 hours \n" }, { "code": null, "e": 8789, "s": 8749, "text": " Harshit Srivastava, Pranjal Srivastava" }, { "code": null, "e": 8824, "s": 8789, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8864, "s": 8824, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 8871, "s": 8864, "text": " Print" }, { "code": null, "e": 8882, "s": 8871, "text": " Add Notes" } ]
Airbyte — Worth the hype?. A simple example and checking its... | by Tomas Peluritis | Towards Data Science
Airbyte seems to be on the hype train at the moment. The majority of people in the data world are using it or planning to use it, so I decided to evaluate it from my point of view. I'm aware that it's processing row by row and in some parallel fashion with zero or very minimal transformations. It's pretty obvious since it's an EL tool. You can use multiple connections for sources and destinations created by the community members or Airbyte developers. You can even ask for some specific ones in the marketplace. Of course, you can contribute to the project as well since it's an open-source project! I'm not going to cover the basic setup in this post. If you wish to replicate this tutorial, you should have available: Local (or remote if you prefer) Airflow running with apache-airflow-providers-airbyte installed for Airbyte operator (and any other libraries you'll need).Postgres DB running (can be the same as Airflow backend DB)Airbyte spun up. I've used official docs.Have AWS account and created some s3 bucket and have AWS access key id and Secret Key Local (or remote if you prefer) Airflow running with apache-airflow-providers-airbyte installed for Airbyte operator (and any other libraries you'll need). Postgres DB running (can be the same as Airflow backend DB) Airbyte spun up. I've used official docs. Have AWS account and created some s3 bucket and have AWS access key id and Secret Key Let's take the famous NYC taxi data set and call it our provider data, which we can access by downloading it. To be fault-tolerant and idempotent in our data flow, we should store it in the S3 bucket and have it available no matter what application we're using. From there, we're going to leverage Airbyte and load to our Postgres DB staging schema. Or long story short, you can check out the data flow in this image below: For these operations, I'm going to leverage two operators—one to download the data and then the next one to upload it to s3. Keep in mind that my Airflow instance is running locally in a docker container. I don't want to add anything on top of my existing setup to make it a heavy behemoth, only the bare minimum things I'm adding to it. By splitting my tasks into atomical actions, I can guarantee that each step will work as it should and when I re-run it, it will return the same results. For downloading the data, I'm going to use a straightforward Bash operator that is going to execute the curl command: download = BashOperator( task_id="download_data", bash_command="""curl -o /opt/downloads/{{ macros.ds_format(ds, "%Y-%m-%d", "%Y-%m") }}.csv -L https://s3.amazonaws.com/nyc-tlc/trip+data/yellow_tripdata_{{ macros.ds_format(ds, "%Y-%m-%d", "%Y-%m") }}.csv""",) Since I'm mimicking monthly file creation, I'm using ds macro here as the file name. I think it's one of those rare cases where I prefer ds over next_ds in my flows (if you're familiar with Airflow, you know where my hate for these macros comes from, if you’re not I strongly suggest reading about macros and execution dates in Data Pipelines with Apache Airflow by Bas P. Harenslak and Julian Rutger de Ruiter, Astronomer training courses on Fundamentals and DAG authoring or check out Marc Lamberti Youtube Channel). So to load to S3, I'm going Airflow way, and I'm going to use the S3 hook to do so. Using task flow API, I've created this task: @task.pythondef upload_file_to_s3(s3_conn_id, file_name, **kwargs): s3 = S3Hook(aws_conn_id=s3_conn_id) s3.get_conn() s3.load_file(filename=file_name, bucket_name="tomasp-dwh-staging", key=file_name.split("/")[-1]) First thing first, what I like is the UI. Super clean, easy to understand, though the tool itself is pretty simple. Set up source, set up the destination. Map the flows and add a timer if you want it triggered periodically. Also, kudos for the images with Octopus (Not a Squid, but an Octopus! People in Slack channel pointed it out to me 😅 Octavia Squidington III) in the Airbyte Slack channel. For me, it’s an excellent way to do a simple onboarding to your product in an easy, non-invasive, but interactive way. So let's start the setup. You can go away and start setting up sources and destinations separately and then map them in the connections section. I'm too lazy to browse multiple tabs. Let's see if onboarding from connections will work for me right away. Again coming back to the octopus, still super lovely! Let’s get back to what I came here to do — create a new connection, as the squid says! We can already see that our intro flow here is quite simple three steps. create a source create a destination create a connection If you'd created source and destination before, you'd be able to connect them here. Otherwise, if you're using onboarding flow, you'll see something like this: So what I like is that there were many sources already, and worst case, you can ask for a new connector right from here! Also, you can check out their marketplace and request a connector there. It will open an issue in GitHub on their project. But, clicking on health status puts me on the page not found error :( No worries, it's just a wrong link. Got an answer in the slack that we should see the contents in different link. I think I sidetracked a bit here. So let's choose S3 as a source (since our yellow taxi data is residing there). And we can already see that our settings part just expanded. So fill the data with what you want. I'm going to use some of the configuration properties for the yellow taxi data. The dataset name I chose is yellow_taxi, and I'm taking only CSV files. Here I could set up multiple folders to check for data and other rules as specified in the helper text, but it didn't relate to my use case, though it's a nice and simple feature to handle multiple places where files land. I've mentioned before that we need a bucket created, and if your bucket is not public — you have to pass credentials so that Airbyte can access them. Also, the nice thing is that you can configure block size. It can give an improvement to your EL flow performance. Keep in mind that Airbyte process all information in memory before pushing to the destination! If your DB has better tips and tricks (i.e., Redshift/Postgres copy command), try to leverage them instead (or open a PR on Airbyte if you have a solution to contribute to open source!). If you've set up everything correctly, you should get no errors and be thrown to "Create a destination part." This part is a bit more straightforward in my case. Simple connection configuration to my Postgres local instance: Setting up was also a success, so we're directed to the "Set up connection" part at last! Here we can choose how often our syncs should happen: It depends on your use case, of course. In my case, I'm going to use Airflow for orchestrating the whole thing, so I'm going to choose manual here. The next part is the namespace configuration. Here we see three options Mirror source structure Destination connector settings Custom format You can read more in detail about the differences here in official Airbyte docs. In my case, I want to go for mirroring source structure. Let's create yellow_taxi as a table prefix if multiple tables are crated based on a per-connection basis. Refresh the schema! By default, it will just contain some systemic columns. Always double check if you're columns appear in the mapping part: Now let's check the sync modes available. Super happy for Incremental ones to be there: Check out more in-depth explanations about incremental append (new or changed data is processed only) and incremental deduped + history (SCD Type 1 on provided Unique key). My case is simple it's a fact table import, so Full refresh with Overwrite. The next step is Normalization and transformations. Once again, I'm reminding you that Airbyte runs in memory to process row by row. No normalization in options means that it will be stored in the end table as a JSON together with some metadata by Airbyte! My later transformations will be executed on tabular data, so I prefer to use the normalization option here. Spoilers: it uses dbt in order to normalize your data! Another thing is that we can add some transformations here in this pipeline too! From what it looks like, it will run your transformations in a docker image and push to the destination afterward! First thoughts were how it would handle private repositories, but checking in the docs, I've got all the answers and examples! This is super neat if you're data is synced periodically and not using any orchestrator. Use dbt models after the load is done—getting rid of Airflow to some extent. In my example, I'm managing flows with Airflow, so I can have it all in one DAG and have complete control over it. The only thing left — Airflow to call Airbyte when we're done moving data around. If you haven't set up an Airbyte connection Airflow, follow their official docs. Though with docker images, you might encounter some issues communicating in between. Run docker ps to get Airbyte server docker image id and then run docker inspect IMAGE_ID. Take gateway as your host in the connections part: Connection for me looked like this: The only thing that was left I need to do is to add the Airbyte part to my DAG: airbyte_s3_to_postgres = AirbyteTriggerSyncOperator(task_id='sync_airbyte_s3_to_postgres', airbyte_conn_id='local_airbyte', connection_id='902284d9-c0c3-43a7-a71f-636afd3c1b73', timeout=3600, wait_seconds=30 ) connection_id is what you see in the URL when you open your connection. Wait_seconds is poking time; how often it will check for completion. So our final flow to the staging area Airflow looks like this: While our Airflow dag is running, we can go to the Airbyte UI and check for our connection if it's running, which would signal that all is fine: So we can see that it's running like a charm! So with my docker settings: Data for 2020–11 yellow taxis data (consisting of 1508000 rows) took ~7mins to load. Data size 132M, so I would say it's a bit slow for those amounts. I think I'd need to do some tuning on some parameters inside Airbyte or my docker ones or move it out of the local docker container to a different environment. The only thing left is to check our DB and what was created inside: One table with raw table row information as a JSON: and then the yellow_taxi, which has data in tabular format. With self-service becoming a must in the data world, I'd say it's an excellent and easy tool for companies to adopt. However, I don't think it's quite mature enough (not all connectors available, early stages and they're just working on their cloud solution to attract revenue, not only from investors). I've missed some parameters passing in the operator. If data flow to the s3 bucket by some other flow, my Airflow flow wouldn't be idempotent. I might consume more files than I should! So I tried incremental load. The disclaimer is that I dropped the file from s3 before and uploaded November and December right away and triggered the flow (Incremental|Append sync mode). What happened was that I've loaded them both; since both of them were modified, they got processed🤦 . I was lucky since I had 2020–01 on my laptop, so I quickly uploaded it and triggered sync manually again. So it had the last update timestamp of files and processed only the new one. Anyway, sometimes we should have some order in place, so providing specific files to sync would also be nice. In general, it's pretty fresh, but if you're an early adopter — go for it. I see it's pretty integrated with dbt (it even created a normalized table out of JSON one using dbt): My verdict here: if you're using dbt, Airbyte will add a nice touch to your whole pipeline model even without using Airflow! If you have Airflow, it will nicely fit inside as well!
[ { "code": null, "e": 776, "s": 172, "text": "Airbyte seems to be on the hype train at the moment. The majority of people in the data world are using it or planning to use it, so I decided to evaluate it from my point of view. I'm aware that it's processing row by row and in some parallel fashion with zero or very minimal transformations. It's pretty obvious since it's an EL tool. You can use multiple connections for sources and destinations created by the community members or Airbyte developers. You can even ask for some specific ones in the marketplace. Of course, you can contribute to the project as well since it's an open-source project!" }, { "code": null, "e": 896, "s": 776, "text": "I'm not going to cover the basic setup in this post. If you wish to replicate this tutorial, you should have available:" }, { "code": null, "e": 1237, "s": 896, "text": "Local (or remote if you prefer) Airflow running with apache-airflow-providers-airbyte installed for Airbyte operator (and any other libraries you'll need).Postgres DB running (can be the same as Airflow backend DB)Airbyte spun up. I've used official docs.Have AWS account and created some s3 bucket and have AWS access key id and Secret Key" }, { "code": null, "e": 1393, "s": 1237, "text": "Local (or remote if you prefer) Airflow running with apache-airflow-providers-airbyte installed for Airbyte operator (and any other libraries you'll need)." }, { "code": null, "e": 1453, "s": 1393, "text": "Postgres DB running (can be the same as Airflow backend DB)" }, { "code": null, "e": 1495, "s": 1453, "text": "Airbyte spun up. I've used official docs." }, { "code": null, "e": 1581, "s": 1495, "text": "Have AWS account and created some s3 bucket and have AWS access key id and Secret Key" }, { "code": null, "e": 1931, "s": 1581, "text": "Let's take the famous NYC taxi data set and call it our provider data, which we can access by downloading it. To be fault-tolerant and idempotent in our data flow, we should store it in the S3 bucket and have it available no matter what application we're using. From there, we're going to leverage Airbyte and load to our Postgres DB staging schema." }, { "code": null, "e": 2005, "s": 1931, "text": "Or long story short, you can check out the data flow in this image below:" }, { "code": null, "e": 2497, "s": 2005, "text": "For these operations, I'm going to leverage two operators—one to download the data and then the next one to upload it to s3. Keep in mind that my Airflow instance is running locally in a docker container. I don't want to add anything on top of my existing setup to make it a heavy behemoth, only the bare minimum things I'm adding to it. By splitting my tasks into atomical actions, I can guarantee that each step will work as it should and when I re-run it, it will return the same results." }, { "code": null, "e": 2615, "s": 2497, "text": "For downloading the data, I'm going to use a straightforward Bash operator that is going to execute the curl command:" }, { "code": null, "e": 2881, "s": 2615, "text": "download = BashOperator( task_id=\"download_data\", bash_command=\"\"\"curl -o /opt/downloads/{{ macros.ds_format(ds, \"%Y-%m-%d\", \"%Y-%m\") }}.csv -L https://s3.amazonaws.com/nyc-tlc/trip+data/yellow_tripdata_{{ macros.ds_format(ds, \"%Y-%m-%d\", \"%Y-%m\") }}.csv\"\"\",)" }, { "code": null, "e": 3400, "s": 2881, "text": "Since I'm mimicking monthly file creation, I'm using ds macro here as the file name. I think it's one of those rare cases where I prefer ds over next_ds in my flows (if you're familiar with Airflow, you know where my hate for these macros comes from, if you’re not I strongly suggest reading about macros and execution dates in Data Pipelines with Apache Airflow by Bas P. Harenslak and Julian Rutger de Ruiter, Astronomer training courses on Fundamentals and DAG authoring or check out Marc Lamberti Youtube Channel)." }, { "code": null, "e": 3529, "s": 3400, "text": "So to load to S3, I'm going Airflow way, and I'm going to use the S3 hook to do so. Using task flow API, I've created this task:" }, { "code": null, "e": 3785, "s": 3529, "text": "@task.pythondef upload_file_to_s3(s3_conn_id, file_name, **kwargs): s3 = S3Hook(aws_conn_id=s3_conn_id) s3.get_conn() s3.load_file(filename=file_name, bucket_name=\"tomasp-dwh-staging\", key=file_name.split(\"/\")[-1])" }, { "code": null, "e": 4009, "s": 3785, "text": "First thing first, what I like is the UI. Super clean, easy to understand, though the tool itself is pretty simple. Set up source, set up the destination. Map the flows and add a timer if you want it triggered periodically." }, { "code": null, "e": 4300, "s": 4009, "text": "Also, kudos for the images with Octopus (Not a Squid, but an Octopus! People in Slack channel pointed it out to me 😅 Octavia Squidington III) in the Airbyte Slack channel. For me, it’s an excellent way to do a simple onboarding to your product in an easy, non-invasive, but interactive way." }, { "code": null, "e": 4553, "s": 4300, "text": "So let's start the setup. You can go away and start setting up sources and destinations separately and then map them in the connections section. I'm too lazy to browse multiple tabs. Let's see if onboarding from connections will work for me right away." }, { "code": null, "e": 4694, "s": 4553, "text": "Again coming back to the octopus, still super lovely! Let’s get back to what I came here to do — create a new connection, as the squid says!" }, { "code": null, "e": 4767, "s": 4694, "text": "We can already see that our intro flow here is quite simple three steps." }, { "code": null, "e": 4783, "s": 4767, "text": "create a source" }, { "code": null, "e": 4804, "s": 4783, "text": "create a destination" }, { "code": null, "e": 4824, "s": 4804, "text": "create a connection" }, { "code": null, "e": 4984, "s": 4824, "text": "If you'd created source and destination before, you'd be able to connect them here. Otherwise, if you're using onboarding flow, you'll see something like this:" }, { "code": null, "e": 5105, "s": 4984, "text": "So what I like is that there were many sources already, and worst case, you can ask for a new connector right from here!" }, { "code": null, "e": 5228, "s": 5105, "text": "Also, you can check out their marketplace and request a connector there. It will open an issue in GitHub on their project." }, { "code": null, "e": 5298, "s": 5228, "text": "But, clicking on health status puts me on the page not found error :(" }, { "code": null, "e": 5412, "s": 5298, "text": "No worries, it's just a wrong link. Got an answer in the slack that we should see the contents in different link." }, { "code": null, "e": 5998, "s": 5412, "text": "I think I sidetracked a bit here. So let's choose S3 as a source (since our yellow taxi data is residing there). And we can already see that our settings part just expanded. So fill the data with what you want. I'm going to use some of the configuration properties for the yellow taxi data. The dataset name I chose is yellow_taxi, and I'm taking only CSV files. Here I could set up multiple folders to check for data and other rules as specified in the helper text, but it didn't relate to my use case, though it's a nice and simple feature to handle multiple places where files land." }, { "code": null, "e": 6148, "s": 5998, "text": "I've mentioned before that we need a bucket created, and if your bucket is not public — you have to pass credentials so that Airbyte can access them." }, { "code": null, "e": 6263, "s": 6148, "text": "Also, the nice thing is that you can configure block size. It can give an improvement to your EL flow performance." }, { "code": null, "e": 6545, "s": 6263, "text": "Keep in mind that Airbyte process all information in memory before pushing to the destination! If your DB has better tips and tricks (i.e., Redshift/Postgres copy command), try to leverage them instead (or open a PR on Airbyte if you have a solution to contribute to open source!)." }, { "code": null, "e": 6655, "s": 6545, "text": "If you've set up everything correctly, you should get no errors and be thrown to \"Create a destination part.\"" }, { "code": null, "e": 6770, "s": 6655, "text": "This part is a bit more straightforward in my case. Simple connection configuration to my Postgres local instance:" }, { "code": null, "e": 6860, "s": 6770, "text": "Setting up was also a success, so we're directed to the \"Set up connection\" part at last!" }, { "code": null, "e": 6914, "s": 6860, "text": "Here we can choose how often our syncs should happen:" }, { "code": null, "e": 7062, "s": 6914, "text": "It depends on your use case, of course. In my case, I'm going to use Airflow for orchestrating the whole thing, so I'm going to choose manual here." }, { "code": null, "e": 7134, "s": 7062, "text": "The next part is the namespace configuration. Here we see three options" }, { "code": null, "e": 7158, "s": 7134, "text": "Mirror source structure" }, { "code": null, "e": 7189, "s": 7158, "text": "Destination connector settings" }, { "code": null, "e": 7203, "s": 7189, "text": "Custom format" }, { "code": null, "e": 7341, "s": 7203, "text": "You can read more in detail about the differences here in official Airbyte docs. In my case, I want to go for mirroring source structure." }, { "code": null, "e": 7447, "s": 7341, "text": "Let's create yellow_taxi as a table prefix if multiple tables are crated based on a per-connection basis." }, { "code": null, "e": 7589, "s": 7447, "text": "Refresh the schema! By default, it will just contain some systemic columns. Always double check if you're columns appear in the mapping part:" }, { "code": null, "e": 7677, "s": 7589, "text": "Now let's check the sync modes available. Super happy for Incremental ones to be there:" }, { "code": null, "e": 7926, "s": 7677, "text": "Check out more in-depth explanations about incremental append (new or changed data is processed only) and incremental deduped + history (SCD Type 1 on provided Unique key). My case is simple it's a fact table import, so Full refresh with Overwrite." }, { "code": null, "e": 8292, "s": 7926, "text": "The next step is Normalization and transformations. Once again, I'm reminding you that Airbyte runs in memory to process row by row. No normalization in options means that it will be stored in the end table as a JSON together with some metadata by Airbyte! My later transformations will be executed on tabular data, so I prefer to use the normalization option here." }, { "code": null, "e": 8347, "s": 8292, "text": "Spoilers: it uses dbt in order to normalize your data!" }, { "code": null, "e": 8543, "s": 8347, "text": "Another thing is that we can add some transformations here in this pipeline too! From what it looks like, it will run your transformations in a docker image and push to the destination afterward!" }, { "code": null, "e": 8836, "s": 8543, "text": "First thoughts were how it would handle private repositories, but checking in the docs, I've got all the answers and examples! This is super neat if you're data is synced periodically and not using any orchestrator. Use dbt models after the load is done—getting rid of Airflow to some extent." }, { "code": null, "e": 8951, "s": 8836, "text": "In my example, I'm managing flows with Airflow, so I can have it all in one DAG and have complete control over it." }, { "code": null, "e": 9033, "s": 8951, "text": "The only thing left — Airflow to call Airbyte when we're done moving data around." }, { "code": null, "e": 9340, "s": 9033, "text": "If you haven't set up an Airbyte connection Airflow, follow their official docs. Though with docker images, you might encounter some issues communicating in between. Run docker ps to get Airbyte server docker image id and then run docker inspect IMAGE_ID. Take gateway as your host in the connections part:" }, { "code": null, "e": 9376, "s": 9340, "text": "Connection for me looked like this:" }, { "code": null, "e": 9456, "s": 9376, "text": "The only thing that was left I need to do is to add the Airbyte part to my DAG:" }, { "code": null, "e": 9921, "s": 9456, "text": "airbyte_s3_to_postgres = AirbyteTriggerSyncOperator(task_id='sync_airbyte_s3_to_postgres', airbyte_conn_id='local_airbyte', connection_id='902284d9-c0c3-43a7-a71f-636afd3c1b73', timeout=3600, wait_seconds=30 )" }, { "code": null, "e": 10062, "s": 9921, "text": "connection_id is what you see in the URL when you open your connection. Wait_seconds is poking time; how often it will check for completion." }, { "code": null, "e": 10125, "s": 10062, "text": "So our final flow to the staging area Airflow looks like this:" }, { "code": null, "e": 10270, "s": 10125, "text": "While our Airflow dag is running, we can go to the Airbyte UI and check for our connection if it's running, which would signal that all is fine:" }, { "code": null, "e": 10344, "s": 10270, "text": "So we can see that it's running like a charm! So with my docker settings:" }, { "code": null, "e": 10655, "s": 10344, "text": "Data for 2020–11 yellow taxis data (consisting of 1508000 rows) took ~7mins to load. Data size 132M, so I would say it's a bit slow for those amounts. I think I'd need to do some tuning on some parameters inside Airbyte or my docker ones or move it out of the local docker container to a different environment." }, { "code": null, "e": 10723, "s": 10655, "text": "The only thing left is to check our DB and what was created inside:" }, { "code": null, "e": 10775, "s": 10723, "text": "One table with raw table row information as a JSON:" }, { "code": null, "e": 10835, "s": 10775, "text": "and then the yellow_taxi, which has data in tabular format." }, { "code": null, "e": 11139, "s": 10835, "text": "With self-service becoming a must in the data world, I'd say it's an excellent and easy tool for companies to adopt. However, I don't think it's quite mature enough (not all connectors available, early stages and they're just working on their cloud solution to attract revenue, not only from investors)." }, { "code": null, "e": 11324, "s": 11139, "text": "I've missed some parameters passing in the operator. If data flow to the s3 bucket by some other flow, my Airflow flow wouldn't be idempotent. I might consume more files than I should!" }, { "code": null, "e": 11906, "s": 11324, "text": "So I tried incremental load. The disclaimer is that I dropped the file from s3 before and uploaded November and December right away and triggered the flow (Incremental|Append sync mode). What happened was that I've loaded them both; since both of them were modified, they got processed🤦 . I was lucky since I had 2020–01 on my laptop, so I quickly uploaded it and triggered sync manually again. So it had the last update timestamp of files and processed only the new one. Anyway, sometimes we should have some order in place, so providing specific files to sync would also be nice." }, { "code": null, "e": 12083, "s": 11906, "text": "In general, it's pretty fresh, but if you're an early adopter — go for it. I see it's pretty integrated with dbt (it even created a normalized table out of JSON one using dbt):" } ]
How to plot a Pandas multi-index dataFrame with all xticks (Matplotlib)?
To plot a Pandas multi-index data frame with all xticks, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Create index value with 1000 smaples data. Make a one-dimensional ndarray with axis labels. Get the mean value of the series. Plot g dataframe. Set the ticks and ticklabel on the current axes To display the figure, use show() method. import numpy as np import matplotlib.pyplot as plt import pandas as pd plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True idx = pd.date_range("2020-01-01", periods=1000) val = np.random.rand(1000) s = pd.Series(val, idx) g = s.groupby([s.index.year, s.index.month]).mean() ax = g.plot() ax.set_xticks(range(len(g))) ax.set_xticklabels(["%s-%02d" % item for item in g.index.tolist()], rotation=45, ha='center') plt.show()
[ { "code": null, "e": 1153, "s": 1062, "text": "To plot a Pandas multi-index data frame with all xticks, we can take the following steps −" }, { "code": null, "e": 1229, "s": 1153, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1272, "s": 1229, "text": "Create index value with 1000 smaples data." }, { "code": null, "e": 1321, "s": 1272, "text": "Make a one-dimensional ndarray with axis labels." }, { "code": null, "e": 1355, "s": 1321, "text": "Get the mean value of the series." }, { "code": null, "e": 1373, "s": 1355, "text": "Plot g dataframe." }, { "code": null, "e": 1421, "s": 1373, "text": "Set the ticks and ticklabel on the current axes" }, { "code": null, "e": 1463, "s": 1421, "text": "To display the figure, use show() method." }, { "code": null, "e": 1925, "s": 1463, "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nidx = pd.date_range(\"2020-01-01\", periods=1000)\nval = np.random.rand(1000)\ns = pd.Series(val, idx)\n\ng = s.groupby([s.index.year, s.index.month]).mean()\n\nax = g.plot()\nax.set_xticks(range(len(g)))\nax.set_xticklabels([\"%s-%02d\" % item for item in g.index.tolist()],\nrotation=45, ha='center')\n\nplt.show()" } ]
How to achieve parallel execution in TestNG?
We can achieve parallel execution with the help of TestNG. There is a parallel attribute in TestNG which is used for this implementation. The parallel execution in TestNG is associated with another attribute called thread-count. The parallel attribute can have the values listed below − Methods. Methods. Classes. Classes. Instances Instances Tests Tests Testng xml file. <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" > <suite name = "Tutorialspoint Test" parallel ="tests" thread-count= ="5"> <test name = "Test Cycle 1"> <groups> <run> <include name = "Smoke"/> </run> </groups> <classes> <class name = "TestQA" /> </classes> </test> </suite> The execution will trigger in parallel mode for tests with the thread count of 5.
[ { "code": null, "e": 1291, "s": 1062, "text": "We can achieve parallel execution with the help of TestNG. There is a parallel attribute in TestNG which is used for this implementation. The parallel execution in TestNG is associated with another attribute called thread-count." }, { "code": null, "e": 1349, "s": 1291, "text": "The parallel attribute can have the values listed below −" }, { "code": null, "e": 1358, "s": 1349, "text": "Methods." }, { "code": null, "e": 1367, "s": 1358, "text": "Methods." }, { "code": null, "e": 1376, "s": 1367, "text": "Classes." }, { "code": null, "e": 1385, "s": 1376, "text": "Classes." }, { "code": null, "e": 1395, "s": 1385, "text": "Instances" }, { "code": null, "e": 1405, "s": 1395, "text": "Instances" }, { "code": null, "e": 1411, "s": 1405, "text": "Tests" }, { "code": null, "e": 1417, "s": 1411, "text": "Tests" }, { "code": null, "e": 1434, "s": 1417, "text": "Testng xml file." }, { "code": null, "e": 1831, "s": 1434, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE suite SYSTEM \"http://testng.org/testng-1.0.dtd\" >\n<suite name = \"Tutorialspoint Test\" parallel =\"tests\" thread-count= =\"5\">\n <test name = \"Test Cycle 1\">\n <groups>\n <run>\n <include name = \"Smoke\"/>\n </run>\n </groups>\n <classes>\n <class name = \"TestQA\" />\n </classes>\n </test>\n</suite>" }, { "code": null, "e": 1913, "s": 1831, "text": "The execution will trigger in parallel mode for tests with the thread count of 5." } ]
Count Divisors of n in O(n^1/3) - GeeksforGeeks
10 Mar, 2022 Given a number n, count all distinct divisors of it. Examples: Input : 18 Output : 6 Divisors of 18 are 1, 2, 3, 6, 9 and 18. Input : 100 Output : 9 Divisors of 100 are 1, 2, 4, 5, 10, 20, 25, 50 and 100 A Naïve Solution would be to iterate all the numbers from 1 to sqrt(n), checking if that number divides n and incrementing number of divisors. This approach takes O(sqrt(n)) time. C++ Java Python3 C# PHP Javascript // C implementation of Naive method to count all// divisors#include <bits/stdc++.h>using namespace std; // function to count the divisorsint countDivisors(int n){ int cnt = 0; for (int i = 1; i <= sqrt(n); i++) { if (n % i == 0) { // If divisors are equal, // count only one if (n / i == i) cnt++; else // Otherwise count both cnt = cnt + 2; } } return cnt;} /* Driver program to test above function */int main(){ printf("Total distinct divisors of 100 are : %d", countDivisors(100)); return 0;} // JAVA implementation of Naive method// to count all divisorsimport java.io.*;import java.math.*; class GFG { // function to count the divisors static int countDivisors(int n) { int cnt = 0; for (int i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { // If divisors are equal, // count only one if (n / i == i) cnt++; else // Otherwise count both cnt = cnt + 2; } } return cnt; } /* Driver program to test above function */ public static void main(String args[]) { System.out.println("Total distinct " + "divisors of 100 are : " + countDivisors(100)); }} /*This code is contributed by Nikita Tiwari.*/ # Python3 implementation of Naive method# to count all divisors import math # function to count the divisorsdef countDivisors(n) : cnt = 0 for i in range(1, (int)(math.sqrt(n)) + 1) : if (n % i == 0) : # If divisors are equal, # count only one if (n / i == i) : cnt = cnt + 1 else : # Otherwise count both cnt = cnt + 2 return cnt # Driver program to test above function */ print("Total distinct divisors of 100 are : ", countDivisors(100)) # This code is contributed by Nikita Tiwari. // C# implementation of Naive method// to count all divisorsusing System; class GFG { // function to count the divisors static int countDivisors(int n) { int cnt = 0; for (int i = 1; i <= Math.Sqrt(n); i++) { if (n % i == 0) { // If divisors are equal, // count only one if (n / i == i) cnt++; // Otherwise count both else cnt = cnt + 2; } } return cnt; } // Driver program public static void Main() { Console.WriteLine("Total distinct" + " divisors of 100 are : " + countDivisors(100)); }} // This code is contributed by anuj_67. <?php// PHP implementation of Naive// method to count all divisors // function to count the divisors function countDivisors($n){ $cnt = 0; for ($i = 1; $i <= sqrt($n); $i++) { if ($n % $i == 0) { // If divisors are equal, // count only one if ($n / $i == $i) $cnt++; // Otherwise count both else $cnt = $cnt + 2; } } return $cnt;} // Driver Codeecho "Total distinct divisors of 100 are : ", countDivisors(100); // This code is contributed by Ajit?> <script> // JavaScript program for the above approach // function to count the divisors function countDivisors(n) { let cnt = 0; for (let i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { // If divisors are equal, // count only one if (n / i == i) cnt++; else // Otherwise count both cnt = cnt + 2; } } return cnt; } // Driver Code document.write("Total distinct " + "divisors of 100 are : " + countDivisors(100)); // This code is contributed by susmitakundugoaldanga. </script> Output : Total distinct divisors of 100 are : 9 Optimized Solution (O(n^1/3)) For a number N, we try to find a number X ≤ ∛N i.e. X^3 ≤ N such that it divides the number, and another number Y such that N = X * Y. X consists of all the prime factor of N, which are less than ∛N and Y contains all the prime factors that are greater. Thus, they have no common factor and their HCF is 1. We iterate through the numbers 1 to ∛N, and for all primes, we check if the number divides N. If the prime is divisible, we divide it as many times as we can from the number N, so that, that specific prime factor no longer remains. We keep doing this for all prime factors less than ∛N. Therefore, the number remaining after the loop won’t have any prime factors less than ∛N. For N = p1e1 *p2e2*p3e3... where p1, p2, p3.. are the prime factors, the number of divisors is given by (e1+1) * (e2+1) * (e3+1) ... The for loop gives us the product of (e+1) for each prime factor less than ∛N. The remaining number can only have a maximum of 2 prime factors. We’ll prove this by contradiction. Assume Y = p1 * p2 * p3 where p1,p2,p3 are prime and p1,p2,p3 > ∛N [Explained above]. Since p1 >∛N and p2 > ∛N and p3 > ∛N p1*p2*p3 > ∛N*∛N*∛N => p1*p2*p3 > N. But Y is a factor of N and cannot be greater than N. Therefore, there is a contradiction, which implies that one of p1, p2, p3 must be less than ∛N. But since all primes less than ∛N have been absorbed by X, this is not possible. So, Y cannot have more than 2 prime factors. Y can therefore have: 1 prime factors if it is prime (Y) with exponent 1 1 prime factors if it is a square of a prime (sqrt(Y)), with exponent 2 2 prime factors if composite (p1, p2) with exponent 1 and 1 Therefore, we multiply: If Y is prime => (exponent of y .i.e. 1 +1) = 2 If Y is a square of prime => (exponent of sqrt(y) .i.e. 2+1) = 3 If Y is composite => (exponent of p1 +1)*(exponent of p2+1) = 2 * 2 = 4 C++ Java Python3 C# PHP Javascript // C++ program to count distinct divisors// of a given number n#include <bits/stdc++.h>using namespace std; void SieveOfEratosthenes(int n, bool prime[], bool primesquare[], int a[]){ //For more details check out: https://www.geeksforgeeks.org/sieve-of-eratosthenes/ // Create a boolean array "prime[0..n]" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // Not a prime, else true. for (int i = 2; i <= n; i++) prime[i] = true; // Create a boolean array "primesquare[0..n*n+1]" // and initialize all entries it as false. A value // in squareprime[i] will finally be true if i is // square of prime, else false. for (int i = 0; i <= (n * n + 1); i++) primesquare[i] = false; // 1 is not a prime number prime[1] = false; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p starting from p * p for (int i = p * p; i <= n; i += p) prime[i] = false; } } int j = 0; for (int p = 2; p <= n; p++) { if (prime[p]) { // Storing primes in an array a[j] = p; // Update value in primesquare[p*p], // if p is prime. primesquare[p * p] = true; j++; } }} // Function to count divisorsint countDivisors(int n){ // If number is 1, then it will have only 1 // as a factor. So, total factors will be 1. if (n == 1) return 1; bool prime[n + 1], primesquare[n * n + 1]; int a[n]; // for storing primes upto n // Calling SieveOfEratosthenes to store prime // factors of n and to store square of prime // factors of n SieveOfEratosthenes(n, prime, primesquare, a); // ans will contain total number of distinct // divisors int ans = 1; // Loop for counting factors of n for (int i = 0;; i++) { // a[i] is not less than cube root n if (a[i] * a[i] * a[i] > n) break; // Calculating power of a[i] in n. int cnt = 1; // cnt is power of prime a[i] in n. while (n % a[i] == 0) // if a[i] is a factor of n { n = n / a[i]; cnt = cnt + 1; // incrementing power } // Calculating the number of divisors // If n = a^p * b^q then total divisors of n // are (p+1)*(q+1) ans = ans * cnt; } // if a[i] is greater than cube root of n // First case if (prime[n]) ans = ans * 2; // Second case else if (primesquare[n]) ans = ans * 3; // Third case else if (n != 1) ans = ans * 4; return ans; // Total divisors} // Driver Programint main(){ cout << "Total distinct divisors of 100 are : " << countDivisors(100) << endl; return 0;} // JAVA program to count distinct// divisors of a given number nimport java.io.*; class GFG { static void SieveOfEratosthenes(int n, boolean prime[], boolean primesquare[], int a[]) { // Create a boolean array "prime[0..n]" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // Not a prime, else true. for (int i = 2; i <= n; i++) prime[i] = true; /* Create a boolean array "primesquare[0..n*n+1]" and initialize all entries it as false. A value in squareprime[i] will finally be true if i is square of prime, else false.*/ for (int i = 0; i < ((n * n) + 1); i++) primesquare[i] = false; // 1 is not a prime number prime[1] = false; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } int j = 0; for (int p = 2; p <= n; p++) { if (prime[p]) { // Storing primes in an array a[j] = p; // Update value in // primesquare[p*p], // if p is prime. primesquare[p * p] = true; j++; } } } // Function to count divisors static int countDivisors(int n) { // If number is 1, then it will // have only 1 as a factor. So, // total factors will be 1. if (n == 1) return 1; boolean prime[] = new boolean[n + 1]; boolean primesquare[] = new boolean[(n * n) + 1]; // for storing primes upto n int a[] = new int[n]; // Calling SieveOfEratosthenes to // store prime factors of n and to // store square of prime factors of n SieveOfEratosthenes(n, prime, primesquare, a); // ans will contain total number // of distinct divisors int ans = 1; // Loop for counting factors of n for (int i = 0;; i++) { // a[i] is not less than cube root n if (a[i] * a[i] * a[i] > n) break; // Calculating power of a[i] in n. // cnt is power of prime a[i] in n. int cnt = 1; // if a[i] is a factor of n while (n % a[i] == 0) { n = n / a[i]; // incrementing power cnt = cnt + 1; } // Calculating the number of divisors // If n = a^p * b^q then total // divisors of n are (p+1)*(q+1) ans = ans * cnt; } // if a[i] is greater than cube root // of n // First case if (prime[n]) ans = ans * 2; // Second case else if (primesquare[n]) ans = ans * 3; // Third case else if (n != 1) ans = ans * 4; return ans; // Total divisors } // Driver Program public static void main(String args[]) { System.out.println("Total distinct divisors" + " of 100 are : " + countDivisors(100)); }} /*This code is contributed by Nikita Tiwari*/ # Python3 program to count distinct# divisors of a given number n def SieveOfEratosthenes(n, prime,primesquare, a): # Create a boolean array "prime[0..n]" # and initialize all entries it as # true. A value in prime[i] will finally # be false if i is not a prime, else true. for i in range(2,n+1): prime[i] = True # Create a boolean array "primesquare[0..n*n+1]" # and initialize all entries it as false. # A value in squareprime[i] will finally be # true if i is square of prime, else false. for i in range((n * n + 1)+1): primesquare[i] = False # 1 is not a prime number prime[1] = False p = 2 while(p * p <= n): # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Update all multiples of p i = p * 2 while(i <= n): prime[i] = False i += p p+=1 j = 0 for p in range(2,n+1): if (prime[p]==True): # Storing primes in an array a[j] = p # Update value in primesquare[p*p], # if p is prime. primesquare[p * p] = True j+=1 # Function to count divisorsdef countDivisors(n): # If number is 1, then it will # have only 1 as a factor. So, # total factors will be 1. if (n == 1): return 1 prime = [False]*(n + 2) primesquare = [False]*(n * n + 2) # for storing primes upto n a = [0]*n # Calling SieveOfEratosthenes to # store prime factors of n and to # store square of prime factors of n SieveOfEratosthenes(n, prime, primesquare, a) # ans will contain total # number of distinct divisors ans = 1 # Loop for counting factors of n i=0 while(1): # a[i] is not less than cube root n if(a[i] * a[i] * a[i] > n): break # Calculating power of a[i] in n. cnt = 1 # cnt is power of # prime a[i] in n. while (n % a[i] == 0): # if a[i] is a factor of n n = n / a[i] cnt = cnt + 1 # incrementing power # Calculating number of divisors # If n = a^p * b^q then total # divisors of n are (p+1)*(q+1) ans = ans * cnt i+=1 # if a[i] is greater than # cube root of n n=int(n) # First case if (prime[n]==True): ans = ans * 2 # Second case else if (primesquare[n]==True): ans = ans * 3 # Third case else if (n != 1): ans = ans * 4 return ans # Total divisors # Driver Codeif __name__=='__main__': print("Total distinct divisors of 100 are :",countDivisors(100)) # This code is contributed# by mits // C# program to count distinct// divisors of a given number nusing System; class GFG { static void SieveOfEratosthenes(int n, bool[] prime, bool[] primesquare, int[] a) { // Create a boolean array "prime[0..n]" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // Not a prime, else true. for (int i = 2; i <= n; i++) prime[i] = true; /* Create a boolean array "primesquare[0..n*n+1]" and initialize all entries it as false. A value in squareprime[i] will finally be true if i is square of prime, else false.*/ for (int i = 0; i < ((n * n) + 1); i++) primesquare[i] = false; // 1 is not a prime number prime[1] = false; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } int j = 0; for (int p = 2; p <= n; p++) { if (prime[p]) { // Storing primes in an array a[j] = p; // Update value in // primesquare[p*p], // if p is prime. primesquare[p * p] = true; j++; } } } // Function to count divisors static int countDivisors(int n) { // If number is 1, then it will // have only 1 as a factor. So, // total factors will be 1. if (n == 1) return 1; bool[] prime = new bool[n + 1]; bool[] primesquare = new bool[(n * n) + 1]; // for storing primes upto n int[] a = new int[n]; // Calling SieveOfEratosthenes to // store prime factors of n and to // store square of prime factors of n SieveOfEratosthenes(n, prime, primesquare, a); // ans will contain total number // of distinct divisors int ans = 1; // Loop for counting factors of n for (int i = 0;; i++) { // a[i] is not less than cube root n if (a[i] * a[i] * a[i] > n) break; // Calculating power of a[i] in n. // cnt is power of prime a[i] in n. int cnt = 1; // if a[i] is a factor of n while (n % a[i] == 0) { n = n / a[i]; // incrementing power cnt = cnt + 1; } // Calculating the number of divisors // If n = a^p * b^q then total // divisors of n are (p+1)*(q+1) ans = ans * cnt; } // if a[i] is greater than cube root // of n // First case if (prime[n]) ans = ans * 2; // Second case else if (primesquare[n]) ans = ans * 3; // Third case else if (n != 1) ans = ans * 4; return ans; // Total divisors } // Driver Program public static void Main() { Console.Write("Total distinct divisors" + " of 100 are : " + countDivisors(100)); }} // This code is contributed by parashar. <?php// PHP program to count distinct// divisors of a given number n function SieveOfEratosthenes($n, &$prime, &$primesquare, &$a){ // Create a boolean array "prime[0..n]" // and initialize all entries it as // true. A value in prime[i] will finally // be false if i is not a prime, else true. for ($i = 2; $i <= $n; $i++) $prime[$i] = true; // Create a boolean array "primesquare[0..n*n+1]" // and initialize all entries it as false. // A value in squareprime[i] will finally be // true if i is square of prime, else false. for ($i = 0; $i <= ($n * $n + 1); $i++) $primesquare[$i] = false; // 1 is not a prime number $prime[1] = false; for ($p = 2; $p * $p <= $n; $p++) { // If prime[p] is not changed, // then it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p * 2; $i <= $n; $i += $p) $prime[$i] = false; } } $j = 0; for ($p = 2; $p <= $n; $p++) { if ($prime[$p]) { // Storing primes in an array $a[$j] = $p; // Update value in primesquare[p*p], // if p is prime. $primesquare[$p * $p] = true; $j++; } }} // Function to count divisorsfunction countDivisors($n){ // If number is 1, then it will // have only 1 as a factor. So, // total factors will be 1. if ($n == 1) return 1; $prime = array_fill(false, $n + 1, NULL); $primesquare = array_fill(false, $n * $n + 1, NULL); // for storing primes upto n $a = array_fill(0, $n, NULL); // Calling SieveOfEratosthenes to // store prime factors of n and to // store square of prime factors of n SieveOfEratosthenes($n, $prime, $primesquare, $a); // ans will contain total // number of distinct divisors $ans = 1; // Loop for counting factors of n for ($i = 0;; $i++) { // a[i] is not less than cube root n if ($a[$i] * $a[$i] * $a[$i] > $n) break; // Calculating power of a[i] in n. $cnt = 1; // cnt is power of // prime a[i] in n. while ($n % $a[$i] == 0) // if a[i] is a // factor of n { $n = $n / $a[$i]; $cnt = $cnt + 1; // incrementing power } // Calculating the number of divisors // If n = a^p * b^q then total // divisors of n are (p+1)*(q+1) $ans = $ans * $cnt; } // if a[i] is greater than // cube root of n // First case if ($prime[$n]) $ans = $ans * 2; // Second case else if ($primesquare[$n]) $ans = $ans * 3; // Third case else if ($n != 1) $ans = $ans * 4; return $ans; // Total divisors} // Driver Codeecho "Total distinct divisors of 100 are : ". countDivisors(100). "\n"; // This code is contributed// by ChitraNayal?> <script> // Javascript program to count distinct// divisors of a given number n function SieveOfEratosthenes(n, prime, primesquare, a){ // Create a boolean array "prime[0..n]" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // Not a prime, else true. for(let i = 2; i <= n; i++) prime[i] = true; // Create a boolean array "primesquare[0..n*n+1]" // and initialize all entries it as false. // A value in squareprime[i] will finally // be true if i is square of prime, // else false. for(let i = 0; i < ((n * n) + 1); i++) primesquare[i] = false; // 1 is not a prime number prime[1] = false; for(let p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for(let i = p * 2; i <= n; i += p) prime[i] = false; } } let j = 0; for(let p = 2; p <= n; p++) { if (prime[p]) { // Storing primes in an array a[j] = p; // Update value in // primesquare[p*p], // if p is prime. primesquare[p * p] = true; j++; } }} // Function to count divisorsfunction countDivisors(n){ // If number is 1, then it will // have only 1 as a factor. So, // total factors will be 1. if (n == 1) return 1; let prime = new Array(n + 1); let primesquare = new Array((n * n) + 1); // For storing primes upto n let a = new Array(n); for(let i = 0; i < n; i++) { a[i] = 0; } // Calling SieveOfEratosthenes to // store prime factors of n and to // store square of prime factors of n SieveOfEratosthenes(n, prime, primesquare, a); // ans will contain total number // of distinct divisors let ans = 1; // Loop for counting factors of n for(let i = 0;; i++) { // a[i] is not less than cube root n if (a[i] * a[i] * a[i] > n) break; // Calculating power of a[i] in n. // cnt is power of prime a[i] in n. let cnt = 1; // If a[i] is a factor of n while (n % a[i] == 0) { n = n / a[i]; // Incrementing power cnt = cnt + 1; } // Calculating the number of divisors // If n = a^p * b^q then total // divisors of n are (p+1)*(q+1) ans = ans * cnt; } // If a[i] is greater than cube root // of n // First case if (prime[n]) ans = ans * 2; // Second case else if (primesquare[n]) ans = ans * 3; // Third case else if (n != 1) ans = ans * 4; // Total divisors return ans;} // Driver Codedocument.write("Total distinct divisors" + " of 100 are : " + countDivisors(100)); // This code is contributed by avanitrachhadiya2155 </script> Output : Total distinct divisors of 100 are : 9 Time Complexity: O(n1/3) This article is contributed by Karun Anantharaman. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. parashar jit_t vt_m ukasp Mithun Kumar Apoorva_Kumar susmitakundugoaldanga avanitrachhadiya2155 karun19049 demishassabis simmytarika5 divisors Numbers sieve Mathematical Technical Scripter Mathematical Numbers sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find sum of elements in a given array Program for Decimal to Binary Conversion Program for factorial of a number Operators in C / C++ The Knight's tour problem | Backtracking-1 Find minimum number of coins that make a given value Minimum number of jumps to reach end
[ { "code": null, "e": 24726, "s": 24698, "text": "\n10 Mar, 2022" }, { "code": null, "e": 24779, "s": 24726, "text": "Given a number n, count all distinct divisors of it." }, { "code": null, "e": 24790, "s": 24779, "text": "Examples: " }, { "code": null, "e": 24932, "s": 24790, "text": "Input : 18\nOutput : 6\nDivisors of 18 are 1, 2, 3, 6, 9 and 18.\n\nInput : 100\nOutput : 9\nDivisors of 100 are 1, 2, 4, 5, 10, 20,\n25, 50 and 100" }, { "code": null, "e": 25114, "s": 24932, "text": "A Naïve Solution would be to iterate all the numbers from 1 to sqrt(n), checking if that number divides n and incrementing number of divisors. This approach takes O(sqrt(n)) time. " }, { "code": null, "e": 25118, "s": 25114, "text": "C++" }, { "code": null, "e": 25123, "s": 25118, "text": "Java" }, { "code": null, "e": 25131, "s": 25123, "text": "Python3" }, { "code": null, "e": 25134, "s": 25131, "text": "C#" }, { "code": null, "e": 25138, "s": 25134, "text": "PHP" }, { "code": null, "e": 25149, "s": 25138, "text": "Javascript" }, { "code": "// C implementation of Naive method to count all// divisors#include <bits/stdc++.h>using namespace std; // function to count the divisorsint countDivisors(int n){ int cnt = 0; for (int i = 1; i <= sqrt(n); i++) { if (n % i == 0) { // If divisors are equal, // count only one if (n / i == i) cnt++; else // Otherwise count both cnt = cnt + 2; } } return cnt;} /* Driver program to test above function */int main(){ printf(\"Total distinct divisors of 100 are : %d\", countDivisors(100)); return 0;}", "e": 25762, "s": 25149, "text": null }, { "code": "// JAVA implementation of Naive method// to count all divisorsimport java.io.*;import java.math.*; class GFG { // function to count the divisors static int countDivisors(int n) { int cnt = 0; for (int i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { // If divisors are equal, // count only one if (n / i == i) cnt++; else // Otherwise count both cnt = cnt + 2; } } return cnt; } /* Driver program to test above function */ public static void main(String args[]) { System.out.println(\"Total distinct \" + \"divisors of 100 are : \" + countDivisors(100)); }} /*This code is contributed by Nikita Tiwari.*/", "e": 26594, "s": 25762, "text": null }, { "code": "# Python3 implementation of Naive method# to count all divisors import math # function to count the divisorsdef countDivisors(n) : cnt = 0 for i in range(1, (int)(math.sqrt(n)) + 1) : if (n % i == 0) : # If divisors are equal, # count only one if (n / i == i) : cnt = cnt + 1 else : # Otherwise count both cnt = cnt + 2 return cnt # Driver program to test above function */ print(\"Total distinct divisors of 100 are : \", countDivisors(100)) # This code is contributed by Nikita Tiwari.", "e": 27209, "s": 26594, "text": null }, { "code": "// C# implementation of Naive method// to count all divisorsusing System; class GFG { // function to count the divisors static int countDivisors(int n) { int cnt = 0; for (int i = 1; i <= Math.Sqrt(n); i++) { if (n % i == 0) { // If divisors are equal, // count only one if (n / i == i) cnt++; // Otherwise count both else cnt = cnt + 2; } } return cnt; } // Driver program public static void Main() { Console.WriteLine(\"Total distinct\" + \" divisors of 100 are : \" + countDivisors(100)); }} // This code is contributed by anuj_67.", "e": 28040, "s": 27209, "text": null }, { "code": "<?php// PHP implementation of Naive// method to count all divisors // function to count the divisors function countDivisors($n){ $cnt = 0; for ($i = 1; $i <= sqrt($n); $i++) { if ($n % $i == 0) { // If divisors are equal, // count only one if ($n / $i == $i) $cnt++; // Otherwise count both else $cnt = $cnt + 2; } } return $cnt;} // Driver Codeecho \"Total distinct divisors of 100 are : \", countDivisors(100); // This code is contributed by Ajit?>", "e": 28614, "s": 28040, "text": null }, { "code": "<script> // JavaScript program for the above approach // function to count the divisors function countDivisors(n) { let cnt = 0; for (let i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { // If divisors are equal, // count only one if (n / i == i) cnt++; else // Otherwise count both cnt = cnt + 2; } } return cnt; } // Driver Code document.write(\"Total distinct \" + \"divisors of 100 are : \" + countDivisors(100)); // This code is contributed by susmitakundugoaldanga. </script>", "e": 29333, "s": 28614, "text": null }, { "code": null, "e": 29343, "s": 29333, "text": "Output : " }, { "code": null, "e": 29382, "s": 29343, "text": "Total distinct divisors of 100 are : 9" }, { "code": null, "e": 29413, "s": 29382, "text": "Optimized Solution (O(n^1/3)) " }, { "code": null, "e": 29722, "s": 29413, "text": "For a number N, we try to find a number X ≤ ∛N i.e. X^3 ≤ N such that it divides the number, and another number Y such that N = X * Y. X consists of all the prime factor of N, which are less than ∛N and Y contains all the prime factors that are greater. Thus, they have no common factor and their HCF is 1." }, { "code": null, "e": 29818, "s": 29722, "text": "We iterate through the numbers 1 to ∛N, and for all primes, we check if the number divides N. " }, { "code": null, "e": 30101, "s": 29818, "text": "If the prime is divisible, we divide it as many times as we can from the number N, so that, that specific prime factor no longer remains. We keep doing this for all prime factors less than ∛N. Therefore, the number remaining after the loop won’t have any prime factors less than ∛N." }, { "code": null, "e": 30234, "s": 30101, "text": "For N = p1e1 *p2e2*p3e3... where p1, p2, p3.. are the prime factors, the number of divisors is given by (e1+1) * (e2+1) * (e3+1) ..." }, { "code": null, "e": 30313, "s": 30234, "text": "The for loop gives us the product of (e+1) for each prime factor less than ∛N." }, { "code": null, "e": 30413, "s": 30313, "text": "The remaining number can only have a maximum of 2 prime factors. We’ll prove this by contradiction." }, { "code": null, "e": 30499, "s": 30413, "text": "Assume Y = p1 * p2 * p3 where p1,p2,p3 are prime and p1,p2,p3 > ∛N [Explained above]." }, { "code": null, "e": 30536, "s": 30499, "text": "Since p1 >∛N and p2 > ∛N and p3 > ∛N" }, { "code": null, "e": 30556, "s": 30536, "text": "p1*p2*p3 > ∛N*∛N*∛N" }, { "code": null, "e": 30626, "s": 30556, "text": "=> p1*p2*p3 > N. But Y is a factor of N and cannot be greater than N." }, { "code": null, "e": 30722, "s": 30626, "text": "Therefore, there is a contradiction, which implies that one of p1, p2, p3 must be less than ∛N." }, { "code": null, "e": 30803, "s": 30722, "text": "But since all primes less than ∛N have been absorbed by X, this is not possible." }, { "code": null, "e": 30848, "s": 30803, "text": "So, Y cannot have more than 2 prime factors." }, { "code": null, "e": 30870, "s": 30848, "text": "Y can therefore have:" }, { "code": null, "e": 30921, "s": 30870, "text": "1 prime factors if it is prime (Y) with exponent 1" }, { "code": null, "e": 30993, "s": 30921, "text": "1 prime factors if it is a square of a prime (sqrt(Y)), with exponent 2" }, { "code": null, "e": 31053, "s": 30993, "text": "2 prime factors if composite (p1, p2) with exponent 1 and 1" }, { "code": null, "e": 31077, "s": 31053, "text": "Therefore, we multiply:" }, { "code": null, "e": 31125, "s": 31077, "text": "If Y is prime => (exponent of y .i.e. 1 +1) = 2" }, { "code": null, "e": 31190, "s": 31125, "text": "If Y is a square of prime => (exponent of sqrt(y) .i.e. 2+1) = 3" }, { "code": null, "e": 31262, "s": 31190, "text": "If Y is composite => (exponent of p1 +1)*(exponent of p2+1) = 2 * 2 = 4" }, { "code": null, "e": 31266, "s": 31262, "text": "C++" }, { "code": null, "e": 31271, "s": 31266, "text": "Java" }, { "code": null, "e": 31279, "s": 31271, "text": "Python3" }, { "code": null, "e": 31282, "s": 31279, "text": "C#" }, { "code": null, "e": 31286, "s": 31282, "text": "PHP" }, { "code": null, "e": 31297, "s": 31286, "text": "Javascript" }, { "code": "// C++ program to count distinct divisors// of a given number n#include <bits/stdc++.h>using namespace std; void SieveOfEratosthenes(int n, bool prime[], bool primesquare[], int a[]){ //For more details check out: https://www.geeksforgeeks.org/sieve-of-eratosthenes/ // Create a boolean array \"prime[0..n]\" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // Not a prime, else true. for (int i = 2; i <= n; i++) prime[i] = true; // Create a boolean array \"primesquare[0..n*n+1]\" // and initialize all entries it as false. A value // in squareprime[i] will finally be true if i is // square of prime, else false. for (int i = 0; i <= (n * n + 1); i++) primesquare[i] = false; // 1 is not a prime number prime[1] = false; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p starting from p * p for (int i = p * p; i <= n; i += p) prime[i] = false; } } int j = 0; for (int p = 2; p <= n; p++) { if (prime[p]) { // Storing primes in an array a[j] = p; // Update value in primesquare[p*p], // if p is prime. primesquare[p * p] = true; j++; } }} // Function to count divisorsint countDivisors(int n){ // If number is 1, then it will have only 1 // as a factor. So, total factors will be 1. if (n == 1) return 1; bool prime[n + 1], primesquare[n * n + 1]; int a[n]; // for storing primes upto n // Calling SieveOfEratosthenes to store prime // factors of n and to store square of prime // factors of n SieveOfEratosthenes(n, prime, primesquare, a); // ans will contain total number of distinct // divisors int ans = 1; // Loop for counting factors of n for (int i = 0;; i++) { // a[i] is not less than cube root n if (a[i] * a[i] * a[i] > n) break; // Calculating power of a[i] in n. int cnt = 1; // cnt is power of prime a[i] in n. while (n % a[i] == 0) // if a[i] is a factor of n { n = n / a[i]; cnt = cnt + 1; // incrementing power } // Calculating the number of divisors // If n = a^p * b^q then total divisors of n // are (p+1)*(q+1) ans = ans * cnt; } // if a[i] is greater than cube root of n // First case if (prime[n]) ans = ans * 2; // Second case else if (primesquare[n]) ans = ans * 3; // Third case else if (n != 1) ans = ans * 4; return ans; // Total divisors} // Driver Programint main(){ cout << \"Total distinct divisors of 100 are : \" << countDivisors(100) << endl; return 0;}", "e": 34205, "s": 31297, "text": null }, { "code": "// JAVA program to count distinct// divisors of a given number nimport java.io.*; class GFG { static void SieveOfEratosthenes(int n, boolean prime[], boolean primesquare[], int a[]) { // Create a boolean array \"prime[0..n]\" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // Not a prime, else true. for (int i = 2; i <= n; i++) prime[i] = true; /* Create a boolean array \"primesquare[0..n*n+1]\" and initialize all entries it as false. A value in squareprime[i] will finally be true if i is square of prime, else false.*/ for (int i = 0; i < ((n * n) + 1); i++) primesquare[i] = false; // 1 is not a prime number prime[1] = false; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } int j = 0; for (int p = 2; p <= n; p++) { if (prime[p]) { // Storing primes in an array a[j] = p; // Update value in // primesquare[p*p], // if p is prime. primesquare[p * p] = true; j++; } } } // Function to count divisors static int countDivisors(int n) { // If number is 1, then it will // have only 1 as a factor. So, // total factors will be 1. if (n == 1) return 1; boolean prime[] = new boolean[n + 1]; boolean primesquare[] = new boolean[(n * n) + 1]; // for storing primes upto n int a[] = new int[n]; // Calling SieveOfEratosthenes to // store prime factors of n and to // store square of prime factors of n SieveOfEratosthenes(n, prime, primesquare, a); // ans will contain total number // of distinct divisors int ans = 1; // Loop for counting factors of n for (int i = 0;; i++) { // a[i] is not less than cube root n if (a[i] * a[i] * a[i] > n) break; // Calculating power of a[i] in n. // cnt is power of prime a[i] in n. int cnt = 1; // if a[i] is a factor of n while (n % a[i] == 0) { n = n / a[i]; // incrementing power cnt = cnt + 1; } // Calculating the number of divisors // If n = a^p * b^q then total // divisors of n are (p+1)*(q+1) ans = ans * cnt; } // if a[i] is greater than cube root // of n // First case if (prime[n]) ans = ans * 2; // Second case else if (primesquare[n]) ans = ans * 3; // Third case else if (n != 1) ans = ans * 4; return ans; // Total divisors } // Driver Program public static void main(String args[]) { System.out.println(\"Total distinct divisors\" + \" of 100 are : \" + countDivisors(100)); }} /*This code is contributed by Nikita Tiwari*/", "e": 37592, "s": 34205, "text": null }, { "code": "# Python3 program to count distinct# divisors of a given number n def SieveOfEratosthenes(n, prime,primesquare, a): # Create a boolean array \"prime[0..n]\" # and initialize all entries it as # true. A value in prime[i] will finally # be false if i is not a prime, else true. for i in range(2,n+1): prime[i] = True # Create a boolean array \"primesquare[0..n*n+1]\" # and initialize all entries it as false. # A value in squareprime[i] will finally be # true if i is square of prime, else false. for i in range((n * n + 1)+1): primesquare[i] = False # 1 is not a prime number prime[1] = False p = 2 while(p * p <= n): # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Update all multiples of p i = p * 2 while(i <= n): prime[i] = False i += p p+=1 j = 0 for p in range(2,n+1): if (prime[p]==True): # Storing primes in an array a[j] = p # Update value in primesquare[p*p], # if p is prime. primesquare[p * p] = True j+=1 # Function to count divisorsdef countDivisors(n): # If number is 1, then it will # have only 1 as a factor. So, # total factors will be 1. if (n == 1): return 1 prime = [False]*(n + 2) primesquare = [False]*(n * n + 2) # for storing primes upto n a = [0]*n # Calling SieveOfEratosthenes to # store prime factors of n and to # store square of prime factors of n SieveOfEratosthenes(n, prime, primesquare, a) # ans will contain total # number of distinct divisors ans = 1 # Loop for counting factors of n i=0 while(1): # a[i] is not less than cube root n if(a[i] * a[i] * a[i] > n): break # Calculating power of a[i] in n. cnt = 1 # cnt is power of # prime a[i] in n. while (n % a[i] == 0): # if a[i] is a factor of n n = n / a[i] cnt = cnt + 1 # incrementing power # Calculating number of divisors # If n = a^p * b^q then total # divisors of n are (p+1)*(q+1) ans = ans * cnt i+=1 # if a[i] is greater than # cube root of n n=int(n) # First case if (prime[n]==True): ans = ans * 2 # Second case else if (primesquare[n]==True): ans = ans * 3 # Third case else if (n != 1): ans = ans * 4 return ans # Total divisors # Driver Codeif __name__=='__main__': print(\"Total distinct divisors of 100 are :\",countDivisors(100)) # This code is contributed# by mits", "e": 40275, "s": 37592, "text": null }, { "code": "// C# program to count distinct// divisors of a given number nusing System; class GFG { static void SieveOfEratosthenes(int n, bool[] prime, bool[] primesquare, int[] a) { // Create a boolean array \"prime[0..n]\" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // Not a prime, else true. for (int i = 2; i <= n; i++) prime[i] = true; /* Create a boolean array \"primesquare[0..n*n+1]\" and initialize all entries it as false. A value in squareprime[i] will finally be true if i is square of prime, else false.*/ for (int i = 0; i < ((n * n) + 1); i++) primesquare[i] = false; // 1 is not a prime number prime[1] = false; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } int j = 0; for (int p = 2; p <= n; p++) { if (prime[p]) { // Storing primes in an array a[j] = p; // Update value in // primesquare[p*p], // if p is prime. primesquare[p * p] = true; j++; } } } // Function to count divisors static int countDivisors(int n) { // If number is 1, then it will // have only 1 as a factor. So, // total factors will be 1. if (n == 1) return 1; bool[] prime = new bool[n + 1]; bool[] primesquare = new bool[(n * n) + 1]; // for storing primes upto n int[] a = new int[n]; // Calling SieveOfEratosthenes to // store prime factors of n and to // store square of prime factors of n SieveOfEratosthenes(n, prime, primesquare, a); // ans will contain total number // of distinct divisors int ans = 1; // Loop for counting factors of n for (int i = 0;; i++) { // a[i] is not less than cube root n if (a[i] * a[i] * a[i] > n) break; // Calculating power of a[i] in n. // cnt is power of prime a[i] in n. int cnt = 1; // if a[i] is a factor of n while (n % a[i] == 0) { n = n / a[i]; // incrementing power cnt = cnt + 1; } // Calculating the number of divisors // If n = a^p * b^q then total // divisors of n are (p+1)*(q+1) ans = ans * cnt; } // if a[i] is greater than cube root // of n // First case if (prime[n]) ans = ans * 2; // Second case else if (primesquare[n]) ans = ans * 3; // Third case else if (n != 1) ans = ans * 4; return ans; // Total divisors } // Driver Program public static void Main() { Console.Write(\"Total distinct divisors\" + \" of 100 are : \" + countDivisors(100)); }} // This code is contributed by parashar.", "e": 43612, "s": 40275, "text": null }, { "code": "<?php// PHP program to count distinct// divisors of a given number n function SieveOfEratosthenes($n, &$prime, &$primesquare, &$a){ // Create a boolean array \"prime[0..n]\" // and initialize all entries it as // true. A value in prime[i] will finally // be false if i is not a prime, else true. for ($i = 2; $i <= $n; $i++) $prime[$i] = true; // Create a boolean array \"primesquare[0..n*n+1]\" // and initialize all entries it as false. // A value in squareprime[i] will finally be // true if i is square of prime, else false. for ($i = 0; $i <= ($n * $n + 1); $i++) $primesquare[$i] = false; // 1 is not a prime number $prime[1] = false; for ($p = 2; $p * $p <= $n; $p++) { // If prime[p] is not changed, // then it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p * 2; $i <= $n; $i += $p) $prime[$i] = false; } } $j = 0; for ($p = 2; $p <= $n; $p++) { if ($prime[$p]) { // Storing primes in an array $a[$j] = $p; // Update value in primesquare[p*p], // if p is prime. $primesquare[$p * $p] = true; $j++; } }} // Function to count divisorsfunction countDivisors($n){ // If number is 1, then it will // have only 1 as a factor. So, // total factors will be 1. if ($n == 1) return 1; $prime = array_fill(false, $n + 1, NULL); $primesquare = array_fill(false, $n * $n + 1, NULL); // for storing primes upto n $a = array_fill(0, $n, NULL); // Calling SieveOfEratosthenes to // store prime factors of n and to // store square of prime factors of n SieveOfEratosthenes($n, $prime, $primesquare, $a); // ans will contain total // number of distinct divisors $ans = 1; // Loop for counting factors of n for ($i = 0;; $i++) { // a[i] is not less than cube root n if ($a[$i] * $a[$i] * $a[$i] > $n) break; // Calculating power of a[i] in n. $cnt = 1; // cnt is power of // prime a[i] in n. while ($n % $a[$i] == 0) // if a[i] is a // factor of n { $n = $n / $a[$i]; $cnt = $cnt + 1; // incrementing power } // Calculating the number of divisors // If n = a^p * b^q then total // divisors of n are (p+1)*(q+1) $ans = $ans * $cnt; } // if a[i] is greater than // cube root of n // First case if ($prime[$n]) $ans = $ans * 2; // Second case else if ($primesquare[$n]) $ans = $ans * 3; // Third case else if ($n != 1) $ans = $ans * 4; return $ans; // Total divisors} // Driver Codeecho \"Total distinct divisors of 100 are : \". countDivisors(100). \"\\n\"; // This code is contributed// by ChitraNayal?>", "e": 46661, "s": 43612, "text": null }, { "code": "<script> // Javascript program to count distinct// divisors of a given number n function SieveOfEratosthenes(n, prime, primesquare, a){ // Create a boolean array \"prime[0..n]\" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // Not a prime, else true. for(let i = 2; i <= n; i++) prime[i] = true; // Create a boolean array \"primesquare[0..n*n+1]\" // and initialize all entries it as false. // A value in squareprime[i] will finally // be true if i is square of prime, // else false. for(let i = 0; i < ((n * n) + 1); i++) primesquare[i] = false; // 1 is not a prime number prime[1] = false; for(let p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for(let i = p * 2; i <= n; i += p) prime[i] = false; } } let j = 0; for(let p = 2; p <= n; p++) { if (prime[p]) { // Storing primes in an array a[j] = p; // Update value in // primesquare[p*p], // if p is prime. primesquare[p * p] = true; j++; } }} // Function to count divisorsfunction countDivisors(n){ // If number is 1, then it will // have only 1 as a factor. So, // total factors will be 1. if (n == 1) return 1; let prime = new Array(n + 1); let primesquare = new Array((n * n) + 1); // For storing primes upto n let a = new Array(n); for(let i = 0; i < n; i++) { a[i] = 0; } // Calling SieveOfEratosthenes to // store prime factors of n and to // store square of prime factors of n SieveOfEratosthenes(n, prime, primesquare, a); // ans will contain total number // of distinct divisors let ans = 1; // Loop for counting factors of n for(let i = 0;; i++) { // a[i] is not less than cube root n if (a[i] * a[i] * a[i] > n) break; // Calculating power of a[i] in n. // cnt is power of prime a[i] in n. let cnt = 1; // If a[i] is a factor of n while (n % a[i] == 0) { n = n / a[i]; // Incrementing power cnt = cnt + 1; } // Calculating the number of divisors // If n = a^p * b^q then total // divisors of n are (p+1)*(q+1) ans = ans * cnt; } // If a[i] is greater than cube root // of n // First case if (prime[n]) ans = ans * 2; // Second case else if (primesquare[n]) ans = ans * 3; // Third case else if (n != 1) ans = ans * 4; // Total divisors return ans;} // Driver Codedocument.write(\"Total distinct divisors\" + \" of 100 are : \" + countDivisors(100)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 49680, "s": 46661, "text": null }, { "code": null, "e": 49690, "s": 49680, "text": "Output : " }, { "code": null, "e": 49729, "s": 49690, "text": "Total distinct divisors of 100 are : 9" }, { "code": null, "e": 49754, "s": 49729, "text": "Time Complexity: O(n1/3)" }, { "code": null, "e": 50181, "s": 49754, "text": "This article is contributed by Karun Anantharaman. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 50190, "s": 50181, "text": "parashar" }, { "code": null, "e": 50196, "s": 50190, "text": "jit_t" }, { "code": null, "e": 50201, "s": 50196, "text": "vt_m" }, { "code": null, "e": 50207, "s": 50201, "text": "ukasp" }, { "code": null, "e": 50220, "s": 50207, "text": "Mithun Kumar" }, { "code": null, "e": 50234, "s": 50220, "text": "Apoorva_Kumar" }, { "code": null, "e": 50256, "s": 50234, "text": "susmitakundugoaldanga" }, { "code": null, "e": 50277, "s": 50256, "text": "avanitrachhadiya2155" }, { "code": null, "e": 50288, "s": 50277, "text": "karun19049" }, { "code": null, "e": 50302, "s": 50288, "text": "demishassabis" }, { "code": null, "e": 50315, "s": 50302, "text": "simmytarika5" }, { "code": null, "e": 50324, "s": 50315, "text": "divisors" }, { "code": null, "e": 50332, "s": 50324, "text": "Numbers" }, { "code": null, "e": 50338, "s": 50332, "text": "sieve" }, { "code": null, "e": 50351, "s": 50338, "text": "Mathematical" }, { "code": null, "e": 50370, "s": 50351, "text": "Technical Scripter" }, { "code": null, "e": 50383, "s": 50370, "text": "Mathematical" }, { "code": null, "e": 50391, "s": 50383, "text": "Numbers" }, { "code": null, "e": 50397, "s": 50391, "text": "sieve" }, { "code": null, "e": 50495, "s": 50397, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 50519, "s": 50495, "text": "Merge two sorted arrays" }, { "code": null, "e": 50562, "s": 50519, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 50576, "s": 50562, "text": "Prime Numbers" }, { "code": null, "e": 50625, "s": 50576, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 50666, "s": 50625, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 50700, "s": 50666, "text": "Program for factorial of a number" }, { "code": null, "e": 50721, "s": 50700, "text": "Operators in C / C++" }, { "code": null, "e": 50764, "s": 50721, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 50817, "s": 50764, "text": "Find minimum number of coins that make a given value" } ]
Chaining Multiple MapReduce Jobs with Hadoop/ Java | by Tri Nguyen | Towards Data Science
I learned about MapReduce briefly pretty much a year ago when my job required a bit of Hadoop. I then had not touched MapReduce, let along doing it with Java. So when an assignment asked me to implement multiple MapReduce jobs under one script, it was a mess searching up Stack Overflow and Youtube. So, why not write something about it? Yes, I am. MapReduce is a computation abstraction that works well with The Hadoop Distributed File System (HDFS). It comprises of a “Map” step and a “Reduce” step. Map performs filtering and sorting into another set of data while Reduce performs a summary operation. In both steps, individual elements are broken down into tuples of key and value pairs. MapReduce gains its popularity by being able to easily scale data processing over multiple computing nodes behind the scene. Hence, it works well with extremely large datasets. To illustrate how to chain multiple MapReduce jobs in one script, I will be using the NYC Taxi & Limousine Commission dataset of around 7.6 million rows to compute the distribution of degree differences of locations. The .tsv file I am using has the following structure: Let’s say we want to use MapReduce to obtain the following output of two columns: where “diff” is a location ID’s out-degree minus its in-degree. The out-degree of a location is the number of times that location is used for pickup and the in-degree is the number of times it is used for dropoff. Then, “count” is the frequency for a particular “diff”. Therefore, one way to accomplish this is to have two MapReduce jobs. One is to calculate the “diff” for each location and the other is to turn that output of the first job into “count” as we want above. MAP-REDUCE JOB #1 The Map procedure for Job #1 simply loops through and breaks the .tsv input into 4 different values for each line: PickUpLocation ID, DropOffLocation ID, PassengerCount, and TotalFare. However, only PickUpLocation ID and DropOffLocation ID are relevant for our task here. Then, for each element, the class also creates an inDegree variable that is 1 and an outDegree variable that is -1. Then, it writes each (PickUpLocation, inDegree) and (DropOffLocation, outDegree) as a key-value tuple that will be processed further by the Reduce procedure, which takes form like below where the first column is location ID and the second column indicates whether it is a pickup or dropoff from each location ID. Then, what the Reduce procedure does is simply grouping by location ID and aggregate by summing up the second column to achieve the “diff”. Then it writes (Location ID, diff) as a key-value tuple. The output takes the form of the following: MAP-REDUCE JOB #2 The output of Job #1 is then passed in as the input for Job #2. In order to group by “diff” to achieve the final output, the Map procedure of Job 2 needs to swap the input key-value pairs (Location ID, diff) into (diff, Location ID) because Reduce procedure groups by keys. Essentially, the output of the Map procedure this time looks like: Finally, that is then passed into the second Reduce procedure to finish the task: What happens here is that the Reduce procedure simply loops through the input and for each occurrence of a unique “diff”, its count increases by 1. At the end of the loop, it writes (diff, count) as key-value pair into the final output file: CHAINING JOB #1 & JOB #2 The challenging step that I found is connecting the above two MapReduce jobs so that Job #2 could take the output of Job #1 as input without the need for Job #1 to physically write out a file. I had to look for and experiment with multiple suggestions online until I found the combination that is easiest to understand. Basically, the key is to create two different configurations for the two jobs as “conf” and “conf2” where they also get two different instances. Configuration conf = new Configuration();Job job1 = Job.getInstance(conf, "degree");Configuration conf2 = new Configuration();Job job2 = Job.getInstance(conf2, "frequency"); Then, Job #2 can only be executed when Job #1 finishes with job1.waitForCompletion(true); But note that the system does not terminate here. Then, the output of Job #1 is the same as the input of Job #2: FileOutputFormat.setOutputPath(job1, new Path(args[1]));FileInputFormat.addInputPath(job2, new Path(args[1])); And that’s it. With this technique, you are not limited to only two MapReduce jobs but can also increase to three, five, or even ten to fit your task. I hope this quick note helps whoever that are struggling to find a comprehensive and easy to understand guide on chaining MapReduce jobs.
[ { "code": null, "e": 472, "s": 172, "text": "I learned about MapReduce briefly pretty much a year ago when my job required a bit of Hadoop. I then had not touched MapReduce, let along doing it with Java. So when an assignment asked me to implement multiple MapReduce jobs under one script, it was a mess searching up Stack Overflow and Youtube." }, { "code": null, "e": 521, "s": 472, "text": "So, why not write something about it? Yes, I am." }, { "code": null, "e": 864, "s": 521, "text": "MapReduce is a computation abstraction that works well with The Hadoop Distributed File System (HDFS). It comprises of a “Map” step and a “Reduce” step. Map performs filtering and sorting into another set of data while Reduce performs a summary operation. In both steps, individual elements are broken down into tuples of key and value pairs." }, { "code": null, "e": 1015, "s": 864, "text": "MapReduce gains its popularity by being able to easily scale data processing over multiple computing nodes behind the scene. Hence, it works well with" }, { "code": null, "e": 1041, "s": 1015, "text": "extremely large datasets." }, { "code": null, "e": 1312, "s": 1041, "text": "To illustrate how to chain multiple MapReduce jobs in one script, I will be using the NYC Taxi & Limousine Commission dataset of around 7.6 million rows to compute the distribution of degree differences of locations. The .tsv file I am using has the following structure:" }, { "code": null, "e": 1394, "s": 1312, "text": "Let’s say we want to use MapReduce to obtain the following output of two columns:" }, { "code": null, "e": 1664, "s": 1394, "text": "where “diff” is a location ID’s out-degree minus its in-degree. The out-degree of a location is the number of times that location is used for pickup and the in-degree is the number of times it is used for dropoff. Then, “count” is the frequency for a particular “diff”." }, { "code": null, "e": 1867, "s": 1664, "text": "Therefore, one way to accomplish this is to have two MapReduce jobs. One is to calculate the “diff” for each location and the other is to turn that output of the first job into “count” as we want above." }, { "code": null, "e": 1885, "s": 1867, "text": "MAP-REDUCE JOB #1" }, { "code": null, "e": 2273, "s": 1885, "text": "The Map procedure for Job #1 simply loops through and breaks the .tsv input into 4 different values for each line: PickUpLocation ID, DropOffLocation ID, PassengerCount, and TotalFare. However, only PickUpLocation ID and DropOffLocation ID are relevant for our task here. Then, for each element, the class also creates an inDegree variable that is 1 and an outDegree variable that is -1." }, { "code": null, "e": 2586, "s": 2273, "text": "Then, it writes each (PickUpLocation, inDegree) and (DropOffLocation, outDegree) as a key-value tuple that will be processed further by the Reduce procedure, which takes form like below where the first column is location ID and the second column indicates whether it is a pickup or dropoff from each location ID." }, { "code": null, "e": 2783, "s": 2586, "text": "Then, what the Reduce procedure does is simply grouping by location ID and aggregate by summing up the second column to achieve the “diff”. Then it writes (Location ID, diff) as a key-value tuple." }, { "code": null, "e": 2827, "s": 2783, "text": "The output takes the form of the following:" }, { "code": null, "e": 2845, "s": 2827, "text": "MAP-REDUCE JOB #2" }, { "code": null, "e": 2909, "s": 2845, "text": "The output of Job #1 is then passed in as the input for Job #2." }, { "code": null, "e": 3119, "s": 2909, "text": "In order to group by “diff” to achieve the final output, the Map procedure of Job 2 needs to swap the input key-value pairs (Location ID, diff) into (diff, Location ID) because Reduce procedure groups by keys." }, { "code": null, "e": 3186, "s": 3119, "text": "Essentially, the output of the Map procedure this time looks like:" }, { "code": null, "e": 3268, "s": 3186, "text": "Finally, that is then passed into the second Reduce procedure to finish the task:" }, { "code": null, "e": 3510, "s": 3268, "text": "What happens here is that the Reduce procedure simply loops through the input and for each occurrence of a unique “diff”, its count increases by 1. At the end of the loop, it writes (diff, count) as key-value pair into the final output file:" }, { "code": null, "e": 3535, "s": 3510, "text": "CHAINING JOB #1 & JOB #2" }, { "code": null, "e": 3728, "s": 3535, "text": "The challenging step that I found is connecting the above two MapReduce jobs so that Job #2 could take the output of Job #1 as input without the need for Job #1 to physically write out a file." }, { "code": null, "e": 3855, "s": 3728, "text": "I had to look for and experiment with multiple suggestions online until I found the combination that is easiest to understand." }, { "code": null, "e": 4000, "s": 3855, "text": "Basically, the key is to create two different configurations for the two jobs as “conf” and “conf2” where they also get two different instances." }, { "code": null, "e": 4174, "s": 4000, "text": "Configuration conf = new Configuration();Job job1 = Job.getInstance(conf, \"degree\");Configuration conf2 = new Configuration();Job job2 = Job.getInstance(conf2, \"frequency\");" }, { "code": null, "e": 4234, "s": 4174, "text": "Then, Job #2 can only be executed when Job #1 finishes with" }, { "code": null, "e": 4264, "s": 4234, "text": "job1.waitForCompletion(true);" }, { "code": null, "e": 4377, "s": 4264, "text": "But note that the system does not terminate here. Then, the output of Job #1 is the same as the input of Job #2:" }, { "code": null, "e": 4488, "s": 4377, "text": "FileOutputFormat.setOutputPath(job1, new Path(args[1]));FileInputFormat.addInputPath(job2, new Path(args[1]));" }, { "code": null, "e": 4639, "s": 4488, "text": "And that’s it. With this technique, you are not limited to only two MapReduce jobs but can also increase to three, five, or even ten to fit your task." } ]
How to remove a column from a data frame that contains same value in R?
If we have only one value in all of the rows of an R data frame then we might want to remove the whole column because the effect of that column will not make any sense in the data analysis objectives. Thus, instead of removing the column we can extract the columns that contains different values. Live Demo set.seed(1001) x1<-sample(0:1,20,replace=TRUE) x2<-rep(5,20) x3<-sample(0:5,20,replace=TRUE) x4<-sample(1:10,20,replace=TRUE) df1<-data.frame(x1,x2,x3,x4) df1 x1 x2 x3 x4 1 0 5 1 6 2 0 5 1 4 3 0 5 3 7 4 0 5 2 5 5 1 5 3 5 6 0 5 0 5 7 1 5 1 7 8 0 5 5 5 9 1 5 5 4 10 1 5 2 1 11 1 5 4 6 12 1 5 5 8 13 1 5 0 4 14 1 5 1 9 15 1 5 2 9 16 0 5 5 8 17 0 5 1 6 18 0 5 1 4 19 1 5 3 7 20 0 5 4 2 Removing column that contains 5 − df1[,c(1,3,4)] x1 x3 x4 1 0 1 6 2 0 1 4 3 0 3 7 4 0 2 5 5 1 3 5 6 0 0 5 7 1 1 7 8 0 5 5 9 1 5 4 10 1 2 1 11 1 4 6 12 1 5 8 13 1 0 4 14 1 1 9 15 1 2 9 16 0 5 8 17 0 1 6 18 0 1 4 19 1 3 7 20 0 4 2 Let’s have a look at another example − Live Demo y1<-sample(1:3,20,replace=TRUE) y2<-sample(1:5,20,replace=TRUE) y3<-rep(1,20) y4<-sample(1:2,20,replace=TRUE) y5<-sample(1:6,20,replace=TRUE) y6<-sample(1:8,20,replace=TRUE) df2<-data.frame(y1,y2,y3,y4,y5,y6) df2 y1 y2 y3 y4 y5 y6 1 3 2 1 1 3 1 2 2 2 1 2 3 5 3 2 5 1 1 2 6 4 2 4 1 1 4 6 5 1 1 1 1 1 4 6 1 2 1 1 3 6 7 1 3 1 2 5 2 8 3 2 1 2 5 1 9 1 3 1 1 3 6 10 3 1 1 2 6 1 11 3 3 1 2 4 2 12 2 4 1 2 5 5 13 3 5 1 2 4 7 14 3 2 1 1 1 5 15 3 1 1 2 3 1 16 2 4 1 2 5 5 17 2 3 1 2 3 6 18 3 4 1 1 1 6 19 1 1 1 1 6 5 20 1 3 1 1 6 1 Removing column 3 from data frame df2 − df2[,c(1,2,4,5,6)] y1 y2 y4 y5 y6 1 3 2 1 3 1 2 2 2 2 3 5 3 2 5 1 2 6 4 2 4 1 4 6 5 1 1 1 1 4 6 1 2 1 3 6 7 1 3 2 5 2 8 3 2 2 5 1 9 1 3 1 3 6 10 3 1 2 6 1 11 3 3 2 4 2 12 2 4 2 5 5 13 3 5 2 4 7 14 3 2 1 1 5 15 3 1 2 3 1 16 2 4 2 5 5 17 2 3 2 3 6 18 3 4 1 1 6 19 1 1 1 6 5 20 1 3 1 6 1
[ { "code": null, "e": 1359, "s": 1062, "text": "If we have only one value in all of the rows of an R data frame then we might want to remove the whole column because the effect of that column will not make any sense in the data analysis objectives. Thus, instead of removing the column we can extract the columns that contains different values." }, { "code": null, "e": 1370, "s": 1359, "text": " Live Demo" }, { "code": null, "e": 1529, "s": 1370, "text": "set.seed(1001)\nx1<-sample(0:1,20,replace=TRUE)\nx2<-rep(5,20)\nx3<-sample(0:5,20,replace=TRUE)\nx4<-sample(1:10,20,replace=TRUE)\ndf1<-data.frame(x1,x2,x3,x4)\ndf1" }, { "code": null, "e": 1803, "s": 1529, "text": " x1 x2 x3 x4\n1 0 5 1 6\n2 0 5 1 4\n3 0 5 3 7\n4 0 5 2 5\n5 1 5 3 5\n6 0 5 0 5\n7 1 5 1 7\n8 0 5 5 5\n9 1 5 5 4\n10 1 5 2 1\n11 1 5 4 6\n12 1 5 5 8\n13 1 5 0 4\n14 1 5 1 9\n15 1 5 2 9\n16 0 5 5 8\n17 0 5 1 6\n18 0 5 1 4\n19 1 5 3 7\n20 0 5 4 2" }, { "code": null, "e": 1837, "s": 1803, "text": "Removing column that contains 5 −" }, { "code": null, "e": 1852, "s": 1837, "text": "df1[,c(1,3,4)]" }, { "code": null, "e": 2063, "s": 1852, "text": " x1 x3 x4\n1 0 1 6\n2 0 1 4\n3 0 3 7\n4 0 2 5\n5 1 3 5\n6 0 0 5\n7 1 1 7\n8 0 5 5\n9 1 5 4\n10 1 2 1\n11 1 4 6\n12 1 5 8\n13 1 0 4\n14 1 1 9\n15 1 2 9\n16 0 5 8\n17 0 1 6\n18 0 1 4\n19 1 3 7\n20 0 4 2" }, { "code": null, "e": 2102, "s": 2063, "text": "Let’s have a look at another example −" }, { "code": null, "e": 2113, "s": 2102, "text": " Live Demo" }, { "code": null, "e": 2326, "s": 2113, "text": "y1<-sample(1:3,20,replace=TRUE)\ny2<-sample(1:5,20,replace=TRUE)\ny3<-rep(1,20)\ny4<-sample(1:2,20,replace=TRUE)\ny5<-sample(1:6,20,replace=TRUE)\ny6<-sample(1:8,20,replace=TRUE)\ndf2<-data.frame(y1,y2,y3,y4,y5,y6)\ndf2" }, { "code": null, "e": 2726, "s": 2326, "text": " y1 y2 y3 y4 y5 y6\n1 3 2 1 1 3 1\n2 2 2 1 2 3 5\n3 2 5 1 1 2 6\n4 2 4 1 1 4 6\n5 1 1 1 1 1 4\n6 1 2 1 1 3 6\n7 1 3 1 2 5 2\n8 3 2 1 2 5 1\n9 1 3 1 1 3 6\n10 3 1 1 2 6 1\n11 3 3 1 2 4 2\n12 2 4 1 2 5 5\n13 3 5 1 2 4 7\n14 3 2 1 1 1 5\n15 3 1 1 2 3 1\n16 2 4 1 2 5 5\n17 2 3 1 2 3 6\n18 3 4 1 1 1 6\n19 1 1 1 1 6 5\n20 1 3 1 1 6 1" }, { "code": null, "e": 2766, "s": 2726, "text": "Removing column 3 from data frame df2 −" }, { "code": null, "e": 2785, "s": 2766, "text": "df2[,c(1,2,4,5,6)]" }, { "code": null, "e": 3142, "s": 2785, "text": " y1 y2 y4 y5 y6\n1 3 2 1 3 1\n2 2 2 2 3 5\n3 2 5 1 2 6\n4 2 4 1 4 6\n5 1 1 1 1 4\n6 1 2 1 3 6\n7 1 3 2 5 2\n8 3 2 2 5 1\n9 1 3 1 3 6\n10 3 1 2 6 1\n11 3 3 2 4 2\n12 2 4 2 5 5\n13 3 5 2 4 7\n14 3 2 1 1 5\n15 3 1 2 3 1\n16 2 4 2 5 5\n17 2 3 2 3 6\n18 3 4 1 1 6\n19 1 1 1 6 5\n20 1 3 1 6 1" } ]
CSS Layout - The position Property
The position property specifies the type of positioning method used for an element (static, relative, fixed, absolute or sticky). The position property specifies the type of positioning method used for an element. There are five different position values: static relative fixed absolute sticky Elements are then positioned using the top, bottom, left, and right properties. However, these properties will not work unless the position property is set first. They also work differently depending on the position value. HTML elements are positioned static by default. Static positioned elements are not affected by the top, bottom, left, and right properties. An element with position: static; is not positioned in any special way; it is always positioned according to the normal flow of the page: Here is the CSS that is used: An element with position: relative; is positioned relative to its normal position. Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it to be adjusted away from its normal position. Other content will not be adjusted to fit into any gap left by the element. Here is the CSS that is used: An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used to position the element. A fixed element does not leave a gap in the page where it would normally have been located. Notice the fixed element in the lower-right corner of the page. Here is the CSS that is used: An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed). However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling. Note: Absolute positioned elements are removed from the normal flow, and can overlap elements. Here is a simple example: Here is the CSS that is used: An element with position: sticky; is positioned based on the user's scroll position. A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed). Try to scroll inside this frame to understand how sticky positioning works. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus. Note: Internet Explorer does not support sticky positioning. Safari requires a -webkit- prefix (see example below). You must also specify at least one of top, right, bottom or left for sticky positioning to work. In this example, the sticky element sticks to the top of the page (top: 0), when you reach its scroll position. How to position text over an image: Try it Yourself: Set the shape of an element This example demonstrates how to set the shape of an element. The element is clipped into this shape, and displayed. Position the <h1> element to always be 50px from the top, and 10px from the right, relative to the window/frame edges. <style> h1 { : ; : 50px; : 10px; } </style> <body> <h1>This is a heading</h1> <p>This is a paragraph</p> <p>This is a paragraph</p> </body> Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 132, "s": 0, "text": "The position property specifies the type of \npositioning method used for an element (static, relative, fixed, absolute or \nsticky)." }, { "code": null, "e": 216, "s": 132, "text": "The position property specifies the type of positioning method used for an element." }, { "code": null, "e": 259, "s": 216, "text": "There are five different position values: " }, { "code": null, "e": 266, "s": 259, "text": "static" }, { "code": null, "e": 275, "s": 266, "text": "relative" }, { "code": null, "e": 281, "s": 275, "text": "fixed" }, { "code": null, "e": 290, "s": 281, "text": "absolute" }, { "code": null, "e": 297, "s": 290, "text": "sticky" }, { "code": null, "e": 523, "s": 297, "text": "Elements are then positioned using the top, bottom, left, and right \nproperties. However, these properties will not work unless the position \nproperty is set first. They also work differently depending on the position \nvalue." }, { "code": null, "e": 571, "s": 523, "text": "HTML elements are positioned static by default." }, { "code": null, "e": 663, "s": 571, "text": "Static positioned elements are not affected by the top, bottom, left, and right properties." }, { "code": null, "e": 802, "s": 663, "text": "An element with position: static; is not positioned in any special way; it is \nalways positioned according to the normal flow of the page:" }, { "code": null, "e": 832, "s": 802, "text": "Here is the CSS that is used:" }, { "code": null, "e": 915, "s": 832, "text": "An element with position: relative; is positioned relative to its normal position." }, { "code": null, "e": 1139, "s": 915, "text": "Setting the top, right, bottom, and left properties of a relatively-positioned element will cause\nit to be adjusted away from its normal position. Other content will not be adjusted to fit into any gap left by the \nelement." }, { "code": null, "e": 1169, "s": 1139, "text": "Here is the CSS that is used:" }, { "code": null, "e": 1398, "s": 1169, "text": "An element with position: fixed; is positioned relative to the viewport, which means it always \nstays in the same place even if the page is scrolled. The top, \nright, bottom, and left properties are used to position the element." }, { "code": null, "e": 1490, "s": 1398, "text": "A fixed element does not leave a gap in the page where it would normally have been located." }, { "code": null, "e": 1584, "s": 1490, "text": "Notice the fixed element in the lower-right corner of the page. Here is the CSS that is used:" }, { "code": null, "e": 1741, "s": 1584, "text": "An element with position: absolute; is positioned relative to the nearest positioned ancestor \n(instead of positioned relative to the viewport, like fixed)." }, { "code": null, "e": 1878, "s": 1741, "text": "However; if an absolute positioned element has no positioned ancestors, \nit uses the document body, and moves along with page scrolling." }, { "code": null, "e": 1973, "s": 1878, "text": "Note: Absolute positioned elements are removed from the normal flow, and can overlap elements." }, { "code": null, "e": 1999, "s": 1973, "text": "Here is a simple example:" }, { "code": null, "e": 2029, "s": 1999, "text": "Here is the CSS that is used:" }, { "code": null, "e": 2114, "s": 2029, "text": "An element with position: sticky; is positioned based on the user's scroll position." }, { "code": null, "e": 2331, "s": 2114, "text": "A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it \"sticks\" in place (like position:fixed)." }, { "code": null, "e": 2407, "s": 2331, "text": "Try to scroll inside this frame to understand how sticky positioning works." }, { "code": null, "e": 2677, "s": 2407, "text": "Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus." }, { "code": null, "e": 2947, "s": 2677, "text": "Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus." }, { "code": null, "e": 3217, "s": 2947, "text": "Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus." }, { "code": null, "e": 3432, "s": 3217, "text": "Note: Internet Explorer does not support sticky positioning. Safari requires a -webkit- \nprefix (see example below). You must also specify at least one of top, right, bottom or left for \nsticky positioning to work." }, { "code": null, "e": 3544, "s": 3432, "text": "In this example, the sticky element sticks to the top of the page (top: 0), when you reach its scroll position." }, { "code": null, "e": 3580, "s": 3544, "text": "How to position text over an image:" }, { "code": null, "e": 3597, "s": 3580, "text": "Try it Yourself:" }, { "code": null, "e": 3742, "s": 3597, "text": "Set the shape of an element\nThis example demonstrates how to set the shape of an element. The element is clipped into this shape, and displayed." }, { "code": null, "e": 3861, "s": 3742, "text": "Position the <h1> element to always be 50px from the top,\nand 10px from the right, relative to the window/frame edges." }, { "code": null, "e": 4015, "s": 3861, "text": "<style>\nh1 {\n : ;\n : 50px;\n : 10px;\n}\n</style>\n\n<body>\n <h1>This is a heading</h1>\n <p>This is a paragraph</p>\n <p>This is a paragraph</p>\n</body>\n" }, { "code": null, "e": 4034, "s": 4015, "text": "Start the Exercise" }, { "code": null, "e": 4067, "s": 4034, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 4109, "s": 4067, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 4216, "s": 4109, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 4235, "s": 4216, "text": "help@w3schools.com" } ]
ES6 - Browsers
It is important to understand the differences between different browsers in order to handle each in the way it is expected. So it is important to know which browser your web page is running in. To get information about the browser your webpage is currently running in, use the built-in navigator object. There are several Navigator related properties that you can use in your webpage. The following is a list of the names and its description. appCodeName This property is a string that contains the code name of the browser, Netscape for Netscape and Microsoft Internet Explorer for Internet Explorer. appVersion This property is a string that contains the version of the browser as well as other useful information such as its language and compatibility. language This property contains the two-letter abbreviation for the language that is used by the browser. Netscape only. mimTypes[] This property is an array that contains all MIME types supported by the client. Netscape only. platform[] This property is a string that contains the platform for which the browser was compiled. "Win32" for 32-bit Windows operating systems. plugins[] This property is an array containing all the plug-ins that have been installed on the client. Netscape only. userAgent[] This property is a string that contains the code name and version of the browser. This value is sent to the originating server to identify the client. There are several Navigator-specific methods. Here is a list of their names and descriptions. javaEnabled() This method determines if JavaScript is enabled in the client. If JavaScript is enabled, this method returns true; otherwise, it returns false. plugings.refresh This method makes newly installed plug-ins available and populates the plugins array with all new plug-in names. Netscape only preference(name,value) This method allows a signed script to get and set some Netscape preferences. If the second parameter is omitted, this method will return the value of the specified preference; otherwise, it sets the value. Netscape only taintEnabled() This method returns true if data tainting is enabled; false otherwise The following JavaScript code can be used to find out the name of a browser and then accordingly an HTML page can be served to the user. <html> <head> <title>Browser Detection Example</title> </head> <body> <script type = "text/javascript"> <!-- var userAgent = navigator.userAgent; var opera = (userAgent.indexOf('Opera') ! = -1); var ie = (userAgent.indexOf('MSIE') != -1); var gecko = (userAgent.indexOf('Gecko') ! = -1); var netscape = (userAgent.indexOf('Mozilla') ! = -1); var version = navigator.appVersion; if (opera) { document.write("Opera based browser"); // Keep your opera specific URL here. } else if (gecko) { document.write("Mozilla based browser"); // Keep your gecko specific URL here. } else if (ie) { document.write("IE based browser"); // Keep your IE specific URL here. } else if (netscape) { document.write("Netscape based browser"); // Keep your Netscape specific URL here. } else { document.write("Unknown browser"); } // You can include version to along with any above condition. document.write("<br /> Browser version info : " + version ); // --> </script> </body> </html> The following output is displayed on successful execution of the above code. Mozilla based browser Browser version info : 5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36 32 Lectures 3.5 hours Sharad Kumar 40 Lectures 5 hours Richa Maheshwari 16 Lectures 1 hours Anadi Sharma 50 Lectures 6.5 hours Gowthami Swarna 14 Lectures 1 hours Deepti Trivedi 31 Lectures 1.5 hours Shweta Print Add Notes Bookmark this page
[ { "code": null, "e": 2581, "s": 2277, "text": "It is important to understand the differences between different browsers in order to handle each in the way it is expected. So it is important to know which browser your web page is running in. To get information about the browser your webpage is currently running in, use the built-in navigator object." }, { "code": null, "e": 2720, "s": 2581, "text": "There are several Navigator related properties that you can use in your webpage. The following is a list of the names and its description." }, { "code": null, "e": 2732, "s": 2720, "text": "appCodeName" }, { "code": null, "e": 2879, "s": 2732, "text": "This property is a string that contains the code name of the browser, Netscape for Netscape and Microsoft Internet Explorer for Internet Explorer." }, { "code": null, "e": 2890, "s": 2879, "text": "appVersion" }, { "code": null, "e": 3033, "s": 2890, "text": "This property is a string that contains the version of the browser as well as other useful information such as its language and compatibility." }, { "code": null, "e": 3042, "s": 3033, "text": "language" }, { "code": null, "e": 3154, "s": 3042, "text": "This property contains the two-letter abbreviation for the language that is used by the browser. Netscape only." }, { "code": null, "e": 3165, "s": 3154, "text": "mimTypes[]" }, { "code": null, "e": 3260, "s": 3165, "text": "This property is an array that contains all MIME types supported by the client. Netscape only." }, { "code": null, "e": 3271, "s": 3260, "text": "platform[]" }, { "code": null, "e": 3406, "s": 3271, "text": "This property is a string that contains the platform for which the browser was compiled. \"Win32\" for 32-bit Windows operating systems." }, { "code": null, "e": 3416, "s": 3406, "text": "plugins[]" }, { "code": null, "e": 3525, "s": 3416, "text": "This property is an array containing all the plug-ins that have been installed on the client. Netscape only." }, { "code": null, "e": 3537, "s": 3525, "text": "userAgent[]" }, { "code": null, "e": 3688, "s": 3537, "text": "This property is a string that contains the code name and version of the browser. This value is sent to the originating server to identify the client." }, { "code": null, "e": 3782, "s": 3688, "text": "There are several Navigator-specific methods. Here is a list of their names and descriptions." }, { "code": null, "e": 3796, "s": 3782, "text": "javaEnabled()" }, { "code": null, "e": 3940, "s": 3796, "text": "This method determines if JavaScript is enabled in the client. If JavaScript is enabled, this method returns true; otherwise, it returns false." }, { "code": null, "e": 3957, "s": 3940, "text": "plugings.refresh" }, { "code": null, "e": 4084, "s": 3957, "text": "This method makes newly installed plug-ins available and populates the plugins array with all new plug-in names. Netscape only" }, { "code": null, "e": 4107, "s": 4084, "text": "preference(name,value)" }, { "code": null, "e": 4327, "s": 4107, "text": "This method allows a signed script to get and set some Netscape preferences. If the second parameter is omitted, this method will return the value of the specified preference; otherwise, it sets the value. Netscape only" }, { "code": null, "e": 4342, "s": 4327, "text": "taintEnabled()" }, { "code": null, "e": 4412, "s": 4342, "text": "This method returns true if data tainting is enabled; false otherwise" }, { "code": null, "e": 4549, "s": 4412, "text": "The following JavaScript code can be used to find out the name of a browser and then accordingly an HTML page can be served to the user." }, { "code": null, "e": 5971, "s": 4549, "text": "<html> \n <head> \n <title>Browser Detection Example</title> \n </head> \n\n <body> \n <script type = \"text/javascript\"> \n <!-- \n var userAgent = navigator.userAgent; \n var opera = (userAgent.indexOf('Opera') \n ! = -1); var ie = (userAgent.indexOf('MSIE') \n != -1); var gecko = (userAgent.indexOf('Gecko') \n ! = -1); var netscape = (userAgent.indexOf('Mozilla') \n ! = -1); var version = navigator.appVersion; \n\n if (opera) { \n document.write(\"Opera based browser\"); \n // Keep your opera specific URL here. \n } else if (gecko) {\n document.write(\"Mozilla based browser\"); \n // Keep your gecko specific URL here. \n } else if (ie) { \n document.write(\"IE based browser\"); \n // Keep your IE specific URL here. \n } else if (netscape) { \n document.write(\"Netscape based browser\"); \n // Keep your Netscape specific URL here. \n } else { \n document.write(\"Unknown browser\"); \n } \n // You can include version to along with any above condition. \n document.write(\"<br /> Browser version info : \" + version ); \n //\n --> \n </script> \n </body> \n \n</html>" }, { "code": null, "e": 6048, "s": 5971, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 6101, "s": 6048, "text": "Mozilla based browser \nBrowser version info : 5.0 \n" }, { "code": null, "e": 6199, "s": 6101, "text": "(Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, { "code": null, "e": 6234, "s": 6199, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6248, "s": 6234, "text": " Sharad Kumar" }, { "code": null, "e": 6281, "s": 6248, "text": "\n 40 Lectures \n 5 hours \n" }, { "code": null, "e": 6299, "s": 6281, "text": " Richa Maheshwari" }, { "code": null, "e": 6332, "s": 6299, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 6346, "s": 6332, "text": " Anadi Sharma" }, { "code": null, "e": 6381, "s": 6346, "text": "\n 50 Lectures \n 6.5 hours \n" }, { "code": null, "e": 6398, "s": 6381, "text": " Gowthami Swarna" }, { "code": null, "e": 6431, "s": 6398, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 6447, "s": 6431, "text": " Deepti Trivedi" }, { "code": null, "e": 6482, "s": 6447, "text": "\n 31 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6490, "s": 6482, "text": " Shweta" }, { "code": null, "e": 6497, "s": 6490, "text": " Print" }, { "code": null, "e": 6508, "s": 6497, "text": " Add Notes" } ]
KnockoutJS - Enable Binding
This binding is used to enable certain DOM element based on specified condition. This is useful with form elements such as input, select, and textarea. Syntax enable: <binding-value> Parameters Parameter consists of Boolean like value which decides whether the element should be enabled or not. Element is enabled, if the parameter is true or true like value. Parameter consists of Boolean like value which decides whether the element should be enabled or not. Element is enabled, if the parameter is true or true like value. Non-Boolean values are considered as loosely Boolean values. Meaning 0 and null are considered as false-like value, and Integer and non null objects are considered as true-like value. Non-Boolean values are considered as loosely Boolean values. Meaning 0 and null are considered as false-like value, and Integer and non null objects are considered as true-like value. If the condition in the parameter contains any observable value, then the condition is re-evaluated whenever observable value changes. Correspondingly, related markup will be enabled based on the condition result. If the condition in the parameter contains any observable value, then the condition is re-evaluated whenever observable value changes. Correspondingly, related markup will be enabled based on the condition result. Example Let us take a look at the following example which demonstrates the use of enable binding. <!DOCTYPE html> <head> <title>KnockoutJS Enable Binding</title> <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js" type = "text/javascript"></script> </head> <body> <p> Enter your feedback here:<br><br> <textarea rows = 5 data-bind = "value: hasFeedback, valueUpdate: 'afterkeydown'" ></textarea> </p> <p><button data-bind = "enable: hasFeedback">Save Feedback</button></p> <script type = "text/javascript"> function ViewModel () { hasFeedback = ko.observable(''); }; var vm = new ViewModel(); ko.applyBindings(vm); </script> </body> </html> Output Let's carry out the following steps to see how the above code works − Save the above code in enable-bind.htm file. Save the above code in enable-bind.htm file. Open this HTML file in a browser. Open this HTML file in a browser. The save button is enabled only when the user has entered a feedback. The save button is enabled only when the user has entered a feedback. Enter your feedback here: Save Feedback You can also use a random expression to decide whether the element should be enabled or not. Example Let us take a look at the following example which demonstrates the use of random expression to invoke enable binding. <!DOCTYPE html> <head> <title>KnockoutJS Enable binding</title> <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js" type = "text/javascript"></script> </head> <body> <p>Below button will be enabled only when product stock is available.</p> <button data-bind = "enable: productStock() > 0 "> Product Details </button> <script type = "text/javascript"> function AppViewModel() { this.productStock = ko.observable(-10); }; var vm = new AppViewModel(); ko.applyBindings(vm); </script> </body> </html> Output Let's carry out the following steps to see how the above code works − Save the above code in enable-random-bind.htm file. Save the above code in enable-random-bind.htm file. Open this HTML file in a browser. Open this HTML file in a browser. The Product Details button is enabled only when the product stock is available. The Product Details button is enabled only when the product stock is available. Below button will be enabled only when product stock is available. 38 Lectures 2 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2004, "s": 1852, "text": "This binding is used to enable certain DOM element based on specified condition. This is useful with form elements such as input, select, and textarea." }, { "code": null, "e": 2011, "s": 2004, "text": "Syntax" }, { "code": null, "e": 2036, "s": 2011, "text": "enable: <binding-value>\n" }, { "code": null, "e": 2047, "s": 2036, "text": "Parameters" }, { "code": null, "e": 2213, "s": 2047, "text": "Parameter consists of Boolean like value which decides whether the element should be enabled or not. Element is enabled, if the parameter is true or true like value." }, { "code": null, "e": 2379, "s": 2213, "text": "Parameter consists of Boolean like value which decides whether the element should be enabled or not. Element is enabled, if the parameter is true or true like value." }, { "code": null, "e": 2563, "s": 2379, "text": "Non-Boolean values are considered as loosely Boolean values. Meaning 0 and null are considered as false-like value, and Integer and non null objects are considered as true-like value." }, { "code": null, "e": 2747, "s": 2563, "text": "Non-Boolean values are considered as loosely Boolean values. Meaning 0 and null are considered as false-like value, and Integer and non null objects are considered as true-like value." }, { "code": null, "e": 2961, "s": 2747, "text": "If the condition in the parameter contains any observable value, then the condition is re-evaluated whenever observable value changes. Correspondingly, related markup will be enabled based on the condition result." }, { "code": null, "e": 3175, "s": 2961, "text": "If the condition in the parameter contains any observable value, then the condition is re-evaluated whenever observable value changes. Correspondingly, related markup will be enabled based on the condition result." }, { "code": null, "e": 3183, "s": 3175, "text": "Example" }, { "code": null, "e": 3273, "s": 3183, "text": "Let us take a look at the following example which demonstrates the use of enable binding." }, { "code": null, "e": 3989, "s": 3273, "text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS Enable Binding</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js\"\n type = \"text/javascript\"></script>\n </head>\n\n <body>\n <p> Enter your feedback here:<br><br>\n <textarea rows = 5 data-bind = \"value: hasFeedback, \n valueUpdate: 'afterkeydown'\" ></textarea>\n </p>\n \n <p><button data-bind = \"enable: hasFeedback\">Save Feedback</button></p>\n\n <script type = \"text/javascript\">\n function ViewModel () {\n hasFeedback = ko.observable('');\n };\n\n var vm = new ViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 3996, "s": 3989, "text": "Output" }, { "code": null, "e": 4066, "s": 3996, "text": "Let's carry out the following steps to see how the above code works −" }, { "code": null, "e": 4111, "s": 4066, "text": "Save the above code in enable-bind.htm file." }, { "code": null, "e": 4156, "s": 4111, "text": "Save the above code in enable-bind.htm file." }, { "code": null, "e": 4190, "s": 4156, "text": "Open this HTML file in a browser." }, { "code": null, "e": 4224, "s": 4190, "text": "Open this HTML file in a browser." }, { "code": null, "e": 4294, "s": 4224, "text": "The save button is enabled only when the user has entered a feedback." }, { "code": null, "e": 4364, "s": 4294, "text": "The save button is enabled only when the user has entered a feedback." }, { "code": null, "e": 4392, "s": 4364, "text": " Enter your feedback here:\n" }, { "code": null, "e": 4406, "s": 4392, "text": "Save Feedback" }, { "code": null, "e": 4499, "s": 4406, "text": "You can also use a random expression to decide whether the element should be enabled or not." }, { "code": null, "e": 4507, "s": 4499, "text": "Example" }, { "code": null, "e": 4625, "s": 4507, "text": "Let us take a look at the following example which demonstrates the use of random expression to invoke enable binding." }, { "code": null, "e": 5284, "s": 4625, "text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS Enable binding</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js\"\n type = \"text/javascript\"></script>\n </head>\n\n <body>\n <p>Below button will be enabled only when product stock is available.</p>\n <button data-bind = \"enable: productStock() > 0 \">\n Product Details\n </button>\n\n <script type = \"text/javascript\">\n function AppViewModel() {\n this.productStock = ko.observable(-10);\n };\n \n var vm = new AppViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 5291, "s": 5284, "text": "Output" }, { "code": null, "e": 5361, "s": 5291, "text": "Let's carry out the following steps to see how the above code works −" }, { "code": null, "e": 5413, "s": 5361, "text": "Save the above code in enable-random-bind.htm file." }, { "code": null, "e": 5465, "s": 5413, "text": "Save the above code in enable-random-bind.htm file." }, { "code": null, "e": 5499, "s": 5465, "text": "Open this HTML file in a browser." }, { "code": null, "e": 5533, "s": 5499, "text": "Open this HTML file in a browser." }, { "code": null, "e": 5613, "s": 5533, "text": "The Product Details button is enabled only when the product stock is available." }, { "code": null, "e": 5693, "s": 5613, "text": "The Product Details button is enabled only when the product stock is available." }, { "code": null, "e": 5760, "s": 5693, "text": "Below button will be enabled only when product stock is available." }, { "code": null, "e": 5793, "s": 5760, "text": "\n 38 Lectures \n 2 hours \n" }, { "code": null, "e": 5813, "s": 5793, "text": " Skillbakerystudios" }, { "code": null, "e": 5820, "s": 5813, "text": " Print" }, { "code": null, "e": 5831, "s": 5820, "text": " Add Notes" } ]
fgets() and gets() in C language - GeeksforGeeks
15 Nov, 2017 For reading a string value with spaces, we can use either gets() or fgets() in C programming language. Here, we will see what is the difference between gets() and fgets(). fgets() It reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.Syntax : char *fgets(char *str, int n, FILE *stream) str : Pointer to an array of chars where the string read is copied. n : Maximum number of characters to be copied into str (including the terminating null-character). *stream : Pointer to a FILE object that identifies an input stream. stdin can be used as argument to read from the standard input. returns : the function returns str It follow some parameter such as Maximum length, buffer, input device reference. It is safe to use because it checks the array bound. It keep on reading until new line character encountered or maximum limit of character array. Example : Let’s say the maximum number of characters are 15 and input length is greater than 15 but still fgets() will read only 15 character and print it. // C program to illustrate// fgets()#include <stdio.h>#define MAX 15int main(){ char buf[MAX]; fgets(buf, MAX, stdin); printf("string is: %s\n", buf); return 0;} Since fgets() reads input from user, we need to provide input during runtime. Input: Hello and welcome to GeeksforGeeks Output: Hello and welc gets() Reads characters from the standard input (stdin) and stores them as a C string into str until a newline character or the end-of-file is reached.Syntax: char * gets ( char * str ); str :Pointer to a block of memory (array of char) where the string read is copied as a C string. returns : the function returns str It is not safe to use because it does not check the array bound. It is used to read string from user until newline character not encountered. Example : Suppose we have a character array of 15 characters and input is greater than 15 characters, gets() will read all these characters and store them into variable.Since, gets() do not check the maximum limit of input characters, so at any time compiler may return buffer overflow error. // C program to illustrate// gets()#include <stdio.h>#define MAX 15 int main(){ char buf[MAX]; printf("Enter a string: "); gets(buf); printf("string is: %s\n", buf); return 0;} Since gets() reads input from user, we need to provide input during runtime. Input: Hello and welcome to GeeksforGeeks Output: Hello and welcome to GeeksforGeeks C-File Handling C Language Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. fork() in C Command line arguments in C/C++ Function Pointer in C Substring in C++ Structures in C Top 10 algorithms in Interview Questions vector::push_back() and vector::pop_back() in C++ STL Overview of Data Structures | Set 1 (Linear Data Structures) How to write Regular Expressions? Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)
[ { "code": null, "e": 24514, "s": 24486, "text": "\n15 Nov, 2017" }, { "code": null, "e": 24686, "s": 24514, "text": "For reading a string value with spaces, we can use either gets() or fgets() in C programming language. Here, we will see what is the difference between gets() and fgets()." }, { "code": null, "e": 24694, "s": 24686, "text": "fgets()" }, { "code": null, "e": 24926, "s": 24694, "text": "It reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.Syntax :" }, { "code": null, "e": 25306, "s": 24926, "text": "char *fgets(char *str, int n, FILE *stream)\nstr : Pointer to an array of chars where the string read is copied.\nn : Maximum number of characters to be copied into str \n(including the terminating null-character).\n*stream : Pointer to a FILE object that identifies an input stream.\nstdin can be used as argument to read from the standard input.\n\nreturns : the function returns str\n" }, { "code": null, "e": 25387, "s": 25306, "text": "It follow some parameter such as Maximum length, buffer, input device reference." }, { "code": null, "e": 25440, "s": 25387, "text": "It is safe to use because it checks the array bound." }, { "code": null, "e": 25533, "s": 25440, "text": "It keep on reading until new line character encountered or maximum limit of character array." }, { "code": null, "e": 25689, "s": 25533, "text": "Example : Let’s say the maximum number of characters are 15 and input length is greater than 15 but still fgets() will read only 15 character and print it." }, { "code": "// C program to illustrate// fgets()#include <stdio.h>#define MAX 15int main(){ char buf[MAX]; fgets(buf, MAX, stdin); printf(\"string is: %s\\n\", buf); return 0;}", "e": 25865, "s": 25689, "text": null }, { "code": null, "e": 25943, "s": 25865, "text": "Since fgets() reads input from user, we need to provide input during runtime." }, { "code": null, "e": 26010, "s": 25943, "text": "Input:\nHello and welcome to GeeksforGeeks\n\nOutput:\nHello and welc\n" }, { "code": null, "e": 26017, "s": 26010, "text": "gets()" }, { "code": null, "e": 26169, "s": 26017, "text": "Reads characters from the standard input (stdin) and stores them as a C string into str until a newline character or the end-of-file is reached.Syntax:" }, { "code": null, "e": 26332, "s": 26169, "text": "char * gets ( char * str );\nstr :Pointer to a block of memory (array of char) \nwhere the string read is copied as a C string.\nreturns : the function returns str\n " }, { "code": null, "e": 26397, "s": 26332, "text": "It is not safe to use because it does not check the array bound." }, { "code": null, "e": 26474, "s": 26397, "text": "It is used to read string from user until newline character not encountered." }, { "code": null, "e": 26767, "s": 26474, "text": "Example : Suppose we have a character array of 15 characters and input is greater than 15 characters, gets() will read all these characters and store them into variable.Since, gets() do not check the maximum limit of input characters, so at any time compiler may return buffer overflow error." }, { "code": "// C program to illustrate// gets()#include <stdio.h>#define MAX 15 int main(){ char buf[MAX]; printf(\"Enter a string: \"); gets(buf); printf(\"string is: %s\\n\", buf); return 0;}", "e": 26964, "s": 26767, "text": null }, { "code": null, "e": 27041, "s": 26964, "text": "Since gets() reads input from user, we need to provide input during runtime." }, { "code": null, "e": 27128, "s": 27041, "text": "Input:\nHello and welcome to GeeksforGeeks\n\nOutput:\nHello and welcome to GeeksforGeeks\n" }, { "code": null, "e": 27144, "s": 27128, "text": "C-File Handling" }, { "code": null, "e": 27155, "s": 27144, "text": "C Language" }, { "code": null, "e": 27160, "s": 27155, "text": "Misc" }, { "code": null, "e": 27165, "s": 27160, "text": "Misc" }, { "code": null, "e": 27170, "s": 27165, "text": "Misc" }, { "code": null, "e": 27268, "s": 27170, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27280, "s": 27268, "text": "fork() in C" }, { "code": null, "e": 27312, "s": 27280, "text": "Command line arguments in C/C++" }, { "code": null, "e": 27334, "s": 27312, "text": "Function Pointer in C" }, { "code": null, "e": 27351, "s": 27334, "text": "Substring in C++" }, { "code": null, "e": 27367, "s": 27351, "text": "Structures in C" }, { "code": null, "e": 27408, "s": 27367, "text": "Top 10 algorithms in Interview Questions" }, { "code": null, "e": 27462, "s": 27408, "text": "vector::push_back() and vector::pop_back() in C++ STL" }, { "code": null, "e": 27523, "s": 27462, "text": "Overview of Data Structures | Set 1 (Linear Data Structures)" }, { "code": null, "e": 27557, "s": 27523, "text": "How to write Regular Expressions?" } ]
How to draw a rectangle on HTML5 Canvas?
The HTML5 <canvas> tag is used to draw graphics, animations, etc. using scripting. It is a new tag introduced in HTML5. The canvas element has a DOM method called getContext, which obtains rendering context and its drawing functions. This function takes one parameter, the type of context 2d. To draw a rectangle with HTML5 canvas, use the fillRect(x, y, width, height) method: You can try to run the following code to learn how to draw a rectangle with HTML5 Canvas <!DOCTYPE html> <html> <head> <title>HTML5 Canvas Tag</title> </head> <body> <canvas id="newCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas> <script> var c = document.getElementById('newCanvas'); var ctx = c.getContext('2d'); ctx.fillStyle = '#7cce2b'; ctx.fillRect(0,0,300,100); </script> </body> </html>
[ { "code": null, "e": 1355, "s": 1062, "text": "The HTML5 <canvas> tag is used to draw graphics, animations, etc. using scripting. It is a new tag introduced in HTML5. The canvas element has a DOM method called getContext, which obtains rendering context and its drawing functions. This function takes one parameter, the type of context 2d." }, { "code": null, "e": 1440, "s": 1355, "text": "To draw a rectangle with HTML5 canvas, use the fillRect(x, y, width, height) method:" }, { "code": null, "e": 1529, "s": 1440, "text": "You can try to run the following code to learn how to draw a rectangle with HTML5 Canvas" }, { "code": null, "e": 1948, "s": 1529, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML5 Canvas Tag</title>\n </head>\n \n <body>\n <canvas id=\"newCanvas\" width=\"200\" height=\"100\" style=\"border:1px\n solid #000000;\"></canvas>\n <script>\n var c = document.getElementById('newCanvas');\n var ctx = c.getContext('2d');\n ctx.fillStyle = '#7cce2b';\n ctx.fillRect(0,0,300,100);\n </script>\n </body>\n</html>" } ]
C program to print area of triangle, square, circle, rectangle and polygon using switch case.
Write a program to calculate the area of triangle, square, circle, rectangle and polygon by using the switch case. Based on case number, the area of triangle, square, circle, rectangle and polygon is calculated. The logic used to find area of triangle is as follows − Enter sides of a triangle a,b,c s=(float)(a+b+c)/2; area=(float)(sqrt(s*(s-a)*(s-b)*(s-c))); The logic used to find area of square is as follows − Enter the side of square at runtime. area=(float)side*side; The logic used to find area of circle is as follows − Enter the radius of circle at runtime area=(float)3.14159*radius*radius; The logic used to find area of rectangle is as follows − Enter length and breadth of rectangle at runtime area=(float)len*breadth; The logic used to find area of parallelogram is as follows − Enter base and height of parallelogram area=(float)base*height; Following is the C program to calculate the area of triangle, square, circle, rectangle and polygon by using the switch case − #include<stdio.h> #include<math.h> main(){ int choice; printf("Enter\n1 to find area of Triangle\n2 for finding area of Square\n3 for finding area of Circle\n4 for finding area of Rectangle\n5 for Parallelogram\n"); scanf("%d",&choice); switch(choice) { case 1: { int a,b,c; float s,area; printf("Enter sides of triangle\n"); scanf("%d%d %d",&a,&b,&c); s=(float)(a+b+c)/2; area=(float)(sqrt(s*(s-a)*(s-b)*(s-c))); printf("Area of Triangle is %f\n",area); break; } case 2: { float side,area; printf("Enter Sides of Square\n"); scanf("%f",&side); area=(float)side*side; printf("Area of Square is %f\n",area); break; } case 3: { float radius,area; printf("Enter Radius of Circle\n"); scanf("%f",&radius); area=(float)3.14159*radius*radius; printf("Area of Circle %f\n",area); break; } case 4: { float len,breadth,area; printf("Enter Length and Breadth of Rectangle\n"); scanf("%f %f",&len,&breadth); area=(float)len*breadth; printf("Area of Rectangle is %f\n",area); break; } case 5: { float base,height,area; printf("Enter base and height of Parallelogram\n"); scanf("%f %f",&base,&height); area=(float)base*height; printf("Enter area of Parallelogram is %f\n",area); break; } default: { printf("Invalid Choice\n"); break; } } } When the above program is executed, it produces the following output − When the above program is executed, it produces the following output: Run 1: 1 to find area of Triangle 2 for finding area of Square 3 for finding area of Circle 4 for finding area of Rectangle 5 for Parallelogram 5 Enter base and height of Parallelogram 2 4 6 8 Enter area of Parallelogram is 8.000000 Run 2: 1 to find area of Triangle 2 for finding area of Square 3 for finding area of Circle 4 for finding area of Rectangle 5 for Parallelogram 3 Enter Radius of Circle 4.5 Area of Circle is 63.617199
[ { "code": null, "e": 1177, "s": 1062, "text": "Write a program to calculate the area of triangle, square, circle, rectangle and polygon by using the switch case." }, { "code": null, "e": 1274, "s": 1177, "text": "Based on case number, the area of triangle, square, circle, rectangle and polygon is calculated." }, { "code": null, "e": 1330, "s": 1274, "text": "The logic used to find area of triangle is as follows −" }, { "code": null, "e": 1362, "s": 1330, "text": "Enter sides of a triangle a,b,c" }, { "code": null, "e": 1423, "s": 1362, "text": "s=(float)(a+b+c)/2;\narea=(float)(sqrt(s*(s-a)*(s-b)*(s-c)));" }, { "code": null, "e": 1477, "s": 1423, "text": "The logic used to find area of square is as follows −" }, { "code": null, "e": 1514, "s": 1477, "text": "Enter the side of square at runtime." }, { "code": null, "e": 1537, "s": 1514, "text": "area=(float)side*side;" }, { "code": null, "e": 1591, "s": 1537, "text": "The logic used to find area of circle is as follows −" }, { "code": null, "e": 1629, "s": 1591, "text": "Enter the radius of circle at runtime" }, { "code": null, "e": 1664, "s": 1629, "text": "area=(float)3.14159*radius*radius;" }, { "code": null, "e": 1721, "s": 1664, "text": "The logic used to find area of rectangle is as follows −" }, { "code": null, "e": 1770, "s": 1721, "text": "Enter length and breadth of rectangle at runtime" }, { "code": null, "e": 1795, "s": 1770, "text": "area=(float)len*breadth;" }, { "code": null, "e": 1856, "s": 1795, "text": "The logic used to find area of parallelogram is as follows −" }, { "code": null, "e": 1895, "s": 1856, "text": "Enter base and height of parallelogram" }, { "code": null, "e": 1920, "s": 1895, "text": "area=(float)base*height;" }, { "code": null, "e": 2047, "s": 1920, "text": "Following is the C program to calculate the area of triangle, square, circle, rectangle and polygon by using the switch case −" }, { "code": null, "e": 3667, "s": 2047, "text": "#include<stdio.h>\n#include<math.h>\nmain(){\n int choice;\n printf(\"Enter\\n1 to find area of Triangle\\n2 for finding area of Square\\n3 for finding area of Circle\\n4 for finding area of Rectangle\\n5 for Parallelogram\\n\");\n scanf(\"%d\",&choice);\n switch(choice) {\n case 1: {\n int a,b,c;\n float s,area;\n printf(\"Enter sides of triangle\\n\");\n scanf(\"%d%d %d\",&a,&b,&c);\n s=(float)(a+b+c)/2;\n area=(float)(sqrt(s*(s-a)*(s-b)*(s-c)));\n printf(\"Area of Triangle is %f\\n\",area);\n break;\n }\n case 2: {\n float side,area;\n printf(\"Enter Sides of Square\\n\");\n scanf(\"%f\",&side);\n area=(float)side*side;\n printf(\"Area of Square is %f\\n\",area);\n break;\n }\n case 3: {\n float radius,area;\n printf(\"Enter Radius of Circle\\n\");\n scanf(\"%f\",&radius);\n area=(float)3.14159*radius*radius;\n printf(\"Area of Circle %f\\n\",area);\n break;\n }\n case 4: {\n float len,breadth,area;\n printf(\"Enter Length and Breadth of Rectangle\\n\");\n scanf(\"%f %f\",&len,&breadth);\n area=(float)len*breadth;\n printf(\"Area of Rectangle is %f\\n\",area);\n break;\n }\n case 5: {\n float base,height,area;\n printf(\"Enter base and height of Parallelogram\\n\");\n scanf(\"%f %f\",&base,&height);\n area=(float)base*height;\n printf(\"Enter area of Parallelogram is %f\\n\",area);\n break;\n }\n default: {\n printf(\"Invalid Choice\\n\");\n break;\n }\n }\n}" }, { "code": null, "e": 3738, "s": 3667, "text": "When the above program is executed, it produces the following output −" }, { "code": null, "e": 4242, "s": 3738, "text": "When the above program is executed, it produces the following output:\nRun 1:\n1 to find area of Triangle\n2 for finding area of Square\n3 for finding area of Circle\n4 for finding area of Rectangle\n5 for Parallelogram\n5\nEnter base and height of Parallelogram\n2 4 6 8\nEnter area of Parallelogram is 8.000000\nRun 2:\n1 to find area of Triangle\n2 for finding area of Square\n3 for finding area of Circle\n4 for finding area of Rectangle\n5 for Parallelogram\n3\nEnter Radius of Circle\n4.5\nArea of Circle is 63.617199" } ]
PowerBI RS: Setting Data Refresh in Trigger Mode | by Davis Zhang | Towards Data Science
Using the Power BI Report Server database can do a lot of things you can’t do in Power BI Services, one of them is to set a triggered data refresh on the report data set. As the name implies, it is to trigger the dataset of your PBI reports to refresh with events. For example, when the data source referenced by the report has changed (added, changed, or deleted), then the trigger condition is activated to allow the PBI report to refresh the data immediately and keep the PBI report data up to date. The typical application process is as follows: In PBIRS, there are two main types of data refresh for PBI reports: scheduled refresh and DirectQuery. DirectQuery enables users to continuously obtain the latest data every time they use a report, but the disadvantage is that when the report query logic is complex, it may seriously affect the performance of the report. Besides, some DAX functions are not supported by the calculation engine (such as time intelligence functions). While in scheduled refresh mode, theoretically, your report performance will not be affected by the refresh behavior, and you can use any DAX function that supports PowerBI, that’s great, however, you cannot guarantee that users will get the latest data when they using reports. Therefore, this has become a very embarrassing fact. Imagine that you need to develop a report, which requires the use of DAX time intelligence functions (instead of SQL), and you must ensure that users can see the latest data in time when they using it. So how do you choose the refresh mode for your dataset? Maybe you will set your report to refresh every one minute, but if your report has more data, it will not only increase the probability of data refresh failure but also cause a certain burden on the server. Therefore, data refresh in trigger mode has become the best solution. It combines the advantages of both DirectQuery and scheduled refresh. Data refresh will only be performed when the data has changed. This can not only ensure that users can see the latest data when using reports but also reduce the burden on the server without affecting report performance. That’s why you should refresh your report data in trigger mode. First, I create a table in the database as an example. As shown below, I created a new table, inserting three rows of data-the three great generals of Ancient China in the Warring States period (475–221 BC): Bai Qi, Lian Po, and Wang Jian, simple like this: CREATE TABLE [TriggerRefreshTest]([No_] int,[Name] nvarchar(10),[Country] nvarchar(20))Insert Into [TriggerRefreshTest]values(1, 'BaiQi', 'The Kingdom of Qin'),(2, 'LianPo', 'The Kingdom of Zhao'),(3, 'WangJian', 'The Kingdom of Qin') Import the data into Power BI Desktop and publish it as follows: The effect we want to achieve now is when I insert a new row of data in the database-(Li Mu, The Kingdom of Zhao), and then immediately trigger a data refresh event to keep the report data up to date. In SSMS, create a new trigger event, as shown below: Then we need to write a trigger script with SQL. It’s OK for readers who haven’t learned SQL. You can directly use the following code. I have simplified and optimized the script. You only need to replace the following code (where I have annotated) with your report information: SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOIF OBJECT_ID( N'trigger_data_refresh') is not nullDROP TRIGGER trigger_data_refresh;GOCREATE TRIGGER trigger_data_refresh ON [TriggerRefreshTest] --Replace with your table name hereAFTER INSERTAS SET NOCOUNT ON;DECLARE @REPORT_NAME NVARCHAR( 50),@REPORT_ID VARCHAR( 100),@SUBSCRIPTION_ID VARCHAR( 100)SET @REPORT_NAME = 'WarringStates' --Replace with your PBI report name.SET @REPORT_ID = ( SELECT TOP 1 [ItemID] FROM [ReportServer].[dbo].[Catalog] WHERE [Name] = @REPORT_NAME)SET @SUBSCRIPTION_ID = ( SELECT TOP 1 SubscriptionID FROM [ReportServer].[dbo].[ReportSchedule] WHERE [ReportID] = @REPORT_ID)BEGINWAITFOR DELAY '0:0:3'exec [ReportServer].dbo.AddEvent @EventType='DataModelRefresh',@EventData=@SUBSCRIPTION_IDENDGO Finally, run the code, so our trigger refresh is now set up. Let’s insert a new row into the table — [TriggerRefreshTest]: Insert Into [TriggerRefreshTest]values (4, 'LiMu', 'The Kingdom of Zhao') Now our trigger mechanism has detected data changes, so data refresh event has been activated. Return to the report page of Power BI RS, click “Refresh” to refresh the cache, as you can see, the data just inserted is immediately shown in the report! If the data source table is maintained by multiple users, then they may modify the data at the same time, which may cause problems (such as table locking). I think one of the solutions is to force a minimum refresh interval. This can be achieved by modifying stored procedures. End~ (This article was first published in Chinese on D-BI in DEC, 2019)
[ { "code": null, "e": 342, "s": 171, "text": "Using the Power BI Report Server database can do a lot of things you can’t do in Power BI Services, one of them is to set a triggered data refresh on the report data set." }, { "code": null, "e": 721, "s": 342, "text": "As the name implies, it is to trigger the dataset of your PBI reports to refresh with events. For example, when the data source referenced by the report has changed (added, changed, or deleted), then the trigger condition is activated to allow the PBI report to refresh the data immediately and keep the PBI report data up to date. The typical application process is as follows:" }, { "code": null, "e": 1433, "s": 721, "text": "In PBIRS, there are two main types of data refresh for PBI reports: scheduled refresh and DirectQuery. DirectQuery enables users to continuously obtain the latest data every time they use a report, but the disadvantage is that when the report query logic is complex, it may seriously affect the performance of the report. Besides, some DAX functions are not supported by the calculation engine (such as time intelligence functions). While in scheduled refresh mode, theoretically, your report performance will not be affected by the refresh behavior, and you can use any DAX function that supports PowerBI, that’s great, however, you cannot guarantee that users will get the latest data when they using reports." }, { "code": null, "e": 2376, "s": 1433, "text": "Therefore, this has become a very embarrassing fact. Imagine that you need to develop a report, which requires the use of DAX time intelligence functions (instead of SQL), and you must ensure that users can see the latest data in time when they using it. So how do you choose the refresh mode for your dataset? Maybe you will set your report to refresh every one minute, but if your report has more data, it will not only increase the probability of data refresh failure but also cause a certain burden on the server. Therefore, data refresh in trigger mode has become the best solution. It combines the advantages of both DirectQuery and scheduled refresh. Data refresh will only be performed when the data has changed. This can not only ensure that users can see the latest data when using reports but also reduce the burden on the server without affecting report performance. That’s why you should refresh your report data in trigger mode." }, { "code": null, "e": 2634, "s": 2376, "text": "First, I create a table in the database as an example. As shown below, I created a new table, inserting three rows of data-the three great generals of Ancient China in the Warring States period (475–221 BC): Bai Qi, Lian Po, and Wang Jian, simple like this:" }, { "code": null, "e": 2869, "s": 2634, "text": "CREATE TABLE [TriggerRefreshTest]([No_] int,[Name] nvarchar(10),[Country] nvarchar(20))Insert Into [TriggerRefreshTest]values(1, 'BaiQi', 'The Kingdom of Qin'),(2, 'LianPo', 'The Kingdom of Zhao'),(3, 'WangJian', 'The Kingdom of Qin')" }, { "code": null, "e": 2934, "s": 2869, "text": "Import the data into Power BI Desktop and publish it as follows:" }, { "code": null, "e": 3188, "s": 2934, "text": "The effect we want to achieve now is when I insert a new row of data in the database-(Li Mu, The Kingdom of Zhao), and then immediately trigger a data refresh event to keep the report data up to date. In SSMS, create a new trigger event, as shown below:" }, { "code": null, "e": 3466, "s": 3188, "text": "Then we need to write a trigger script with SQL. It’s OK for readers who haven’t learned SQL. You can directly use the following code. I have simplified and optimized the script. You only need to replace the following code (where I have annotated) with your report information:" }, { "code": null, "e": 4267, "s": 3466, "text": "SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOIF OBJECT_ID( N'trigger_data_refresh') is not nullDROP TRIGGER trigger_data_refresh;GOCREATE TRIGGER trigger_data_refresh ON [TriggerRefreshTest] --Replace with your table name hereAFTER INSERTAS SET NOCOUNT ON;DECLARE @REPORT_NAME NVARCHAR( 50),@REPORT_ID VARCHAR( 100),@SUBSCRIPTION_ID VARCHAR( 100)SET @REPORT_NAME = 'WarringStates' --Replace with your PBI report name.SET @REPORT_ID = ( SELECT TOP 1 [ItemID] FROM [ReportServer].[dbo].[Catalog] WHERE [Name] = @REPORT_NAME)SET @SUBSCRIPTION_ID = ( SELECT TOP 1 SubscriptionID FROM [ReportServer].[dbo].[ReportSchedule] WHERE [ReportID] = @REPORT_ID)BEGINWAITFOR DELAY '0:0:3'exec [ReportServer].dbo.AddEvent @EventType='DataModelRefresh',@EventData=@SUBSCRIPTION_IDENDGO" }, { "code": null, "e": 4390, "s": 4267, "text": "Finally, run the code, so our trigger refresh is now set up. Let’s insert a new row into the table — [TriggerRefreshTest]:" }, { "code": null, "e": 4464, "s": 4390, "text": "Insert Into [TriggerRefreshTest]values (4, 'LiMu', 'The Kingdom of Zhao')" }, { "code": null, "e": 4714, "s": 4464, "text": "Now our trigger mechanism has detected data changes, so data refresh event has been activated. Return to the report page of Power BI RS, click “Refresh” to refresh the cache, as you can see, the data just inserted is immediately shown in the report!" }, { "code": null, "e": 4992, "s": 4714, "text": "If the data source table is maintained by multiple users, then they may modify the data at the same time, which may cause problems (such as table locking). I think one of the solutions is to force a minimum refresh interval. This can be achieved by modifying stored procedures." }, { "code": null, "e": 4997, "s": 4992, "text": "End~" } ]
Count total bits in a number - GeeksforGeeks
12 Jan, 2022 Given a positive number n, count total bit in it.Examples: Input : 13 Output : 4 Binary representation of 13 is 1101 Input : 183 Output : 8 Input : 4096 Output : 13 Method 1 (Using Log) The log2(n) logarithm in base 2 of n, which is the exponent to which 2 is raised to get n only integer and we add 1 find total bit in a number in log(n) time. C++ C Java Python3 C# PHP Javascript // C++ program to find total bit in given number#include <iostream> #include <cmath> unsigned countBits(unsigned int number){ // log function in base 2 // take only integer part return (int)log2(number)+1;} // Driven program int main(){ unsigned int num = 65; std::cout<<countBits(num)<<'\n'; return 0;} // This code is contributed by thedev05. // C program to find total bit in given number#include <stdio.h> #include <math.h> unsigned countBits(unsigned int number){ // log function in base 2 // take only integer part return (int)log2(number)+1;} // Driven program int main(){ unsigned int num = 65; printf("%d\n", countBits(num)); return 0;} // Java program to// find total bit// in given numberimport java.io.*; class GFG{ static int countBits(int number) { // log function in base 2 // take only integer part return (int)(Math.log(number) / Math.log(2) + 1); } // Driver code public static void main (String[] args) { int num = 65; System.out.println(countBits(num)); }} // This code is contributed by vij # Python3 program to find# total bit in given numberimport mathdef countBits(number): # log function in base 2 # take only integer part return int((math.log(number) / math.log(2)) + 1); # Driver Codenum = 65;print(countBits(num)); # This code is contributed by mits // C# program to find total bit// in given numberusing System; class GFG { static uint countBits(uint number) { // log function in base 2 // take only integer part return (uint)Math.Log(number , 2.0) + 1; } // Driver code public static void Main() { uint num = 65; Console.WriteLine(countBits(num)); }} // This code is contributed by Sam007. <?php// PHP program to find total// bit in given number function countBits($number){ // log function in base 2 // take only integer part return (int)(log($number) / log(2)) + 1;} // Driver Code$num = 65;echo(countBits($num)); // This code is contributed by Ajit.?> <script>// JavaScript program to find total bit in given number function countBits(number) { // log function in base 2 // take only integer part return Math.floor(Math.log2(number)+1); } // Driven program let num = 65; document.write(countBits(num)); // This code is contributed by Surbhi Tyagi</script> 7 Method 2 (Using Bit Traversal) C Java Python3 C# PHP Javascript /* Function to get no of bits in binary representation of positive integer */#include <stdio.h> unsigned int countBits(unsigned int n){ unsigned int count = 0; while (n) { count++; n >>= 1; } return count;} /* Driver program*/int main(){ int i = 65; printf("%d", countBits(i)); return 0;} /* Function to get no of bits in binaryrepresentation of positive integer */class GFG { static int countBits(int n) { int count = 0; while (n != 0) { count++; n >>= 1; } return count; } /* Driver program*/ public static void main(String[] arg) { int i = 65; System.out.print(countBits(i)); }} // This code is contributed by Smitha. # Function to get no of bits# in binary representation# of positive integer def countBits(n): count = 0 while (n): count += 1 n >>= 1 return count # Driver programi = 65print(countBits(i)) # This code is contributed# by Smitha /* Function to get no of bitsin binary representation ofpositive integer */using System; class GFG{ static int countBits(int n) { int count = 0; while (n != 0) { count++; n >>= 1; } return count; } // Driver Code static public void Main () { int i = 65; Console.Write(countBits(i)); }} // This code is contributed// by akt_mit. <?php// PHP Code to get no of bits in binary// representation of positive integer // Function to get no of bits in binary// representation of positive integerfunction countBits($n){ $count = 0; while ($n) { $count++; $n >>= 1; } return $count;} // Driver Code$i = 65;echo(countBits($i)); // This code is contributed by Ajit.?> <script> /* Function to get no of bitsin binary representation ofpositive integer */function countBits(n){ var count = 0; while (n != 0) { count++; n >>= 1; } return count;} // Driver Codevar i = 65;document.write(countBits(i)); </script> 7 Method 3 ( Using conversion from binary to string) Python3 # function to count the number of bits in a number ndef count_bits(n): # bin(n) returns a binary string representation of n preceded by '0b' in python binary = bin(n) # we did -2 from length of binary string to ignore '0b' return len(binary)-2 a = 65b = 183 print(f"Total bits in {a}: {count_bits(a)}")print(f"Total bits in {b}: {count_bits(b)}") # This code is contributed by udit Total bits : 7 Total bits : 8 YouTubeGeeksforGeeks500K subscribersCount total bits in a number | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:56•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=OIOJRd6ca2g" 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 Gyayak Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t Sam007 Smitha Dinesh Semwal Mahadev99 Mithun Kumar shaktipravesh surbhityagi15 rutvik_56 thedev05 harshitchandani uditkuma01 Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Cyclic Redundancy Check and Modulo-2 Division Little and Big Endian Mystery Add two numbers without using arithmetic operators Find the element that appears once Bits manipulation (Important tactics) Set, Clear and Toggle a given bit of a number in C Bit Fields in C C++ bitset and its application Write an Efficient C Program to Reverse Bits of a Number Check whether K-th bit is set or not
[ { "code": null, "e": 24908, "s": 24880, "text": "\n12 Jan, 2022" }, { "code": null, "e": 24969, "s": 24908, "text": "Given a positive number n, count total bit in it.Examples: " }, { "code": null, "e": 25079, "s": 24969, "text": "Input : 13\nOutput : 4\nBinary representation of 13 is 1101\n\nInput : 183\nOutput : 8\n\nInput : 4096\nOutput : 13" }, { "code": null, "e": 25104, "s": 25083, "text": "Method 1 (Using Log)" }, { "code": null, "e": 25264, "s": 25104, "text": "The log2(n) logarithm in base 2 of n, which is the exponent to which 2 is raised to get n only integer and we add 1 find total bit in a number in log(n) time. " }, { "code": null, "e": 25268, "s": 25264, "text": "C++" }, { "code": null, "e": 25270, "s": 25268, "text": "C" }, { "code": null, "e": 25275, "s": 25270, "text": "Java" }, { "code": null, "e": 25283, "s": 25275, "text": "Python3" }, { "code": null, "e": 25286, "s": 25283, "text": "C#" }, { "code": null, "e": 25290, "s": 25286, "text": "PHP" }, { "code": null, "e": 25301, "s": 25290, "text": "Javascript" }, { "code": "// C++ program to find total bit in given number#include <iostream> #include <cmath> unsigned countBits(unsigned int number){ // log function in base 2 // take only integer part return (int)log2(number)+1;} // Driven program int main(){ unsigned int num = 65; std::cout<<countBits(num)<<'\\n'; return 0;} // This code is contributed by thedev05.", "e": 25674, "s": 25301, "text": null }, { "code": "// C program to find total bit in given number#include <stdio.h> #include <math.h> unsigned countBits(unsigned int number){ // log function in base 2 // take only integer part return (int)log2(number)+1;} // Driven program int main(){ unsigned int num = 65; printf(\"%d\\n\", countBits(num)); return 0;}", "e": 26013, "s": 25674, "text": null }, { "code": "// Java program to// find total bit// in given numberimport java.io.*; class GFG{ static int countBits(int number) { // log function in base 2 // take only integer part return (int)(Math.log(number) / Math.log(2) + 1); } // Driver code public static void main (String[] args) { int num = 65; System.out.println(countBits(num)); }} // This code is contributed by vij", "e": 26511, "s": 26013, "text": null }, { "code": "# Python3 program to find# total bit in given numberimport mathdef countBits(number): # log function in base 2 # take only integer part return int((math.log(number) / math.log(2)) + 1); # Driver Codenum = 65;print(countBits(num)); # This code is contributed by mits", "e": 26806, "s": 26511, "text": null }, { "code": "// C# program to find total bit// in given numberusing System; class GFG { static uint countBits(uint number) { // log function in base 2 // take only integer part return (uint)Math.Log(number , 2.0) + 1; } // Driver code public static void Main() { uint num = 65; Console.WriteLine(countBits(num)); }} // This code is contributed by Sam007.", "e": 27269, "s": 26806, "text": null }, { "code": "<?php// PHP program to find total// bit in given number function countBits($number){ // log function in base 2 // take only integer part return (int)(log($number) / log(2)) + 1;} // Driver Code$num = 65;echo(countBits($num)); // This code is contributed by Ajit.?>", "e": 27566, "s": 27269, "text": null }, { "code": "<script>// JavaScript program to find total bit in given number function countBits(number) { // log function in base 2 // take only integer part return Math.floor(Math.log2(number)+1); } // Driven program let num = 65; document.write(countBits(num)); // This code is contributed by Surbhi Tyagi</script>", "e": 27920, "s": 27566, "text": null }, { "code": null, "e": 27922, "s": 27920, "text": "7" }, { "code": null, "e": 27955, "s": 27924, "text": "Method 2 (Using Bit Traversal)" }, { "code": null, "e": 27959, "s": 27957, "text": "C" }, { "code": null, "e": 27964, "s": 27959, "text": "Java" }, { "code": null, "e": 27972, "s": 27964, "text": "Python3" }, { "code": null, "e": 27975, "s": 27972, "text": "C#" }, { "code": null, "e": 27979, "s": 27975, "text": "PHP" }, { "code": null, "e": 27990, "s": 27979, "text": "Javascript" }, { "code": "/* Function to get no of bits in binary representation of positive integer */#include <stdio.h> unsigned int countBits(unsigned int n){ unsigned int count = 0; while (n) { count++; n >>= 1; } return count;} /* Driver program*/int main(){ int i = 65; printf(\"%d\", countBits(i)); return 0;}", "e": 28328, "s": 27990, "text": null }, { "code": "/* Function to get no of bits in binaryrepresentation of positive integer */class GFG { static int countBits(int n) { int count = 0; while (n != 0) { count++; n >>= 1; } return count; } /* Driver program*/ public static void main(String[] arg) { int i = 65; System.out.print(countBits(i)); }} // This code is contributed by Smitha.", "e": 28767, "s": 28328, "text": null }, { "code": "# Function to get no of bits# in binary representation# of positive integer def countBits(n): count = 0 while (n): count += 1 n >>= 1 return count # Driver programi = 65print(countBits(i)) # This code is contributed# by Smitha", "e": 29027, "s": 28767, "text": null }, { "code": "/* Function to get no of bitsin binary representation ofpositive integer */using System; class GFG{ static int countBits(int n) { int count = 0; while (n != 0) { count++; n >>= 1; } return count; } // Driver Code static public void Main () { int i = 65; Console.Write(countBits(i)); }} // This code is contributed// by akt_mit.", "e": 29461, "s": 29027, "text": null }, { "code": "<?php// PHP Code to get no of bits in binary// representation of positive integer // Function to get no of bits in binary// representation of positive integerfunction countBits($n){ $count = 0; while ($n) { $count++; $n >>= 1; } return $count;} // Driver Code$i = 65;echo(countBits($i)); // This code is contributed by Ajit.?>", "e": 29817, "s": 29461, "text": null }, { "code": "<script> /* Function to get no of bitsin binary representation ofpositive integer */function countBits(n){ var count = 0; while (n != 0) { count++; n >>= 1; } return count;} // Driver Codevar i = 65;document.write(countBits(i)); </script>", "e": 30090, "s": 29817, "text": null }, { "code": null, "e": 30092, "s": 30090, "text": "7" }, { "code": null, "e": 30143, "s": 30092, "text": "Method 3 ( Using conversion from binary to string)" }, { "code": null, "e": 30151, "s": 30143, "text": "Python3" }, { "code": "# function to count the number of bits in a number ndef count_bits(n): # bin(n) returns a binary string representation of n preceded by '0b' in python binary = bin(n) # we did -2 from length of binary string to ignore '0b' return len(binary)-2 a = 65b = 183 print(f\"Total bits in {a}: {count_bits(a)}\")print(f\"Total bits in {b}: {count_bits(b)}\") # This code is contributed by udit", "e": 30540, "s": 30151, "text": null }, { "code": null, "e": 30570, "s": 30540, "text": "Total bits : 7\nTotal bits : 8" }, { "code": null, "e": 31399, "s": 30572, "text": "YouTubeGeeksforGeeks500K subscribersCount total bits in a number | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:56•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=OIOJRd6ca2g\" 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": 31819, "s": 31399, "text": "This article is contributed by Gyayak Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 31825, "s": 31819, "text": "jit_t" }, { "code": null, "e": 31832, "s": 31825, "text": "Sam007" }, { "code": null, "e": 31853, "s": 31832, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 31863, "s": 31853, "text": "Mahadev99" }, { "code": null, "e": 31876, "s": 31863, "text": "Mithun Kumar" }, { "code": null, "e": 31890, "s": 31876, "text": "shaktipravesh" }, { "code": null, "e": 31904, "s": 31890, "text": "surbhityagi15" }, { "code": null, "e": 31914, "s": 31904, "text": "rutvik_56" }, { "code": null, "e": 31923, "s": 31914, "text": "thedev05" }, { "code": null, "e": 31939, "s": 31923, "text": "harshitchandani" }, { "code": null, "e": 31950, "s": 31939, "text": "uditkuma01" }, { "code": null, "e": 31960, "s": 31950, "text": "Bit Magic" }, { "code": null, "e": 31970, "s": 31960, "text": "Bit Magic" }, { "code": null, "e": 32068, "s": 31970, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32077, "s": 32068, "text": "Comments" }, { "code": null, "e": 32090, "s": 32077, "text": "Old Comments" }, { "code": null, "e": 32136, "s": 32090, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 32166, "s": 32136, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 32217, "s": 32166, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 32252, "s": 32217, "text": "Find the element that appears once" }, { "code": null, "e": 32290, "s": 32252, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 32341, "s": 32290, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 32357, "s": 32341, "text": "Bit Fields in C" }, { "code": null, "e": 32388, "s": 32357, "text": "C++ bitset and its application" }, { "code": null, "e": 32445, "s": 32388, "text": "Write an Efficient C Program to Reverse Bits of a Number" } ]
Check if given Preorder, Inorder and Postorder traversals are of same tree - GeeksforGeeks
17 Mar, 2022 Given Preorder, Inorder, and Postorder traversals of some tree. Write a program to check if they all are of the same tree. Examples: Input : Inorder -> 4 2 5 1 3 Preorder -> 1 2 4 5 3 Postorder -> 4 5 2 3 1 Output : Yes Explanation : All of the above three traversals are of the same tree 1 / \ 2 3 / \ 4 5 Input : Inorder -> 4 2 5 1 3 Preorder -> 1 5 4 2 3 Postorder -> 4 1 2 3 5 Output : No The most basic approach to solve this problem will be to first construct a tree using two of the three given traversals and then do the third traversal on this constructed tree and compare it with the given traversal. If both of the traversals are same then print Yes otherwise print No. Here, we use Inorder and Preorder traversals to construct the tree. We may also use Inorder and Postorder traversal instead of Preorder traversal for tree construction. You may refer to this post on how to construct a tree from given Inorder and Preorder traversal. After constructing the tree, we will obtain the Postorder traversal of this tree and compare it with the given Postorder traversal.Below is the implementation of the above approach: C++ Java Python3 C# Javascript /* C++ program to check if all three given traversals are of the same tree */#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node{ int data; struct Node *left, *right;}; // Utility function to create a new tree nodeNode* newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} /* Function to find index of value in arr[start...end] The function assumes that value is present in in[] */int search(int arr[], int strt, int end, int value){ for (int i = strt; i <= end; i++) { if(arr[i] == value) return i; }} /* Recursive function to construct binary tree of size len from Inorder traversal in[] and Preorder traversal pre[]. Initial values of inStrt and inEnd should be 0 and len -1. The function doesn't do any error checking for cases where inorder and preorder do not form a tree */Node* buildTree(int in[], int pre[], int inStrt, int inEnd){ static int preIndex = 0; if(inStrt > inEnd) return NULL; /* Pick current node from Preorder traversal using preIndex and increment preIndex */ Node *tNode = newNode(pre[preIndex++]); /* If this node has no children then return */ if (inStrt == inEnd) return tNode; /* Else find the index of this node in Inorder traversal */ int inIndex = search(in, inStrt, inEnd, tNode->data); /* Using index in Inorder traversal, construct left and right subtress */ tNode->left = buildTree(in, pre, inStrt, inIndex-1); tNode->right = buildTree(in, pre, inIndex+1, inEnd); return tNode;} /* function to compare Postorder traversal on constructed tree and given Postorder */int checkPostorder(Node* node, int postOrder[], int index){ if (node == NULL) return index; /* first recur on left child */ index = checkPostorder(node->left,postOrder,index); /* now recur on right child */ index = checkPostorder(node->right,postOrder,index); /* Compare if data at current index in both Postorder traversals are same */ if (node->data == postOrder[index]) index++; else return -1; return index;} // Driver program to test above functionsint main(){ int inOrder[] = {4, 2, 5, 1, 3}; int preOrder[] = {1, 2, 4, 5, 3}; int postOrder[] = {4, 5, 2, 3, 1}; int len = sizeof(inOrder)/sizeof(inOrder[0]); // build tree from given // Inorder and Preorder traversals Node *root = buildTree(inOrder, preOrder, 0, len - 1); // compare postorder traversal on constructed // tree with given Postorder traversal int index = checkPostorder(root,postOrder,0); // If both postorder traversals are same if (index == len) cout << "Yes"; else cout << "No"; return 0;} /* Java program to check if all three giventraversals are of the same tree */import java.util.*;class GfG { static int preIndex = 0; // A Binary Tree Nodestatic class Node{ int data; Node left, right;} // Utility function to create a new tree nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp;} /* Function to find index of value in arr[start...end]The function assumes that value is present in in[] */static int search(int arr[], int strt, int end, int value){ for (int i = strt; i <= end; i++) { if(arr[i] == value) return i; } return -1;} /* Recursive function to construct binary treeof size len from Inorder traversal in[] andPreorder traversal pre[]. Initial valuesof inStrt and inEnd should be 0 and len -1.The function doesn't do any error checking forcases where inorder and preorder do not form atree */static Node buildTree(int in[], int pre[], int inStrt, int inEnd){ if(inStrt > inEnd) return null; /* Pick current node from Preorder traversal using preIndex and increment preIndex */ Node tNode = newNode(pre[preIndex++]); /* If this node has no children then return */ if (inStrt == inEnd) return tNode; /* Else find the index of this node in Inorder traversal */ int inIndex = search(in, inStrt, inEnd, tNode.data); /* Using index in Inorder traversal, construct left and right subtress */ tNode.left = buildTree(in, pre, inStrt, inIndex-1); tNode.right = buildTree(in, pre, inIndex+1, inEnd); return tNode;} /* function to compare Postorder traversalon constructed tree and given Postorder */static int checkPostorder(Node node, int postOrder[], int index){ if (node == null) return index; /* first recur on left child */ index = checkPostorder(node.left,postOrder,index); /* now recur on right child */ index = checkPostorder(node.right,postOrder,index); /* Compare if data at current index in both Postorder traversals are same */ if (node.data == postOrder[index]) index++; else return -1; return index;} // Driver program to test above functionspublic static void main(String[] args){ int inOrder[] = {4, 2, 5, 1, 3}; int preOrder[] = {1, 2, 4, 5, 3}; int postOrder[] = {4, 5, 2, 3, 1}; int len = inOrder.length; // build tree from given // Inorder and Preorder traversals Node root = buildTree(inOrder, preOrder, 0, len - 1); // compare postorder traversal on constructed // tree with given Postorder traversal int index = checkPostorder(root,postOrder,0); // If both postorder traversals are same if (index == len) System.out.println("Yes"); else System.out.println("No"); }} # Python3 program to check if# all three given traversals# are of the same treeclass node: def __init__(self, x): self.data = x self.left = None self.right = None preIndex = 0 # Function to find index of value# in arr[start...end]. The function# assumes that value is present in indef search(arr, strt, end, value): for i in range(strt, end + 1): if(arr[i] == value): return i # Recursive function to construct# binary tree of size lenn from# Inorder traversal in and Preorder# traversal pre[]. Initial values# of inStrt and inEnd should be 0# and lenn -1. The function doesn't# do any error checking for cases# where inorder and preorder do not# form a treedef buildTree(inn, pre, inStrt, inEnd): global preIndex if(inStrt > inEnd): return None # Pick current node from Preorder # traversal using preIndex and # increment preIndex tNode = node(pre[preIndex]) preIndex += 1 # If this node has no children # then return if (inStrt == inEnd): return tNode # Else find the index of this # node in Inorder traversal inIndex = search(inn, inStrt, inEnd, tNode.data) # Using index in Inorder traversal, # construct left and right subtress tNode.left = buildTree(inn, pre, inStrt, inIndex - 1) tNode.right = buildTree(inn, pre, inIndex + 1, inEnd) return tNode # function to compare Postorder traversal# on constructed tree and given Postorderdef checkPostorder(node, postOrder, index): if (node == None): return index # first recur on left child index = checkPostorder(node.left, postOrder, index) # now recur on right child index = checkPostorder(node.right, postOrder, index) # Compare if data at current index in # both Postorder traversals are same if (node.data == postOrder[index]): index += 1 else: return - 1 return index # Driver codeif __name__ == '__main__': inOrder = [4, 2, 5, 1, 3] preOrder = [1, 2, 4, 5, 3] postOrder = [4, 5, 2, 3, 1] lenn = len(inOrder) # build tree from given # Inorder and Preorder traversals root = buildTree(inOrder, preOrder, 0, lenn - 1) # compare postorder traversal on # constructed tree with given # Postorder traversal index = checkPostorder(root, postOrder, 0) # If both postorder traversals are same if (index == lenn): print("Yes") else: print("No") # This code is contributed by Mohit Kumar 29 /* C# program to check if all three giventraversals are of the same tree */using System; public class GfG{ static int preIndex = 0; // A Binary Tree Node class Node { public int data; public Node left, right; } // Utility function to create a new tree node static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp; } /* Function to find index of value in arr[start...end] The function assumes that value is present in in[] */ static int search(int []arr, int strt, int end, int value) { for (int i = strt; i <= end; i++) { if(arr[i] == value) return i; } return -1; } /* Recursive function to construct binary tree of size len from Inorder traversal in[] and Preorder traversal pre[]. Initial values of inStrt and inEnd should be 0 and len -1. The function doesn't do any error checking for cases where inorder and preorder do not form a tree */ static Node buildTree(int []In, int []pre, int inStrt, int inEnd) { if(inStrt > inEnd) return null; /* Pick current node from Preorder traversal using preIndex and increment preIndex */ Node tNode = newNode(pre[preIndex++]); /* If this node has no children then return */ if (inStrt == inEnd) return tNode; /* Else find the index of this node in Inorder traversal */ int inIndex = search(In, inStrt, inEnd, tNode.data); /* Using index in Inorder traversal, construct left and right subtress */ tNode.left = buildTree(In, pre, inStrt, inIndex - 1); tNode.right = buildTree(In, pre, inIndex + 1, inEnd); return tNode; } /* function to compare Postorder traversal on constructed tree and given Postorder */ static int checkPostorder(Node node, int []postOrder, int index) { if (node == null) return index; /* first recur on left child */ index = checkPostorder(node.left,postOrder,index); /* now recur on right child */ index = checkPostorder(node.right,postOrder,index); /* Compare if data at current index in both Postorder traversals are same */ if (node.data == postOrder[index]) index++; else return -1; return index; } // Driver code public static void Main() { int []inOrder = {4, 2, 5, 1, 3}; int []preOrder = {1, 2, 4, 5, 3}; int []postOrder = {4, 5, 2, 3, 1}; int len = inOrder.Length; // build tree from given // Inorder and Preorder traversals Node root = buildTree(inOrder, preOrder, 0, len - 1); // compare postorder traversal on constructed // tree with given Postorder traversal int index = checkPostorder(root, postOrder, 0); // If both postorder traversals are same if (index == len) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} /* This code is contributed PrinciRaj1992 */ <script>/* Javascript program to check if all three giventraversals are of the same tree */ let preIndex = 0; // A Binary Tree Node class Node { // Utility function to create a new tree node constructor(data) { this.data=data; this.left=this.right=null; } } /* Function to find index of value in arr[start...end]The function assumes that value is present in in[] */ function search(arr,strt,end,value){ for (let i = strt; i <= end; i++) { if(arr[i] == value) return i; } return -1;} /* Recursive function to construct binary treeof size len from Inorder traversal in[] andPreorder traversal pre[]. Initial valuesof inStrt and inEnd should be 0 and len -1.The function doesn't do any error checking forcases where inorder and preorder do not form atree */function buildTree(In,pre,inStrt,inEnd){ if(inStrt > inEnd) return null; /* Pick current node from Preorder traversal using preIndex and increment preIndex */ let tNode = new Node(pre[preIndex++]); /* If this node has no children then return */ if (inStrt == inEnd) return tNode; /* Else find the index of this node in Inorder traversal */ let inIndex = search(In, inStrt, inEnd, tNode.data); /* Using index in Inorder traversal, construct left and right subtress */ tNode.left = buildTree(In, pre, inStrt, inIndex-1); tNode.right = buildTree(In, pre, inIndex+1, inEnd); return tNode;} /* function to compare Postorder traversalon constructed tree and given Postorder */function checkPostorder(node,postOrder,index){ if (node == null) return index; /* first recur on left child */ index = checkPostorder(node.left,postOrder,index); /* now recur on right child */ index = checkPostorder(node.right,postOrder,index); /* Compare if data at current index in both Postorder traversals are same */ if (node.data == postOrder[index]) index++; else return -1; return index;} // Driver program to test above functionslet inOrder=[4, 2, 5, 1, 3];let preOrder=[1, 2, 4, 5, 3];let postOrder=[4, 5, 2, 3, 1]; let len = inOrder.length; // build tree from given // Inorder and Preorder traversals let root = buildTree(inOrder, preOrder, 0, len - 1); // compare postorder traversal on constructed // tree with given Postorder traversal let index = checkPostorder(root,postOrder,0); // If both postorder traversals are same if (index == len) document.write("Yes"); else document.write("No"); // This code is contributed by patel2127</script> Yes Time Complexity : O( n * n ), where n is number of nodes in the tree.This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Efficient algorithm using hash map to store indices of inorder elements : While building the tree from Inorder and Preorder traversal we need to check if the inorder and preorder traversals are valid themself for some tree, and if yes , then keep building the tree, but if valid binary tree can not be built from given inorder and preorder traversal, then we must stop building the tree and return false. And also we can build the tree from inorder and preorder traversal in O(n) time using hashmap to store the indices of the inorder elements’ array. C++ #include <bits/stdc++.h>using namespace std;struct Node { int data; Node *left, *right; Node(int val) { data = val; left = right = NULL; }};Node* buildTreeFromInorderPreorder( int inStart, int inEnd, int& preIndex, int preorder[], unordered_map<int, int>& inorderIndexMap, bool& notPossible){ if (inStart > inEnd) return NULL; // build the current Node int rootData = preorder[preIndex]; Node* root = new Node(rootData); preIndex++; // find the node in inorderIndexMap if (inorderIndexMap.find(rootData) == inorderIndexMap.end()) { notPossible = true; return root; } int inorderIndex = inorderIndexMap[rootData]; if (!(inStart <= inorderIndex && inorderIndex <= inEnd)) { notPossible = true; return root; } int leftInorderStart = inStart, leftInorderEnd = inorderIndex - 1, rightInorderStart = inorderIndex + 1, rightInorderEnd = inEnd; root->left = buildTreeFromInorderPreorder( leftInorderStart, leftInorderEnd, preIndex, preorder, inorderIndexMap, notPossible); if (notPossible) return root; root->right = buildTreeFromInorderPreorder( rightInorderStart, rightInorderEnd, preIndex, preorder, inorderIndexMap, notPossible); return root;} bool checkPostorderCorrect(Node* root, int& postIndex, int postorder[]){ if (!root) return true; if (!checkPostorderCorrect(root->left, postIndex, postorder)) return false; if (!checkPostorderCorrect(root->right, postIndex, postorder)) return false; return (root->data == postorder[postIndex++]);} void printPostorder(Node* root){ if (!root) return; printPostorder(root->left); printPostorder(root->right); cout << root->data << ", ";} void printInorder(Node* root){ if (!root) return; printInorder(root->left); cout << root->data << ", "; printInorder(root->right);} bool checktree(int preorder[], int inorder[], int postorder[], int N){ // Your code goes here if (N == 0) return true; unordered_map<int, int> inorderIndexMap; for (int i = 0; i < N; i++) inorderIndexMap[inorder[i]] = i; int preIndex = 0; // return checkInorderPreorder(0, N - 1, preIndex, // preorder, inorderIndexMap) && // checkInorderPostorder(0, N - 1, postIndex, postorder, // inorderIndexMap); bool notPossible = false; Node* root = buildTreeFromInorderPreorder( 0, N - 1, preIndex, preorder, inorderIndexMap, notPossible); if (notPossible) return false; int postIndex = 0; return checkPostorderCorrect(root, postIndex, postorder);} // Driver program to test above functionsint main(){ int inOrder[] = { 4, 2, 5, 1, 3 }; int preOrder[] = { 1, 2, 4, 5, 3 }; int postOrder[] = { 4, 5, 2, 3, 1 }; int len = sizeof(inOrder) / sizeof(inOrder[0]); // If both postorder traversals are same if (checktree(preOrder, inOrder, postOrder, len)) cout << "Yes"; else cout << "No"; return 0;} Yes Time Complexity: O(N)Auxiliary Space: O(N), where N is number of nodes in the tree. prerna saini princiraj1992 mohit kumar 29 patel2127 sourashis69 surinderdawra388 Binary Tree Tree Traversals Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Decision Tree Inorder Tree Traversal without recursion and without stack! Construct Tree from given Inorder and Preorder traversals Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1 Binary Tree (Array implementation) BFS vs DFS for Binary Tree Insertion in a Binary Tree in level order Deletion in a Binary Tree
[ { "code": null, "e": 24935, "s": 24907, "text": "\n17 Mar, 2022" }, { "code": null, "e": 25069, "s": 24935, "text": "Given Preorder, Inorder, and Postorder traversals of some tree. Write a program to check if they all are of the same tree. Examples: " }, { "code": null, "e": 25481, "s": 25069, "text": "Input : Inorder -> 4 2 5 1 3\n Preorder -> 1 2 4 5 3\n Postorder -> 4 5 2 3 1\nOutput : Yes\nExplanation : All of the above three traversals are of \nthe same tree 1\n / \\\n 2 3\n / \\\n 4 5\n\nInput : Inorder -> 4 2 5 1 3\n Preorder -> 1 5 4 2 3\n Postorder -> 4 1 2 3 5\nOutput : No " }, { "code": null, "e": 26219, "s": 25481, "text": "The most basic approach to solve this problem will be to first construct a tree using two of the three given traversals and then do the third traversal on this constructed tree and compare it with the given traversal. If both of the traversals are same then print Yes otherwise print No. Here, we use Inorder and Preorder traversals to construct the tree. We may also use Inorder and Postorder traversal instead of Preorder traversal for tree construction. You may refer to this post on how to construct a tree from given Inorder and Preorder traversal. After constructing the tree, we will obtain the Postorder traversal of this tree and compare it with the given Postorder traversal.Below is the implementation of the above approach: " }, { "code": null, "e": 26223, "s": 26219, "text": "C++" }, { "code": null, "e": 26228, "s": 26223, "text": "Java" }, { "code": null, "e": 26236, "s": 26228, "text": "Python3" }, { "code": null, "e": 26239, "s": 26236, "text": "C#" }, { "code": null, "e": 26250, "s": 26239, "text": "Javascript" }, { "code": "/* C++ program to check if all three given traversals are of the same tree */#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node{ int data; struct Node *left, *right;}; // Utility function to create a new tree nodeNode* newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} /* Function to find index of value in arr[start...end] The function assumes that value is present in in[] */int search(int arr[], int strt, int end, int value){ for (int i = strt; i <= end; i++) { if(arr[i] == value) return i; }} /* Recursive function to construct binary tree of size len from Inorder traversal in[] and Preorder traversal pre[]. Initial values of inStrt and inEnd should be 0 and len -1. The function doesn't do any error checking for cases where inorder and preorder do not form a tree */Node* buildTree(int in[], int pre[], int inStrt, int inEnd){ static int preIndex = 0; if(inStrt > inEnd) return NULL; /* Pick current node from Preorder traversal using preIndex and increment preIndex */ Node *tNode = newNode(pre[preIndex++]); /* If this node has no children then return */ if (inStrt == inEnd) return tNode; /* Else find the index of this node in Inorder traversal */ int inIndex = search(in, inStrt, inEnd, tNode->data); /* Using index in Inorder traversal, construct left and right subtress */ tNode->left = buildTree(in, pre, inStrt, inIndex-1); tNode->right = buildTree(in, pre, inIndex+1, inEnd); return tNode;} /* function to compare Postorder traversal on constructed tree and given Postorder */int checkPostorder(Node* node, int postOrder[], int index){ if (node == NULL) return index; /* first recur on left child */ index = checkPostorder(node->left,postOrder,index); /* now recur on right child */ index = checkPostorder(node->right,postOrder,index); /* Compare if data at current index in both Postorder traversals are same */ if (node->data == postOrder[index]) index++; else return -1; return index;} // Driver program to test above functionsint main(){ int inOrder[] = {4, 2, 5, 1, 3}; int preOrder[] = {1, 2, 4, 5, 3}; int postOrder[] = {4, 5, 2, 3, 1}; int len = sizeof(inOrder)/sizeof(inOrder[0]); // build tree from given // Inorder and Preorder traversals Node *root = buildTree(inOrder, preOrder, 0, len - 1); // compare postorder traversal on constructed // tree with given Postorder traversal int index = checkPostorder(root,postOrder,0); // If both postorder traversals are same if (index == len) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 29107, "s": 26250, "text": null }, { "code": "/* Java program to check if all three giventraversals are of the same tree */import java.util.*;class GfG { static int preIndex = 0; // A Binary Tree Nodestatic class Node{ int data; Node left, right;} // Utility function to create a new tree nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp;} /* Function to find index of value in arr[start...end]The function assumes that value is present in in[] */static int search(int arr[], int strt, int end, int value){ for (int i = strt; i <= end; i++) { if(arr[i] == value) return i; } return -1;} /* Recursive function to construct binary treeof size len from Inorder traversal in[] andPreorder traversal pre[]. Initial valuesof inStrt and inEnd should be 0 and len -1.The function doesn't do any error checking forcases where inorder and preorder do not form atree */static Node buildTree(int in[], int pre[], int inStrt, int inEnd){ if(inStrt > inEnd) return null; /* Pick current node from Preorder traversal using preIndex and increment preIndex */ Node tNode = newNode(pre[preIndex++]); /* If this node has no children then return */ if (inStrt == inEnd) return tNode; /* Else find the index of this node in Inorder traversal */ int inIndex = search(in, inStrt, inEnd, tNode.data); /* Using index in Inorder traversal, construct left and right subtress */ tNode.left = buildTree(in, pre, inStrt, inIndex-1); tNode.right = buildTree(in, pre, inIndex+1, inEnd); return tNode;} /* function to compare Postorder traversalon constructed tree and given Postorder */static int checkPostorder(Node node, int postOrder[], int index){ if (node == null) return index; /* first recur on left child */ index = checkPostorder(node.left,postOrder,index); /* now recur on right child */ index = checkPostorder(node.right,postOrder,index); /* Compare if data at current index in both Postorder traversals are same */ if (node.data == postOrder[index]) index++; else return -1; return index;} // Driver program to test above functionspublic static void main(String[] args){ int inOrder[] = {4, 2, 5, 1, 3}; int preOrder[] = {1, 2, 4, 5, 3}; int postOrder[] = {4, 5, 2, 3, 1}; int len = inOrder.length; // build tree from given // Inorder and Preorder traversals Node root = buildTree(inOrder, preOrder, 0, len - 1); // compare postorder traversal on constructed // tree with given Postorder traversal int index = checkPostorder(root,postOrder,0); // If both postorder traversals are same if (index == len) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}", "e": 31922, "s": 29107, "text": null }, { "code": "# Python3 program to check if# all three given traversals# are of the same treeclass node: def __init__(self, x): self.data = x self.left = None self.right = None preIndex = 0 # Function to find index of value# in arr[start...end]. The function# assumes that value is present in indef search(arr, strt, end, value): for i in range(strt, end + 1): if(arr[i] == value): return i # Recursive function to construct# binary tree of size lenn from# Inorder traversal in and Preorder# traversal pre[]. Initial values# of inStrt and inEnd should be 0# and lenn -1. The function doesn't# do any error checking for cases# where inorder and preorder do not# form a treedef buildTree(inn, pre, inStrt, inEnd): global preIndex if(inStrt > inEnd): return None # Pick current node from Preorder # traversal using preIndex and # increment preIndex tNode = node(pre[preIndex]) preIndex += 1 # If this node has no children # then return if (inStrt == inEnd): return tNode # Else find the index of this # node in Inorder traversal inIndex = search(inn, inStrt, inEnd, tNode.data) # Using index in Inorder traversal, # construct left and right subtress tNode.left = buildTree(inn, pre, inStrt, inIndex - 1) tNode.right = buildTree(inn, pre, inIndex + 1, inEnd) return tNode # function to compare Postorder traversal# on constructed tree and given Postorderdef checkPostorder(node, postOrder, index): if (node == None): return index # first recur on left child index = checkPostorder(node.left, postOrder, index) # now recur on right child index = checkPostorder(node.right, postOrder, index) # Compare if data at current index in # both Postorder traversals are same if (node.data == postOrder[index]): index += 1 else: return - 1 return index # Driver codeif __name__ == '__main__': inOrder = [4, 2, 5, 1, 3] preOrder = [1, 2, 4, 5, 3] postOrder = [4, 5, 2, 3, 1] lenn = len(inOrder) # build tree from given # Inorder and Preorder traversals root = buildTree(inOrder, preOrder, 0, lenn - 1) # compare postorder traversal on # constructed tree with given # Postorder traversal index = checkPostorder(root, postOrder, 0) # If both postorder traversals are same if (index == lenn): print(\"Yes\") else: print(\"No\") # This code is contributed by Mohit Kumar 29", "e": 34608, "s": 31922, "text": null }, { "code": "/* C# program to check if all three giventraversals are of the same tree */using System; public class GfG{ static int preIndex = 0; // A Binary Tree Node class Node { public int data; public Node left, right; } // Utility function to create a new tree node static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp; } /* Function to find index of value in arr[start...end] The function assumes that value is present in in[] */ static int search(int []arr, int strt, int end, int value) { for (int i = strt; i <= end; i++) { if(arr[i] == value) return i; } return -1; } /* Recursive function to construct binary tree of size len from Inorder traversal in[] and Preorder traversal pre[]. Initial values of inStrt and inEnd should be 0 and len -1. The function doesn't do any error checking for cases where inorder and preorder do not form a tree */ static Node buildTree(int []In, int []pre, int inStrt, int inEnd) { if(inStrt > inEnd) return null; /* Pick current node from Preorder traversal using preIndex and increment preIndex */ Node tNode = newNode(pre[preIndex++]); /* If this node has no children then return */ if (inStrt == inEnd) return tNode; /* Else find the index of this node in Inorder traversal */ int inIndex = search(In, inStrt, inEnd, tNode.data); /* Using index in Inorder traversal, construct left and right subtress */ tNode.left = buildTree(In, pre, inStrt, inIndex - 1); tNode.right = buildTree(In, pre, inIndex + 1, inEnd); return tNode; } /* function to compare Postorder traversal on constructed tree and given Postorder */ static int checkPostorder(Node node, int []postOrder, int index) { if (node == null) return index; /* first recur on left child */ index = checkPostorder(node.left,postOrder,index); /* now recur on right child */ index = checkPostorder(node.right,postOrder,index); /* Compare if data at current index in both Postorder traversals are same */ if (node.data == postOrder[index]) index++; else return -1; return index; } // Driver code public static void Main() { int []inOrder = {4, 2, 5, 1, 3}; int []preOrder = {1, 2, 4, 5, 3}; int []postOrder = {4, 5, 2, 3, 1}; int len = inOrder.Length; // build tree from given // Inorder and Preorder traversals Node root = buildTree(inOrder, preOrder, 0, len - 1); // compare postorder traversal on constructed // tree with given Postorder traversal int index = checkPostorder(root, postOrder, 0); // If both postorder traversals are same if (index == len) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} /* This code is contributed PrinciRaj1992 */", "e": 37849, "s": 34608, "text": null }, { "code": "<script>/* Javascript program to check if all three giventraversals are of the same tree */ let preIndex = 0; // A Binary Tree Node class Node { // Utility function to create a new tree node constructor(data) { this.data=data; this.left=this.right=null; } } /* Function to find index of value in arr[start...end]The function assumes that value is present in in[] */ function search(arr,strt,end,value){ for (let i = strt; i <= end; i++) { if(arr[i] == value) return i; } return -1;} /* Recursive function to construct binary treeof size len from Inorder traversal in[] andPreorder traversal pre[]. Initial valuesof inStrt and inEnd should be 0 and len -1.The function doesn't do any error checking forcases where inorder and preorder do not form atree */function buildTree(In,pre,inStrt,inEnd){ if(inStrt > inEnd) return null; /* Pick current node from Preorder traversal using preIndex and increment preIndex */ let tNode = new Node(pre[preIndex++]); /* If this node has no children then return */ if (inStrt == inEnd) return tNode; /* Else find the index of this node in Inorder traversal */ let inIndex = search(In, inStrt, inEnd, tNode.data); /* Using index in Inorder traversal, construct left and right subtress */ tNode.left = buildTree(In, pre, inStrt, inIndex-1); tNode.right = buildTree(In, pre, inIndex+1, inEnd); return tNode;} /* function to compare Postorder traversalon constructed tree and given Postorder */function checkPostorder(node,postOrder,index){ if (node == null) return index; /* first recur on left child */ index = checkPostorder(node.left,postOrder,index); /* now recur on right child */ index = checkPostorder(node.right,postOrder,index); /* Compare if data at current index in both Postorder traversals are same */ if (node.data == postOrder[index]) index++; else return -1; return index;} // Driver program to test above functionslet inOrder=[4, 2, 5, 1, 3];let preOrder=[1, 2, 4, 5, 3];let postOrder=[4, 5, 2, 3, 1]; let len = inOrder.length; // build tree from given // Inorder and Preorder traversals let root = buildTree(inOrder, preOrder, 0, len - 1); // compare postorder traversal on constructed // tree with given Postorder traversal let index = checkPostorder(root,postOrder,0); // If both postorder traversals are same if (index == len) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by patel2127</script>", "e": 40522, "s": 37849, "text": null }, { "code": null, "e": 40526, "s": 40522, "text": "Yes" }, { "code": null, "e": 41016, "s": 40526, "text": "Time Complexity : O( n * n ), where n is number of nodes in the tree.This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 41090, "s": 41016, "text": "Efficient algorithm using hash map to store indices of inorder elements :" }, { "code": null, "e": 41568, "s": 41090, "text": "While building the tree from Inorder and Preorder traversal we need to check if the inorder and preorder traversals are valid themself for some tree, and if yes , then keep building the tree, but if valid binary tree can not be built from given inorder and preorder traversal, then we must stop building the tree and return false. And also we can build the tree from inorder and preorder traversal in O(n) time using hashmap to store the indices of the inorder elements’ array." }, { "code": null, "e": 41572, "s": 41568, "text": "C++" }, { "code": "#include <bits/stdc++.h>using namespace std;struct Node { int data; Node *left, *right; Node(int val) { data = val; left = right = NULL; }};Node* buildTreeFromInorderPreorder( int inStart, int inEnd, int& preIndex, int preorder[], unordered_map<int, int>& inorderIndexMap, bool& notPossible){ if (inStart > inEnd) return NULL; // build the current Node int rootData = preorder[preIndex]; Node* root = new Node(rootData); preIndex++; // find the node in inorderIndexMap if (inorderIndexMap.find(rootData) == inorderIndexMap.end()) { notPossible = true; return root; } int inorderIndex = inorderIndexMap[rootData]; if (!(inStart <= inorderIndex && inorderIndex <= inEnd)) { notPossible = true; return root; } int leftInorderStart = inStart, leftInorderEnd = inorderIndex - 1, rightInorderStart = inorderIndex + 1, rightInorderEnd = inEnd; root->left = buildTreeFromInorderPreorder( leftInorderStart, leftInorderEnd, preIndex, preorder, inorderIndexMap, notPossible); if (notPossible) return root; root->right = buildTreeFromInorderPreorder( rightInorderStart, rightInorderEnd, preIndex, preorder, inorderIndexMap, notPossible); return root;} bool checkPostorderCorrect(Node* root, int& postIndex, int postorder[]){ if (!root) return true; if (!checkPostorderCorrect(root->left, postIndex, postorder)) return false; if (!checkPostorderCorrect(root->right, postIndex, postorder)) return false; return (root->data == postorder[postIndex++]);} void printPostorder(Node* root){ if (!root) return; printPostorder(root->left); printPostorder(root->right); cout << root->data << \", \";} void printInorder(Node* root){ if (!root) return; printInorder(root->left); cout << root->data << \", \"; printInorder(root->right);} bool checktree(int preorder[], int inorder[], int postorder[], int N){ // Your code goes here if (N == 0) return true; unordered_map<int, int> inorderIndexMap; for (int i = 0; i < N; i++) inorderIndexMap[inorder[i]] = i; int preIndex = 0; // return checkInorderPreorder(0, N - 1, preIndex, // preorder, inorderIndexMap) && // checkInorderPostorder(0, N - 1, postIndex, postorder, // inorderIndexMap); bool notPossible = false; Node* root = buildTreeFromInorderPreorder( 0, N - 1, preIndex, preorder, inorderIndexMap, notPossible); if (notPossible) return false; int postIndex = 0; return checkPostorderCorrect(root, postIndex, postorder);} // Driver program to test above functionsint main(){ int inOrder[] = { 4, 2, 5, 1, 3 }; int preOrder[] = { 1, 2, 4, 5, 3 }; int postOrder[] = { 4, 5, 2, 3, 1 }; int len = sizeof(inOrder) / sizeof(inOrder[0]); // If both postorder traversals are same if (checktree(preOrder, inOrder, postOrder, len)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 44801, "s": 41572, "text": null }, { "code": null, "e": 44805, "s": 44801, "text": "Yes" }, { "code": null, "e": 44889, "s": 44805, "text": "Time Complexity: O(N)Auxiliary Space: O(N), where N is number of nodes in the tree." }, { "code": null, "e": 44902, "s": 44889, "text": "prerna saini" }, { "code": null, "e": 44916, "s": 44902, "text": "princiraj1992" }, { "code": null, "e": 44931, "s": 44916, "text": "mohit kumar 29" }, { "code": null, "e": 44941, "s": 44931, "text": "patel2127" }, { "code": null, "e": 44953, "s": 44941, "text": "sourashis69" }, { "code": null, "e": 44970, "s": 44953, "text": "surinderdawra388" }, { "code": null, "e": 44982, "s": 44970, "text": "Binary Tree" }, { "code": null, "e": 44998, "s": 44982, "text": "Tree Traversals" }, { "code": null, "e": 45003, "s": 44998, "text": "Tree" }, { "code": null, "e": 45008, "s": 45003, "text": "Tree" }, { "code": null, "e": 45106, "s": 45008, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45115, "s": 45106, "text": "Comments" }, { "code": null, "e": 45128, "s": 45115, "text": "Old Comments" }, { "code": null, "e": 45142, "s": 45128, "text": "Decision Tree" }, { "code": null, "e": 45202, "s": 45142, "text": "Inorder Tree Traversal without recursion and without stack!" }, { "code": null, "e": 45260, "s": 45202, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 45343, "s": 45260, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 45379, "s": 45343, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 45427, "s": 45379, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" }, { "code": null, "e": 45462, "s": 45427, "text": "Binary Tree (Array implementation)" }, { "code": null, "e": 45489, "s": 45462, "text": "BFS vs DFS for Binary Tree" }, { "code": null, "e": 45531, "s": 45489, "text": "Insertion in a Binary Tree in level order" } ]
Java Program for check if a given number is Fibonacci number?
Following is the Java program to check if a given number is Fibonacci − Live Demo public class Demo{ static boolean perfect_square_check(int val){ int s = (int) Math.sqrt(val); return (s*s == val); } static boolean fibonacci_num_check(int n){ return perfect_square_check(5*n*n + 4) || perfect_square_check(5*n*n - 4); } public static void main(String[] args){ for (int i = 6; i <= 17; i++) System.out.println(fibonacci_num_check(i) ? i + " is a Fibonacci number" : i + " is a not Fibonacci number"); } } 6 is a not Fibonacci number 7 is a not Fibonacci number 8 is a Fibonacci number 9 is a not Fibonacci number 10 is a not Fibonacci number 11 is a not Fibonacci number 12 is a not Fibonacci number 13 is a Fibonacci number 14 is a not Fibonacci number 15 is a not Fibonacci number 16 is a not Fibonacci number 17 is a not Fibonacci number A class named Demo defines a static Boolean function that takes in an integer value as parameter. It checks the square root of the value and assigns it to another value. If the product of square root multiplied by square root is equal to the value passed, then it is returned. Next, another Boolean static function is defined that calls the previous function. In the main function, the starting number, and the ending number are iterated through, and relevant message is printed as well as checking whether every number is a Fibonacci number or not.
[ { "code": null, "e": 1134, "s": 1062, "text": "Following is the Java program to check if a given number is Fibonacci −" }, { "code": null, "e": 1145, "s": 1134, "text": " Live Demo" }, { "code": null, "e": 1621, "s": 1145, "text": "public class Demo{\n static boolean perfect_square_check(int val){\n int s = (int) Math.sqrt(val);\n return (s*s == val);\n }\n static boolean fibonacci_num_check(int n){\n return perfect_square_check(5*n*n + 4) || perfect_square_check(5*n*n - 4);\n }\n public static void main(String[] args){\n for (int i = 6; i <= 17; i++)\n System.out.println(fibonacci_num_check(i) ? i + \" is a Fibonacci number\" :\n i + \" is a not Fibonacci number\");\n }\n}" }, { "code": null, "e": 1957, "s": 1621, "text": "6 is a not Fibonacci number\n7 is a not Fibonacci number\n8 is a Fibonacci number\n9 is a not Fibonacci number\n10 is a not Fibonacci number\n11 is a not Fibonacci number\n12 is a not Fibonacci number\n13 is a Fibonacci number\n14 is a not Fibonacci number\n15 is a not Fibonacci number\n16 is a not Fibonacci number\n17 is a not Fibonacci number" }, { "code": null, "e": 2234, "s": 1957, "text": "A class named Demo defines a static Boolean function that takes in an integer value as parameter. It checks the square root of the value and assigns it to another value. If the product of square root multiplied by square root is equal to the value passed, then it is returned." }, { "code": null, "e": 2507, "s": 2234, "text": "Next, another Boolean static function is defined that calls the previous function. In the main function, the starting number, and the ending number are iterated through, and relevant message is printed as well as checking whether every number is a Fibonacci number or not." } ]
C++ Queue Library - size() Function
The C++ function std::priority_queue::size() returns the total number of elements present in the priority_queue. Following is the declaration for std::priority_queue::size() function form std::queue header. size_type size() const; None Returns the total number of elements present in the priority_queue. This member function never throws exception. Constant i.e. O(1) The following example shows the usage of std::priority_queue::size() function. #include <iostream> #include <queue> using namespace std; int main(void) { priority_queue<int> q; cout << "Initial size of queue = " << q.size() << endl; for (int i = 0; i < 5; ++i) q.push(i + 1); cout << "After push opration size of queue = " << q.size() << endl; return 0; } Let us compile and run the above program, this will produce the following result − Initial size of queue = 0 After push opration size of queue = 5 Print Add Notes Bookmark this page
[ { "code": null, "e": 2716, "s": 2603, "text": "The C++ function std::priority_queue::size() returns the total number of elements present in the priority_queue." }, { "code": null, "e": 2810, "s": 2716, "text": "Following is the declaration for std::priority_queue::size() function form std::queue header." }, { "code": null, "e": 2835, "s": 2810, "text": "size_type size() const;\n" }, { "code": null, "e": 2840, "s": 2835, "text": "None" }, { "code": null, "e": 2908, "s": 2840, "text": "Returns the total number of elements present in the priority_queue." }, { "code": null, "e": 2953, "s": 2908, "text": "This member function never throws exception." }, { "code": null, "e": 2972, "s": 2953, "text": "Constant i.e. O(1)" }, { "code": null, "e": 3051, "s": 2972, "text": "The following example shows the usage of std::priority_queue::size() function." }, { "code": null, "e": 3355, "s": 3051, "text": "#include <iostream>\n#include <queue>\n\nusing namespace std;\n\nint main(void) {\n priority_queue<int> q;\n\n cout << \"Initial size of queue = \" << q.size() << endl;\n\n for (int i = 0; i < 5; ++i)\n q.push(i + 1);\n\n cout << \"After push opration size of queue = \" << q.size() << endl;\n\n return 0;\n}" }, { "code": null, "e": 3438, "s": 3355, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3503, "s": 3438, "text": "Initial size of queue = 0\nAfter push opration size of queue = 5\n" }, { "code": null, "e": 3510, "s": 3503, "text": " Print" }, { "code": null, "e": 3521, "s": 3510, "text": " Add Notes" } ]
Biopython - Genome Analysis
A genome is complete set of DNA, including all of its genes. Genome analysis refers to the study of individual genes and their roles in inheritance. Genome diagram represents the genetic information as charts. Biopython uses Bio.Graphics.GenomeDiagram module to represent GenomeDiagram. The GenomeDiagram module requires ReportLab to be installed. The process of creating a diagram generally follows the below simple pattern − Create a FeatureSet for each separate set of features you want to display, and add Bio.SeqFeature objects to them. Create a FeatureSet for each separate set of features you want to display, and add Bio.SeqFeature objects to them. Create a GraphSet for each graph you want to display, and add graph data to them. Create a GraphSet for each graph you want to display, and add graph data to them. Create a Track for each track you want on the diagram, and add GraphSets and FeatureSets to the tracks you require. Create a Track for each track you want on the diagram, and add GraphSets and FeatureSets to the tracks you require. Create a Diagram, and add the Tracks to it. Create a Diagram, and add the Tracks to it. Tell the Diagram to draw the image. Tell the Diagram to draw the image. Write the image to a file. Write the image to a file. Let us take an example of input GenBank file − https://raw.githubusercontent.com/biopython/biopython/master/Doc/examples/ls_orchid.gbk and read records from SeqRecord object then finally draw a genome diagram. It is explained below, We shall import all the modules first as shown below − >>> from reportlab.lib import colors >>> from reportlab.lib.units import cm >>> from Bio.Graphics import GenomeDiagram Now, import SeqIO module to read data − >>> from Bio import SeqIO record = SeqIO.read("example.gb", "genbank") Here, the record reads the sequence from genbank file. Now, create an empty diagram to add track and feature set − >>> diagram = GenomeDiagram.Diagram( "Yersinia pestis biovar Microtus plasmid pPCP1") >>> track = diagram.new_track(1, name="Annotated Features") >>> feature = track.new_set() Now, we can apply color theme changes using alternative colors from green to grey as defined below − >>> for feature in record.features: >>> if feature.type != "gene": >>> continue >>> if len(feature) % 2 == 0: >>> color = colors.blue >>> else: >>> color = colors.red >>> >>> feature.add_feature(feature, color=color, label=True) Now you could see the below response on your screen − <Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d3dc90> <Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d3dfd0> <Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x1007627d0> <Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d57290> <Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d57050> <Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d57390> <Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d57590> <Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d57410> <Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d57490> <Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d574d0> Let us draw a diagram for the above input records − >>> diagram.draw( format = "linear", orientation = "landscape", pagesize = 'A4', ... fragments = 4, start = 0, end = len(record)) >>> diagram.write("orchid.pdf", "PDF") >>> diagram.write("orchid.eps", "EPS") >>> diagram.write("orchid.svg", "SVG") >>> diagram.write("orchid.png", "PNG") After executing the above command, you could see the following image saved in your Biopython directory. ** Result ** genome.png You can also draw the image in circular format by making the below changes − >>> diagram.draw( format = "circular", circular = True, pagesize = (20*cm,20*cm), ... start = 0, end = len(record), circle_core = 0.7) >>> diagram.write("circular.pdf", "PDF") DNA molecule is packaged into thread-like structures called chromosomes. Each chromosome is made up of DNA tightly coiled many times around proteins called histones that support its structure. Chromosomes are not visible in the cell’s nucleus — not even under a microscope —when the cell is not dividing. However, the DNA that makes up chromosomes becomes more tightly packed during cell division and is then visible under a microscope. In humans, each cell normally contains 23 pairs of chromosomes, for a total of 46. Twenty-two of these pairs, called autosomes, look the same in both males and females. The 23rd pair, the sex chromosomes, differ between males and females. Females have two copies of the X chromosome, while males have one X and one Y chromosome. Print Add Notes Bookmark this page
[ { "code": null, "e": 2255, "s": 2106, "text": "A genome is complete set of DNA, including all of its genes. Genome analysis refers to the study of individual genes and their roles in inheritance." }, { "code": null, "e": 2454, "s": 2255, "text": "Genome diagram represents the genetic information as charts. Biopython uses Bio.Graphics.GenomeDiagram module to represent GenomeDiagram. The GenomeDiagram module requires ReportLab to be installed." }, { "code": null, "e": 2533, "s": 2454, "text": "The process of creating a diagram generally follows the below simple pattern −" }, { "code": null, "e": 2648, "s": 2533, "text": "Create a FeatureSet for each separate set of features you want to display, and add Bio.SeqFeature objects to them." }, { "code": null, "e": 2763, "s": 2648, "text": "Create a FeatureSet for each separate set of features you want to display, and add Bio.SeqFeature objects to them." }, { "code": null, "e": 2845, "s": 2763, "text": "Create a GraphSet for each graph you want to display, and add graph data to them." }, { "code": null, "e": 2927, "s": 2845, "text": "Create a GraphSet for each graph you want to display, and add graph data to them." }, { "code": null, "e": 3043, "s": 2927, "text": "Create a Track for each track you want on the diagram, and add GraphSets and FeatureSets to the tracks you require." }, { "code": null, "e": 3159, "s": 3043, "text": "Create a Track for each track you want on the diagram, and add GraphSets and FeatureSets to the tracks you require." }, { "code": null, "e": 3203, "s": 3159, "text": "Create a Diagram, and add the Tracks to it." }, { "code": null, "e": 3247, "s": 3203, "text": "Create a Diagram, and add the Tracks to it." }, { "code": null, "e": 3283, "s": 3247, "text": "Tell the Diagram to draw the image." }, { "code": null, "e": 3319, "s": 3283, "text": "Tell the Diagram to draw the image." }, { "code": null, "e": 3346, "s": 3319, "text": "Write the image to a file." }, { "code": null, "e": 3373, "s": 3346, "text": "Write the image to a file." }, { "code": null, "e": 3420, "s": 3373, "text": "Let us take an example of input GenBank file −" }, { "code": null, "e": 3606, "s": 3420, "text": "https://raw.githubusercontent.com/biopython/biopython/master/Doc/examples/ls_orchid.gbk and read records from SeqRecord object then finally draw a genome diagram. It is explained below," }, { "code": null, "e": 3661, "s": 3606, "text": "We shall import all the modules first as shown below −" }, { "code": null, "e": 3782, "s": 3661, "text": ">>> from reportlab.lib import colors \n>>> from reportlab.lib.units import cm \n>>> from Bio.Graphics import GenomeDiagram" }, { "code": null, "e": 3822, "s": 3782, "text": "Now, import SeqIO module to read data −" }, { "code": null, "e": 3894, "s": 3822, "text": ">>> from Bio import SeqIO \nrecord = SeqIO.read(\"example.gb\", \"genbank\")" }, { "code": null, "e": 3949, "s": 3894, "text": "Here, the record reads the sequence from genbank file." }, { "code": null, "e": 4009, "s": 3949, "text": "Now, create an empty diagram to add track and feature set −" }, { "code": null, "e": 4190, "s": 4009, "text": ">>> diagram = GenomeDiagram.Diagram(\n \"Yersinia pestis biovar Microtus plasmid pPCP1\") \n>>> track = diagram.new_track(1, name=\"Annotated Features\") \n>>> feature = track.new_set()" }, { "code": null, "e": 4291, "s": 4190, "text": "Now, we can apply color theme changes using alternative colors from green to grey as defined below −" }, { "code": null, "e": 4558, "s": 4291, "text": ">>> for feature in record.features: \n>>> if feature.type != \"gene\": \n>>> continue \n>>> if len(feature) % 2 == 0: \n>>> color = colors.blue \n>>> else: \n>>> color = colors.red \n>>> \n>>> feature.add_feature(feature, color=color, label=True)" }, { "code": null, "e": 4612, "s": 4558, "text": "Now you could see the below response on your screen −" }, { "code": null, "e": 5302, "s": 4612, "text": "<Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d3dc90> \n<Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d3dfd0> \n<Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x1007627d0> \n<Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d57290> \n<Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d57050> \n<Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d57390> \n<Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d57590> \n<Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d57410> \n<Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d57490> \n<Bio.Graphics.GenomeDiagram._Feature.Feature object at 0x105d574d0>\n" }, { "code": null, "e": 5354, "s": 5302, "text": "Let us draw a diagram for the above input records −" }, { "code": null, "e": 5651, "s": 5354, "text": ">>> diagram.draw(\n format = \"linear\", orientation = \"landscape\", pagesize = 'A4', \n ... fragments = 4, start = 0, end = len(record)) \n>>> diagram.write(\"orchid.pdf\", \"PDF\") \n>>> diagram.write(\"orchid.eps\", \"EPS\") \n>>> diagram.write(\"orchid.svg\", \"SVG\") \n>>> diagram.write(\"orchid.png\", \"PNG\")" }, { "code": null, "e": 5755, "s": 5651, "text": "After executing the above command, you could see the following image saved in your Biopython directory." }, { "code": null, "e": 5780, "s": 5755, "text": "** Result **\ngenome.png\n" }, { "code": null, "e": 5857, "s": 5780, "text": "You can also draw the image in circular format by making the below changes −" }, { "code": null, "e": 6041, "s": 5857, "text": ">>> diagram.draw(\n format = \"circular\", circular = True, pagesize = (20*cm,20*cm), \n ... start = 0, end = len(record), circle_core = 0.7) \n>>> diagram.write(\"circular.pdf\", \"PDF\")" }, { "code": null, "e": 6234, "s": 6041, "text": "DNA molecule is packaged into thread-like structures called chromosomes. Each chromosome is made up of DNA tightly coiled many times around proteins called histones that support its structure." }, { "code": null, "e": 6478, "s": 6234, "text": "Chromosomes are not visible in the cell’s nucleus — not even under a microscope —when the cell is not dividing. However, the DNA that makes up chromosomes becomes more tightly packed during cell division and is then visible under a microscope." }, { "code": null, "e": 6807, "s": 6478, "text": "In humans, each cell normally contains 23 pairs of chromosomes, for a total of 46. Twenty-two of these pairs, called autosomes, look the same in both males and females. The 23rd pair, the sex chromosomes, differ between males and females. Females have two copies of the X chromosome, while males have one X and one Y chromosome." }, { "code": null, "e": 6814, "s": 6807, "text": " Print" }, { "code": null, "e": 6825, "s": 6814, "text": " Add Notes" } ]
NHibernate - Hibernate Query Language
In this chapter, we will be covering Hibernate Query Language. HQL is shared across both Java's Hibernate and NHibernate. It is the oldest query mechanism along with Criteria. It is the oldest query mechanism along with Criteria. It was implemented very early and it is a string-based query API. It was implemented very early and it is a string-based query API. You access it through ISession CreateQuery, and it is almost similar to SQL. You access it through ISession CreateQuery, and it is almost similar to SQL. It uses many of the same keywords, but has a simplified syntax. It uses many of the same keywords, but has a simplified syntax. It is one of the most common examples, if you're looking for how to perform a query you'll often find HQL examples. It is one of the most common examples, if you're looking for how to perform a query you'll often find HQL examples. The following is a simple example of HQL − var customers = session.CreateQuery("select c from Customer c where c.FirstName = 'Laverne'"); So here you can see that they select C from customer, it looks a lot like SQL. This is an opaque string as far as NHibernate is concerned, so you don't know whether this is a valid HQL until runtime, which is one of the disadvantages. So here you can see that they select C from customer, it looks a lot like SQL. This is an opaque string as far as NHibernate is concerned, so you don't know whether this is a valid HQL until runtime, which is one of the disadvantages. One of the strengths of the LINQ provider is you can get to compile time support. One of the strengths of the LINQ provider is you can get to compile time support. But HQL, is one of the most flexible query mechanisms oftenly used. It is said that, if there's no other way to do it then there's a way to do it in HQL. But HQL, is one of the most flexible query mechanisms oftenly used. It is said that, if there's no other way to do it then there's a way to do it in HQL. Let’s have a look into a simpe example in which we will recreate our LINQ queries using HQL instead. You can get access to HQL by calling the session.CreateQuery and pass as a parameter using an HQL string. using System; using System.Data; using System.Linq; using System.Reflection; using HibernatingRhinos.Profiler.Appender.NHibernate; using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Dialect; using NHibernate.Driver; using NHibernate.Linq; namespace NHibernateDemo { internal class Program { private static void Main() { var cfg = ConfigureNHibernate(); var sessionFactory = cfg.BuildSessionFactory(); using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { var customers = session.CreateQuery("select c from Customer c where c.FirstName = 'Laverne'"); foreach (var customer in customers.List<Customer>()) { Console.WriteLine(customer); } tx.Commit(); } Console.WriteLine("Press <ENTER> to exit..."); Console.ReadLine(); } private static Configuration ConfigureNHibernate() { NHibernateProfiler.Initialize(); var cfg = new Configuration(); cfg.DataBaseIntegration(x => { x.ConnectionStringName = "default"; x.Driver<SqlClientDriver>(); x.Dialect<MsSql2008Dialect>(); x.IsolationLevel = IsolationLevel.RepeatableRead; x.Timeout = 10; x.BatchSize = 10; }); cfg.SessionFactory().GenerateStatistics(); cfg.AddAssembly(Assembly.GetExecutingAssembly()); return cfg; } } } This HQL string looks a lot like SQL, the main difference is that FirstName is the property name and not the column name. This HQL string looks a lot like SQL, the main difference is that FirstName is the property name and not the column name. So, if there's a discrepancy between the two, you use the property name. Same thing, it looks like a table name, but it's actually the name of the class that we are selecting from. So, if there's a discrepancy between the two, you use the property name. Same thing, it looks like a table name, but it's actually the name of the class that we are selecting from. If the back end table was named as Customers, we would still use Customer in our HQL query. If the back end table was named as Customers, we would still use Customer in our HQL query. Let’s run this application and you will see the following output. Laverne Hegmann (4e97c816-6bce-11e1-b095-6cf049ee52be) Points: 74 HasGoldStatus: True MemberSince: 4/4/2009 12:00:00 AM (Utc) CreditRating: Neutral AverageRating: 0 Orders: Order Id: 4ea14d96-6bce-11e1-b095-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b096-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b097-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b098-6cf049ee52be Press <ENTER> to exit... Let’s have a look into another simple example in which we will retrieve all those customers whose FirstName starts with the letter H using HQL. using System; using System.Data; using System.Linq; using System.Reflection; using HibernatingRhinos.Profiler.Appender.NHibernate; using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Dialect; using NHibernate.Driver; using NHibernate.Linq; namespace NHibernateDemo { internal class Program { private static void Main() { var cfg = ConfigureNHibernate(); var sessionFactory = cfg.BuildSessionFactory(); using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { var customers = session.CreateQuery("select c from Customer c where c.FirstName like 'H%'"); foreach (var customer in customers.List<Customer>()) { Console.WriteLine(customer); } tx.Commit(); } Console.WriteLine("Press <ENTER> to exit..."); Console.ReadLine(); } private static Configuration ConfigureNHibernate() { NHibernateProfiler.Initialize(); var cfg = new Configuration(); cfg.DataBaseIntegration(x => { x.ConnectionStringName = "default"; x.Driver<SqlClientDriver>(); x.Dialect<MsSql2008Dialect>(); x.IsolationLevel = IsolationLevel.RepeatableRead; x.Timeout = 10; x.BatchSize = 10; }); cfg.SessionFactory().GenerateStatistics(); cfg.AddAssembly(Assembly.GetExecutingAssembly()); return cfg; } } } Let’s run your application again and you will see that all of the customers whose name starts with H are returned from this query. Herman Crooks (4ead3480-6bce-11e1-b15c-6cf049ee52be) Points: 74 HasGoldStatus: True MemberSince: 12/3/2010 12:00:00 AM (Utc) CreditRating: Neutral AverageRating: 0 Orders: Order Id: 4ead3480-6bce-11e1-b15d-6cf049ee52be Order Id: 4ead3480-6bce-11e1-b15e-6cf049ee52be Order Id: 4ead3480-6bce-11e1-b15f-6cf049ee52be Order Id: 4ead3480-6bce-11e1-b160-6cf049ee52be Order Id: 4ead3480-6bce-11e1-b161-6cf049ee52be Order Id: 4ead3480-6bce-11e1-b162-6cf049ee52be Order Id: 4ead3480-6bce-11e1-b163-6cf049ee52be Hudson Bins (4ec03f80-6bce-11e1-b2b7-6cf049ee52be) Points: 56 HasGoldStatus: False MemberSince: 10/20/2008 12:00:00 AM (Utc) CreditRating: Terrible AverageRating: 0 Orders: Order Id: 4ec03f80-6bce-11e1-b2b8-6cf049ee52be Order Id: 4ec03f80-6bce-11e1-b2b9-6cf049ee52be Order Id: 4ec03f80-6bce-11e1-b2ba-6cf049ee52be Order Id: 4ec03f80-6bce-11e1-b2bb-6cf049ee52be Order Id: 4ec03f80-6bce-11e1-b2bc-6cf049ee52be Order Id: 4ec03f80-6bce-11e1-b2bd-6cf049ee52be Order Id: 4ec03f80-6bce-11e1-b2be-6cf049ee52be Order Id: 4ec03f80-6bce-11e1-b2bf-6cf049ee52be Hettie Feest (4ec50240-6bce-11e1-b300-6cf049ee52be) Points: 82 HasGoldStatus: False MemberSince: 4/10/2009 12:00:00 AM (Utc) CreditRating: Neutral AverageRating: 0 Orders: Order Id: 4ec50240-6bce-11e1-b301-6cf049ee52be Order Id: 4ec50240-6bce-11e1-b302-6cf049ee52be Order Id: 4ec50240-6bce-11e1-b303-6cf049ee52be Press <ENTER> to exit... We can do more complicated things like wanting all orders where customers with an order count is greater than 9. Following is the HQL query for the same. var customers = session.CreateQuery("select c from Customer c where size(c.Orders) > 9"); foreach (var customer in customers.List<Customer>()) { Console.WriteLine(customer); } We also need to indicate that we need a size here or count or length. In HQL, we have the option of using the special size method as shown above. The other way to write this, if you prefer is c.Orders.size, and this has the exact effect. var customers = session.CreateQuery("select c from Customer c where c.Orders.size > 9"); foreach (var customer in customers.List<Customer>()) { Console.WriteLine(customer); } Let's run this application. Lindsay Towne (4ea3aef6-6bce-11e1-b0cb-6cf049ee52be) Points: 50 HasGoldStatus: False MemberSince: 4/13/2007 12:00:00 AM (Utc) CreditRating: VeryGood AverageRating: 0 Orders: Order Id: 4ea3aef6-6bce-11e1-b0cc-6cf049ee52be Order Id: 4ea3aef6-6bce-11e1-b0cd-6cf049ee52be Order Id: 4ea3aef6-6bce-11e1-b0ce-6cf049ee52be Order Id: 4ea3aef6-6bce-11e1-b0cf-6cf049ee52be Order Id: 4ea3aef6-6bce-11e1-b0d0-6cf049ee52be Order Id: 4ea3aef6-6bce-11e1-b0d1-6cf049ee52be Order Id: 4ea3aef6-6bce-11e1-b0d2-6cf049ee52be Order Id: 4ea3aef6-6bce-11e1-b0d3-6cf049ee52be Order Id: 4ea3aef6-6bce-11e1-b0d4-6cf049ee52be Order Id: 4ea3aef6-6bce-11e1-b0d5-6cf049ee52be Wyman Hammes (4ea61056-6bce-11e1-b0e2-6cf049ee52be) Points: 32 HasGoldStatus: False MemberSince: 2/5/2011 12:00:00 AM (Utc) CreditRating: Good AverageRating: 0 Orders: Order Id: 4ea61056-6bce-11e1-b0e3-6cf049ee52be Order Id: 4ea61056-6bce-11e1-b0e4-6cf049ee52be Order Id: 4ea61056-6bce-11e1-b0e5-6cf049ee52be Order Id: 4ea61056-6bce-11e1-b0e6-6cf049ee52be Order Id: 4ea61056-6bce-11e1-b0e7-6cf049ee52be Order Id: 4ea61056-6bce-11e1-b0e8-6cf049ee52be Order Id: 4ea61056-6bce-11e1-b0e9-6cf049ee52be Order Id: 4ea61056-6bce-11e1-b0ea-6cf049ee52be Order Id: 4ea61056-6bce-11e1-b0eb-6cf049ee52be Order Id: 4ea61056-6bce-11e1-b0ec-6cf049ee52be Press <ENTER> to exit... You can see that all the customers, who have more than 9 orders are retrieved from the database. Print Add Notes Bookmark this page
[ { "code": null, "e": 2455, "s": 2333, "text": "In this chapter, we will be covering Hibernate Query Language. HQL is shared across both Java's Hibernate and NHibernate." }, { "code": null, "e": 2509, "s": 2455, "text": "It is the oldest query mechanism along with Criteria." }, { "code": null, "e": 2563, "s": 2509, "text": "It is the oldest query mechanism along with Criteria." }, { "code": null, "e": 2629, "s": 2563, "text": "It was implemented very early and it is a string-based query API." }, { "code": null, "e": 2695, "s": 2629, "text": "It was implemented very early and it is a string-based query API." }, { "code": null, "e": 2772, "s": 2695, "text": "You access it through ISession CreateQuery, and it is almost similar to SQL." }, { "code": null, "e": 2849, "s": 2772, "text": "You access it through ISession CreateQuery, and it is almost similar to SQL." }, { "code": null, "e": 2913, "s": 2849, "text": "It uses many of the same keywords, but has a simplified syntax." }, { "code": null, "e": 2977, "s": 2913, "text": "It uses many of the same keywords, but has a simplified syntax." }, { "code": null, "e": 3093, "s": 2977, "text": "It is one of the most common examples, if you're looking for how to perform a query you'll often find HQL examples." }, { "code": null, "e": 3209, "s": 3093, "text": "It is one of the most common examples, if you're looking for how to perform a query you'll often find HQL examples." }, { "code": null, "e": 3252, "s": 3209, "text": "The following is a simple example of HQL −" }, { "code": null, "e": 3348, "s": 3252, "text": "var customers = session.CreateQuery(\"select c from Customer c where c.FirstName = 'Laverne'\");\n" }, { "code": null, "e": 3583, "s": 3348, "text": "So here you can see that they select C from customer, it looks a lot like SQL. This is an opaque string as far as NHibernate is concerned, so you don't know whether this is a valid HQL until runtime, which is one of the disadvantages." }, { "code": null, "e": 3818, "s": 3583, "text": "So here you can see that they select C from customer, it looks a lot like SQL. This is an opaque string as far as NHibernate is concerned, so you don't know whether this is a valid HQL until runtime, which is one of the disadvantages." }, { "code": null, "e": 3900, "s": 3818, "text": "One of the strengths of the LINQ provider is you can get to compile time support." }, { "code": null, "e": 3982, "s": 3900, "text": "One of the strengths of the LINQ provider is you can get to compile time support." }, { "code": null, "e": 4136, "s": 3982, "text": "But HQL, is one of the most flexible query mechanisms oftenly used. It is said that, if there's no other way to do it then there's a way to do it in HQL." }, { "code": null, "e": 4290, "s": 4136, "text": "But HQL, is one of the most flexible query mechanisms oftenly used. It is said that, if there's no other way to do it then there's a way to do it in HQL." }, { "code": null, "e": 4497, "s": 4290, "text": "Let’s have a look into a simpe example in which we will recreate our LINQ queries using HQL instead. You can get access to HQL by calling the session.CreateQuery and pass as a parameter using an HQL string." }, { "code": null, "e": 6130, "s": 4497, "text": "using System; \nusing System.Data; \nusing System.Linq; \nusing System.Reflection; \n\nusing HibernatingRhinos.Profiler.Appender.NHibernate; \nusing NHibernate.Cfg; \nusing NHibernate.Criterion; \nusing NHibernate.Dialect; \nusing NHibernate.Driver; \nusing NHibernate.Linq;\n\nnamespace NHibernateDemo {\n\n internal class Program { \n \n private static void Main() { \n\t\t\n var cfg = ConfigureNHibernate(); \n var sessionFactory = cfg.BuildSessionFactory();\n using(var session = sessionFactory.OpenSession()) \n \n using(var tx = session.BeginTransaction()) { \n var customers = session.CreateQuery(\"select c from Customer c \n where c.FirstName = 'Laverne'\"); \n \n foreach (var customer in customers.List<Customer>()) { \n Console.WriteLine(customer); \n }\n\t\t\t\t\n tx.Commit(); \n }\n\t\t\t\n Console.WriteLine(\"Press <ENTER> to exit...\"); \n Console.ReadLine(); \n }\n\t\t\n private static Configuration ConfigureNHibernate() { \n\t\t\n NHibernateProfiler.Initialize(); \n var cfg = new Configuration(); \n \n cfg.DataBaseIntegration(x => { \n x.ConnectionStringName = \"default\"; \n x.Driver<SqlClientDriver>(); \n x.Dialect<MsSql2008Dialect>(); \n x.IsolationLevel = IsolationLevel.RepeatableRead; \n x.Timeout = 10; \n x.BatchSize = 10; \n }); \n \n cfg.SessionFactory().GenerateStatistics();\n cfg.AddAssembly(Assembly.GetExecutingAssembly()); \n return cfg; \n } \n } \n}" }, { "code": null, "e": 6252, "s": 6130, "text": "This HQL string looks a lot like SQL, the main difference is that FirstName is the property name and not the column name." }, { "code": null, "e": 6374, "s": 6252, "text": "This HQL string looks a lot like SQL, the main difference is that FirstName is the property name and not the column name." }, { "code": null, "e": 6555, "s": 6374, "text": "So, if there's a discrepancy between the two, you use the property name. Same thing, it looks like a table name, but it's actually the name of the class that we are selecting from." }, { "code": null, "e": 6736, "s": 6555, "text": "So, if there's a discrepancy between the two, you use the property name. Same thing, it looks like a table name, but it's actually the name of the class that we are selecting from." }, { "code": null, "e": 6828, "s": 6736, "text": "If the back end table was named as Customers, we would still use Customer in our HQL query." }, { "code": null, "e": 6920, "s": 6828, "text": "If the back end table was named as Customers, we would still use Customer in our HQL query." }, { "code": null, "e": 6986, "s": 6920, "text": "Let’s run this application and you will see the following output." }, { "code": null, "e": 7419, "s": 6986, "text": "Laverne Hegmann (4e97c816-6bce-11e1-b095-6cf049ee52be)\n Points: 74\n HasGoldStatus: True\n MemberSince: 4/4/2009 12:00:00 AM (Utc)\n CreditRating: Neutral\n AverageRating: 0\n\n Orders:\n Order Id: 4ea14d96-6bce-11e1-b095-6cf049ee52be\n Order Id: 4ea14d96-6bce-11e1-b096-6cf049ee52be\n Order Id: 4ea14d96-6bce-11e1-b097-6cf049ee52be\n Order Id: 4ea14d96-6bce-11e1-b098-6cf049ee52be\n\t\t\nPress <ENTER> to exit...\n" }, { "code": null, "e": 7563, "s": 7419, "text": "Let’s have a look into another simple example in which we will retrieve all those customers whose FirstName starts with the letter H using HQL." }, { "code": null, "e": 9184, "s": 7563, "text": "using System; \nusing System.Data; \nusing System.Linq; \nusing System.Reflection; \n\nusing HibernatingRhinos.Profiler.Appender.NHibernate; \nusing NHibernate.Cfg; \nusing NHibernate.Criterion; \nusing NHibernate.Dialect; \nusing NHibernate.Driver;\nusing NHibernate.Linq; \n\nnamespace NHibernateDemo { \n\n internal class Program {\n\t\n private static void Main() { \n\t\t\n var cfg = ConfigureNHibernate(); \n var sessionFactory = cfg.BuildSessionFactory();\n using(var session = sessionFactory.OpenSession()) \n \n using(var tx = session.BeginTransaction()) { \n var customers = session.CreateQuery(\"select c from Customer c \n where c.FirstName like 'H%'\"); \n \n foreach (var customer in customers.List<Customer>()) { \n Console.WriteLine(customer); \n }\n\t\t\t\t\n tx.Commit(); \n } \n\t\t\t\n Console.WriteLine(\"Press <ENTER> to exit...\"); \n Console.ReadLine(); \n } \n\t\t\n private static Configuration ConfigureNHibernate() {\n\t\t\n NHibernateProfiler.Initialize(); \n var cfg = new Configuration(); \n \n cfg.DataBaseIntegration(x => { \n x.ConnectionStringName = \"default\"; \n x.Driver<SqlClientDriver>(); \n x.Dialect<MsSql2008Dialect>(); \n x.IsolationLevel = IsolationLevel.RepeatableRead; \n x.Timeout = 10; \n x.BatchSize = 10; \n }); \n\t\t\t\n cfg.SessionFactory().GenerateStatistics();\n cfg.AddAssembly(Assembly.GetExecutingAssembly()); \n return cfg; \n } \n } \n}" }, { "code": null, "e": 9315, "s": 9184, "text": "Let’s run your application again and you will see that all of the customers whose name starts with H are returned from this query." }, { "code": null, "e": 10874, "s": 9315, "text": "Herman Crooks (4ead3480-6bce-11e1-b15c-6cf049ee52be)\n Points: 74\n HasGoldStatus: True\n MemberSince: 12/3/2010 12:00:00 AM (Utc)\n CreditRating: Neutral\n AverageRating: 0\n\n Orders:\n Order Id: 4ead3480-6bce-11e1-b15d-6cf049ee52be\n Order Id: 4ead3480-6bce-11e1-b15e-6cf049ee52be\n Order Id: 4ead3480-6bce-11e1-b15f-6cf049ee52be\n Order Id: 4ead3480-6bce-11e1-b160-6cf049ee52be\n Order Id: 4ead3480-6bce-11e1-b161-6cf049ee52be\n Order Id: 4ead3480-6bce-11e1-b162-6cf049ee52be\n Order Id: 4ead3480-6bce-11e1-b163-6cf049ee52be\n\nHudson Bins (4ec03f80-6bce-11e1-b2b7-6cf049ee52be)\n Points: 56\n HasGoldStatus: False\n MemberSince: 10/20/2008 12:00:00 AM (Utc)\n CreditRating: Terrible\n AverageRating: 0\n\n Orders:\n Order Id: 4ec03f80-6bce-11e1-b2b8-6cf049ee52be\n Order Id: 4ec03f80-6bce-11e1-b2b9-6cf049ee52be\n Order Id: 4ec03f80-6bce-11e1-b2ba-6cf049ee52be\n Order Id: 4ec03f80-6bce-11e1-b2bb-6cf049ee52be\n Order Id: 4ec03f80-6bce-11e1-b2bc-6cf049ee52be\n Order Id: 4ec03f80-6bce-11e1-b2bd-6cf049ee52be\n Order Id: 4ec03f80-6bce-11e1-b2be-6cf049ee52be\n Order Id: 4ec03f80-6bce-11e1-b2bf-6cf049ee52be\n\nHettie Feest (4ec50240-6bce-11e1-b300-6cf049ee52be)\n Points: 82\n HasGoldStatus: False\n MemberSince: 4/10/2009 12:00:00 AM (Utc)\n CreditRating: Neutral\n AverageRating: 0\n\n Orders:\n Order Id: 4ec50240-6bce-11e1-b301-6cf049ee52be\n Order Id: 4ec50240-6bce-11e1-b302-6cf049ee52be\n Order Id: 4ec50240-6bce-11e1-b303-6cf049ee52be\n\t\t\nPress <ENTER> to exit...\n" }, { "code": null, "e": 11028, "s": 10874, "text": "We can do more complicated things like wanting all orders where customers with an order count is greater than 9. Following is the HQL query for the same." }, { "code": null, "e": 11216, "s": 11028, "text": "var customers = session.CreateQuery(\"select c from Customer c \n where size(c.Orders) > 9\"); \n\t\nforeach (var customer in customers.List<Customer>()) { \n Console.WriteLine(customer); \n}" }, { "code": null, "e": 11362, "s": 11216, "text": "We also need to indicate that we need a size here or count or length. In HQL, we have the option of using the special size method as shown above." }, { "code": null, "e": 11454, "s": 11362, "text": "The other way to write this, if you prefer is c.Orders.size, and this has the exact effect." }, { "code": null, "e": 11641, "s": 11454, "text": "var customers = session.CreateQuery(\"select c from Customer c \n where c.Orders.size > 9\"); \n\t\nforeach (var customer in customers.List<Customer>()) { \n Console.WriteLine(customer); \n}" }, { "code": null, "e": 11669, "s": 11641, "text": "Let's run this application." }, { "code": null, "e": 13139, "s": 11669, "text": "Lindsay Towne (4ea3aef6-6bce-11e1-b0cb-6cf049ee52be)\n Points: 50\n HasGoldStatus: False\n MemberSince: 4/13/2007 12:00:00 AM (Utc)\n CreditRating: VeryGood\n AverageRating: 0\n\n Orders:\n Order Id: 4ea3aef6-6bce-11e1-b0cc-6cf049ee52be\n Order Id: 4ea3aef6-6bce-11e1-b0cd-6cf049ee52be\n Order Id: 4ea3aef6-6bce-11e1-b0ce-6cf049ee52be\n Order Id: 4ea3aef6-6bce-11e1-b0cf-6cf049ee52be\n Order Id: 4ea3aef6-6bce-11e1-b0d0-6cf049ee52be\n Order Id: 4ea3aef6-6bce-11e1-b0d1-6cf049ee52be\n Order Id: 4ea3aef6-6bce-11e1-b0d2-6cf049ee52be\n Order Id: 4ea3aef6-6bce-11e1-b0d3-6cf049ee52be\n Order Id: 4ea3aef6-6bce-11e1-b0d4-6cf049ee52be\n Order Id: 4ea3aef6-6bce-11e1-b0d5-6cf049ee52be\n\nWyman Hammes (4ea61056-6bce-11e1-b0e2-6cf049ee52be)\n Points: 32\n HasGoldStatus: False\n MemberSince: 2/5/2011 12:00:00 AM (Utc)\n CreditRating: Good\n AverageRating: 0\n\n Orders:\n Order Id: 4ea61056-6bce-11e1-b0e3-6cf049ee52be\n Order Id: 4ea61056-6bce-11e1-b0e4-6cf049ee52be\n Order Id: 4ea61056-6bce-11e1-b0e5-6cf049ee52be\n Order Id: 4ea61056-6bce-11e1-b0e6-6cf049ee52be\n Order Id: 4ea61056-6bce-11e1-b0e7-6cf049ee52be\n Order Id: 4ea61056-6bce-11e1-b0e8-6cf049ee52be\n Order Id: 4ea61056-6bce-11e1-b0e9-6cf049ee52be\n Order Id: 4ea61056-6bce-11e1-b0ea-6cf049ee52be\n Order Id: 4ea61056-6bce-11e1-b0eb-6cf049ee52be\n Order Id: 4ea61056-6bce-11e1-b0ec-6cf049ee52be\n\t\t\nPress <ENTER> to exit...\n" }, { "code": null, "e": 13236, "s": 13139, "text": "You can see that all the customers, who have more than 9 orders are retrieved from the database." }, { "code": null, "e": 13243, "s": 13236, "text": " Print" }, { "code": null, "e": 13254, "s": 13243, "text": " Add Notes" } ]
Business Simulations With Python. Using Monte Carlo to Explore Customer... | by Tony Yiu | Towards Data Science
As I wrote this post on business strategy for data scientists, I realized it might be fun to run a simulation for a marketing campaign and the cohort of new customers that it produces. A lot of my professional life has been spent in the world of finance and investing. I’m more used to thinking about companies as a whole (analyzing them at the aggregate level) than on a day to day level. But I do find the more granular details really interesting. After all, what’s a whole if it’s not the sum of its parts? A great way to learn more about something is to simulate it (with reasonable inputs and assumptions) and then study the results. You will often be surprised by how seemingly simple interactions among a few key variables can produce some surprising results. So let’s use Python to simulate a marketing campaign and see what happens. We will focus our simulation on customer lifetime value (CLTV) and customer acquisition cost (CAC), the key metrics of many a startup (and public companies as well). In my previous business strategy post, I explored these metrics in depth conceptually, so please refer to it if you want more background. The detailed code for this simulation can be found here on my GitHub. But here is the high level overview of what we are trying to do: Define a function that runs a marketing campaign — given some inputs like conversion rate, cost, budget, etc., I want to return a list of newly signed up customers. Define a function that simulates a cohort of customers — given some assumptions about churn, spending frequency, and spending amount, I want to simulate the performance of this cohort of customers and ultimately calculate their average lifetime value to my business. Run a bunch of simulations and look at the distribution of results. Let’s write the function for running a marketing campaign first. We can do this one of two ways — we use a randomly generated number to represent the outcome of each impression (each impression has a tiny probability of turning into a paying customer) and then tally up our results (using a for loop). Or we can take advantage of a statistical model. Let’s go with the latter as looping millions of times is quite slow. Instead we can take advantage of our old friend, the binomial distribution (and it gives me an excuse to link to my old blog post — please read if you are unfamiliar with the binomial distribution). Quoting my previous self: The binomial distribution is the probability distribution of a sequence of experiments where each experiment produces a binary outcome and where each of the outcomes is independent of all the others. Whether or not the outcome of each impression is truly independent or not is debatable, but for our purposes we can safely make that assumption. That means we can use a random variable with a binomial distribution to model our marketing campaign. Our budget and the CPM (cost per 1,000 impressions from an ad vendor like Google) determines the number of trials. And the conversion rate of each impression is the probability of success. The following function does what I just described: # Function for calculating the results of a marketing campaigndef run_campaign(spend, cpm, conversion_rate): return np.random.binomial(spend/cpm*1000, conversion_rate) The conversion rate itself is just an estimate so we should inject some uncertainty into it as well. For a first pass, it’s reasonable to assume that our conversion rate is normally distributed. Note that I set a floor for the conversion rate as negative conversion rates don’t make sense. # From the expected conversion rate and stdev of it, get the# realized conversion ratedef get_conversion_rate(expected, stdev): conversion_rate = max(expected + np.random.normal()*stdev, 0.000001) return conversion_rate Now let’s give it some inputs — spend is the amount that we plan to spend on our marketing campaign, cpm is the cost for 1,000 impressions, and the two conversion rate related variables are our estimates for the rate’s expected value and standard deviation. The expected conversion rate looks small, but it’s actually not that small. Another way to see it is that for every 20,000 impressions served, we expect to get one customer. That sounds like a lot before you realize that thanks to Google, the cost per thousand impressions is $2 — so 20,000 impressions costs us just $40. # Budgetspend = 50000# Cost per thousandcpm = 2# Conversion rateconversion_rate_expected = 0.00005conversion_rate_stdev = 0.00002 Now let’s give our functions a try. The variable cohort_size is the one we are after — it is the number of new customers that result from our marketing campaign. And with it, we can calculate our customer acquisition cost (CAC). CAC is the total cost of our marketing effort divided by the number of customers we gained from that effort. # Let's call it to get the number of new customers from our campaignconversion_rate = get_conversion_rate(conversion_rate_expected, conversion_rate_stdev)cohort_size = run_campaign(spend, cpm, conversion_rate)# And calculate our Customer Acquisition costCAC = spend/cohort_sizeprint('Customers Gained: ', cohort_size)print('CAC: ', round(CAC, 2)) Running the above lines produces the following results: Customers Gained: 1,309 CAC (Customer Acquisition Cost): $50,000 / 1,309 = $38 Of course if we run it again, we would expect to see different values as we’ve injected two layers of randomness (the conversion rate as a normally distributed random variable and the number of people that ultimately become customers as a binomial distributed random variable). Our next step is to write some functions that simulate how our customer cohort changes over time. Each year, some members of the cohort churn (and are no longer customers) while the remaining ones buy goods from us. We can use a random number generator (that generates a float between 0 and 1, uniformly distributed) to simulate whether a specific customer churns each year. The logic goes like this — for each customer in the cohort in a given year, we generate a random number. If the number we generated is below a minimum threshold, then that customer has canceled. For simplicity, we are assuming that all cancels happen at the beginning of the year, so the churned customers make zero purchases from us in the year that they leave. # Function that models the progression of a cohort over timedef simulate_cohort(cohort_size, churn_rate, transactions, price, retention_cost, yrs=5): customers_left = [] spending = [] profit = [] for i in range(yrs): for customer in range(cohort_size): # Assume cancels happen at the start of the year # (for simplicity) churn_random_num = np.random.random() # Generate a random number between 0 and 1, if less # than churn_rate then customer has churned and we # subtract 1 from cohort_size if churn_random_num <= churn_rate: cohort_size += -1 # Calculate and record cohort's data customers_left.append(cohort_size) spending.append(cohort_size*transactions*price) profit.append(cohort_size*(transactions*price -\ retention_cost)) return customers_left, spending, profit Next, let’s collect our inputs and run our function. To be more realistic, we should assume a per customer annual retention cost. This is the amount we need to spend each year to keep a particular customer happy and loyal to our service. Note that I only forecast 5 years of profits — our remaining customers might still buy from us in year 6 but to be conservative, I will assume that a given cohort of customers has at most a 5 year life. churn_rate = 0.20# Number of annual transactions per average cohort membertransactions = 6# Price of goods sold per average transactionprice = 10# Annual cost of retaining/servicing customerretention_cost = 20# Run the functioncustomers_left, spending, profit =\ simulate_cohort(cohort_size, churn_rate, transactions, price, retention_cost, yrs=5) The output we are most interested in is profit, the income to our business produced by our cohort of customers, as that is the primary driver of customer lifetime value. There are other indirect drivers as well such as referrals from satisfied customers but we will not model those here today. Before we can calculate customer lifetime value (CLTV), we need to write a present value function. Customers buy from us over time (by spending a bit on our products each year for as long as they are customers). This means that a lot of the payoff occurs in the future. And future dollars are worth less than today’s dollars because of inflation, opportunity cost, and uncertainty. We can approximately adjust for these effects by applying a haircut to any dollars that we receive in the future (the further out we receive the money, the more it needs to be discounted). The following function does just that: def present_value(cashflows, rate): pvs = [] for i, val in enumerate(cashflows): pvs.append(val/(1 + rate)**(i+1)) return pvs We have what we need to calculate CLTV now. We will apply a discount rate of 10% to transform profits received in the future into present values (in today’s dollars). For those that are curious, discount rates are complicated because we are trying to express numerous factors (inflation, risk, our hopes and dreams, etc) all through one single number — there is a ton of literature out there on how to properly estimate a discount rate so I will not go into it here. # Calculate CLTVrate = 0.10# Get the PV of the profitspvs = present_value(profit, rate)# Value of the cohort in today's dollars is sum of PVscohort_value = sum(pvs)print('Total Cohort Value: ', int(cohort_value))print('CLTV: ', int(cohort_value/cohort_size))print('CLTV-CAC Spread: ', int(cohort_value/cohort_size - CAC)) Let’s take a look at how profits and their present values compare: Profits from the cohort (in blue) decline over time as more and more customers churn. The present values of profits (in orange) decline at an even faster rate because the ones that are further out in the future are discounted more severely. The sum of the present values is the value of our cohort, and our CLTV is the cohort value divided by the initial size of the cohort: Total Cohort Value: $113,285 CLTV (Customer Lifetime Value): $113,285 / 1,309 = $86 CLTV-CAC Spread: $86 - $38 = $48 The value we really care about is the spread between CLTV and CAC — if it’s negative, then we are not going to be in business for long. Granted, there are certain cases when a negative spread is OK. For example, early stage startups that are desperate to scale will spend a ton to attract even low value customers. That’s because their outcome distribution is pretty binary (and their risk/reward is pretty asymmetric). If they scale fast enough, they build a successful business and become rich. If they don’t reach the required scale and fizzle out, well it was other people’s money anyway (this attitude is a byproduct of how cheap and available money has been, especially from venture capitalists, for a number of years now). Of course, the expectation is that the spread for future customer cohorts will be positive — as the company and brand gain steam, CLTV should increase while CAC declines. Finally, we have all the requisite pieces and can run our Monte Carlo simulation now. We will simulate 1,000 marketing campaigns so that we can look at the distribution of outcomes. # Simulate 1000 times and look at the distributionscohort_size_list = []CAC_list = []CLTV_list = []for i in range(1000): # Run marketing campaign sim conversion_rate = get_conversion_rate(conversion_rate_expected, conversion_rate_stdev) cohort_size = run_campaign(spend, cpm, conversion_rate) CAC = spend/cohort_size # Simulate the resulting cohort customers_left, spending, profit =\ simulate_cohort(cohort_size, churn_rate, transactions, price, retention_cost, yrs=5) cohort_value = sum(present_value(profit, rate)) cohort_size_list.append(cohort_size) CAC_list.append(CAC) CLTV_list.append(cohort_value/cohort_size) # Store simulation results in a dataframeresults_df = pd.DataFrame()results_df['initial_cohort_size'] = cohort_size_listresults_df['CLTV'] = CLTV_listresults_df['CAC'] = CAC_listresults_df['Spread'] = results_df['CLTV'] - results_df['CAC'] The starting size of our cohort of customers can vary widely because we have 2 layers of randomness (we allow the “true” conversion rate of each campaign to vary and each impression that goes out is itself a trial with a random outcome): And if the cohort size can vary widely, so can CAC (we expect it to have a median value of around $40 (because or our input assumptions). And wow, it is pretty wide. The median CAC is $40, but it is possible to experience terrible campaign returns (where very few customers sign up) and get CACs in the triple digits — more than 6% of the simulations resulted in a CAC of $100 or more. So don’t expect the worst but do be prepared for it. The shape of the distribution is interesting. From a CAC perspective, it’s asymmetrical — if we sign up a lot of customers, we get a low CAC, but there is a realistic limit to how low it can go (I call it a soft cap to our upside). But if we don’t sign up many customers, we could potentially see very high CACs that could be disastrous for our company. Now let’s look at the revenue side of the picture, CLTV. There is noticeably less variance here because of the way I modeled it. I could have allowed for more variance by injecting randomness into the annual churn rate or the customer transactions (by varying the frequency and value of each transaction). If I had, the bell curve would be wider (due to more sources of variation and uncertainty), but would still have the same mean value and general shape. Finally, let’s take a look at the spread between CLTV and CAC. Here, again we see a long tail and the soft cap, but this time it’s flipped (because we subtract CAC from CLTV when calculating the spread). What it means is twofold: Even if we have a massively successful campaign, there is a limit to the per customer upside (as measured by the spread) we can achieve. This limit exists because of the fact that CAC can only go so low (for example, the lowest CAC encountered in the 1,000 scenarios that I ran was $16) and each customer can only buy so much. On the other hand, if we have a disastrous campaign, the spread could easily be negative, meaning that the resulting customers will likely never make back their cost of acquisition. Depending on the phase of the company and the scale of the marketing campaign, this may not be a deal breaker (it could just be a temporary and one-off hiccup). But this should dissuade us from betting a significant chunk of our firm’s assets or budget on one massive campaign — a failure there could spell doom for the company. Hope this was helpful, cheers! More Data Science and Analytics Related Posts By Me: Business Strategy For Data Scientists What Do Data Scientists Do? Understanding Bayes’ Theorem Understanding The Naive Bayes Classifier The Binomial Distribution
[ { "code": null, "e": 356, "s": 171, "text": "As I wrote this post on business strategy for data scientists, I realized it might be fun to run a simulation for a marketing campaign and the cohort of new customers that it produces." }, { "code": null, "e": 681, "s": 356, "text": "A lot of my professional life has been spent in the world of finance and investing. I’m more used to thinking about companies as a whole (analyzing them at the aggregate level) than on a day to day level. But I do find the more granular details really interesting. After all, what’s a whole if it’s not the sum of its parts?" }, { "code": null, "e": 1013, "s": 681, "text": "A great way to learn more about something is to simulate it (with reasonable inputs and assumptions) and then study the results. You will often be surprised by how seemingly simple interactions among a few key variables can produce some surprising results. So let’s use Python to simulate a marketing campaign and see what happens." }, { "code": null, "e": 1317, "s": 1013, "text": "We will focus our simulation on customer lifetime value (CLTV) and customer acquisition cost (CAC), the key metrics of many a startup (and public companies as well). In my previous business strategy post, I explored these metrics in depth conceptually, so please refer to it if you want more background." }, { "code": null, "e": 1452, "s": 1317, "text": "The detailed code for this simulation can be found here on my GitHub. But here is the high level overview of what we are trying to do:" }, { "code": null, "e": 1617, "s": 1452, "text": "Define a function that runs a marketing campaign — given some inputs like conversion rate, cost, budget, etc., I want to return a list of newly signed up customers." }, { "code": null, "e": 1884, "s": 1617, "text": "Define a function that simulates a cohort of customers — given some assumptions about churn, spending frequency, and spending amount, I want to simulate the performance of this cohort of customers and ultimately calculate their average lifetime value to my business." }, { "code": null, "e": 1952, "s": 1884, "text": "Run a bunch of simulations and look at the distribution of results." }, { "code": null, "e": 2571, "s": 1952, "text": "Let’s write the function for running a marketing campaign first. We can do this one of two ways — we use a randomly generated number to represent the outcome of each impression (each impression has a tiny probability of turning into a paying customer) and then tally up our results (using a for loop). Or we can take advantage of a statistical model. Let’s go with the latter as looping millions of times is quite slow. Instead we can take advantage of our old friend, the binomial distribution (and it gives me an excuse to link to my old blog post — please read if you are unfamiliar with the binomial distribution)." }, { "code": null, "e": 2597, "s": 2571, "text": "Quoting my previous self:" }, { "code": null, "e": 2797, "s": 2597, "text": "The binomial distribution is the probability distribution of a sequence of experiments where each experiment produces a binary outcome and where each of the outcomes is independent of all the others." }, { "code": null, "e": 3284, "s": 2797, "text": "Whether or not the outcome of each impression is truly independent or not is debatable, but for our purposes we can safely make that assumption. That means we can use a random variable with a binomial distribution to model our marketing campaign. Our budget and the CPM (cost per 1,000 impressions from an ad vendor like Google) determines the number of trials. And the conversion rate of each impression is the probability of success. The following function does what I just described:" }, { "code": null, "e": 3455, "s": 3284, "text": "# Function for calculating the results of a marketing campaigndef run_campaign(spend, cpm, conversion_rate): return np.random.binomial(spend/cpm*1000, conversion_rate)" }, { "code": null, "e": 3745, "s": 3455, "text": "The conversion rate itself is just an estimate so we should inject some uncertainty into it as well. For a first pass, it’s reasonable to assume that our conversion rate is normally distributed. Note that I set a floor for the conversion rate as negative conversion rates don’t make sense." }, { "code": null, "e": 3997, "s": 3745, "text": "# From the expected conversion rate and stdev of it, get the# realized conversion ratedef get_conversion_rate(expected, stdev): conversion_rate = max(expected + np.random.normal()*stdev, 0.000001) return conversion_rate" }, { "code": null, "e": 4577, "s": 3997, "text": "Now let’s give it some inputs — spend is the amount that we plan to spend on our marketing campaign, cpm is the cost for 1,000 impressions, and the two conversion rate related variables are our estimates for the rate’s expected value and standard deviation. The expected conversion rate looks small, but it’s actually not that small. Another way to see it is that for every 20,000 impressions served, we expect to get one customer. That sounds like a lot before you realize that thanks to Google, the cost per thousand impressions is $2 — so 20,000 impressions costs us just $40." }, { "code": null, "e": 4707, "s": 4577, "text": "# Budgetspend = 50000# Cost per thousandcpm = 2# Conversion rateconversion_rate_expected = 0.00005conversion_rate_stdev = 0.00002" }, { "code": null, "e": 5045, "s": 4707, "text": "Now let’s give our functions a try. The variable cohort_size is the one we are after — it is the number of new customers that result from our marketing campaign. And with it, we can calculate our customer acquisition cost (CAC). CAC is the total cost of our marketing effort divided by the number of customers we gained from that effort." }, { "code": null, "e": 5430, "s": 5045, "text": "# Let's call it to get the number of new customers from our campaignconversion_rate = get_conversion_rate(conversion_rate_expected, conversion_rate_stdev)cohort_size = run_campaign(spend, cpm, conversion_rate)# And calculate our Customer Acquisition costCAC = spend/cohort_sizeprint('Customers Gained: ', cohort_size)print('CAC: ', round(CAC, 2))" }, { "code": null, "e": 5486, "s": 5430, "text": "Running the above lines produces the following results:" }, { "code": null, "e": 5510, "s": 5486, "text": "Customers Gained: 1,309" }, { "code": null, "e": 5565, "s": 5510, "text": "CAC (Customer Acquisition Cost): $50,000 / 1,309 = $38" }, { "code": null, "e": 5843, "s": 5565, "text": "Of course if we run it again, we would expect to see different values as we’ve injected two layers of randomness (the conversion rate as a normally distributed random variable and the number of people that ultimately become customers as a binomial distributed random variable)." }, { "code": null, "e": 6059, "s": 5843, "text": "Our next step is to write some functions that simulate how our customer cohort changes over time. Each year, some members of the cohort churn (and are no longer customers) while the remaining ones buy goods from us." }, { "code": null, "e": 6581, "s": 6059, "text": "We can use a random number generator (that generates a float between 0 and 1, uniformly distributed) to simulate whether a specific customer churns each year. The logic goes like this — for each customer in the cohort in a given year, we generate a random number. If the number we generated is below a minimum threshold, then that customer has canceled. For simplicity, we are assuming that all cancels happen at the beginning of the year, so the churned customers make zero purchases from us in the year that they leave." }, { "code": null, "e": 7555, "s": 6581, "text": "# Function that models the progression of a cohort over timedef simulate_cohort(cohort_size, churn_rate, transactions, price, retention_cost, yrs=5): customers_left = [] spending = [] profit = [] for i in range(yrs): for customer in range(cohort_size): # Assume cancels happen at the start of the year # (for simplicity) churn_random_num = np.random.random() # Generate a random number between 0 and 1, if less # than churn_rate then customer has churned and we # subtract 1 from cohort_size if churn_random_num <= churn_rate: cohort_size += -1 # Calculate and record cohort's data customers_left.append(cohort_size) spending.append(cohort_size*transactions*price) profit.append(cohort_size*(transactions*price -\\ retention_cost)) return customers_left, spending, profit" }, { "code": null, "e": 7996, "s": 7555, "text": "Next, let’s collect our inputs and run our function. To be more realistic, we should assume a per customer annual retention cost. This is the amount we need to spend each year to keep a particular customer happy and loyal to our service. Note that I only forecast 5 years of profits — our remaining customers might still buy from us in year 6 but to be conservative, I will assume that a given cohort of customers has at most a 5 year life." }, { "code": null, "e": 8367, "s": 7996, "text": "churn_rate = 0.20# Number of annual transactions per average cohort membertransactions = 6# Price of goods sold per average transactionprice = 10# Annual cost of retaining/servicing customerretention_cost = 20# Run the functioncustomers_left, spending, profit =\\ simulate_cohort(cohort_size, churn_rate, transactions, price, retention_cost, yrs=5)" }, { "code": null, "e": 8661, "s": 8367, "text": "The output we are most interested in is profit, the income to our business produced by our cohort of customers, as that is the primary driver of customer lifetime value. There are other indirect drivers as well such as referrals from satisfied customers but we will not model those here today." }, { "code": null, "e": 9271, "s": 8661, "text": "Before we can calculate customer lifetime value (CLTV), we need to write a present value function. Customers buy from us over time (by spending a bit on our products each year for as long as they are customers). This means that a lot of the payoff occurs in the future. And future dollars are worth less than today’s dollars because of inflation, opportunity cost, and uncertainty. We can approximately adjust for these effects by applying a haircut to any dollars that we receive in the future (the further out we receive the money, the more it needs to be discounted). The following function does just that:" }, { "code": null, "e": 9413, "s": 9271, "text": "def present_value(cashflows, rate): pvs = [] for i, val in enumerate(cashflows): pvs.append(val/(1 + rate)**(i+1)) return pvs" }, { "code": null, "e": 9880, "s": 9413, "text": "We have what we need to calculate CLTV now. We will apply a discount rate of 10% to transform profits received in the future into present values (in today’s dollars). For those that are curious, discount rates are complicated because we are trying to express numerous factors (inflation, risk, our hopes and dreams, etc) all through one single number — there is a ton of literature out there on how to properly estimate a discount rate so I will not go into it here." }, { "code": null, "e": 10202, "s": 9880, "text": "# Calculate CLTVrate = 0.10# Get the PV of the profitspvs = present_value(profit, rate)# Value of the cohort in today's dollars is sum of PVscohort_value = sum(pvs)print('Total Cohort Value: ', int(cohort_value))print('CLTV: ', int(cohort_value/cohort_size))print('CLTV-CAC Spread: ', int(cohort_value/cohort_size - CAC))" }, { "code": null, "e": 10269, "s": 10202, "text": "Let’s take a look at how profits and their present values compare:" }, { "code": null, "e": 10510, "s": 10269, "text": "Profits from the cohort (in blue) decline over time as more and more customers churn. The present values of profits (in orange) decline at an even faster rate because the ones that are further out in the future are discounted more severely." }, { "code": null, "e": 10644, "s": 10510, "text": "The sum of the present values is the value of our cohort, and our CLTV is the cohort value divided by the initial size of the cohort:" }, { "code": null, "e": 10673, "s": 10644, "text": "Total Cohort Value: $113,285" }, { "code": null, "e": 10728, "s": 10673, "text": "CLTV (Customer Lifetime Value): $113,285 / 1,309 = $86" }, { "code": null, "e": 10761, "s": 10728, "text": "CLTV-CAC Spread: $86 - $38 = $48" }, { "code": null, "e": 11491, "s": 10761, "text": "The value we really care about is the spread between CLTV and CAC — if it’s negative, then we are not going to be in business for long. Granted, there are certain cases when a negative spread is OK. For example, early stage startups that are desperate to scale will spend a ton to attract even low value customers. That’s because their outcome distribution is pretty binary (and their risk/reward is pretty asymmetric). If they scale fast enough, they build a successful business and become rich. If they don’t reach the required scale and fizzle out, well it was other people’s money anyway (this attitude is a byproduct of how cheap and available money has been, especially from venture capitalists, for a number of years now)." }, { "code": null, "e": 11662, "s": 11491, "text": "Of course, the expectation is that the spread for future customer cohorts will be positive — as the company and brand gain steam, CLTV should increase while CAC declines." }, { "code": null, "e": 11844, "s": 11662, "text": "Finally, we have all the requisite pieces and can run our Monte Carlo simulation now. We will simulate 1,000 marketing campaigns so that we can look at the distribution of outcomes." }, { "code": null, "e": 12821, "s": 11844, "text": "# Simulate 1000 times and look at the distributionscohort_size_list = []CAC_list = []CLTV_list = []for i in range(1000): # Run marketing campaign sim conversion_rate = get_conversion_rate(conversion_rate_expected, conversion_rate_stdev) cohort_size = run_campaign(spend, cpm, conversion_rate) CAC = spend/cohort_size # Simulate the resulting cohort customers_left, spending, profit =\\ simulate_cohort(cohort_size, churn_rate, transactions, price, retention_cost, yrs=5) cohort_value = sum(present_value(profit, rate)) cohort_size_list.append(cohort_size) CAC_list.append(CAC) CLTV_list.append(cohort_value/cohort_size) # Store simulation results in a dataframeresults_df = pd.DataFrame()results_df['initial_cohort_size'] = cohort_size_listresults_df['CLTV'] = CLTV_listresults_df['CAC'] = CAC_listresults_df['Spread'] = results_df['CLTV'] - results_df['CAC']" }, { "code": null, "e": 13059, "s": 12821, "text": "The starting size of our cohort of customers can vary widely because we have 2 layers of randomness (we allow the “true” conversion rate of each campaign to vary and each impression that goes out is itself a trial with a random outcome):" }, { "code": null, "e": 13498, "s": 13059, "text": "And if the cohort size can vary widely, so can CAC (we expect it to have a median value of around $40 (because or our input assumptions). And wow, it is pretty wide. The median CAC is $40, but it is possible to experience terrible campaign returns (where very few customers sign up) and get CACs in the triple digits — more than 6% of the simulations resulted in a CAC of $100 or more. So don’t expect the worst but do be prepared for it." }, { "code": null, "e": 13852, "s": 13498, "text": "The shape of the distribution is interesting. From a CAC perspective, it’s asymmetrical — if we sign up a lot of customers, we get a low CAC, but there is a realistic limit to how low it can go (I call it a soft cap to our upside). But if we don’t sign up many customers, we could potentially see very high CACs that could be disastrous for our company." }, { "code": null, "e": 14310, "s": 13852, "text": "Now let’s look at the revenue side of the picture, CLTV. There is noticeably less variance here because of the way I modeled it. I could have allowed for more variance by injecting randomness into the annual churn rate or the customer transactions (by varying the frequency and value of each transaction). If I had, the bell curve would be wider (due to more sources of variation and uncertainty), but would still have the same mean value and general shape." }, { "code": null, "e": 14540, "s": 14310, "text": "Finally, let’s take a look at the spread between CLTV and CAC. Here, again we see a long tail and the soft cap, but this time it’s flipped (because we subtract CAC from CLTV when calculating the spread). What it means is twofold:" }, { "code": null, "e": 14867, "s": 14540, "text": "Even if we have a massively successful campaign, there is a limit to the per customer upside (as measured by the spread) we can achieve. This limit exists because of the fact that CAC can only go so low (for example, the lowest CAC encountered in the 1,000 scenarios that I ran was $16) and each customer can only buy so much." }, { "code": null, "e": 15378, "s": 14867, "text": "On the other hand, if we have a disastrous campaign, the spread could easily be negative, meaning that the resulting customers will likely never make back their cost of acquisition. Depending on the phase of the company and the scale of the marketing campaign, this may not be a deal breaker (it could just be a temporary and one-off hiccup). But this should dissuade us from betting a significant chunk of our firm’s assets or budget on one massive campaign — a failure there could spell doom for the company." }, { "code": null, "e": 15409, "s": 15378, "text": "Hope this was helpful, cheers!" }, { "code": null, "e": 15462, "s": 15409, "text": "More Data Science and Analytics Related Posts By Me:" }, { "code": null, "e": 15500, "s": 15462, "text": "Business Strategy For Data Scientists" }, { "code": null, "e": 15528, "s": 15500, "text": "What Do Data Scientists Do?" }, { "code": null, "e": 15557, "s": 15528, "text": "Understanding Bayes’ Theorem" }, { "code": null, "e": 15598, "s": 15557, "text": "Understanding The Naive Bayes Classifier" } ]
Explain different types of expressions in C program
An expression is a combination of operators and operands which reduces to a single value. An operation is performed on a data item which is called an operand. An operator indicates an operation to be performed on data. For example, z = 3+2*1 z = 5 Primary expressions − It is an operand which can be a name, a constant or any parenthesized expression. Example − c = a+ (5*b); Primary expressions − It is an operand which can be a name, a constant or any parenthesized expression. Example − c = a+ (5*b); Postfix expressions − In a postfix expression, the operator will be after the operand. Example − ab+ Postfix expressions − In a postfix expression, the operator will be after the operand. Example − ab+ Prefix expressions − n a prefix expression, the operator is before the operand. Example − +ab Prefix expressions − n a prefix expression, the operator is before the operand. Example − +ab Unary expression − It contains one operator and one operand. Example − a++, --b Unary expression − It contains one operator and one operand. Example − a++, --b Binary expression − t contains two operands and one operator. Example − a+b, c-d Binary expression − t contains two operands and one operator. Example − a+b, c-d Ternary expression − It contains three operands and one operator. For Example, Exp1? Exp2 − Exp3. If Exp1 is true, Exp2 is executed. Otherwise, Exp3 is executed. Ternary expression − It contains three operands and one operator. For Example, Exp1? Exp2 − Exp3. If Exp1 is true, Exp2 is executed. Otherwise, Exp3 is executed. Given below is the C program explaining the different types of expressions in C language − Live Demo #include<stdio.h> int main(){ int a,b,c,d,z; int p,q,r,s,t,u,v; printf("enter the values of a,b,c,d:\n"); scanf("%d%d%d%d",&a,&b,&c,&d); r=a++; s=--b; t=a+b; u=c-d; v=a+(5*b); z = (5>3) ? 1:0; printf("unaryexpression=%d\nunary expression=%d\n Binary expression=%d\nBinary expression=%d\nPrimary expression=%d\nTernary expression=%d\n",r,s,t,u,v,z); } You will see the following output − enter the values of a,b,c,d: 2 3 4 6 unary expression=2 unary expression=2 Binary expression=5 Binary expression=-2 Primary expression=13 Ternary expression=1
[ { "code": null, "e": 1281, "s": 1062, "text": "An expression is a combination of operators and operands which reduces to a single value. An operation is performed on a data item which is called an operand. An operator indicates an operation to be performed on data." }, { "code": null, "e": 1304, "s": 1281, "text": "For example, z = 3+2*1" }, { "code": null, "e": 1310, "s": 1304, "text": "z = 5" }, { "code": null, "e": 1438, "s": 1310, "text": "Primary expressions − It is an operand which can be a name, a constant or any parenthesized expression. Example − c = a+ (5*b);" }, { "code": null, "e": 1566, "s": 1438, "text": "Primary expressions − It is an operand which can be a name, a constant or any parenthesized expression. Example − c = a+ (5*b);" }, { "code": null, "e": 1667, "s": 1566, "text": "Postfix expressions − In a postfix expression, the operator will be after the operand. Example − ab+" }, { "code": null, "e": 1768, "s": 1667, "text": "Postfix expressions − In a postfix expression, the operator will be after the operand. Example − ab+" }, { "code": null, "e": 1862, "s": 1768, "text": "Prefix expressions − n a prefix expression, the operator is before the operand. Example − +ab" }, { "code": null, "e": 1956, "s": 1862, "text": "Prefix expressions − n a prefix expression, the operator is before the operand. Example − +ab" }, { "code": null, "e": 2036, "s": 1956, "text": "Unary expression − It contains one operator and one operand. Example − a++, --b" }, { "code": null, "e": 2116, "s": 2036, "text": "Unary expression − It contains one operator and one operand. Example − a++, --b" }, { "code": null, "e": 2197, "s": 2116, "text": "Binary expression − t contains two operands and one operator. Example − a+b, c-d" }, { "code": null, "e": 2278, "s": 2197, "text": "Binary expression − t contains two operands and one operator. Example − a+b, c-d" }, { "code": null, "e": 2440, "s": 2278, "text": "Ternary expression − It contains three operands and one operator. For Example, Exp1? Exp2 − Exp3. If Exp1 is true, Exp2 is executed. Otherwise, Exp3 is executed." }, { "code": null, "e": 2602, "s": 2440, "text": "Ternary expression − It contains three operands and one operator. For Example, Exp1? Exp2 − Exp3. If Exp1 is true, Exp2 is executed. Otherwise, Exp3 is executed." }, { "code": null, "e": 2693, "s": 2602, "text": "Given below is the C program explaining the different types of expressions in C language −" }, { "code": null, "e": 2704, "s": 2693, "text": " Live Demo" }, { "code": null, "e": 3091, "s": 2704, "text": "#include<stdio.h>\nint main(){\n int a,b,c,d,z;\n int p,q,r,s,t,u,v;\n printf(\"enter the values of a,b,c,d:\\n\");\n scanf(\"%d%d%d%d\",&a,&b,&c,&d);\n r=a++;\n s=--b;\n t=a+b;\n u=c-d;\n v=a+(5*b);\n z = (5>3) ? 1:0;\n printf(\"unaryexpression=%d\\nunary expression=%d\\n Binary\n expression=%d\\nBinary expression=%d\\nPrimary expression=%d\\nTernary expression=%d\\n\",r,s,t,u,v,z);\n}" }, { "code": null, "e": 3127, "s": 3091, "text": "You will see the following output −" }, { "code": null, "e": 3286, "s": 3127, "text": "enter the values of a,b,c,d:\n2 3 4 6\nunary expression=2\nunary expression=2\nBinary expression=5\nBinary expression=-2\nPrimary expression=13\nTernary expression=1" } ]
Bootstrap dropdown class
Dropdown menus are toggleable, contextual menus for displaying links in a list format. To use a drop-down, just wrap the drop-down menu within the class .dropdown. You can try to run the following code to implement the dropdown class in Bootstrap Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body> <div class = "dropdown"> <button type = "button" class = "btn dropdown-toggle" id = "dropdownMenu1" data-toggle = "dropdown"> Subjects <span class = "caret"></span> </button> <ul class = "dropdown-menu" role = "menu" aria-labelledby = "dropdownMenu1"> <li role = "presentation"> <a role = "menuitem" tabindex = "-1" href = "#">Java</a> </li> <li role = "presentation"> <a role = "menuitem" tabindex = "-1" href = "#">Data Mining</a> </li> <li role = "presentation"> <a role = "menuitem" tabindex = "-1" href = "#"> C++ </a> </li> <li role = "presentation" class = "divider"></li> <li role = "presentation"> <a role = "menuitem" tabindex = "-1" href = "#">Separated link</a> </li> </ul> </div> </body> </html>
[ { "code": null, "e": 1226, "s": 1062, "text": "Dropdown menus are toggleable, contextual menus for displaying links in a list format. To use a drop-down, just wrap the drop-down menu within the class .dropdown." }, { "code": null, "e": 1309, "s": 1226, "text": "You can try to run the following code to implement the dropdown class in Bootstrap" }, { "code": null, "e": 1319, "s": 1309, "text": "Live Demo" }, { "code": null, "e": 2589, "s": 1319, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"dropdown\">\n <button type = \"button\" class = \"btn dropdown-toggle\" id = \"dropdownMenu1\" data-toggle = \"dropdown\">\n Subjects\n <span class = \"caret\"></span>\n </button>\n <ul class = \"dropdown-menu\" role = \"menu\" aria-labelledby = \"dropdownMenu1\">\n <li role = \"presentation\">\n <a role = \"menuitem\" tabindex = \"-1\" href = \"#\">Java</a>\n </li>\n <li role = \"presentation\">\n <a role = \"menuitem\" tabindex = \"-1\" href = \"#\">Data Mining</a>\n </li>\n <li role = \"presentation\">\n <a role = \"menuitem\" tabindex = \"-1\" href = \"#\">\n C++\n </a>\n </li>\n <li role = \"presentation\" class = \"divider\"></li>\n <li role = \"presentation\">\n <a role = \"menuitem\" tabindex = \"-1\" href = \"#\">Separated link</a>\n </li>\n </ul>\n </div>\n </body>\n</html>" } ]
C++ Vector Library - cbegin() Function
The C++ function std::vector::cbegin() returns a constant random access iterator which points to the beginning of the vector. Iterator obtained by this member function can be used to iterate container but cannot be used to modify the content of object to which it is pointing even if object itself is not constant. Following is the declaration for std::vector::cbegin() function form std::vector header. const_iterator cbegin() const noexcept; None Returns a constant random access iterator which points to the beginning of the vector. This member function never throws exception. Constant i.e. O(1) The following example shows the usage of std::vector::cbegin() function. #include <iostream> #include <vector> using namespace std; int main(void) { auto ilist = {1, 2, 3, 4, 5}; vector<int> v(ilist); for (auto it = v.cbegin(); it != v.end(); ++it) cout << *it << endl; return 0; } Let us compile and run the above program, this will produce the following result − 1 2 3 4 5 Print Add Notes Bookmark this page
[ { "code": null, "e": 2729, "s": 2603, "text": "The C++ function std::vector::cbegin() returns a constant random access iterator which points to the beginning of the vector." }, { "code": null, "e": 2918, "s": 2729, "text": "Iterator obtained by this member function can be used to iterate container but cannot be used to modify the content of object to which it is pointing even if object itself is not constant." }, { "code": null, "e": 3007, "s": 2918, "text": "Following is the declaration for std::vector::cbegin() function form std::vector header." }, { "code": null, "e": 3048, "s": 3007, "text": "const_iterator cbegin() const noexcept;\n" }, { "code": null, "e": 3053, "s": 3048, "text": "None" }, { "code": null, "e": 3140, "s": 3053, "text": "Returns a constant random access iterator which points to the beginning of the vector." }, { "code": null, "e": 3185, "s": 3140, "text": "This member function never throws exception." }, { "code": null, "e": 3204, "s": 3185, "text": "Constant i.e. O(1)" }, { "code": null, "e": 3277, "s": 3204, "text": "The following example shows the usage of std::vector::cbegin() function." }, { "code": null, "e": 3508, "s": 3277, "text": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main(void) {\n auto ilist = {1, 2, 3, 4, 5};\n vector<int> v(ilist);\n\n for (auto it = v.cbegin(); it != v.end(); ++it)\n cout << *it << endl;\n\n return 0;\n}" }, { "code": null, "e": 3591, "s": 3508, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3602, "s": 3591, "text": "1\n2\n3\n4\n5\n" }, { "code": null, "e": 3609, "s": 3602, "text": " Print" }, { "code": null, "e": 3620, "s": 3609, "text": " Add Notes" } ]
Swift - While Loop
A while loop statement in Swift 4 programming language repeatedly executes a target statement as long as a given condition is true. The syntax of a while loop in Swift 4 programming language is − while condition { statement(s) } Here statement(s) may be a single statement or a block of statements. The condition may be any expression. The loop iterates while the condition is true. When the condition becomes false, the program control passes to the line immediately following the loop. The number 0, the strings '0' and "", the empty list(), and undef are all false in a Boolean context and all other values are true. Negation of a true value by ! or not returns a special false value. The key point of a while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. var index = 10 while index < 20 { print( "Value of index is \(index)") index = index + 1 } Here we are using comparison operator < to compare the value of the variable index against 20. While the value of index is less than 20, the while loop continues executing a block of code next to it and as soon as the value of index becomes equal to 20, it comes out. When executed, the above code produces the following result − Value of index is 10 Value of index is 11 Value of index is 12 Value of index is 13 Value of index is 14 Value of index is 15 Value of index is 16 Value of index is 17 Value of index is 18 Value of index is 19 38 Lectures 1 hours Ashish Sharma 13 Lectures 2 hours Three Millennials 7 Lectures 1 hours Three Millennials 22 Lectures 1 hours Frahaan Hussain 12 Lectures 39 mins Devasena Rajendran 40 Lectures 2.5 hours Grant Klimaytys Print Add Notes Bookmark this page
[ { "code": null, "e": 2385, "s": 2253, "text": "A while loop statement in Swift 4 programming language repeatedly executes a target statement as long as a given condition is true." }, { "code": null, "e": 2449, "s": 2385, "text": "The syntax of a while loop in Swift 4 programming language is −" }, { "code": null, "e": 2486, "s": 2449, "text": "while condition {\n statement(s)\n}\n" }, { "code": null, "e": 2745, "s": 2486, "text": "Here statement(s) may be a single statement or a block of statements. The condition may be any expression. The loop iterates while the condition is true. When the condition becomes false, the program control passes to the line immediately following the loop." }, { "code": null, "e": 2945, "s": 2745, "text": "The number 0, the strings '0' and \"\", the empty list(), and undef are all false in a Boolean context and all other values are true. Negation of a true value by ! or not returns a special false value." }, { "code": null, "e": 3159, "s": 2945, "text": "The key point of a while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed." }, { "code": null, "e": 3257, "s": 3159, "text": "var index = 10\n\nwhile index < 20 {\n print( \"Value of index is \\(index)\")\n index = index + 1\n}" }, { "code": null, "e": 3587, "s": 3257, "text": "Here we are using comparison operator < to compare the value of the variable index against 20. While the value of index is less than 20, the while loop continues executing a block of code next to it and as soon as the value of index becomes equal to 20, it comes out. When executed, the above code produces the following result −" }, { "code": null, "e": 3798, "s": 3587, "text": "Value of index is 10\nValue of index is 11\nValue of index is 12\nValue of index is 13\nValue of index is 14\nValue of index is 15\nValue of index is 16\nValue of index is 17\nValue of index is 18\nValue of index is 19\n" }, { "code": null, "e": 3831, "s": 3798, "text": "\n 38 Lectures \n 1 hours \n" }, { "code": null, "e": 3846, "s": 3831, "text": " Ashish Sharma" }, { "code": null, "e": 3879, "s": 3846, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 3898, "s": 3879, "text": " Three Millennials" }, { "code": null, "e": 3930, "s": 3898, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 3949, "s": 3930, "text": " Three Millennials" }, { "code": null, "e": 3982, "s": 3949, "text": "\n 22 Lectures \n 1 hours \n" }, { "code": null, "e": 3999, "s": 3982, "text": " Frahaan Hussain" }, { "code": null, "e": 4031, "s": 3999, "text": "\n 12 Lectures \n 39 mins\n" }, { "code": null, "e": 4051, "s": 4031, "text": " Devasena Rajendran" }, { "code": null, "e": 4086, "s": 4051, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4103, "s": 4086, "text": " Grant Klimaytys" }, { "code": null, "e": 4110, "s": 4103, "text": " Print" }, { "code": null, "e": 4121, "s": 4110, "text": " Add Notes" } ]
Tryit Editor v3.7
Tryit: One font should be the boss
[]
Python | Broadcasting with NumPy Arrays - GeeksforGeeks
10 Jun, 2021 The term broadcasting refers to how numpy treats arrays with different Dimension during arithmetic operations which lead to certain constraints, the smaller array is broadcast across the larger array so that they have compatible shapes. Broadcasting provides a means of vectorizing array operations so that looping occurs in C instead of Python as we know that Numpy implemented in C. It does this without making needless copies of data and which leads to efficient algorithm implementations. There are cases where broadcasting is a bad idea because it leads to inefficient use of memory that slow down the computation.Example – Python3 import numpy as np A = np.array([5, 7, 3, 1])B = np.array([90, 50, 0, 30]) # array are compatible because of same Dimensionc = a * bprint (c) Example to get deeper understanding – Let’s assume that we have a large data set, each datum is a list of parameters. In Numpy we have a 2-D array, where each row is a datum and the number of rows is the size of the data set. Suppose we want to apply some sort of scaling to all these data every parameter gets its own scaling factor or say Every parameter is multiplied by some factor.Just to have some clear understanding, let’s count calories in foods using a macro-nutrient breakdown. Roughly put, the caloric parts of food are made of fats (9 calories per gram), protein (4 cpg) and carbs (4 cpg). So if we list some foods (our data), and for each food list its macro-nutrient breakdown (parameters), we can then multiply each nutrient by its caloric value (apply scaling) to compute the caloric breakdown of every food item. With this transformation, we can now compute all kinds of useful information. For example, what is the total number of calories present in some food or, given a breakdown of my dinner know how much calories did I get from protein and so on.Let’s see a naive way of producing this computation with Numpy: Python3 macros = array([ [0.8, 2.9, 3.9], [52.4, 23.6, 36.5], [55.2, 31.7, 23.9], [14.4, 11, 4.9] ]) # Create a new array filled with zeros,# of the same shape as macros.result = zeros_like(macros) cal_per_macro = array([3, 3, 8]) # Now multiply each row of macros by# cal_per_macro. In Numpy, `*` is# element-wise multiplication between two arrays. for i in range(macros.shape[0]): result[i, :] = macros[i, :] * cal_per_macro result output: array([[ 2.4, 8.7, 31.2 ], [ 157.2, 70.8, 292 ], [ 165.6, 95.1, 191.2], [ 43.2, 33, 39.2]]) Inputs: Array A with m dimensions and array B with n dimensions p = max(m, n) if m < p: left-pad A's shape with 1s until it also has p dimensions else if n < p: left-pad B's shape with 1s until it also has p dimensions result_dims = new list with p elements for i in p-1 ... 0: A_dim_i = A.shape[i] B_dim_i = B.shape[i] if A_dim_i != 1 and B_dim_i != 1 and A_dim_i != B_dim_i: raise ValueError("could not broadcast") else: # Pick the Array which is having maximum Dimension result_dims[i] = max(A_dim_i, B_dim_i) Broadcasting Rules: Broadcasting two arrays together follow these rules: If the arrays don’t have the same rank then prepend the shape of the lower rank array with 1s until both shapes have the same length.The two arrays are compatible in a dimension if they have the same size in the dimension or if one of the arrays has size 1 in that dimension.The arrays can be broadcast together iff they are compatible with all dimensions.After broadcasting, each array behaves as if it had shape equal to the element-wise maximum of shapes of the two input arrays.In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension. If the arrays don’t have the same rank then prepend the shape of the lower rank array with 1s until both shapes have the same length. The two arrays are compatible in a dimension if they have the same size in the dimension or if one of the arrays has size 1 in that dimension. The arrays can be broadcast together iff they are compatible with all dimensions. After broadcasting, each array behaves as if it had shape equal to the element-wise maximum of shapes of the two input arrays. In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension. Example #1: Single Dimension array Python3 import numpy as npa = np.array([17, 11, 19]) # 1x3 Dimension arrayprint(a)b = 3 print(b) # Broadcasting happened because of# miss match in array Dimension.c = a + bprint(c) Output: [17 11 19] 3 [20 14 22] Example 2: Two Dimensional Array Python3 import numpy as npA = np.array([[11, 22, 33], [10, 20, 30]])print(A) b = 4print(b) C = A + bprint(C) Output: [[11 22 33] [10 20 30]] 4 [[15 26 37] [14 24 34]] Example 3: Python3 import numpy as np v = np.array([12, 24, 36]) w = np.array([45, 55]) # To compute an outer product we first# reshape v to a column vector of shape 3x1# then broadcast it against w to yield an output# of shape 3x2 which is the outer product of v and wprint(np.reshape(v, (3, 1)) * w) X = np.array([[12, 22, 33], [45, 55, 66]]) # x has shape 2x3 and v has shape (3, )# so they broadcast to 2x3,print(X + v) # Add a vector to each column of a matrix X has# shape 2x3 and w has shape (2, ) If we transpose X# then it has shape 3x2 and can be broadcast against w# to yield a result of shape 3x2. # Transposing this yields the final result# of shape 2x3 which is the matrix.print((x.T + w).T) # Another solution is to reshape w to be a column# vector of shape 2X1 we can then broadcast it# directly against X to produce the same output.print(x + np.reshape(w, (2, 1))) # Multiply a matrix by a constant, X has shape 2x3.# Numpy treats scalars as arrays of shape();# these can be broadcast together to shape 2x3.print(x * 2) Output: [[ 4 5] [ 8 10] [12 15]] [[2 4 6] [5 7 9]] [[ 5 6 7] [ 9 10 11]] [[ 5 6 7] [ 9 10 11]] [[ 2 4 6] [ 8 10 12]] Plotting a two-dimensional function –Broadcasting is also frequently used in displaying images based on two-dimensional functions. If we want to define a function z=f(x, y).Example: Python3 import numpy as npimport matplotlib.pyplot as plt # Computes x and y coordinates for# points on sine and cosine curvesx = np.arange(0, 3 * np.pi, 0.1)y_sin = np.sin(x)y_cos = np.cos(x) # Plot the points using matplotlibplt.plot(x, y_sin)plt.plot(x, y_cos)plt.xlabel('x axis label')plt.ylabel('y axis label')plt.title('Sine and Cosine')plt.legend(['Sine', 'Cosine']) plt.show() Output: adnanirshad158 Python numpy-arrayManipulation Python-numpy 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 ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Python String | replace() Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 23721, "s": 23693, "text": "\n10 Jun, 2021" }, { "code": null, "e": 24352, "s": 23721, "text": "The term broadcasting refers to how numpy treats arrays with different Dimension during arithmetic operations which lead to certain constraints, the smaller array is broadcast across the larger array so that they have compatible shapes. Broadcasting provides a means of vectorizing array operations so that looping occurs in C instead of Python as we know that Numpy implemented in C. It does this without making needless copies of data and which leads to efficient algorithm implementations. There are cases where broadcasting is a bad idea because it leads to inefficient use of memory that slow down the computation.Example – " }, { "code": null, "e": 24360, "s": 24352, "text": "Python3" }, { "code": "import numpy as np A = np.array([5, 7, 3, 1])B = np.array([90, 50, 0, 30]) # array are compatible because of same Dimensionc = a * bprint (c)", "e": 24502, "s": 24360, "text": null }, { "code": null, "e": 25335, "s": 24502, "text": "Example to get deeper understanding – Let’s assume that we have a large data set, each datum is a list of parameters. In Numpy we have a 2-D array, where each row is a datum and the number of rows is the size of the data set. Suppose we want to apply some sort of scaling to all these data every parameter gets its own scaling factor or say Every parameter is multiplied by some factor.Just to have some clear understanding, let’s count calories in foods using a macro-nutrient breakdown. Roughly put, the caloric parts of food are made of fats (9 calories per gram), protein (4 cpg) and carbs (4 cpg). So if we list some foods (our data), and for each food list its macro-nutrient breakdown (parameters), we can then multiply each nutrient by its caloric value (apply scaling) to compute the caloric breakdown of every food item. " }, { "code": null, "e": 25641, "s": 25335, "text": "With this transformation, we can now compute all kinds of useful information. For example, what is the total number of calories present in some food or, given a breakdown of my dinner know how much calories did I get from protein and so on.Let’s see a naive way of producing this computation with Numpy: " }, { "code": null, "e": 25649, "s": 25641, "text": "Python3" }, { "code": "macros = array([ [0.8, 2.9, 3.9], [52.4, 23.6, 36.5], [55.2, 31.7, 23.9], [14.4, 11, 4.9] ]) # Create a new array filled with zeros,# of the same shape as macros.result = zeros_like(macros) cal_per_macro = array([3, 3, 8]) # Now multiply each row of macros by# cal_per_macro. In Numpy, `*` is# element-wise multiplication between two arrays. for i in range(macros.shape[0]): result[i, :] = macros[i, :] * cal_per_macro result", "e": 26085, "s": 25649, "text": null }, { "code": null, "e": 26095, "s": 26085, "text": "output: " }, { "code": null, "e": 26231, "s": 26095, "text": "array([[ 2.4, 8.7, 31.2 ],\n [ 157.2, 70.8, 292 ],\n [ 165.6, 95.1, 191.2],\n [ 43.2, 33, 39.2]])" }, { "code": null, "e": 26299, "s": 26233, "text": "Inputs: Array A with m dimensions and array B with n dimensions " }, { "code": null, "e": 26799, "s": 26299, "text": "p = max(m, n)\nif m < p:\n left-pad A's shape with 1s until it also has p dimensions\n\nelse if n < p:\n left-pad B's shape with 1s until it also has p dimensions\nresult_dims = new list with p elements\n\nfor i in p-1 ... 0:\n A_dim_i = A.shape[i]\n B_dim_i = B.shape[i]\n if A_dim_i != 1 and B_dim_i != 1 and A_dim_i != B_dim_i:\n raise ValueError(\"could not broadcast\")\n else:\n # Pick the Array which is having maximum Dimension\n result_dims[i] = max(A_dim_i, B_dim_i) " }, { "code": null, "e": 26873, "s": 26799, "text": "Broadcasting Rules: Broadcasting two arrays together follow these rules: " }, { "code": null, "e": 27511, "s": 26873, "text": "If the arrays don’t have the same rank then prepend the shape of the lower rank array with 1s until both shapes have the same length.The two arrays are compatible in a dimension if they have the same size in the dimension or if one of the arrays has size 1 in that dimension.The arrays can be broadcast together iff they are compatible with all dimensions.After broadcasting, each array behaves as if it had shape equal to the element-wise maximum of shapes of the two input arrays.In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension." }, { "code": null, "e": 27645, "s": 27511, "text": "If the arrays don’t have the same rank then prepend the shape of the lower rank array with 1s until both shapes have the same length." }, { "code": null, "e": 27788, "s": 27645, "text": "The two arrays are compatible in a dimension if they have the same size in the dimension or if one of the arrays has size 1 in that dimension." }, { "code": null, "e": 27870, "s": 27788, "text": "The arrays can be broadcast together iff they are compatible with all dimensions." }, { "code": null, "e": 27997, "s": 27870, "text": "After broadcasting, each array behaves as if it had shape equal to the element-wise maximum of shapes of the two input arrays." }, { "code": null, "e": 28153, "s": 27997, "text": "In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension." }, { "code": null, "e": 28192, "s": 28153, "text": " Example #1: Single Dimension array " }, { "code": null, "e": 28200, "s": 28192, "text": "Python3" }, { "code": "import numpy as npa = np.array([17, 11, 19]) # 1x3 Dimension arrayprint(a)b = 3 print(b) # Broadcasting happened because of# miss match in array Dimension.c = a + bprint(c)", "e": 28373, "s": 28200, "text": null }, { "code": null, "e": 28383, "s": 28373, "text": "Output: " }, { "code": null, "e": 28407, "s": 28383, "text": "[17 11 19]\n3\n[20 14 22]" }, { "code": null, "e": 28442, "s": 28407, "text": "Example 2: Two Dimensional Array " }, { "code": null, "e": 28450, "s": 28442, "text": "Python3" }, { "code": "import numpy as npA = np.array([[11, 22, 33], [10, 20, 30]])print(A) b = 4print(b) C = A + bprint(C)", "e": 28551, "s": 28450, "text": null }, { "code": null, "e": 28561, "s": 28551, "text": "Output: " }, { "code": null, "e": 28614, "s": 28561, "text": "[[11 22 33]\n [10 20 30]]\n 4\n[[15 26 37]\n [14 24 34]]" }, { "code": null, "e": 28627, "s": 28614, "text": "Example 3: " }, { "code": null, "e": 28635, "s": 28627, "text": "Python3" }, { "code": "import numpy as np v = np.array([12, 24, 36]) w = np.array([45, 55]) # To compute an outer product we first# reshape v to a column vector of shape 3x1# then broadcast it against w to yield an output# of shape 3x2 which is the outer product of v and wprint(np.reshape(v, (3, 1)) * w) X = np.array([[12, 22, 33], [45, 55, 66]]) # x has shape 2x3 and v has shape (3, )# so they broadcast to 2x3,print(X + v) # Add a vector to each column of a matrix X has# shape 2x3 and w has shape (2, ) If we transpose X# then it has shape 3x2 and can be broadcast against w# to yield a result of shape 3x2. # Transposing this yields the final result# of shape 2x3 which is the matrix.print((x.T + w).T) # Another solution is to reshape w to be a column# vector of shape 2X1 we can then broadcast it# directly against X to produce the same output.print(x + np.reshape(w, (2, 1))) # Multiply a matrix by a constant, X has shape 2x3.# Numpy treats scalars as arrays of shape();# these can be broadcast together to shape 2x3.print(x * 2)", "e": 29659, "s": 28635, "text": null }, { "code": null, "e": 29669, "s": 29659, "text": "Output: " }, { "code": null, "e": 29795, "s": 29669, "text": "[[ 4 5]\n [ 8 10]\n [12 15]]\n\n[[2 4 6]\n [5 7 9]]\n\n[[ 5 6 7]\n [ 9 10 11]]\n\n[[ 5 6 7]\n [ 9 10 11]]\n\n[[ 2 4 6]\n [ 8 10 12]]" }, { "code": null, "e": 29979, "s": 29795, "text": "Plotting a two-dimensional function –Broadcasting is also frequently used in displaying images based on two-dimensional functions. If we want to define a function z=f(x, y).Example: " }, { "code": null, "e": 29987, "s": 29979, "text": "Python3" }, { "code": "import numpy as npimport matplotlib.pyplot as plt # Computes x and y coordinates for# points on sine and cosine curvesx = np.arange(0, 3 * np.pi, 0.1)y_sin = np.sin(x)y_cos = np.cos(x) # Plot the points using matplotlibplt.plot(x, y_sin)plt.plot(x, y_cos)plt.xlabel('x axis label')plt.ylabel('y axis label')plt.title('Sine and Cosine')plt.legend(['Sine', 'Cosine']) plt.show()", "e": 30364, "s": 29987, "text": null }, { "code": null, "e": 30374, "s": 30364, "text": "Output: " }, { "code": null, "e": 30391, "s": 30376, "text": "adnanirshad158" }, { "code": null, "e": 30422, "s": 30391, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 30435, "s": 30422, "text": "Python-numpy" }, { "code": null, "e": 30442, "s": 30435, "text": "Python" }, { "code": null, "e": 30540, "s": 30442, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30549, "s": 30540, "text": "Comments" }, { "code": null, "e": 30562, "s": 30549, "text": "Old Comments" }, { "code": null, "e": 30580, "s": 30562, "text": "Python Dictionary" }, { "code": null, "e": 30615, "s": 30580, "text": "Read a file line by line in Python" }, { "code": null, "e": 30637, "s": 30615, "text": "Enumerate() in Python" }, { "code": null, "e": 30669, "s": 30637, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30699, "s": 30669, "text": "Iterate over a list in Python" }, { "code": null, "e": 30741, "s": 30699, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30784, "s": 30741, "text": "Python program to convert a list to string" }, { "code": null, "e": 30810, "s": 30784, "text": "Python String | replace()" }, { "code": null, "e": 30854, "s": 30810, "text": "Reading and Writing to text files in Python" } ]
BPDR: A New Dimensionality Reduction Technique | by Jamie Weiss | Towards Data Science
Dimensionality reduction algorithms such as LDA, PCA, or t-SNE are great tools to analyze unlabeled (or labeled) data and gain more information about its structure and patterns. Dimensionality Reduction gives us the ability to visualize high-dimension datasets which can be extremely helpful for model selection. I believe that this subset of Machine Learning — call it data exploration — is wildly underdeveloped compared to its counterparts (like supervised learning or deep learning). My view: If someone is starting a new machine learning project, the first thing they do will be an exploratory analysis of the data. Different researchers have their own ideas about how in-depth this step should be, however, the results of the data exploration is knowledge gained about the dataset at hand. This knowledge proves to be extremely valuable down the road when the researcher runs into various problems like model selection and hyper-parameter tuning. By starting at the root and developing beautiful data exploration algorithms that will give the user quality information about the underlying patterns of a dataset, we can thus develop better machine learning pipelines as a whole. The idea behind BPDR was inspired by an image compressor that I wrote for a class in college. The idea is bit-packing: encoding various data points into one — long — binary string. I will spare many of the nitty-gritty details on how the algorithm is constructed. For those interested in the ‘behind the scenes’ of this algorithm, the code can be viewed on my GitHub here. A general overview of the algorithm is the following: The original data columns (which all must be numerical) are first ranked by importance. The data is then normalized to be centered around 0. Next, there are N, 128-bit strings constructed to represent the n_components we are trying to reduce to. The normalized data is binary packed into the 128-bit strings in the order of their feature importance. Finally, we are left with packed binary numbers that can be converted back to integers. For a 4 column dataset that will be reduced to 2 columns, the binary packing looks like this: binary string 1 -> 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 (128-bits) | most important |2nd important col| -----------------------------------binary string 2 -> 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 (128-bits) |3rd important col|4th important col| ------------------------------------> repeat this packing for each row Once again, this section is made as a general overview on how the algorithm works, however, it is not very in depth. I structured the BPDR module such that it mimics how other dimensionality algorithms work in the Scikit-Learn package. Here is an example of its use on the iris dataset. First, the BPDR repository needs to be cloned from GitHub. After navigating to the BPDR directory, run pip install -r requirements.txt to obtain the proper packages to run the algorithm. Now we are finally ready to open a new file and begin exploring data. First, we must import the required packages into our module: We will be obviously using BPDR, as well as the all-to-popular iris dataset, and matplotlib for some visualization: from bitpack import BPDRfrom sklearn import datasetsimport matplotlib.pyplot as plt Next, we load our dataset: iris = datasets.load_iris()iris_data = iris.datairis_targets = iris.target>>> iris_data[0][5.1 3.5 1.4 0.2] We see that there are 4 columns (all numerical). Let us reduce this dataset to 2 columns so that we can graph and visualize the reduced components. We first need to create an instance of the reduction object and initialize its parameters. bpdr = BPDR(n_components=2) Next, by calling the fit_transform function, the data passed in, will then be reduced and returned in a new array: bpdr_data = bpdr.fit_transform(iris_data, iris_targets)>>> bpdr_data[0][7.686143364045647e+17, 4.0992764608243425e+18] Since we passed in labels, we can look at some variance metrics that evaluate how well the reduced data explains the original data: >>> print(bpdr.variances)[3.476833771196913e+36, 4.83034889579370e+36, 9.75667133492751e+36]>>> print(bpdr.scaled_variances)[0.5774239158754918, 0.8022123454852088, 1.6203637386392993]>>> print(bpdr.mean_variance)6.021284667306044e+36 For more information on how these variances are calculated please visit the documentation for the repository. Finally, we now have a dataset that is 2 columns wide which can be graphed and visualized. When component 1 is graphed on the X-axis and component 2 is graphed on the Y-axis, the graph looks like this: The different colors in the graph represent the different labels of the flowers. It is evident that there are distinct clusters for each label group. This structure indicates that the algorithm did a good job representing the full data in a lower dimension. As a comparison, we look at the same graph but with principle component analysis: The BPDR reduction actually creates a dataset that is more linearly separable than PCA. This does not mean BPDR is a better algorithm for all data, it simply means that it is worth investigating, especially when performing linear regression type models. All the code for this article is available in a Jupyter Notebook in the GitHub repository.
[ { "code": null, "e": 660, "s": 172, "text": "Dimensionality reduction algorithms such as LDA, PCA, or t-SNE are great tools to analyze unlabeled (or labeled) data and gain more information about its structure and patterns. Dimensionality Reduction gives us the ability to visualize high-dimension datasets which can be extremely helpful for model selection. I believe that this subset of Machine Learning — call it data exploration — is wildly underdeveloped compared to its counterparts (like supervised learning or deep learning)." }, { "code": null, "e": 1125, "s": 660, "text": "My view: If someone is starting a new machine learning project, the first thing they do will be an exploratory analysis of the data. Different researchers have their own ideas about how in-depth this step should be, however, the results of the data exploration is knowledge gained about the dataset at hand. This knowledge proves to be extremely valuable down the road when the researcher runs into various problems like model selection and hyper-parameter tuning." }, { "code": null, "e": 1356, "s": 1125, "text": "By starting at the root and developing beautiful data exploration algorithms that will give the user quality information about the underlying patterns of a dataset, we can thus develop better machine learning pipelines as a whole." }, { "code": null, "e": 1537, "s": 1356, "text": "The idea behind BPDR was inspired by an image compressor that I wrote for a class in college. The idea is bit-packing: encoding various data points into one — long — binary string." }, { "code": null, "e": 1729, "s": 1537, "text": "I will spare many of the nitty-gritty details on how the algorithm is constructed. For those interested in the ‘behind the scenes’ of this algorithm, the code can be viewed on my GitHub here." }, { "code": null, "e": 2221, "s": 1729, "text": "A general overview of the algorithm is the following: The original data columns (which all must be numerical) are first ranked by importance. The data is then normalized to be centered around 0. Next, there are N, 128-bit strings constructed to represent the n_components we are trying to reduce to. The normalized data is binary packed into the 128-bit strings in the order of their feature importance. Finally, we are left with packed binary numbers that can be converted back to integers." }, { "code": null, "e": 2315, "s": 2221, "text": "For a 4 column dataset that will be reduced to 2 columns, the binary packing looks like this:" }, { "code": null, "e": 2701, "s": 2315, "text": "binary string 1 -> 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 (128-bits) | most important |2nd important col| -----------------------------------binary string 2 -> 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 (128-bits) |3rd important col|4th important col| ------------------------------------> repeat this packing for each row" }, { "code": null, "e": 2818, "s": 2701, "text": "Once again, this section is made as a general overview on how the algorithm works, however, it is not very in depth." }, { "code": null, "e": 2988, "s": 2818, "text": "I structured the BPDR module such that it mimics how other dimensionality algorithms work in the Scikit-Learn package. Here is an example of its use on the iris dataset." }, { "code": null, "e": 3245, "s": 2988, "text": "First, the BPDR repository needs to be cloned from GitHub. After navigating to the BPDR directory, run pip install -r requirements.txt to obtain the proper packages to run the algorithm. Now we are finally ready to open a new file and begin exploring data." }, { "code": null, "e": 3422, "s": 3245, "text": "First, we must import the required packages into our module: We will be obviously using BPDR, as well as the all-to-popular iris dataset, and matplotlib for some visualization:" }, { "code": null, "e": 3506, "s": 3422, "text": "from bitpack import BPDRfrom sklearn import datasetsimport matplotlib.pyplot as plt" }, { "code": null, "e": 3533, "s": 3506, "text": "Next, we load our dataset:" }, { "code": null, "e": 3641, "s": 3533, "text": "iris = datasets.load_iris()iris_data = iris.datairis_targets = iris.target>>> iris_data[0][5.1 3.5 1.4 0.2]" }, { "code": null, "e": 3880, "s": 3641, "text": "We see that there are 4 columns (all numerical). Let us reduce this dataset to 2 columns so that we can graph and visualize the reduced components. We first need to create an instance of the reduction object and initialize its parameters." }, { "code": null, "e": 3908, "s": 3880, "text": "bpdr = BPDR(n_components=2)" }, { "code": null, "e": 4023, "s": 3908, "text": "Next, by calling the fit_transform function, the data passed in, will then be reduced and returned in a new array:" }, { "code": null, "e": 4142, "s": 4023, "text": "bpdr_data = bpdr.fit_transform(iris_data, iris_targets)>>> bpdr_data[0][7.686143364045647e+17, 4.0992764608243425e+18]" }, { "code": null, "e": 4274, "s": 4142, "text": "Since we passed in labels, we can look at some variance metrics that evaluate how well the reduced data explains the original data:" }, { "code": null, "e": 4509, "s": 4274, "text": ">>> print(bpdr.variances)[3.476833771196913e+36, 4.83034889579370e+36, 9.75667133492751e+36]>>> print(bpdr.scaled_variances)[0.5774239158754918, 0.8022123454852088, 1.6203637386392993]>>> print(bpdr.mean_variance)6.021284667306044e+36" }, { "code": null, "e": 4619, "s": 4509, "text": "For more information on how these variances are calculated please visit the documentation for the repository." }, { "code": null, "e": 4821, "s": 4619, "text": "Finally, we now have a dataset that is 2 columns wide which can be graphed and visualized. When component 1 is graphed on the X-axis and component 2 is graphed on the Y-axis, the graph looks like this:" }, { "code": null, "e": 5161, "s": 4821, "text": "The different colors in the graph represent the different labels of the flowers. It is evident that there are distinct clusters for each label group. This structure indicates that the algorithm did a good job representing the full data in a lower dimension. As a comparison, we look at the same graph but with principle component analysis:" }, { "code": null, "e": 5415, "s": 5161, "text": "The BPDR reduction actually creates a dataset that is more linearly separable than PCA. This does not mean BPDR is a better algorithm for all data, it simply means that it is worth investigating, especially when performing linear regression type models." } ]
15 Numpy Functionalities That Every Data Scientist Must Know | by Bharath K | Towards Data Science
A large portion of machine learning is working with mathematical operations. Since math is an integral part of most data science projects, it becomes essential for beginner data scientists to dwell more deeply into the following subject. A great utility that is offered by one of the best programming languages for data science, in Python, is the numpy library. Numerical Python (NumPy) is a quintessential portion of most machine learning and Data Science projects. These numpy arrays find their utility in applications of computer vision for the processing of images and computing them in terms of arrays. They also find tremendous usage for natural language processing tasks during the vectorization of arrays to make them compatible for training ML or DL models. With the help of NumPy arrays, you can achieve the accomplishment of most mathematical calculations with relative ease. It is the best library for most tasks related to linear algebra and computing other similar operations. However, there is also another library that you must check out for simplification of integration and differentiation with a Python library. Check out how to use sympy from the following link provided below for simplifying integral and differential calculus. towardsdatascience.com This article constitutes a beginner’s guide to fifteen must-know numpy functionalities that will be extremely beneficial for a variety of operations. We will try to cover most of the essential ones, but there is so much more to explore. So, let us get started with all the basic functions to learn as a data science enthusiast. x = [1, 2, 3, 4, 5]y = np.array(x)y The first essential step that every data scientist who plans to master numpy must know is how they can create one. When you can create an array, you can manipulate them to perform numerous operations. To create an array, you can perform the following computation in multiple ways. One of the ways is to use the list data structure in Python to store numeric values and then proceed to interpret them in the form of arrays with numpy. An array can also be defined by declaring the numpy array by using the np.array() or np.asarray() functions followed by square brackets for creating single or multi-dimensional arrays. Once you create these arrays, a variety of operations and manipulations can be performed on them. In the next few sections, let us see what actions are usually performed on arrays. a = np.array([[1, 2, 3], [2, 3, 4]])print(a.shape) An essential concept of arrays is the various shapes in which they exist. The shape of a numpy array determines the different types of calculations and manipulations that you can perform on them. The shape of a numpy array can be interpreted as soon as the particular array is created. The .shape attribute of an array will return a tuple of its particular shape. The important topic that one must understand in numpy arrays is the concept of N-dimensional (or nd array). These arrays are those which have more than one dimension (not a row or column dimension) containing items of the same size and type. N-dimensional arrays are most commonly used for performing a variety of mathematical operations. a = np.array([[1, 2, 3], [2, 3, 4]])print("The middle elements are:", a[0][1], "and", a[1][1]) Similar to the indexing of lists, we also have a method of indexing arrays to perform and manipulate a particular element (or elements) in a specific location in the numpy array. With array indexing, we can access any required element with the knowledge of its position. In the above example, we are trying to receive the values of the middle elements from the particular array of the shape (2, 3). The first element in an array starts with the initial index of zero. The particular row number and the column number are specified within the square brackets, which will allow the users to compute the indexing of an array and receive the particular position of the elements. a = np.array([[1, 2, 3], [2, 3, 4]])print(a[1:2]) Another cool operation that we can perform on numpy arrays similar to lists is the concept of slicing. In this technique, we try to obtain only the required elements from the particular numpy array. For the example code block shown above, we are trying to only get all the elements from the second row by slicing off the first row accordingly. I would recommend exploring more such operations on slicing the numpy arrays on your own. Try out numerous slicing operations to observe different results. It is also recommended that you check out one of my previous articles on mastering lists in Python from the below link, as it will help you to gauge a better intuition on indexing and slicing. towardsdatascience.com a = np.array([1, 2, 3])b = np.array([[2],[1], [0]])print(np.matmul(a, b)) With numpy arrays, it is possible to compute the multiplication of matrices with great simplicity. In the above example, we notice that the particular arrays, which are in the shape of 1 X 3 and 3 X 1, are multiplied to receive an output result of a 1 X 1 matrix. Multiple such calculations are possible with numpy arrays. a = np.array([1, 2, 3])b = np.array([[2],[1], [0]])print(np.dot(a, b)) Another significant computation that is possible with numpy arrays is finding the dot products of two variables. The dot product is essentially the sum of all the multiples of two specific arrays. The concept of dot products is used everywhere in machine learning. An example is for the use cases of weights calculation or computing the cost function. According to the following reference, matmul differs from dot in two important ways. Multiplication by scalars is not allowed. Stacks of matrices are broadcast together as if the matrices were elements. a = np.array([1, 2, 3])print(np.sum(a)) Computing the sum of the numerous elements in a numpy array is quite a useful task that can be accomplished with the help of the sum function offered in this library. If you were to perform a similar action with the help of a list, you would probably use a for loop to iterate over all the elements in the list and add them accordingly. This method would increase the overall complexity, and hence, it is preferable to use numpy arrays for such mathematical computations. As a bonus, I would like to mention another method of performing this computation with the help of lists while preserving the time and space complexity. This action is performed with the help of the anonymous functions available in Python. You can make use of the functools library to import the reduce function. Once imported, you can make use of this advanced function to compute the entire calculation in a single line. from functools import reducea = [1, 2, 3]sum = reduce(lambda x, y: x+y, a)print(sum) If you want to learn more about the topic of understanding advanced functions with multiple codes and examples, feel free to check out the article below. It covers the specific concepts in further detail. towardsdatascience.com a = np.array([1, 2, 3])print(np.mean(a)) Numpy also allows the developers to compute the mean of a particular array with relative ease. The mean or average is commutated by adding all the elements and dividing the sum by the total number of elements present in the specified array. The calculation of the mean is significant in several machine learning algorithms such as linear regression for computing the mean squared error. x = 5print(np.exp(x)) A significant operation that is performed in machine learning is the operation of exponentiation. The Euler’s number ‘e,’ whose value is approximated at 2.718, holds great significance in base logarithmic computations. Hence, this function is sometimes used for performing mathematical operations. Another similar function to consider is the pi operation available in numpy. An extremely popular use case of a scenario where the exponentiation operation is used is for defining a sigmoid function. The above image is a representation of the following. To learn more about such activation functions, I would recommend checking out one of my previous articles on a popular activation called rectified linear unit from the below link. towardsdatascience.com a = np.array([[1, 2, 3], [2, 3, 4]])a = np.ndarray.flatten(a)print(a.shape) Whenever we are working with multi-dimensional, we might need to flatten them for specific tasks. The flatten function in numpy will help you to reduce the n-dimensional array into a single entity. The other similar functions that data scientists must explore are the expanding dimensions or squeezing dimensions functions available in numpy. a = np.arange(5, 15, 2)a The arange function is used to create arrays that are usually evenly spaced with specified intervals. You can describe the starting point, stopping point, and the number of steps, respectively, to generate any numpy array of the desired shape. To create a multi-dimensional array of a desired shape with the numpy.arange() function, make sure to use the reshape function. a = np.array([3, 1, 2, 5, 4])np.sort(a) When we have an array with shuffled values, and we want to receive them all arranged in ascending order, that is, in increasing numerical order, the sort function is quite useful. While a similar action can be performed with lists as well, it is worth noting that such actions are possible in numpy arrays. When performing various operations, you might encounter numerous instances where you are appending more elements to a particular numpy array, but once you finish getting a list of values, you might want them all sorted together to identify the values accordingly. In such use cases, the sort() function comes in quite handy. np.random.rand(2, 2) The numpy library also allows the users to randomly generate and create arrays with randomized values. This functionality is similar to the random library in Python. However, the numpy version of random.rand() function, you can generate n-dimensional arrays for performing numerous calculations and computations. One of the critical operations where random numpy operations are usually used in machine learning and deep learning is when we want to initialize a bunch of weights or biases with random values. Usually, the best approach is to initialize certain values with a random value rather than zero. For understanding the concepts of randomness with an example of proportional sampling, it is recommended that you check out the following article provided below. towardsdatascience.com a = np.array([1, 2, -3, 4, 5])print(np.min(a))print(np.max(a))print(np.abs(a)) Looking at some other basic operations that we can perform with numpy arrays are to find out the minimum, maximum, and absolute values of a particular numpy array. The np.min() and np.max() functions are quite self-explanatory as these operations are used to compute the minimum and maximum values in the given numpy array, respectively. While the other two functions return a single value, which is either a single minimum or maximum value, the absolute function will return back an array. However, all the base values are returned without the consideration of the negative sign. The other similar functions which I would recommend the users to experiment with are operations on the ceiling, flooring, and other such operations. print(np.sin(np.pi/3.))print(np.cos(np.pi/3.)) Apart from all the exceptional tasks that you achieve with numpy arrays, you can also perform trigonometric operations with this library. In the above example, we have performed a couple of simple trigonometric operations on sine and cosine for sixty degrees to achieve their respective results. Feel free to explore other similar trigonometric functions. Without mathematics, there’s nothing you can do. Everything around you is mathematics. Everything around you is numbers. — Shakuntala Devi Numpy is one of the best libraries that is available in Python for a wide range of tasks. While machines are not the best with textual or visual information, when these are converted into mathematical arrays with the help of numpy, the computation of many critical tasks becomes possible. Apart from improved compatibility, it also becomes easier to achieve certain tasks. Hence, numpy is one of the best libraries that data scientists must seek to master. In this article, we understood fifteen of the most essential numpy functionalities that every data scientist must know about. While some of the functions we discussed were the numerous activities that could be performed on numpy arrays like shaping, indexing, and slicing, others were various computations that we could perform on numpy arrays. Some of these include the sum(), mean(), arange(), and other similar operations. There is tons more stuff you can try out with these numpy arrays. Make sure to explore and dig deep into the following subject. If you have any queries related to the various points stated in this article, then feel free to let me know in the comments below. I will try to get back to you with a response as soon as possible. Check out some of my other articles that you might enjoy reading! towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com Thank you all for sticking on till the end. I hope all of you enjoyed reading the article. Wish you all a wonderful day!
[ { "code": null, "e": 534, "s": 172, "text": "A large portion of machine learning is working with mathematical operations. Since math is an integral part of most data science projects, it becomes essential for beginner data scientists to dwell more deeply into the following subject. A great utility that is offered by one of the best programming languages for data science, in Python, is the numpy library." }, { "code": null, "e": 939, "s": 534, "text": "Numerical Python (NumPy) is a quintessential portion of most machine learning and Data Science projects. These numpy arrays find their utility in applications of computer vision for the processing of images and computing them in terms of arrays. They also find tremendous usage for natural language processing tasks during the vectorization of arrays to make them compatible for training ML or DL models." }, { "code": null, "e": 1421, "s": 939, "text": "With the help of NumPy arrays, you can achieve the accomplishment of most mathematical calculations with relative ease. It is the best library for most tasks related to linear algebra and computing other similar operations. However, there is also another library that you must check out for simplification of integration and differentiation with a Python library. Check out how to use sympy from the following link provided below for simplifying integral and differential calculus." }, { "code": null, "e": 1444, "s": 1421, "text": "towardsdatascience.com" }, { "code": null, "e": 1772, "s": 1444, "text": "This article constitutes a beginner’s guide to fifteen must-know numpy functionalities that will be extremely beneficial for a variety of operations. We will try to cover most of the essential ones, but there is so much more to explore. So, let us get started with all the basic functions to learn as a data science enthusiast." }, { "code": null, "e": 1808, "s": 1772, "text": "x = [1, 2, 3, 4, 5]y = np.array(x)y" }, { "code": null, "e": 2242, "s": 1808, "text": "The first essential step that every data scientist who plans to master numpy must know is how they can create one. When you can create an array, you can manipulate them to perform numerous operations. To create an array, you can perform the following computation in multiple ways. One of the ways is to use the list data structure in Python to store numeric values and then proceed to interpret them in the form of arrays with numpy." }, { "code": null, "e": 2608, "s": 2242, "text": "An array can also be defined by declaring the numpy array by using the np.array() or np.asarray() functions followed by square brackets for creating single or multi-dimensional arrays. Once you create these arrays, a variety of operations and manipulations can be performed on them. In the next few sections, let us see what actions are usually performed on arrays." }, { "code": null, "e": 2659, "s": 2608, "text": "a = np.array([[1, 2, 3], [2, 3, 4]])print(a.shape)" }, { "code": null, "e": 3023, "s": 2659, "text": "An essential concept of arrays is the various shapes in which they exist. The shape of a numpy array determines the different types of calculations and manipulations that you can perform on them. The shape of a numpy array can be interpreted as soon as the particular array is created. The .shape attribute of an array will return a tuple of its particular shape." }, { "code": null, "e": 3362, "s": 3023, "text": "The important topic that one must understand in numpy arrays is the concept of N-dimensional (or nd array). These arrays are those which have more than one dimension (not a row or column dimension) containing items of the same size and type. N-dimensional arrays are most commonly used for performing a variety of mathematical operations." }, { "code": null, "e": 3457, "s": 3362, "text": "a = np.array([[1, 2, 3], [2, 3, 4]])print(\"The middle elements are:\", a[0][1], \"and\", a[1][1])" }, { "code": null, "e": 3728, "s": 3457, "text": "Similar to the indexing of lists, we also have a method of indexing arrays to perform and manipulate a particular element (or elements) in a specific location in the numpy array. With array indexing, we can access any required element with the knowledge of its position." }, { "code": null, "e": 4131, "s": 3728, "text": "In the above example, we are trying to receive the values of the middle elements from the particular array of the shape (2, 3). The first element in an array starts with the initial index of zero. The particular row number and the column number are specified within the square brackets, which will allow the users to compute the indexing of an array and receive the particular position of the elements." }, { "code": null, "e": 4181, "s": 4131, "text": "a = np.array([[1, 2, 3], [2, 3, 4]])print(a[1:2])" }, { "code": null, "e": 4525, "s": 4181, "text": "Another cool operation that we can perform on numpy arrays similar to lists is the concept of slicing. In this technique, we try to obtain only the required elements from the particular numpy array. For the example code block shown above, we are trying to only get all the elements from the second row by slicing off the first row accordingly." }, { "code": null, "e": 4874, "s": 4525, "text": "I would recommend exploring more such operations on slicing the numpy arrays on your own. Try out numerous slicing operations to observe different results. It is also recommended that you check out one of my previous articles on mastering lists in Python from the below link, as it will help you to gauge a better intuition on indexing and slicing." }, { "code": null, "e": 4897, "s": 4874, "text": "towardsdatascience.com" }, { "code": null, "e": 4971, "s": 4897, "text": "a = np.array([1, 2, 3])b = np.array([[2],[1], [0]])print(np.matmul(a, b))" }, { "code": null, "e": 5294, "s": 4971, "text": "With numpy arrays, it is possible to compute the multiplication of matrices with great simplicity. In the above example, we notice that the particular arrays, which are in the shape of 1 X 3 and 3 X 1, are multiplied to receive an output result of a 1 X 1 matrix. Multiple such calculations are possible with numpy arrays." }, { "code": null, "e": 5365, "s": 5294, "text": "a = np.array([1, 2, 3])b = np.array([[2],[1], [0]])print(np.dot(a, b))" }, { "code": null, "e": 5717, "s": 5365, "text": "Another significant computation that is possible with numpy arrays is finding the dot products of two variables. The dot product is essentially the sum of all the multiples of two specific arrays. The concept of dot products is used everywhere in machine learning. An example is for the use cases of weights calculation or computing the cost function." }, { "code": null, "e": 5802, "s": 5717, "text": "According to the following reference, matmul differs from dot in two important ways." }, { "code": null, "e": 5844, "s": 5802, "text": "Multiplication by scalars is not allowed." }, { "code": null, "e": 5920, "s": 5844, "text": "Stacks of matrices are broadcast together as if the matrices were elements." }, { "code": null, "e": 5960, "s": 5920, "text": "a = np.array([1, 2, 3])print(np.sum(a))" }, { "code": null, "e": 6432, "s": 5960, "text": "Computing the sum of the numerous elements in a numpy array is quite a useful task that can be accomplished with the help of the sum function offered in this library. If you were to perform a similar action with the help of a list, you would probably use a for loop to iterate over all the elements in the list and add them accordingly. This method would increase the overall complexity, and hence, it is preferable to use numpy arrays for such mathematical computations." }, { "code": null, "e": 6855, "s": 6432, "text": "As a bonus, I would like to mention another method of performing this computation with the help of lists while preserving the time and space complexity. This action is performed with the help of the anonymous functions available in Python. You can make use of the functools library to import the reduce function. Once imported, you can make use of this advanced function to compute the entire calculation in a single line." }, { "code": null, "e": 6940, "s": 6855, "text": "from functools import reducea = [1, 2, 3]sum = reduce(lambda x, y: x+y, a)print(sum)" }, { "code": null, "e": 7145, "s": 6940, "text": "If you want to learn more about the topic of understanding advanced functions with multiple codes and examples, feel free to check out the article below. It covers the specific concepts in further detail." }, { "code": null, "e": 7168, "s": 7145, "text": "towardsdatascience.com" }, { "code": null, "e": 7209, "s": 7168, "text": "a = np.array([1, 2, 3])print(np.mean(a))" }, { "code": null, "e": 7596, "s": 7209, "text": "Numpy also allows the developers to compute the mean of a particular array with relative ease. The mean or average is commutated by adding all the elements and dividing the sum by the total number of elements present in the specified array. The calculation of the mean is significant in several machine learning algorithms such as linear regression for computing the mean squared error." }, { "code": null, "e": 7618, "s": 7596, "text": "x = 5print(np.exp(x))" }, { "code": null, "e": 7993, "s": 7618, "text": "A significant operation that is performed in machine learning is the operation of exponentiation. The Euler’s number ‘e,’ whose value is approximated at 2.718, holds great significance in base logarithmic computations. Hence, this function is sometimes used for performing mathematical operations. Another similar function to consider is the pi operation available in numpy." }, { "code": null, "e": 8350, "s": 7993, "text": "An extremely popular use case of a scenario where the exponentiation operation is used is for defining a sigmoid function. The above image is a representation of the following. To learn more about such activation functions, I would recommend checking out one of my previous articles on a popular activation called rectified linear unit from the below link." }, { "code": null, "e": 8373, "s": 8350, "text": "towardsdatascience.com" }, { "code": null, "e": 8449, "s": 8373, "text": "a = np.array([[1, 2, 3], [2, 3, 4]])a = np.ndarray.flatten(a)print(a.shape)" }, { "code": null, "e": 8792, "s": 8449, "text": "Whenever we are working with multi-dimensional, we might need to flatten them for specific tasks. The flatten function in numpy will help you to reduce the n-dimensional array into a single entity. The other similar functions that data scientists must explore are the expanding dimensions or squeezing dimensions functions available in numpy." }, { "code": null, "e": 8817, "s": 8792, "text": "a = np.arange(5, 15, 2)a" }, { "code": null, "e": 9189, "s": 8817, "text": "The arange function is used to create arrays that are usually evenly spaced with specified intervals. You can describe the starting point, stopping point, and the number of steps, respectively, to generate any numpy array of the desired shape. To create a multi-dimensional array of a desired shape with the numpy.arange() function, make sure to use the reshape function." }, { "code": null, "e": 9229, "s": 9189, "text": "a = np.array([3, 1, 2, 5, 4])np.sort(a)" }, { "code": null, "e": 9536, "s": 9229, "text": "When we have an array with shuffled values, and we want to receive them all arranged in ascending order, that is, in increasing numerical order, the sort function is quite useful. While a similar action can be performed with lists as well, it is worth noting that such actions are possible in numpy arrays." }, { "code": null, "e": 9861, "s": 9536, "text": "When performing various operations, you might encounter numerous instances where you are appending more elements to a particular numpy array, but once you finish getting a list of values, you might want them all sorted together to identify the values accordingly. In such use cases, the sort() function comes in quite handy." }, { "code": null, "e": 9882, "s": 9861, "text": "np.random.rand(2, 2)" }, { "code": null, "e": 10195, "s": 9882, "text": "The numpy library also allows the users to randomly generate and create arrays with randomized values. This functionality is similar to the random library in Python. However, the numpy version of random.rand() function, you can generate n-dimensional arrays for performing numerous calculations and computations." }, { "code": null, "e": 10649, "s": 10195, "text": "One of the critical operations where random numpy operations are usually used in machine learning and deep learning is when we want to initialize a bunch of weights or biases with random values. Usually, the best approach is to initialize certain values with a random value rather than zero. For understanding the concepts of randomness with an example of proportional sampling, it is recommended that you check out the following article provided below." }, { "code": null, "e": 10672, "s": 10649, "text": "towardsdatascience.com" }, { "code": null, "e": 10751, "s": 10672, "text": "a = np.array([1, 2, -3, 4, 5])print(np.min(a))print(np.max(a))print(np.abs(a))" }, { "code": null, "e": 11089, "s": 10751, "text": "Looking at some other basic operations that we can perform with numpy arrays are to find out the minimum, maximum, and absolute values of a particular numpy array. The np.min() and np.max() functions are quite self-explanatory as these operations are used to compute the minimum and maximum values in the given numpy array, respectively." }, { "code": null, "e": 11481, "s": 11089, "text": "While the other two functions return a single value, which is either a single minimum or maximum value, the absolute function will return back an array. However, all the base values are returned without the consideration of the negative sign. The other similar functions which I would recommend the users to experiment with are operations on the ceiling, flooring, and other such operations." }, { "code": null, "e": 11528, "s": 11481, "text": "print(np.sin(np.pi/3.))print(np.cos(np.pi/3.))" }, { "code": null, "e": 11884, "s": 11528, "text": "Apart from all the exceptional tasks that you achieve with numpy arrays, you can also perform trigonometric operations with this library. In the above example, we have performed a couple of simple trigonometric operations on sine and cosine for sixty degrees to achieve their respective results. Feel free to explore other similar trigonometric functions." }, { "code": null, "e": 12023, "s": 11884, "text": "Without mathematics, there’s nothing you can do. Everything around you is mathematics. Everything around you is numbers. — Shakuntala Devi" }, { "code": null, "e": 12480, "s": 12023, "text": "Numpy is one of the best libraries that is available in Python for a wide range of tasks. While machines are not the best with textual or visual information, when these are converted into mathematical arrays with the help of numpy, the computation of many critical tasks becomes possible. Apart from improved compatibility, it also becomes easier to achieve certain tasks. Hence, numpy is one of the best libraries that data scientists must seek to master." }, { "code": null, "e": 12906, "s": 12480, "text": "In this article, we understood fifteen of the most essential numpy functionalities that every data scientist must know about. While some of the functions we discussed were the numerous activities that could be performed on numpy arrays like shaping, indexing, and slicing, others were various computations that we could perform on numpy arrays. Some of these include the sum(), mean(), arange(), and other similar operations." }, { "code": null, "e": 13232, "s": 12906, "text": "There is tons more stuff you can try out with these numpy arrays. Make sure to explore and dig deep into the following subject. If you have any queries related to the various points stated in this article, then feel free to let me know in the comments below. I will try to get back to you with a response as soon as possible." }, { "code": null, "e": 13298, "s": 13232, "text": "Check out some of my other articles that you might enjoy reading!" }, { "code": null, "e": 13321, "s": 13298, "text": "towardsdatascience.com" }, { "code": null, "e": 13344, "s": 13321, "text": "towardsdatascience.com" }, { "code": null, "e": 13367, "s": 13344, "text": "towardsdatascience.com" }, { "code": null, "e": 13390, "s": 13367, "text": "towardsdatascience.com" }, { "code": null, "e": 13413, "s": 13390, "text": "towardsdatascience.com" } ]
Type.GetMember() Method in C#
The Type.GetMember() method in C# is used to get the specified members of the current Type. Following is the syntax − public System.Reflection.MemberInfo[] GetMember (string name); public virtual System.Reflection.MemberInfo[] GetMember (string name, System.Reflection.BindingFlags bindingAttr); Let us now see an example to implement the Type.GetMember() method − using System; using System.Reflection; public class Demo { public static void Main(){ Type type = typeof(Subject); try { FieldInfo fieldInfo = type.GetField("SubName"); MemberInfo[] info = type.GetMember("SubName"); Console.Write("Members = "); for (int i = 0; i < info.Length; i++) Console.WriteLine(" {0}", info[i]); Console.WriteLine("FieldInfo = {0}", fieldInfo); } catch (ArgumentNullException e){ Console.Write("{0}", e.GetType(), e.Message); } } } public class Subject{ public string SubName = "Science"; } This will produce the following output − Members = System.String SubName FieldInfo = System.String SubName Let us now see another example to implement the Type.GetMember(String, BindingFlags) method − using System; using System.Reflection; public class Demo { public static void Main(){ Type type = typeof(Subject); try { FieldInfo fieldInfo = type.GetField("SubName"); MemberInfo[] info = type.GetMember("SubName", BindingFlags.Public | BindingFlags.Instance); Console.Write("Members = "); for (int i = 0; i < info.Length; i++) Console.WriteLine(" {0}", info[i]); Console.WriteLine("FieldInfo = {0}", fieldInfo); } catch (ArgumentNullException e){ Console.Write("{0}", e.GetType(), e.Message); } } } public class Subject{ public string SubName = "Science"; } This will produce the following output − Members = System.String SubName FieldInfo = System.String SubName
[ { "code": null, "e": 1154, "s": 1062, "text": "The Type.GetMember() method in C# is used to get the specified members of the current Type." }, { "code": null, "e": 1180, "s": 1154, "text": "Following is the syntax −" }, { "code": null, "e": 1358, "s": 1180, "text": "public System.Reflection.MemberInfo[] GetMember (string name);\npublic virtual System.Reflection.MemberInfo[] GetMember (string name, System.Reflection.BindingFlags bindingAttr);" }, { "code": null, "e": 1427, "s": 1358, "text": "Let us now see an example to implement the Type.GetMember() method −" }, { "code": null, "e": 2046, "s": 1427, "text": "using System;\nusing System.Reflection;\npublic class Demo {\n public static void Main(){\n Type type = typeof(Subject);\n try {\n FieldInfo fieldInfo = type.GetField(\"SubName\");\n MemberInfo[] info = type.GetMember(\"SubName\");\n Console.Write(\"Members = \");\n for (int i = 0; i < info.Length; i++)\n Console.WriteLine(\" {0}\", info[i]);\n Console.WriteLine(\"FieldInfo = {0}\", fieldInfo);\n }\n catch (ArgumentNullException e){\n Console.Write(\"{0}\", e.GetType(), e.Message);\n }\n }\n}\npublic class Subject{\n public string SubName = \"Science\";\n}" }, { "code": null, "e": 2087, "s": 2046, "text": "This will produce the following output −" }, { "code": null, "e": 2153, "s": 2087, "text": "Members = System.String SubName\nFieldInfo = System.String SubName" }, { "code": null, "e": 2247, "s": 2153, "text": "Let us now see another example to implement the Type.GetMember(String, BindingFlags) method −" }, { "code": null, "e": 2911, "s": 2247, "text": "using System;\nusing System.Reflection;\npublic class Demo {\n public static void Main(){\n Type type = typeof(Subject);\n try {\n FieldInfo fieldInfo = type.GetField(\"SubName\");\n MemberInfo[] info = type.GetMember(\"SubName\", BindingFlags.Public | BindingFlags.Instance);\n Console.Write(\"Members = \");\n for (int i = 0; i < info.Length; i++)\n Console.WriteLine(\" {0}\", info[i]);\n Console.WriteLine(\"FieldInfo = {0}\", fieldInfo);\n }\n catch (ArgumentNullException e){\n Console.Write(\"{0}\", e.GetType(), e.Message);\n }\n }\n}\npublic class Subject{\n public string SubName = \"Science\";\n}" }, { "code": null, "e": 2952, "s": 2911, "text": "This will produce the following output −" }, { "code": null, "e": 3018, "s": 2952, "text": "Members = System.String SubName\nFieldInfo = System.String SubName" } ]
How to create GUI in C programming using GTK Toolkit - GeeksforGeeks
19 Feb, 2020 Many programming languages bolster GUI improvement as one of the centrepieces of its language highlights. C has no such library connected to it like the string library, IO library, etc, that we every now and again use. This weakness opened the skyline for engineers to pick from a wide assortment of GUI library toolbox accessible in C. GTK+ is one of them. It represents GIMP (GNU Image Manipulation Program) Toolkit and can be utilized to program current GUI interfaces. The beneficial thing about GTK+ is that it is steady, developed, and its starting point can be followed back to the past times of X Windows that structure the centre GUI arrangement of Linux today. GTK is completely written in C and the GTK+ programming that we regularly use in Linux is additionally written in C. The work area administrators, for example, GNOME and XFCE, likewise are manufactured utilizing GTK. A GTK+ application isn’t limited to the Linux stage no one but; it very well may be ported to non-UNIX/Linux stages also. Here, we will cling to the fundamental type of GTK+, which is its C avatar on the Linux stage. The official webpage to download GTK+ is https://www.gtk.org. The site contains API documentation, instructional exercises, and other Gnome libraries that are frequently utilized alongside GTK. Truth be told, GTK is based over libraries, for example, ATK: This library provides help to create accessibility tools such as sticky keys, screen readers, etc. Glib: It is a universally useful utility library that offers help for threads, dynamic loading, event loops, low-level data structures, etc. GObject: This library gives full-featured object-oriented help in C, without utilizing C++. This library encourages the language binding made for different languages to give you simple access to C APIs. GdkPixBuf: This library gives picture control capacities. GDK (GIMP Drawing Toolkit): This is the designs library that gives low-level drawing capacities over Xlib. Pango: This library helps in content and design rendering Xlib: This library provides low-level graphics support for Linux system When composing code with GTK, we regularly locate that a significant number of the primitive data types are prefixed with ‘g‘ as in gint, gchar, gshort, gpointer, etc. These data types guarantee that the code can be recompiled on any platform without rolling out any improvements. These data types are characterized in these libraries to help in making it platform-independent. GUI programming inherent object-oriented in it which is the main issue. In this, a procedural worldview doesn’t fit consummately in this scheme. Thus, regardless of GTK being written in C, it gives object-oriented help through GObject. Note that this item arranged help has nothing to do with C++. C++ has its own GTK library, called gtkmm. GObject encourages a portion of the object-oriented principles, similar to polymorphism and inheritance with the assistance of macros. The following diagram illustrates the hierarchical relation. GtkWindow inherits GtkBin, which itself is a child of GtkContainer; in this manner, an object of GtkWindow can call the function defined in GtkBin or GtkContainer. This is an example of object-oriented implementation in C by GTK. Let us comprehend a couple of things from our first GTK code in C. To start with, we incorporate the header file. This incorporates all the file one needs to make a GUI, including the Glib library.#include <gtk/gtk.h> #include <gtk/gtk.h> Presently, we declare a pointer to GtkWidget, which is only a window for our situation. What’s more, another GtkWidget pointer will be the button. Review that GtkWidget is a top-level storage type for widgets in the hierarchy.GtkWidget *window; GtkWidget *button; GtkWidget *window; GtkWidget *button; Next, we invoke gtk_init function to initialize the GTK+ libraries by passing the command line parameters of the main function.gtk_init(&argc, &argv); gtk_init(&argc, &argv); All GTK+ applications are instated as such; it is an “absolute necessity” statement. It parses the command arguments line and returns back to the application. Accordingly, these parameters might be utilized to alter the run time conduct of the application. Now, we create the window and the button.window = gtk_window_new(GTK_WINDOW_TOPLEVEL); button = gtk_button_new_with_label ("Click Me!"); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); button = gtk_button_new_with_label ("Click Me!"); The window type value GTK_WINDOW_TOPLEVEL implies that the window made will be a standard framed window. Other sort values might be GTK_WINDOW_POPUP, which implies a frameless dialogue window will be made. When we make a window, it must be closable with the goal that the client should at any rate ready to close the application because of the client hitting the upper right close the window. This implies the window must have the option to react to an event (close event). Like all windowing system, GTK+ additionally executes events and event handlers. Since the code that transmits the signal is interior to a specific object, we have to compose an interfacing callback function. The organization of a regular callback function is:void my_callback_function(GtkWidget *widget, gpointer data); void my_callback_function(GtkWidget *widget, gpointer data); The primary parameter represents the widget that produces the signal and the subsequent parameter is a void pointer that might be utilized for any reason. Along these lines, the callback function to deal with the close events of our window will be as per the following:void destroy( GtkWidget *widget, gpointer data ) { gtk_main_quit (); } void destroy( GtkWidget *widget, gpointer data ) { gtk_main_quit (); } The function gtk_main_quit() shuts the application. Presently, we should interface the window object with the callback function.g_signal_connect (window, "destroy", G_CALLBACK (destroy), NULL); g_signal_connect (window, "destroy", G_CALLBACK (destroy), NULL); Likewise, we make the callback function to deal with the button event and associate it with the button widget.void greet( GtkWidget *widget, gpointer data ) { g_print ("Welcome to GTK\n"); g_print ("%s clicked %d times\n", (char*)data, ++counter); } g_signal_connect (GTK_OBJECT(button), "clicked", G_CALLBACK (greet), "button"); void greet( GtkWidget *widget, gpointer data ) { g_print ("Welcome to GTK\n"); g_print ("%s clicked %d times\n", (char*)data, ++counter); } g_signal_connect (GTK_OBJECT(button), "clicked", G_CALLBACK (greet), "button"); Since the button widget is contained inside the window, we should explicitly add it to the container.gtk_container_add (GTK_CONTAINER (window), button); gtk_container_add (GTK_CONTAINER (window), button); Also, at long last, we show the widgets made in memory with the gtk_widget_show_all() function that takes a reference to the window we have made. Finally, the gtk_main() function is summoned to begin the interactive procedure.gtk_widget_show_all(window); gtk_main(); gtk_widget_show_all(window); gtk_main(); This is a key function on the grounds that ordinarily a C program ends in the wake of executing the last statement. Here, it passes the control of the program to GTK+ and stays away for the indefinite future until the gtk_main_quit event is activated by the client tapping the close button for our situation. Below is the implementation of the above steps: #include <gtk/gtk.h> static int counter = 0; void greet(GtkWidget* widget, gpointer data){ // printf equivalent in GTK+ g_print("Welcome to GTK\n"); g_print("%s clicked %d times\n", (char*)data, ++counter);} void destroy(GtkWidget* widget, gpointer data){ gtk_main_quit();} int main(int argc, char* argv[]){ GtkWidget* window; GtkWidget* button; gtk_init(&argc, &argv); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); g_signal_connect(window, "destroy", G_CALLBACK(destroy), NULL); /* Let's set the border width of the window to 20. * You may play with the value and see the * difference. */ gtk_container_set_border_width(GTK_CONTAINER(window), 20); button = gtk_button_new_with_label("Click Me!"); g_signal_connect(GTK_OBJECT(button), "clicked", G_CALLBACK(greet), "button"); gtk_container_add(GTK_CONTAINER(window), button); gtk_widget_show_all(window); gtk_main(); return 0;} For Compiling write the following command (with GCC in Linux)gcc main.c -o p1 `pkg-config --cflags --libs gtk+-2.0` gcc main.c -o p1 `pkg-config --cflags --libs gtk+-2.0` To run it write the following command./p1 ./p1 ConclusionGTK+ has all the GUI segments one needs to make an expert looking interface. The essential thought of GUI occasion driven programming with GTK+ isn’t very different from the one appeared in the model. Include a couple of more parts, utilize various sorts of compartments, play with designs, and obviously always remember to counsel the GTK+ documentation. Proficient developers frequently utilized RAD tools, for example, Glade to plan the GUI interface rapidly. Be that as it may, in the first place, have a go at composing the code without any preparation to get a vibe of what goes where and how it is really done. It will compensate you later. AkhilKG c-graphics Picked C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C Arrow operator -> in C/C++ with Examples 'this' pointer in C++ How to split a string in C/C++, Python and Java? UDP Server-Client implementation in C Smart Pointers in C++ and How to Use Them How to dynamically allocate a 2D array in C? Unordered Sets in C++ Standard Template Library
[ { "code": null, "e": 23817, "s": 23789, "text": "\n19 Feb, 2020" }, { "code": null, "e": 24290, "s": 23817, "text": "Many programming languages bolster GUI improvement as one of the centrepieces of its language highlights. C has no such library connected to it like the string library, IO library, etc, that we every now and again use. This weakness opened the skyline for engineers to pick from a wide assortment of GUI library toolbox accessible in C. GTK+ is one of them. It represents GIMP (GNU Image Manipulation Program) Toolkit and can be utilized to program current GUI interfaces." }, { "code": null, "e": 24705, "s": 24290, "text": "The beneficial thing about GTK+ is that it is steady, developed, and its starting point can be followed back to the past times of X Windows that structure the centre GUI arrangement of Linux today. GTK is completely written in C and the GTK+ programming that we regularly use in Linux is additionally written in C. The work area administrators, for example, GNOME and XFCE, likewise are manufactured utilizing GTK." }, { "code": null, "e": 24827, "s": 24705, "text": "A GTK+ application isn’t limited to the Linux stage no one but; it very well may be ported to non-UNIX/Linux stages also." }, { "code": null, "e": 25173, "s": 24827, "text": "Here, we will cling to the fundamental type of GTK+, which is its C avatar on the Linux stage. The official webpage to download GTK+ is https://www.gtk.org. The site contains API documentation, instructional exercises, and other Gnome libraries that are frequently utilized alongside GTK. Truth be told, GTK is based over libraries, for example," }, { "code": null, "e": 25277, "s": 25173, "text": "ATK: This library provides help to create accessibility tools such as sticky keys, screen readers, etc." }, { "code": null, "e": 25418, "s": 25277, "text": "Glib: It is a universally useful utility library that offers help for threads, dynamic loading, event loops, low-level data structures, etc." }, { "code": null, "e": 25621, "s": 25418, "text": "GObject: This library gives full-featured object-oriented help in C, without utilizing C++. This library encourages the language binding made for different languages to give you simple access to C APIs." }, { "code": null, "e": 25679, "s": 25621, "text": "GdkPixBuf: This library gives picture control capacities." }, { "code": null, "e": 25786, "s": 25679, "text": "GDK (GIMP Drawing Toolkit): This is the designs library that gives low-level drawing capacities over Xlib." }, { "code": null, "e": 25844, "s": 25786, "text": "Pango: This library helps in content and design rendering" }, { "code": null, "e": 25916, "s": 25844, "text": "Xlib: This library provides low-level graphics support for Linux system" }, { "code": null, "e": 26048, "s": 25916, "text": "When composing code with GTK, we regularly locate that a significant number of the primitive data types are prefixed with ‘g‘ as in" }, { "code": null, "e": 26054, "s": 26048, "text": "gint," }, { "code": null, "e": 26061, "s": 26054, "text": "gchar," }, { "code": null, "e": 26069, "s": 26061, "text": "gshort," }, { "code": null, "e": 26079, "s": 26069, "text": "gpointer," }, { "code": null, "e": 26084, "s": 26079, "text": "etc." }, { "code": null, "e": 26294, "s": 26084, "text": "These data types guarantee that the code can be recompiled on any platform without rolling out any improvements. These data types are characterized in these libraries to help in making it platform-independent." }, { "code": null, "e": 26831, "s": 26294, "text": "GUI programming inherent object-oriented in it which is the main issue. In this, a procedural worldview doesn’t fit consummately in this scheme. Thus, regardless of GTK being written in C, it gives object-oriented help through GObject. Note that this item arranged help has nothing to do with C++. C++ has its own GTK library, called gtkmm. GObject encourages a portion of the object-oriented principles, similar to polymorphism and inheritance with the assistance of macros. The following diagram illustrates the hierarchical relation." }, { "code": null, "e": 27061, "s": 26831, "text": "GtkWindow inherits GtkBin, which itself is a child of GtkContainer; in this manner, an object of GtkWindow can call the function defined in GtkBin or GtkContainer. This is an example of object-oriented implementation in C by GTK." }, { "code": null, "e": 27128, "s": 27061, "text": "Let us comprehend a couple of things from our first GTK code in C." }, { "code": null, "e": 27279, "s": 27128, "text": "To start with, we incorporate the header file. This incorporates all the file one needs to make a GUI, including the Glib library.#include <gtk/gtk.h>" }, { "code": null, "e": 27300, "s": 27279, "text": "#include <gtk/gtk.h>" }, { "code": null, "e": 27564, "s": 27300, "text": "Presently, we declare a pointer to GtkWidget, which is only a window for our situation. What’s more, another GtkWidget pointer will be the button. Review that GtkWidget is a top-level storage type for widgets in the hierarchy.GtkWidget *window;\nGtkWidget *button;" }, { "code": null, "e": 27602, "s": 27564, "text": "GtkWidget *window;\nGtkWidget *button;" }, { "code": null, "e": 27753, "s": 27602, "text": "Next, we invoke gtk_init function to initialize the GTK+ libraries by passing the command line parameters of the main function.gtk_init(&argc, &argv);" }, { "code": null, "e": 27777, "s": 27753, "text": "gtk_init(&argc, &argv);" }, { "code": null, "e": 28034, "s": 27777, "text": "All GTK+ applications are instated as such; it is an “absolute necessity” statement. It parses the command arguments line and returns back to the application. Accordingly, these parameters might be utilized to alter the run time conduct of the application." }, { "code": null, "e": 28174, "s": 28034, "text": "Now, we create the window and the button.window = gtk_window_new(GTK_WINDOW_TOPLEVEL);\nbutton = gtk_button_new_with_label\n (\"Click Me!\");" }, { "code": null, "e": 28273, "s": 28174, "text": "window = gtk_window_new(GTK_WINDOW_TOPLEVEL);\nbutton = gtk_button_new_with_label\n (\"Click Me!\");" }, { "code": null, "e": 28479, "s": 28273, "text": "The window type value GTK_WINDOW_TOPLEVEL implies that the window made will be a standard framed window. Other sort values might be GTK_WINDOW_POPUP, which implies a frameless dialogue window will be made." }, { "code": null, "e": 28747, "s": 28479, "text": "When we make a window, it must be closable with the goal that the client should at any rate ready to close the application because of the client hitting the upper right close the window. This implies the window must have the option to react to an event (close event)." }, { "code": null, "e": 28956, "s": 28747, "text": "Like all windowing system, GTK+ additionally executes events and event handlers. Since the code that transmits the signal is interior to a specific object, we have to compose an interfacing callback function." }, { "code": null, "e": 29068, "s": 28956, "text": "The organization of a regular callback function is:void my_callback_function(GtkWidget *widget, gpointer data);" }, { "code": null, "e": 29129, "s": 29068, "text": "void my_callback_function(GtkWidget *widget, gpointer data);" }, { "code": null, "e": 29475, "s": 29129, "text": "The primary parameter represents the widget that produces the signal and the subsequent parameter is a void pointer that might be utilized for any reason. Along these lines, the callback function to deal with the close events of our window will be as per the following:void destroy( GtkWidget *widget, gpointer data )\n{\n gtk_main_quit ();\n}\n" }, { "code": null, "e": 29552, "s": 29475, "text": "void destroy( GtkWidget *widget, gpointer data )\n{\n gtk_main_quit ();\n}\n" }, { "code": null, "e": 29782, "s": 29552, "text": "The function gtk_main_quit() shuts the application. Presently, we should interface the window object with the callback function.g_signal_connect (window, \"destroy\",\n G_CALLBACK (destroy),\n NULL);" }, { "code": null, "e": 29884, "s": 29782, "text": "g_signal_connect (window, \"destroy\",\n G_CALLBACK (destroy),\n NULL);" }, { "code": null, "e": 30229, "s": 29884, "text": "Likewise, we make the callback function to deal with the button event and associate it with the button widget.void greet( GtkWidget *widget, gpointer data )\n{\n g_print (\"Welcome to GTK\\n\");\n g_print (\"%s clicked %d times\\n\",\n (char*)data, ++counter);\n}\ng_signal_connect (GTK_OBJECT(button), \"clicked\",\n G_CALLBACK (greet), \"button\");" }, { "code": null, "e": 30464, "s": 30229, "text": "void greet( GtkWidget *widget, gpointer data )\n{\n g_print (\"Welcome to GTK\\n\");\n g_print (\"%s clicked %d times\\n\",\n (char*)data, ++counter);\n}\ng_signal_connect (GTK_OBJECT(button), \"clicked\",\n G_CALLBACK (greet), \"button\");" }, { "code": null, "e": 30617, "s": 30464, "text": "Since the button widget is contained inside the window, we should explicitly add it to the container.gtk_container_add (GTK_CONTAINER (window), button);" }, { "code": null, "e": 30669, "s": 30617, "text": "gtk_container_add (GTK_CONTAINER (window), button);" }, { "code": null, "e": 30815, "s": 30669, "text": "Also, at long last, we show the widgets made in memory with the gtk_widget_show_all() function that takes a reference to the window we have made." }, { "code": null, "e": 30936, "s": 30815, "text": "Finally, the gtk_main() function is summoned to begin the interactive procedure.gtk_widget_show_all(window);\ngtk_main();" }, { "code": null, "e": 30977, "s": 30936, "text": "gtk_widget_show_all(window);\ngtk_main();" }, { "code": null, "e": 31286, "s": 30977, "text": "This is a key function on the grounds that ordinarily a C program ends in the wake of executing the last statement. Here, it passes the control of the program to GTK+ and stays away for the indefinite future until the gtk_main_quit event is activated by the client tapping the close button for our situation." }, { "code": null, "e": 31334, "s": 31286, "text": "Below is the implementation of the above steps:" }, { "code": "#include <gtk/gtk.h> static int counter = 0; void greet(GtkWidget* widget, gpointer data){ // printf equivalent in GTK+ g_print(\"Welcome to GTK\\n\"); g_print(\"%s clicked %d times\\n\", (char*)data, ++counter);} void destroy(GtkWidget* widget, gpointer data){ gtk_main_quit();} int main(int argc, char* argv[]){ GtkWidget* window; GtkWidget* button; gtk_init(&argc, &argv); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); g_signal_connect(window, \"destroy\", G_CALLBACK(destroy), NULL); /* Let's set the border width of the window to 20. * You may play with the value and see the * difference. */ gtk_container_set_border_width(GTK_CONTAINER(window), 20); button = gtk_button_new_with_label(\"Click Me!\"); g_signal_connect(GTK_OBJECT(button), \"clicked\", G_CALLBACK(greet), \"button\"); gtk_container_add(GTK_CONTAINER(window), button); gtk_widget_show_all(window); gtk_main(); return 0;}", "e": 32362, "s": 31334, "text": null }, { "code": null, "e": 32481, "s": 32362, "text": "For Compiling write the following command (with GCC in Linux)gcc main.c -o p1\n `pkg-config --cflags --libs gtk+-2.0`" }, { "code": null, "e": 32539, "s": 32481, "text": "gcc main.c -o p1\n `pkg-config --cflags --libs gtk+-2.0`" }, { "code": null, "e": 32581, "s": 32539, "text": "To run it write the following command./p1" }, { "code": null, "e": 32586, "s": 32581, "text": "./p1" }, { "code": null, "e": 33244, "s": 32586, "text": "ConclusionGTK+ has all the GUI segments one needs to make an expert looking interface. The essential thought of GUI occasion driven programming with GTK+ isn’t very different from the one appeared in the model. Include a couple of more parts, utilize various sorts of compartments, play with designs, and obviously always remember to counsel the GTK+ documentation. Proficient developers frequently utilized RAD tools, for example, Glade to plan the GUI interface rapidly. Be that as it may, in the first place, have a go at composing the code without any preparation to get a vibe of what goes where and how it is really done. It will compensate you later." }, { "code": null, "e": 33252, "s": 33244, "text": "AkhilKG" }, { "code": null, "e": 33263, "s": 33252, "text": "c-graphics" }, { "code": null, "e": 33270, "s": 33263, "text": "Picked" }, { "code": null, "e": 33281, "s": 33270, "text": "C Language" }, { "code": null, "e": 33379, "s": 33281, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33388, "s": 33379, "text": "Comments" }, { "code": null, "e": 33401, "s": 33388, "text": "Old Comments" }, { "code": null, "e": 33439, "s": 33401, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 33465, "s": 33439, "text": "Exception Handling in C++" }, { "code": null, "e": 33485, "s": 33465, "text": "Multithreading in C" }, { "code": null, "e": 33526, "s": 33485, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 33548, "s": 33526, "text": "'this' pointer in C++" }, { "code": null, "e": 33597, "s": 33548, "text": "How to split a string in C/C++, Python and Java?" }, { "code": null, "e": 33635, "s": 33597, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 33677, "s": 33635, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 33722, "s": 33677, "text": "How to dynamically allocate a 2D array in C?" } ]
Explorations in Named Entity Recognition, and was Eleanor Roosevelt right? | by Mikael Davidsson | Towards Data Science
Eleanor Roosevelt is alleged to have said: Great minds discuss ideas; average minds discuss events; small minds discuss people. And although this might be a misattribution, the statement as such seems to resonate with a lot of people’s intuition, but how true is it? Does it stand up to scrutiny? There are many ways in which this could be investigated, one fun approach might be to look through a bunch of newspapers for ideas, events and people and see if the fraction in which they appear can be correlated to the “mind size” (great, average, small) of its readers. To mine the newspaper articles for information, I decided to use a natural language processing technique called Named Entity Recognition (NER), which is used to identify something called “named entities” in a sentence. Named entities are things such as products, countries, companies, numbers. I will use the spaCy natural language processing lib for this. Here’s an example from their documentation of how NER-tagging can look: spaCy recognizes the following entities: PERSON: People, including fictional.NORP: Nationalities or religious or political groups.FAC: Buildings, airports, highways, bridges, etc.ORG: Companies, agencies, institutions, etc.GPE: Countries, cities, states.LOC: Non-GPE locations, mountain ranges, bodies of water.PRODUCT: Objects, vehicles, foods, etc. (Not services.)EVENT: Named hurricanes, battles, wars, sports events, etc.WORK_OF_ART: Titles of books, songs, etc.LAW: Named documents made into laws.LANGUAGE: Any named language.DATE: Absolute or relative dates or periods.TIME: Times smaller than a day.PERCENT: Percentage, including ”%“.MONEY: Monetary values, including unit.QUANTITY: Measurements, as of weight or distance.ORDINAL: “first”, “second”, etc.CARDINAL: Numerals that do not fall under another type. As can be seen we have PERSON and EVENT, but IDEA is sorely lacking. To rectify this we will need to choose one of the others to take the role as a proxy for ideas. For this I have chosen PERCENT. The reason for this is that percent usually is a way to describe abstract ideas, one uses it when talking about for example humanity as a whole, instead of this or that person. It is not a perfect map from ideas but we have to work with what we got. As for the “mind size” of the readers, I’m going to go with the Coleman-Liau readability index. This is a way to quantify at what education level the reader must be to understand the text and is calculated using the formula: Coleman_Liau = 0.0588*L–0.296*S-15.8L = Average number of letters per 100 charactersS = Average number of sentences per 100 characters Again, the analogy is not perfect, but hopefully good enough. Looks like we have our methodology all set up, lets start working with the data! We are going to use the news feed provided by a free subscription to newsapi.org. This means that we will get a Title, a Description (a summary of the article) and the first 260 characters of the Content of the article. I decided to pick a few popular English language newspapers mostly from USA and England: sources = ['abc-news', 'cnn', 'fox-news', 'cbs-news', 'the-new-york-times', 'reuters', 'the-wall-street-journal', 'the-washington-post', 'bloomberg', 'buzzfeed', 'bbc-news', 'daily-mail'] After getting the data (13,368 articles from June 2019) I inspected it and found that there were a few articles in Chinese and Arabic that will cause problems for spaCy. I cleaned it using a function I found on StackOverflow: latin_letters= {}def is_latin(uchr): try: return latin_letters[uchr] except KeyError: try: return latin_letters.setdefault( uchr, 'LATIN' in ud.name(uchr)) except: print(uchr) raise Exception()def only_roman_chars(unistr): return all(is_latin(uchr) for uchr in unistr if uchr.isalpha()) After cleaning we have 11458 posts left, distributed over the different sources: df.groupby('source').count()['title']abc-news 1563bbc-news 1076bloomberg 56buzzfeed 295cbs-news 780cnn 809daily-mail 1306fox-news 1366reuters 916the-new-york-times 1467the-wall-street-journal 590the-washington-post 1234 I decided to use Description as basis for the NER tagging since we want to tag the article based on what it’s about, and Description seemed to be the best fit for that. For Coleman-Liau we will use Content since that better reflect the overall writing style of the article. Now when that is done we can start extracting our entities: ners = ['PERSON','NORP','FAC','ORG','GPE','LOC','PRODUCT','EVENT','WORK_OF_ART','LAW','LANGUAGE','DATE','TIME','PERCENT','MONEY','QUANTITY','ORDINAL','CARDINAL']# The ners we are most interested inners_small = ['PERSON', 'EVENT', 'PERCENT']nlp = spacy.load("en_core_web_sm")df['ner'] = df['Description'].apply(lambda desc: dict(Counter([ent.label_ for ent in nlp(desc).ents])))for ner in ners: df[ner] = df['ner'].apply(lambda n: n[ner] if ner in n else 0) We group them by source and normalize them: df_grouped_mean = df.groupby('source').mean()# Normalize df_grouped = df_grouped_mean[ners].div( df_grouped_mean[ners].sum(axis=1), axis=0)df_grouped['coleman_content'] = df_grouped_mean['coleman_content']# Do the same for the smaller ners-setdf_grouped_small = df_grouped_mean[ners_small].div( df_grouped_mean[ners_small].sum(axis=1), axis=0)df_grouped_small['coleman_content'] = df_grouped_mean['coleman_content'] fig, axes = plt.subplots(nrows=3, ncols=1)df_grouped[ners].iloc[:4].plot(kind='bar', figsize=(20,14), rot=10, ax=axes[0], legend=False);df_grouped[ners].iloc[4:8].plot(kind='bar', figsize=(20,14), rot=10, ax=axes[1]);df_grouped[ners].iloc[8:].plot(kind='bar', figsize=(20,14), rot=10, ax=axes[2], legend=False); This bar plot might be a bit hard to interpret so let’s look at the different news sources focus areas, or the entities that they have the most of: focus = []for source in df_grouped[ners].values: focus.append(sorted([(ners[i],x) for i,x in enumerate(source)], key=lambda x: x[1], reverse=True)[:3]) df_grouped['focus'] = [' '.join([y[0] for y in x]) for x in focus]df_grouped['focus']abc-news ORG GPE DATEbbc-news GPE PERSON ORGbloomberg ORG GPE PERSONbuzzfeed ORG PERSON CARDINALcbs-news PERSON ORG GPEcnn PERSON ORG GPEdaily-mail PERSON DATE GPEfox-news ORG PERSON GPEreuters DATE GPE ORGthe-new-york-times PERSON GPE ORGthe-wall-street-journal ORG GPE PERSONthe-washington-post GPE ORG PERSON And also, let’s list the news sources that have the largest fraction in a certain topic: largest_in_topic = {}for n in ners: largest_in_topic[n] = list(df_grouped.sort_values(n,ascending=False).index[:3])largest_in_topic{'PERSON': ['cnn', 'daily-mail', 'the-new-york-times'], 'NORP': ['the-washington-post', 'the-new-york-times', 'fox-news'], 'FAC': ['the-new-york-times', 'abc-news', 'fox-news'], 'ORG': ['buzzfeed', 'the-wall-street-journal', 'bloomberg'], 'GPE': ['abc-news', 'the-washington-post', 'bbc-news'], 'LOC': ['bloomberg', 'abc-news', 'the-washington-post'], 'PRODUCT': ['the-wall-street-journal', 'daily-mail', 'buzzfeed'], 'EVENT': ['bbc-news', 'bloomberg', 'reuters'], 'WORK_OF_ART': ['cbs-news', 'fox-news', 'the-new-york-times'], 'LAW': ['bloomberg', 'the-wall-street-journal', 'cnn'], 'LANGUAGE': ['bbc-news', 'fox-news', 'the-new-york-times'], 'DATE': ['reuters', 'daily-mail', 'cbs-news'], 'TIME': ['bbc-news', 'daily-mail', 'cbs-news'], 'PERCENT': ['bloomberg', 'buzzfeed', 'cbs-news'], 'MONEY': ['bloomberg', 'the-wall-street-journal', 'cbs-news'], 'QUANTITY': ['buzzfeed', 'bbc-news', 'cnn'], 'ORDINAL': ['bbc-news', 'cbs-news', 'reuters'], 'CARDINAL': ['bloomberg', 'cbs-news', 'abc-news']} There are a few interesting things to notice here: Almost everyone likes to talk about countries, companies and persons. The Wall Street Journal and Bloomberg likes money and organizations, just as expected. Reuters likes to be precise about dates. If we only look at the smaller NER-set we get: Ok, so that looks good. It’s time to calculate the Coleman-Liau index. For this we need to be able to split into sentences, which is a harder task than one might suspect. I will use a function from StackOverflow: import realphabets= "([A-Za-z])"prefixes = "(Mr|St|Mrs|Ms|Dr)[.]"suffixes = "(Inc|Ltd|Jr|Sr|Co)"starters = "(Mr|Mrs|Ms|Dr|He\s|She\s|It\s|They\s|Their\s|Our\s|We\s|But\s|However\s|That\s|This\s|Wherever)"acronyms = "([A-Z][.][A-Z][.](?:[A-Z][.])?)"websites = "[.](com|net|org|io|gov)"def split_into_sentences(text): text = " " + text + " " text = text.replace("\n"," ") text = re.sub(prefixes,"\\1<prd>",text) text = re.sub(websites,"<prd>\\1",text) if "Ph.D" in text: text = text.replace("Ph.D.","Ph<prd>D<prd>") text = re.sub("\s" + alphabets + "[.] "," \\1<prd> ",text) text = re.sub(acronyms+" "+starters,"\\1<stop> \\2",text) text = re.sub(alphabets + "[.]" + alphabets + "[.]" + alphabets + "[.]","\\1<prd>\\2<prd>\\3<prd>",text) text = re.sub(alphabets + "[.]" + alphabets + "[.]","\\1<prd>\\2<prd>",text) text = re.sub(" "+suffixes+"[.] "+starters," \\1<stop> \\2",text) text = re.sub(" "+suffixes+"[.]"," \\1<prd>",text) text = re.sub(" " + alphabets + "[.]"," \\1<prd>",text) if "”" in text: text = text.replace(".”","”.") if "\"" in text: text = text.replace(".\"","\".") if "!" in text: text = text.replace("!\"","\"!") if "?" in text: text = text.replace("?\"","\"?") text = text.replace(".",".<stop>") text = text.replace("?","?<stop>") text = text.replace("!","!<stop>") text = text.replace("<prd>",".") sentences = text.split("<stop>") sentences = sentences[:-1] sentences = [s.strip() for s in sentences] return sentences Do the calculation: def calculate_coleman(letter_count, word_count, sentence_count): return 0.0588 * letter_count*100/word_count - 0.296 * sentence_count*100/word_count - 15.8df['coleman'] = df['split_content'].apply(lambda x: calculate_coleman( len(' '.join(x).replace(' ', '').replace('.', '')), len([y for y in ' '.join(x).replace('’', '').split() if not y.isnumeric()]), len(x)))df_grouped['coleman'].sort_values(ascending=False)bloomberg 14.606977reuters 13.641115bbc-news 13.453002fox-news 13.167492abc-news 13.076667the-washington-post 13.025180the-wall-street-journal 12.762103cbs-news 12.753429daily-mail 12.030524cnn 11.988568the-new-york-times 11.682979buzzfeed 10.184662 This is a bit surprising; I would have expected The New York Times to be higher up for example, but then on the other hand it just might be right. It would probably be more accurate if I had more than 260 chars of content, but the next tier of newsapi is $449/month. Just to be sure I will double check against an external source for readability score later on. Let’s plot the readability against people, event and percent: Interestingly there actually seems to be a bit of correlation, at least on PERSON and EVENT. Let’s calculate the correlation score: df_grouped_small.corr() Looking at the coleman_content column there might actually be something to the Eleanor Roosevelt quote! At least insofar that there is a negative correlation between Coleman-Liau and PERSON and a positive one between Coleman-Liau and EVENT. Since EVENT is supposed to be for “average” minds we would expect the scatter plot to move to the middle for high EVENT values, like so: This is not really what we see though, but the negative/positive correlation for PERSON/EVENT still lend some credibility to the quote. Of course, this is to be taken with a bucket load of salt. Apart from all the concession we have made so far we don’t have nearly enough samples to reach statistical significance. In fact, let’s look at the p value (function from StackOverflow): from scipy.stats import pearsonrdef calculate_pvalues(df): df = df.dropna()._get_numeric_data() dfcols = pd.DataFrame(columns=df.columns) pvalues = dfcols.transpose().join(dfcols, how='outer') for r in df.columns: for c in df.columns: pvalues[r][c] = round(pearsonr(df[r], df[c])[1], 4) return pvaluescalculate_pvalues(df_grouped_small) As expected, the p-values are low, except for PERCENT. Since the calculated Coleman-Liau levels seemed to be a bit off I decided to test with the following readability levels, taken from http://www.adamsherk.com/publishing/news-sites-google-reading-level/ reading_level = {'abc-news': (41,57,1),'cnn': (27,69,2), 'fox-news': (23,73,2),'cbs-news': (28,70,0), 'the-new-york-times': (7,85,7),'reuters': (6,85,7), 'the-wall-street-journal': (9,88,2), 'the-washington-post': (24,72,2),'bloomberg': (6,81,11)} They give 3 values (Basic, Intermediate, Advanced) which I gave different weights (-1,0,1) to calculate a singe value. df_grouped_small['external_reading_level'] = df_grouped_small.index.map( lambda x: reading_level[x][2]-reading_level[x][0] if x in reading_level else 0) Looking at the correlation df_grouped_small[df_grouped_small['external_reading_level'] != 0][ners_small + ['external_reading_level']].corr() We find that the correlation is similar to what we got before, except that we actually have an even higher positive correlation with PERCENT. Our results indicate that there actually might be some truth to the quote, but the statistical significance is so low that further research is needed. Also, it turns out that no matter the size of the mind, people love to talk about other people, a lot. Even the brainiest news (Bloomberg, with a whooping 14.6 Coleman-Liau level) talks about people 7 times more than it talks about events or percent. Another thing that stands out looking at the bar plots is how similar the newspapers are in their choice of content. So even though there are differences in peoples interests, ultimately we are more similar than we are different.
[ { "code": null, "e": 215, "s": 172, "text": "Eleanor Roosevelt is alleged to have said:" }, { "code": null, "e": 300, "s": 215, "text": "Great minds discuss ideas; average minds discuss events; small minds discuss people." }, { "code": null, "e": 469, "s": 300, "text": "And although this might be a misattribution, the statement as such seems to resonate with a lot of people’s intuition, but how true is it? Does it stand up to scrutiny?" }, { "code": null, "e": 741, "s": 469, "text": "There are many ways in which this could be investigated, one fun approach might be to look through a bunch of newspapers for ideas, events and people and see if the fraction in which they appear can be correlated to the “mind size” (great, average, small) of its readers." }, { "code": null, "e": 1170, "s": 741, "text": "To mine the newspaper articles for information, I decided to use a natural language processing technique called Named Entity Recognition (NER), which is used to identify something called “named entities” in a sentence. Named entities are things such as products, countries, companies, numbers. I will use the spaCy natural language processing lib for this. Here’s an example from their documentation of how NER-tagging can look:" }, { "code": null, "e": 1211, "s": 1170, "text": "spaCy recognizes the following entities:" }, { "code": null, "e": 2086, "s": 1211, "text": "PERSON: People, including fictional.NORP: Nationalities or religious or political groups.FAC: Buildings, airports, highways, bridges, etc.ORG: Companies, agencies, institutions, etc.GPE: Countries, cities, states.LOC: Non-GPE locations, mountain ranges, bodies of water.PRODUCT: Objects, vehicles, foods, etc. (Not services.)EVENT: Named hurricanes, battles, wars, sports events, etc.WORK_OF_ART: Titles of books, songs, etc.LAW: Named documents made into laws.LANGUAGE: Any named language.DATE: Absolute or relative dates or periods.TIME: Times smaller than a day.PERCENT: Percentage, including ”%“.MONEY: Monetary values, including unit.QUANTITY: Measurements, as of weight or distance.ORDINAL: “first”, “second”, etc.CARDINAL: Numerals that do not fall under another type." }, { "code": null, "e": 2533, "s": 2086, "text": "As can be seen we have PERSON and EVENT, but IDEA is sorely lacking. To rectify this we will need to choose one of the others to take the role as a proxy for ideas. For this I have chosen PERCENT. The reason for this is that percent usually is a way to describe abstract ideas, one uses it when talking about for example humanity as a whole, instead of this or that person. It is not a perfect map from ideas but we have to work with what we got." }, { "code": null, "e": 2758, "s": 2533, "text": "As for the “mind size” of the readers, I’m going to go with the Coleman-Liau readability index. This is a way to quantify at what education level the reader must be to understand the text and is calculated using the formula:" }, { "code": null, "e": 2893, "s": 2758, "text": "Coleman_Liau = 0.0588*L–0.296*S-15.8L = Average number of letters per 100 charactersS = Average number of sentences per 100 characters" }, { "code": null, "e": 2955, "s": 2893, "text": "Again, the analogy is not perfect, but hopefully good enough." }, { "code": null, "e": 3036, "s": 2955, "text": "Looks like we have our methodology all set up, lets start working with the data!" }, { "code": null, "e": 3345, "s": 3036, "text": "We are going to use the news feed provided by a free subscription to newsapi.org. This means that we will get a Title, a Description (a summary of the article) and the first 260 characters of the Content of the article. I decided to pick a few popular English language newspapers mostly from USA and England:" }, { "code": null, "e": 3533, "s": 3345, "text": "sources = ['abc-news', 'cnn', 'fox-news', 'cbs-news', 'the-new-york-times', 'reuters', 'the-wall-street-journal', 'the-washington-post', 'bloomberg', 'buzzfeed', 'bbc-news', 'daily-mail']" }, { "code": null, "e": 3759, "s": 3533, "text": "After getting the data (13,368 articles from June 2019) I inspected it and found that there were a few articles in Chinese and Arabic that will cause problems for spaCy. I cleaned it using a function I found on StackOverflow:" }, { "code": null, "e": 4123, "s": 3759, "text": "latin_letters= {}def is_latin(uchr): try: return latin_letters[uchr] except KeyError: try: return latin_letters.setdefault( uchr, 'LATIN' in ud.name(uchr)) except: print(uchr) raise Exception()def only_roman_chars(unistr): return all(is_latin(uchr) for uchr in unistr if uchr.isalpha())" }, { "code": null, "e": 4204, "s": 4123, "text": "After cleaning we have 11458 posts left, distributed over the different sources:" }, { "code": null, "e": 4614, "s": 4204, "text": "df.groupby('source').count()['title']abc-news 1563bbc-news 1076bloomberg 56buzzfeed 295cbs-news 780cnn 809daily-mail 1306fox-news 1366reuters 916the-new-york-times 1467the-wall-street-journal 590the-washington-post 1234" }, { "code": null, "e": 4783, "s": 4614, "text": "I decided to use Description as basis for the NER tagging since we want to tag the article based on what it’s about, and Description seemed to be the best fit for that." }, { "code": null, "e": 4888, "s": 4783, "text": "For Coleman-Liau we will use Content since that better reflect the overall writing style of the article." }, { "code": null, "e": 4948, "s": 4888, "text": "Now when that is done we can start extracting our entities:" }, { "code": null, "e": 5408, "s": 4948, "text": "ners = ['PERSON','NORP','FAC','ORG','GPE','LOC','PRODUCT','EVENT','WORK_OF_ART','LAW','LANGUAGE','DATE','TIME','PERCENT','MONEY','QUANTITY','ORDINAL','CARDINAL']# The ners we are most interested inners_small = ['PERSON', 'EVENT', 'PERCENT']nlp = spacy.load(\"en_core_web_sm\")df['ner'] = df['Description'].apply(lambda desc: dict(Counter([ent.label_ for ent in nlp(desc).ents])))for ner in ners: df[ner] = df['ner'].apply(lambda n: n[ner] if ner in n else 0)" }, { "code": null, "e": 5452, "s": 5408, "text": "We group them by source and normalize them:" }, { "code": null, "e": 5876, "s": 5452, "text": "df_grouped_mean = df.groupby('source').mean()# Normalize df_grouped = df_grouped_mean[ners].div( df_grouped_mean[ners].sum(axis=1), axis=0)df_grouped['coleman_content'] = df_grouped_mean['coleman_content']# Do the same for the smaller ners-setdf_grouped_small = df_grouped_mean[ners_small].div( df_grouped_mean[ners_small].sum(axis=1), axis=0)df_grouped_small['coleman_content'] = df_grouped_mean['coleman_content']" }, { "code": null, "e": 6188, "s": 5876, "text": "fig, axes = plt.subplots(nrows=3, ncols=1)df_grouped[ners].iloc[:4].plot(kind='bar', figsize=(20,14), rot=10, ax=axes[0], legend=False);df_grouped[ners].iloc[4:8].plot(kind='bar', figsize=(20,14), rot=10, ax=axes[1]);df_grouped[ners].iloc[8:].plot(kind='bar', figsize=(20,14), rot=10, ax=axes[2], legend=False);" }, { "code": null, "e": 6336, "s": 6188, "text": "This bar plot might be a bit hard to interpret so let’s look at the different news sources focus areas, or the entities that they have the most of:" }, { "code": null, "e": 7136, "s": 6336, "text": "focus = []for source in df_grouped[ners].values: focus.append(sorted([(ners[i],x) for i,x in enumerate(source)], key=lambda x: x[1], reverse=True)[:3]) df_grouped['focus'] = [' '.join([y[0] for y in x]) for x in focus]df_grouped['focus']abc-news ORG GPE DATEbbc-news GPE PERSON ORGbloomberg ORG GPE PERSONbuzzfeed ORG PERSON CARDINALcbs-news PERSON ORG GPEcnn PERSON ORG GPEdaily-mail PERSON DATE GPEfox-news ORG PERSON GPEreuters DATE GPE ORGthe-new-york-times PERSON GPE ORGthe-wall-street-journal ORG GPE PERSONthe-washington-post GPE ORG PERSON" }, { "code": null, "e": 7225, "s": 7136, "text": "And also, let’s list the news sources that have the largest fraction in a certain topic:" }, { "code": null, "e": 8355, "s": 7225, "text": "largest_in_topic = {}for n in ners: largest_in_topic[n] = list(df_grouped.sort_values(n,ascending=False).index[:3])largest_in_topic{'PERSON': ['cnn', 'daily-mail', 'the-new-york-times'], 'NORP': ['the-washington-post', 'the-new-york-times', 'fox-news'], 'FAC': ['the-new-york-times', 'abc-news', 'fox-news'], 'ORG': ['buzzfeed', 'the-wall-street-journal', 'bloomberg'], 'GPE': ['abc-news', 'the-washington-post', 'bbc-news'], 'LOC': ['bloomberg', 'abc-news', 'the-washington-post'], 'PRODUCT': ['the-wall-street-journal', 'daily-mail', 'buzzfeed'], 'EVENT': ['bbc-news', 'bloomberg', 'reuters'], 'WORK_OF_ART': ['cbs-news', 'fox-news', 'the-new-york-times'], 'LAW': ['bloomberg', 'the-wall-street-journal', 'cnn'], 'LANGUAGE': ['bbc-news', 'fox-news', 'the-new-york-times'], 'DATE': ['reuters', 'daily-mail', 'cbs-news'], 'TIME': ['bbc-news', 'daily-mail', 'cbs-news'], 'PERCENT': ['bloomberg', 'buzzfeed', 'cbs-news'], 'MONEY': ['bloomberg', 'the-wall-street-journal', 'cbs-news'], 'QUANTITY': ['buzzfeed', 'bbc-news', 'cnn'], 'ORDINAL': ['bbc-news', 'cbs-news', 'reuters'], 'CARDINAL': ['bloomberg', 'cbs-news', 'abc-news']}" }, { "code": null, "e": 8406, "s": 8355, "text": "There are a few interesting things to notice here:" }, { "code": null, "e": 8476, "s": 8406, "text": "Almost everyone likes to talk about countries, companies and persons." }, { "code": null, "e": 8563, "s": 8476, "text": "The Wall Street Journal and Bloomberg likes money and organizations, just as expected." }, { "code": null, "e": 8604, "s": 8563, "text": "Reuters likes to be precise about dates." }, { "code": null, "e": 8651, "s": 8604, "text": "If we only look at the smaller NER-set we get:" }, { "code": null, "e": 8864, "s": 8651, "text": "Ok, so that looks good. It’s time to calculate the Coleman-Liau index. For this we need to be able to split into sentences, which is a harder task than one might suspect. I will use a function from StackOverflow:" }, { "code": null, "e": 10376, "s": 8864, "text": "import realphabets= \"([A-Za-z])\"prefixes = \"(Mr|St|Mrs|Ms|Dr)[.]\"suffixes = \"(Inc|Ltd|Jr|Sr|Co)\"starters = \"(Mr|Mrs|Ms|Dr|He\\s|She\\s|It\\s|They\\s|Their\\s|Our\\s|We\\s|But\\s|However\\s|That\\s|This\\s|Wherever)\"acronyms = \"([A-Z][.][A-Z][.](?:[A-Z][.])?)\"websites = \"[.](com|net|org|io|gov)\"def split_into_sentences(text): text = \" \" + text + \" \" text = text.replace(\"\\n\",\" \") text = re.sub(prefixes,\"\\\\1<prd>\",text) text = re.sub(websites,\"<prd>\\\\1\",text) if \"Ph.D\" in text: text = text.replace(\"Ph.D.\",\"Ph<prd>D<prd>\") text = re.sub(\"\\s\" + alphabets + \"[.] \",\" \\\\1<prd> \",text) text = re.sub(acronyms+\" \"+starters,\"\\\\1<stop> \\\\2\",text) text = re.sub(alphabets + \"[.]\" + alphabets + \"[.]\" + alphabets + \"[.]\",\"\\\\1<prd>\\\\2<prd>\\\\3<prd>\",text) text = re.sub(alphabets + \"[.]\" + alphabets + \"[.]\",\"\\\\1<prd>\\\\2<prd>\",text) text = re.sub(\" \"+suffixes+\"[.] \"+starters,\" \\\\1<stop> \\\\2\",text) text = re.sub(\" \"+suffixes+\"[.]\",\" \\\\1<prd>\",text) text = re.sub(\" \" + alphabets + \"[.]\",\" \\\\1<prd>\",text) if \"”\" in text: text = text.replace(\".”\",\"”.\") if \"\\\"\" in text: text = text.replace(\".\\\"\",\"\\\".\") if \"!\" in text: text = text.replace(\"!\\\"\",\"\\\"!\") if \"?\" in text: text = text.replace(\"?\\\"\",\"\\\"?\") text = text.replace(\".\",\".<stop>\") text = text.replace(\"?\",\"?<stop>\") text = text.replace(\"!\",\"!<stop>\") text = text.replace(\"<prd>\",\".\") sentences = text.split(\"<stop>\") sentences = sentences[:-1] sentences = [s.strip() for s in sentences] return sentences" }, { "code": null, "e": 10396, "s": 10376, "text": "Do the calculation:" }, { "code": null, "e": 11267, "s": 10396, "text": "def calculate_coleman(letter_count, word_count, sentence_count): return 0.0588 * letter_count*100/word_count - 0.296 * sentence_count*100/word_count - 15.8df['coleman'] = df['split_content'].apply(lambda x: calculate_coleman( len(' '.join(x).replace(' ', '').replace('.', '')), len([y for y in ' '.join(x).replace('’', '').split() if not y.isnumeric()]), len(x)))df_grouped['coleman'].sort_values(ascending=False)bloomberg 14.606977reuters 13.641115bbc-news 13.453002fox-news 13.167492abc-news 13.076667the-washington-post 13.025180the-wall-street-journal 12.762103cbs-news 12.753429daily-mail 12.030524cnn 11.988568the-new-york-times 11.682979buzzfeed 10.184662" }, { "code": null, "e": 11629, "s": 11267, "text": "This is a bit surprising; I would have expected The New York Times to be higher up for example, but then on the other hand it just might be right. It would probably be more accurate if I had more than 260 chars of content, but the next tier of newsapi is $449/month. Just to be sure I will double check against an external source for readability score later on." }, { "code": null, "e": 11691, "s": 11629, "text": "Let’s plot the readability against people, event and percent:" }, { "code": null, "e": 11823, "s": 11691, "text": "Interestingly there actually seems to be a bit of correlation, at least on PERSON and EVENT. Let’s calculate the correlation score:" }, { "code": null, "e": 11847, "s": 11823, "text": "df_grouped_small.corr()" }, { "code": null, "e": 12088, "s": 11847, "text": "Looking at the coleman_content column there might actually be something to the Eleanor Roosevelt quote! At least insofar that there is a negative correlation between Coleman-Liau and PERSON and a positive one between Coleman-Liau and EVENT." }, { "code": null, "e": 12225, "s": 12088, "text": "Since EVENT is supposed to be for “average” minds we would expect the scatter plot to move to the middle for high EVENT values, like so:" }, { "code": null, "e": 12361, "s": 12225, "text": "This is not really what we see though, but the negative/positive correlation for PERSON/EVENT still lend some credibility to the quote." }, { "code": null, "e": 12607, "s": 12361, "text": "Of course, this is to be taken with a bucket load of salt. Apart from all the concession we have made so far we don’t have nearly enough samples to reach statistical significance. In fact, let’s look at the p value (function from StackOverflow):" }, { "code": null, "e": 12977, "s": 12607, "text": "from scipy.stats import pearsonrdef calculate_pvalues(df): df = df.dropna()._get_numeric_data() dfcols = pd.DataFrame(columns=df.columns) pvalues = dfcols.transpose().join(dfcols, how='outer') for r in df.columns: for c in df.columns: pvalues[r][c] = round(pearsonr(df[r], df[c])[1], 4) return pvaluescalculate_pvalues(df_grouped_small)" }, { "code": null, "e": 13032, "s": 12977, "text": "As expected, the p-values are low, except for PERCENT." }, { "code": null, "e": 13233, "s": 13032, "text": "Since the calculated Coleman-Liau levels seemed to be a bit off I decided to test with the following readability levels, taken from http://www.adamsherk.com/publishing/news-sites-google-reading-level/" }, { "code": null, "e": 13489, "s": 13233, "text": "reading_level = {'abc-news': (41,57,1),'cnn': (27,69,2), 'fox-news': (23,73,2),'cbs-news': (28,70,0), 'the-new-york-times': (7,85,7),'reuters': (6,85,7), 'the-wall-street-journal': (9,88,2), 'the-washington-post': (24,72,2),'bloomberg': (6,81,11)}" }, { "code": null, "e": 13608, "s": 13489, "text": "They give 3 values (Basic, Intermediate, Advanced) which I gave different weights (-1,0,1) to calculate a singe value." }, { "code": null, "e": 13764, "s": 13608, "text": "df_grouped_small['external_reading_level'] = df_grouped_small.index.map( lambda x: reading_level[x][2]-reading_level[x][0] if x in reading_level else 0)" }, { "code": null, "e": 13791, "s": 13764, "text": "Looking at the correlation" }, { "code": null, "e": 13905, "s": 13791, "text": "df_grouped_small[df_grouped_small['external_reading_level'] != 0][ners_small + ['external_reading_level']].corr()" }, { "code": null, "e": 14047, "s": 13905, "text": "We find that the correlation is similar to what we got before, except that we actually have an even higher positive correlation with PERCENT." }, { "code": null, "e": 14449, "s": 14047, "text": "Our results indicate that there actually might be some truth to the quote, but the statistical significance is so low that further research is needed. Also, it turns out that no matter the size of the mind, people love to talk about other people, a lot. Even the brainiest news (Bloomberg, with a whooping 14.6 Coleman-Liau level) talks about people 7 times more than it talks about events or percent." } ]
Data Structure and Algorithms - AVL Trees
What if the input to binary search tree comes in a sorted (ascending or descending) manner? It will then look like this − It is observed that BST's worst-case performance is closest to linear search algorithms, that is Ο(n). In real-time data, we cannot predict data pattern and their frequencies. So, a need arises to balance out the existing BST. Named after their inventor Adelson, Velski & Landis, AVL trees are height balancing binary search tree. AVL tree checks the height of the left and the right sub-trees and assures that the difference is not more than 1. This difference is called the Balance Factor. Here we see that the first tree is balanced and the next two trees are not balanced − In the second tree, the left subtree of C has height 2 and the right subtree has height 0, so the difference is 2. In the third tree, the right subtree of A has height 2 and the left is missing, so it is 0, and the difference is 2 again. AVL tree permits difference (balance factor) to be only 1. BalanceFactor = height(left-sutree) − height(right-sutree) If the difference in the height of left and right sub-trees is more than 1, the tree is balanced using some rotation techniques. To balance itself, an AVL tree may perform the following four kinds of rotations − Left rotation Right rotation Left-Right rotation Right-Left rotation The first two rotations are single rotations and the next two rotations are double rotations. To have an unbalanced tree, we at least need a tree of height 2. With this simple tree, let's understand them one by one. If a tree becomes unbalanced, when a node is inserted into the right subtree of the right subtree, then we perform a single left rotation − In our example, node A has become unbalanced as a node is inserted in the right subtree of A's right subtree. We perform the left rotation by making A the left-subtree of B. AVL tree may become unbalanced, if a node is inserted in the left subtree of the left subtree. The tree then needs a right rotation. As depicted, the unbalanced node becomes the right child of its left child by performing a right rotation. Double rotations are slightly complex version of already explained versions of rotations. To understand them better, we should take note of each action performed while rotation. Let's first check how to perform Left-Right rotation. A left-right rotation is a combination of left rotation followed by right rotation. The second type of double rotation is Right-Left Rotation. It is a combination of right rotation followed by left rotation. 42 Lectures 1.5 hours Ravi Kiran 141 Lectures 13 hours Arnab Chakraborty 26 Lectures 8.5 hours Parth Panjabi 65 Lectures 6 hours Arnab Chakraborty 75 Lectures 13 hours Eduonix Learning Solutions 64 Lectures 10.5 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2702, "s": 2580, "text": "What if the input to binary search tree comes in a sorted (ascending or descending) manner? It will then look like this −" }, { "code": null, "e": 2929, "s": 2702, "text": "It is observed that BST's worst-case performance is closest to linear search algorithms, that is Ο(n). In real-time data, we cannot predict data pattern and their frequencies. So, a need arises to balance out the existing BST." }, { "code": null, "e": 3194, "s": 2929, "text": "Named after their inventor Adelson, Velski & Landis, AVL trees are height balancing binary search tree. AVL tree checks the height of the left and the right sub-trees and assures that the difference is not more than 1. This difference is called the Balance Factor." }, { "code": null, "e": 3280, "s": 3194, "text": "Here we see that the first tree is balanced and the next two trees are not balanced −" }, { "code": null, "e": 3577, "s": 3280, "text": "In the second tree, the left subtree of C has height 2 and the right subtree has height 0, so the difference is 2. In the third tree, the right subtree of A has height 2 and the left is missing, so it is 0, and the difference is 2 again. AVL tree permits difference (balance factor) to be only 1." }, { "code": null, "e": 3637, "s": 3577, "text": "BalanceFactor = height(left-sutree) − height(right-sutree)\n" }, { "code": null, "e": 3766, "s": 3637, "text": "If the difference in the height of left and right sub-trees is more than 1, the tree is balanced using some rotation techniques." }, { "code": null, "e": 3849, "s": 3766, "text": "To balance itself, an AVL tree may perform the following four kinds of rotations −" }, { "code": null, "e": 3863, "s": 3849, "text": "Left rotation" }, { "code": null, "e": 3878, "s": 3863, "text": "Right rotation" }, { "code": null, "e": 3898, "s": 3878, "text": "Left-Right rotation" }, { "code": null, "e": 3918, "s": 3898, "text": "Right-Left rotation" }, { "code": null, "e": 4134, "s": 3918, "text": "The first two rotations are single rotations and the next two rotations are double rotations. To have an unbalanced tree, we at least need a tree of height 2. With this simple tree, let's understand them one by one." }, { "code": null, "e": 4274, "s": 4134, "text": "If a tree becomes unbalanced, when a node is inserted into the right subtree of the right subtree, then we perform a single left rotation −" }, { "code": null, "e": 4448, "s": 4274, "text": "In our example, node A has become unbalanced as a node is inserted in the right subtree of A's right subtree. We perform the left rotation by making A the left-subtree of B." }, { "code": null, "e": 4581, "s": 4448, "text": "AVL tree may become unbalanced, if a node is inserted in the left subtree of the left subtree. The tree then needs a right rotation." }, { "code": null, "e": 4688, "s": 4581, "text": "As depicted, the unbalanced node becomes the right child of its left child by performing a right rotation." }, { "code": null, "e": 5004, "s": 4688, "text": "Double rotations are slightly complex version of already explained versions of rotations. To understand them better, we should take note of each action performed while rotation. Let's first check how to perform Left-Right rotation. A left-right rotation is a combination of left rotation followed by right rotation." }, { "code": null, "e": 5128, "s": 5004, "text": "The second type of double rotation is Right-Left Rotation. It is a combination of right rotation followed by left rotation." }, { "code": null, "e": 5163, "s": 5128, "text": "\n 42 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5175, "s": 5163, "text": " Ravi Kiran" }, { "code": null, "e": 5210, "s": 5175, "text": "\n 141 Lectures \n 13 hours \n" }, { "code": null, "e": 5229, "s": 5210, "text": " Arnab Chakraborty" }, { "code": null, "e": 5264, "s": 5229, "text": "\n 26 Lectures \n 8.5 hours \n" }, { "code": null, "e": 5279, "s": 5264, "text": " Parth Panjabi" }, { "code": null, "e": 5312, "s": 5279, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 5331, "s": 5312, "text": " Arnab Chakraborty" }, { "code": null, "e": 5365, "s": 5331, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 5393, "s": 5365, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5429, "s": 5393, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 5457, "s": 5429, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5464, "s": 5457, "text": " Print" }, { "code": null, "e": 5475, "s": 5464, "text": " Add Notes" } ]
XAML - Quick Guide
XAML stands for Extensible Application Markup Language. It’s a simple and declarative language based on XML. In XAML, it very easy to create, initialize, and set properties of an object with hierarchical relations. In XAML, it very easy to create, initialize, and set properties of an object with hierarchical relations. It is mainly used for designing GUIs. It is mainly used for designing GUIs. It can be used for other purposes as well, e.g., to declare workflow in Workflow Foundation. It can be used for other purposes as well, e.g., to declare workflow in Workflow Foundation. XAML can be used in different platforms such as WPF (Windows Presentation Foundation), Silverlight, Mobile Development, and Windows Store App. It can be used across different .Net framework and CLR (common language runtime) versions. XAML is a declarative language in the sense it defines the WHAT and HOW you want to do. XAML processor is responsible for the HOW part to find out. Let's have a look at the following schema. It sums up the XAML side of things − The figure illustrates the following actions − The XAML file is interpreted by a platform-specific XAML processor. The XAML file is interpreted by a platform-specific XAML processor. The XAML processor transforms the XAML to internal code that describes the UI element. The XAML processor transforms the XAML to internal code that describes the UI element. The internal code and the C# code are linked together through partial classes definitions and then the .NET compiler builds the app. The internal code and the C# code are linked together through partial classes definitions and then the .NET compiler builds the app. One of the longstanding problems that all of us face with GUI design can be solved by using XAML. It can be used to design UI elements in Windows Forms applications. In the earlier GUI frameworks, there was no real separation between how an application looks like and how it behaves. Both the GUI and its behavior were created in the same language, e.g. C# or VB.net, which would require more effort from the developer to implement both the UI and the behavior associated with it. With XAML, it is very easy to separate the behavior from the designer code. Hence, the XAML programmer and the designer can work in parallel. XAML codes are very easy to read and understand. Microsoft provides two important tools for XAML − Visual Studio Expression Blend Currently, both the tools can create XAML, but the fact is that Visual Studio is used more by developers while Expression Blend is still used more often by designers. Microsoft provides a free version of Visual Studio which can be downloaded from https://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx Note − For this tutorial, we will mostly be using WPF projects and Windows Store App. But the free version of Visual Studio doesn’t support Windows Store App. So for that purpose, you will need a licensed version of Visual Studio. Follow the steps given below to install Visual Studio on your system − After downloading the files, run the installer. The following dialog box will be displayed. After downloading the files, run the installer. The following dialog box will be displayed. Click on the Install button and it will start the installation process. Click on the Install button and it will start the installation process. Once the installation process completes successfully, you will see the following screen. Once the installation process completes successfully, you will see the following screen. Close this dialog box and restart your computer if required. Close this dialog box and restart your computer if required. Now open Visual studio from the Start Menu which will show the following dialog box. It will take some time for the first time, only for preparation. Now open Visual studio from the Start Menu which will show the following dialog box. It will take some time for the first time, only for preparation. Once all is done, you will see the main window of Visual Studio. Let us start with a simple implementation. Follow the steps given below − Click on File → New → Project menu option. Click on File → New → Project menu option. The following dialog box will be displayed − The following dialog box will be displayed − Under Templates, select Visual C# and select WPF Application. Give a name to the project and click the OK button. Under Templates, select Visual C# and select WPF Application. Give a name to the project and click the OK button. In the mainwindow.xaml file, the following XAML tags are written by default. You will understand all these tags later in this tutorial. In the mainwindow.xaml file, the following XAML tags are written by default. You will understand all these tags later in this tutorial. <Window x:Class = "FirstStepDemo.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local = "clr-namespace:FirstStepDemo" mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604"> <Grid> </Grid> </Window> By default, a grid is set as the first element after page. Let's add a button and a text block under the Grid element. This is called object element syntax, a left angle bracket followed by the name of what we want to instantiate, for example a button, then define a content property. The string assigned to the Content will be displayed on the button. Now set the height and width of the button as 30 and 50 respectively. Similarly initialize the properties of the Text block. Now look at the design window. You will get to see a button. Now press F5 to execute this XAML code. <Window x:Class = "FirstStepDemo.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local = "clr-namespace:FirstStepDemo" mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <Button Content = "First Button" Height = "30" Width = "80"/> <TextBlock Text = "Congratulations you have successfully build your first app" Height = "30" Margin = "162,180,122,109"/> </Grid> </Window> When you compile and execute the above code, you will see the following window. Congratulation! You have designed your First Button. XAML applications can be developed on Mac as well. On Mac, XAML can be used as iOS and Android applications. To setup the environment on Mac, go to www.xamarin.com. Click on Products and select the Xamarin Platform. Download Xamarin Studio and install it. It will allow you to develop applications for the various platforms. In this chapter, you will learn the basic XAML syntax/rules to write XAML applications. Let’s have a look at a simple XAML file. <Window x:Class = "Resources.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "525"> <Grid> </Grid> </Window> As you can see in the above XAML file, there are different kinds of tags and elements. The following table briefly describes all the elements. <Window It is the opening object element or container of the root. x:Class="Resources.MainWindow" It is the partial class declaration which connects the markup to the partial class code behind defined in it. xmlns Maps the default XAML namespace for WPF client/framework xmlns:x XAML namespace for XAML language which maps it to x: prefix > End of object element of the root. <Grid> </Grid> Starting and closing tags of an empty grid object. </Window> Closing the object element Syntax rules for XAML is almost similar to XML. If you take a look at an XAML document, then you will notice that actually it is a valid XML file. However, an XML file cannot be a valid XAML file. It is because in XML, the value of the attributes must be a string, while in XAML, it can be a different object which is known as Property element syntax. The syntax of an Object element starts with a left angle bracket (<) followed by the name of the object, e.g. Button. The syntax of an Object element starts with a left angle bracket (<) followed by the name of the object, e.g. Button. Define some Properties and attributes of that object element. Define some Properties and attributes of that object element. The Object element must be closed by a forward slash (/) followed immediately by a right angle bracket (>). The Object element must be closed by a forward slash (/) followed immediately by a right angle bracket (>). Example of simple object with no child element − <Button/> Example of object element with some attributes − <Button Content = "Click Me" Height = "30" Width = "60"/> Example of an alternate syntax to define properties (Property element syntax) − <Button> <Button.Content>Click Me</Button.Content> <Button.Height>30</Button.Height> <Button.Width>60</Button.Width> </Button> Example of Object with Child Element − StackPanel contains Textblock as child element <StackPanel Orientation = "Horizontal"> <TextBlock Text = "Hello"/> </StackPanel> You can use XAML to create, initialize, and set the properties of objects. The same activities can also be performed using programming code. XAML is just another simple and easy way to design UI elements. With XAML, it is up to you to decide whether you want to declare objects in XAML or declare them using code. Let’s take a simple example to demonstrate how to write in XAML − <Window x:Class = "XAMLVsCode.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "525"> <StackPanel> <TextBlock Text = "Welcome to XAML Tutorial" Height = "20" Width = "200" Margin = "5"/> <Button Content = "Ok" Height = "20" Width = "60" Margin = "5"/> </StackPanel> </Window> In this example, we have created a stack panel with a Button and a Text block and defined some of the properties of button and text block such as Height, Width, and Margin. When the above code is compiled and executed, it will produce the following output − Now look at the same code which is written in C#. using System; using System.Text; using System.Windows; using System.Windows.Controls; namespace XAMLVsCode { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); // Create the StackPanel StackPanel stackPanel = new StackPanel(); this.Content = stackPanel; // Create the TextBlock TextBlock textBlock = new TextBlock(); textBlock.Text = "Welcome to XAML Tutorial"; textBlock.Height = 20; textBlock.Width = 200; textBlock.Margin = new Thickness(5); stackPanel.Children.Add(textBlock); // Create the Button Button button = new Button(); button.Content = "OK"; button.Height = 20; button.Width = 50; button.Margin = new Thickness(20); stackPanel.Children.Add(button); } } } When the above code is compiled and executed, it will produce the following output. Note that it is exactly the same as the output of XAML code. Now you can see that how simple it is to use and understand XAML. In this chapter, we will write the same example in VB.Net so that those who are familiar with VB.Net can also understand the advantages of XAML. Let’s take a look at the the same example again which is written in XAML − <Window x:Class = "XAMLVsCode.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <StackPanel> <TextBlock Text = "Welcome to XAML Tutorial with VB.net" Height = "20" Width = "220" Margin = "5"/> <Button Content = "Ok" Height = "20" Width = "60" Margin = "5"/> </StackPanel> </Window> In this example, we have created a stack panel with a button and a Text block and defined some of the properties of the button and the text block such as Height, Width, and Margin. When the above code is compiled and executed, it will produce the following output − Now look at the same code which is written in VB.Net − Public Class MainWindow Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs) Dim panel As New StackPanel() panel.Orientation = Orientation.Vertical Me.Content = panel Dim txtInput As New TextBlock txtInput.Text = "Welcome to XAML Tutorial with VB.net" txtInput.Width = 220 txtInput.Height = 20 txtInput.Margin = New Thickness(5) panel.Children.Add(txtInput) Dim btn As New Button() btn.Content = "Ok" btn.Width = 60 btn.Height = 20 btn.Margin = New Thickness(5) panel.Children.Add(btn) End Sub End Class When the above code is compiled and executed the output is exactly the same as the output of XAML code. You can now visualize how simple it is to work with XAML as compared to VB.Net. In the above example, we have seen that what we can do in XAML can also be done in other procedural languages such as C# and VB.Net. Let’s have a look at another example in which we will use both XAML and VB.Net. We will design a GUI in XAML and the behavior will be implemented in VB.Net. In this example, a button is added to the main window. When the user clicks this button, it displays a message on the message box. Here is the code in XAML in which a Button Object is declared with some properties. <Window x:Class="MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <Button Name = "btn" HorizontalAlignment = "Center" Width = "60" Height = "30" Content = "Click Me" /> </Grid> </Window> In VB.Net, the button click event (behavior) is implemented. This event displays the message on the messagebox. Public Class MainWindow Private Sub btn_Click(sender As Object, e As RoutedEventArgs) Handles btn.Click MessageBox.Show("Button is Clicked") End Sub End Class When the above code is compiled and executed, it will display the following screen − Now click on the above button that says "Click Me". It will display the following message − This chapter will describe some of the basic and important building blocks of XAML applications. It will explain how to create and initialize an object, an object can be modified easily by using resources, styles, and templates, to make an object interactive by using transformations and animations. XAML is a typically declarative language which can create and instantiate objects. It is another way to describe objects based on XML, i.e., which objects need to be created and how they should be initialized before the execution of a program. Objects can be Containers (Stack Panel, Dock Panel) UI Elements / Controls (Button, TextBox, etc.) Resource Dictionaries Resources are normally definitions connected with some object that you just anticipate to use more often than once. It is the ability to store data locally for controls or for the current window or globally for the entire applications. XAML framework provides several strategies to personalize and customize the appearance of an application. Styles give us the flexibility to set some properties of an object and reuse these specific settings across multiple objects for a consistent look. In styles, you can set only the existing properties of an object such as Height, Width, Font size, etc. Only the default behavior of a control can be specified. Multiple properties can be added into a style. In the first diagram, you can see the same height and width properties are set for all the three button separately; but in the second diagram, you can see that height and width which are same for all the buttons are added to a style and then this style is associated with all the buttons. A template describes the overall look and visual appearance of a control. For each control, there is a default template associated with it which gives the appearance to that control. In XAML, you can easily create your own templates when you want to customize the visual behavior and visual appearance of a control. In the following screenshot, there are two buttons, one is with template and the other one is the default button. Now when you hover the mouse over the button, it also changes the color as shown below. With templates, you can access more parts of a control than in styles. You can specify both existing and new behavior of a control. Animations and transformations inside the Windows Runtime can improve your XAML application by building interactivity and movement. You can easily integrate the interactive look and feel in your XAML application by using the animations from Windows Runtime animation library. Animations are used to enhance the user interface or to make it more attractive. to attract the attention of the user to a change. In the following screenshot, you can see a square − When you hover the mouse over this square, it will expend in all directions as shown below. The XAML User Interface framework offers an extensive library of controls that supports UI development for Windows. Some of them have a visual representation such Button, Textbox, TextBlock, etc.; while other controls are used as containers for other controls or content, for example, images. All the XAML controls are inherited from System.Windows.Controls.Control. The complete inheritance hierarchy of controls is as follows − Here is the list of controls which we will discuss one by one in this chapter. A control that responds to user input. Represents a control that enables a user to select a date by using a visual calendar display. A control that a user can select or clear. A drop-down list of items a user can select from. Gets or sets the context menu element that should appear whenever the context menu is requested through a user interface (UI) from within this element. Represents a control that displays data in a customizable grid. A control that lets a user select a date. An application may also display additional windows to the user to gather or display important information. A control that presents a collection of items in rows and columns that can scroll horizontally. A control that presents an image. A control that presents an inline list of items that the user can select from. Represents a Windows menu control that enables you to hierarchically organize elements associated with commands and event handlers. A control for entering passwords. Displays content on top of existing content, within the bounds of the application window. A control that indicates progress by displaying a bar. A control that indicates indeterminate progress by displaying a ring. A control that allows a user to select a single option from a group of options. A control that lets a user edit rich text documents with content like formatted text, hyperlinks, and images. A container control that lets the user pan and zoom its content. A control that lets a user enter search queries. A control that lets the user select from a range of values by moving a Thumb control along a track. A control that displays text. A control that lets a user set a time value. A button that can be toggled between 2 states. A pop-up window that displays information for an element. The root window which provides minimize/maximize option, Title bar, border and close button. In this chapter we will discuss all these controls with implementation. The layout of controls is very important and critical for application usability. It is required to arrange a group of GUI elements in your application. There are certain important points to consider while selecting layout panels; Positions of the child elements. Sizes of the child elements. Layering of overlapping child elements on top of each other. Fixed pixel arrangement of controls doesn’t work when an application has been used on different screen resolutions. XAML provides a rich set of built-in layout panels to arrange GUI elements in an appropriate way. Some of the most commonly used and popular layout panels are as follows − Stack panel is a simple and useful layout panel in XAML. In a stack panel, child elements can be arranged in a single line, either horizontally or vertically, based on the orientation property. In WrapPanel, child elements are positioned in a sequential order from left to right or from top to bottom based on the orientation property. DockPanel defines an area to arrange child elements relative to each other, either horizontally or vertically. With DockPanel, you can easily dock child elements to top, bottom, right, left, and center with Dock property. Canvas panel is the basic layout panel in which child elements can be positioned explicitly using coordinates that are relative to the Canvas any side such as left, right, top, and bottom. A Grid panel provides a flexible area which consists of rows and columns. In a Grid, child elements can be arranged in a tabular form. The general concept of events in XAML is similar to events in other popular programming languages such as .NET and C++. In XAML, all of the controls expose some events so that they can be subscribed for specific purposes. Whenever an event takes place, the application will be notified and the program can react to them, e.g., close buttons are used to close a dialog. There are many types of events that can be subscribed for different behaviors of an application based on the requirement of that application, but the most commonly used events are those which are related to mouse and keyboard such as, Click MouseDown MouseEnter MouseLeave MouseUp KeyDown KeyUp In this chapter, we will use some of the basic and most commonly used events to understand how an event of a specific control can be linked to the code behind where the behavior will be implemented depending on what the user wants to do when a specific event occurs. Let’s have a look at a simple example of a button click event. Given below is the XAML implementation for Button control which is created and initialized with some properties and a Click event (Click="OnClick"). <Window x:Class = "XAMLEventHandling.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <Button x:Name = "button1" Content = "Click" Click = "OnClick" Width = "150" Height = "30" HorizontalAlignment = "Center" /> </Grid> </Window> Whenever this button is clicked, it will fire an OnClick event and you can add any type of behavior as a response to the Click. Let’s have a look at the OnClick event implementation which will show a message when this button is clicked. using System; using System.Windows; using System.Windows.Controls; namespace XAMLEventHandling { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void OnClick(object sender, RoutedEventArgs e) { MessageBox.Show("Button is clicked!"); } } } When you compile and execute the above code, it will produce the following output − When you click on the button, the click (OnClick) event will be fired and the following message will be displayed. Now let’s have a look at a little bit complex example where multiple events are handled. The following example contains a textbox with ContextMenu which manipulates the text within the textbox. The following XAML code creates a TextBox, a ContextMenu, and MenuItems with some properties and events such as Checked, Unchecked, and Click. <Window x:Class = "XAMLContextMenu.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <TextBox Name = "textBox1" TextWrapping = "Wrap" Margin = "10" Grid.Row = "7"> Hi, this is XAML tutorial. <TextBox.ContextMenu> <ContextMenu> <MenuItem Header = "_Bold" IsCheckable = "True" Checked = "Bold_Checked" Unchecked = "Bold_Unchecked" /> <MenuItem Header = "_Italic" IsCheckable = "True" Checked = "Italic_Checked" Unchecked = "Italic_Unchecked" /> <Separator /> <MenuItem Header = "Increase Font Size" Click = "IncreaseFont_Click" /> <MenuItem Header = "_Decrease Font Size" Click = "DecreaseFont_Click" /> </ContextMenu> </TextBox.ContextMenu> </TextBox> </Grid> </Window> Here is the implementation in C# for the different events which will be fired whenever a menu item is checked, unchecked, or clicked. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; namespace XAMLContextMenu { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Bold_Checked(object sender, RoutedEventArgs e) { textBox1.FontWeight = FontWeights.Bold; } private void Bold_Unchecked(object sender, RoutedEventArgs e) { textBox1.FontWeight = FontWeights.Normal; } private void Italic_Checked(object sender, RoutedEventArgs e) { textBox1.FontStyle = FontStyles.Italic; } private void Italic_Unchecked(object sender, RoutedEventArgs e) { textBox1.FontStyle = FontStyles.Normal; } private void IncreaseFont_Click(object sender, RoutedEventArgs e) { if (textBox1.FontSize < 18) { textBox1.FontSize += 2; } } private void DecreaseFont_Click(object sender, RoutedEventArgs e) { if (textBox1.FontSize > 10) { textBox1.FontSize -= 2; } } } } When you compile and execute the above code, it will produce the following output − We recommend you to execute the above example code and experiment with some other events. Checked Fires when a ToggleButton is checked. (Inherited from ToggleButton) Click Occurs when a button control is clicked. (Inherited from ButtonBase) ContextMenuClosing Occurs just before any context menu on the element is closed. (Inherited from FrameworkElement.) ContextMenuOpening Occurs when any context menu on the element is opened. (Inherited from FrameworkElement.) DataContextChanged Occurs when the value of the FrameworkElement.DataContext property changes. (Inherited from FrameworkElement) DragEnter Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement). DragLeave Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement) DragOver Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement) DragStarting Occurs when a drag operation is initiated. (Inherited from UIElement) DropCompleted Occurs when a drag-and-drop operation is ended. (Inherited from UIElement) DropDownClosed Occurs when the drop-down portion of the ComboBox closes. DropDownOpened Occurs when the drop-down portion of the ComboBox opens. GotFocus Occurs when a UIElement receives focus. (Inherited from UIElement) Holding Occurs when an otherwise unhandled Hold interaction occurs over the hit test area of this element. (Inherited from UIElement) Intermediate Fires when the state of a ToggleButton is switched to the indeterminate state. (Inherited from ToggleButton) IsEnabledChanged Occurs when the IsEnabled property changes. (Inherited from Control) KeyDown Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement) KeyUp Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement) LostFocus Occurs when a UIElement loses focus. (Inherited from UIElement) ManipulationCompleted Occurs when a manipulation on the UIElement is complete. (Inherited from UIElement) ManipulationDelta Occurs when the input device changes position during a manipulation. (Inherited from UIElement) ManipulationInertiaStarting Occurs when the input device loses contact with the UIElement object during a manipulation and inertia begins. (Inherited from UIElement) ManipulationStarted Occurs when an input device begins a manipulation on the UIElement. (Inherited from UIElement) ManipulationStarting Occurs when the manipulation processor is first created. (Inherited from UIElement) SelectionChanged Occurs when the text selection has changed. SizeChanged Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement. (Inherited from FrameworkElement) Unchecked Occurs when a ToggleButton is unchecked. (Inherited from ToggleButton) ValueChanged Occurs when the range value changes. (Inherited from RangeBase) Data binding is a mechanism in XAML applications that provides a simple and easy way for Windows Runtime Apps using partial classes to display and interact with data. The management of data is entirely separated from the way the data is displayed in this mechanism. Data binding allows the flow of data between UI elements and data object on user interface. When a binding is established and the data or your business model changes, then it will reflect the updates automatically to the UI elements and vice versa. It is also possible to bind, not to a standard data source, but rather to another element on the page. Data binding can be of two types − One-way data binding Two-way data binding In one-way binding, data is bound from its source (that is the object that holds the data) to its target (that is the object that displays the data). Let’s have a look at a simple example of one-way data binding. The following XAML code creates four text blocks with some properties. <Window x:Class = "DataBindingOneWay.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <StackPanel Name = "Display"> <StackPanel Orientation = "Horizontal" Margin = "50, 50, 0, 0"> <TextBlock Text = "Name: " Margin = "10" Width = "100" /> <TextBlock Margin = "10" Width = "100" Text = "{Binding Name}" /> </StackPanel> <StackPanel Orientation = "Horizontal" Margin = "50,0,50,0"> <TextBlock Text = "Title: " Margin = "10" Width = "100" /> <TextBlock Margin = "10" Width = "100" Text = "{Binding Title}" /> </StackPanel> </StackPanel> </Grid> </Window> Text properties of two text blocks are set to “Name” and “Title” statically, while the other two text blocks Text properties are bound to “Name” and “Title” which are class variables of Employee class which is shown below. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataBindingOneWay { public class Employee { public string Name { get; set; } public string Title { get; set; } public static Employee GetEmployee() { var emp = new Employee() { Name = "Ali Ahmed", Title = "Developer" }; return emp; } } } In this class, we have just two variables, Name and Title, and one static method in which the Employee object is initialized which will return that employee object. So we are binding to a property, Name and Title, but we have not selected what object that property belongs to. The easiest way is to assign an object to DataContext whose properties we are binding in the following C# code − using System; using System.Windows; using System.Windows.Controls; namespace DataBindingOneWay { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = Employee.GetEmployee(); } } } Let's run this application and you can see immediately in our MainWindow that we have successfully bound to the Name and Title of that Employee object. In two-way binding, the user can modify the data through the user interface and have that data updated in the source. If the source changes while the user is looking at the view, you would want to update the view. Let’s have a look at the following example in which one combobox with three combobox items and one textbox are created with some properties. In this example, we don’t have any standard data source, but the UI elements are bound to other UI elements. <Window x:Class = "XAMLTestBinding.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <StackPanel> <ComboBox Name = "comboBox" Margin = "50" Width = "100"> <ComboBoxItem Content = "Green" /> <ComboBoxItem Content = "Yellow" IsSelected = "True" /> <ComboBoxItem Content = "Orange" /> </ComboBox> <TextBox Name = "textBox" Margin = "50" Width = "100" Height = "23" VerticalAlignment = "Top" Text = "{Binding ElementName = comboBox, Path = SelectedItem.Content, Mode = TwoWay, UpdateSourceTrigger = PropertyChanged}" Background = "{Binding ElementName = comboBox, Path = SelectedItem.Content}"> </TextBox> </StackPanel> </Window> When you compile and execute the above code, it will produce the following output. When the user selects an item from the combobox, the textbox text and the background color will be updated accordingly. Similarly, when the user types a valid color name in the textbox, then the combobox and the textbox background color will also be updated. In XAML applications, markup extensions are a method/technique to gain a value that is neither a specific XAML object nor a primitive type. Markup extensions can be defined by opening and closing curly braces and inside that curly braces, the scope of the markup extension is defined. Data binding and static resources are markup extensions. There are some predefined XAML markup extensions in System.xaml which can be used. Let’s have a look at a simple example where StaticResources markup extension is used which is a predefined XAML markup extension. The following XAML code creates two text blocks with some properties and their foreground is defined in Window.Resources. <Window x:Class = "XAMLStaticResourcesMarkupExtension.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "525"> <Window.Resources> <SolidColorBrush Color = "Blue" x:Key = "myBrush"></SolidColorBrush> </Window.Resources> <Grid> <StackPanel Orientation = "Vertical"> <TextBlock Foreground = "{StaticResource myBrush}" Text = "First Name" Width = "100" Margin = "10" /> <TextBlock Foreground = "{StaticResource myBrush}" Text = "Last Name" Width = "100" Margin = "10" /> </StackPanel> </Grid> </Window> In Window.Resources, you can see x:Key is used which uniquely identifies the elements that are created and referenced in an XAML defined dictionary to identify a resource in a resource dictionary. When you compile and execute the above code, it will produce the following MainWindow. You can see the two text blocks with blue foreground color. In XAML, custom markup extensions can also be defined by inheriting MarkupExtension class and overriding the ProvideValue method which is an abstract method in the MarkupExtension class. Let’s have a look at a simple example of custom markup extension. <Window x:Class = "XAMLMarkupExtension.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:my = "clr-namespace:XAMLMarkupExtension" Title = "MainWindow" Height = "350" Width = "525"> <Grid> <Button Content = "{my:MyMarkupExtension FirstStr = Markup, SecondStr = Extension}" Width = "200" Height = "20" /> </Grid> </Window> In the above XAML code, a button is created with some properties and for the content value, a custom markup extension (my:MyMarkupExtension) has been used with two values “Markup” and “Extension” which are assigned to FirstStr and SecondStr respectively. Actually, MyMarkupExtension is a class which is derived from MarkupExtension as shown below in the C# implementation. This class contains two string variables, FirstStr and SecondStr, which are concatenated and return that string from the ProvideValue method to the Content of a button. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace XAMLMarkupExtension { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } } public class MyMarkupExtension : MarkupExtension { public MyMarkupExtension() { } public String FirstStr { get; set; } public String SecondStr { get; set; } public override object ProvideValue(IServiceProvider serviceProvider) { return FirstStr + " " + SecondStr; } } } Let's run this application and you can see immediately in our MainWindow that "markup extension" has been successfully used as the content of the button. A dependency property is a specific type of property where the value is followed by a keen property system which is also a part of the Windows Runtime App. A class which defines a dependency property must be inherited from the DependencyObject class. Many of the UI control classes which are used in XAML are derived from the DependencyObject class and support dependency properties. The following XAML code creates a button with some properties. <Window x:Class = "XAMLDependencyProperty.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local = "clr-namespace:XAMLDependencyProperty" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <Button Height = "40" Width = "175" Margin = "10" Content = "Dependency Property"> <Button.Style> <Style TargetType = "{x:Type Button}"> <Style.Triggers> <Trigger Property = "IsMouseOver" Value = "True"> <Setter Property = "Foreground" Value = "Red" /> </Trigger> </Style.Triggers> </Style> </Button.Style> </Button> </Grid> </Window> The x:Type markup extension in XAML has a similar functionality like typeof() in C#. It is used when attributes are specified that take the type of the object such as <Style TargetType = "{x:Type Button}"> When you compile and execute the above code, it will produce the following MainWindow. When the mouse is over the button, it will change the foreground color of the button. When the mouse leaves the button, it will change back to its original color. The main difference between dependency properties and other CLR properties are − CLR properties can directly read/write from the private member of a class by using getter and setter. In case of dependency properties, it is not stored in a local object. CLR properties can directly read/write from the private member of a class by using getter and setter. In case of dependency properties, it is not stored in a local object. Dependency properties are stored in a dictionary of key/value pairs which is provided by the DependencyObject class. Dependency properties are stored in a dictionary of key/value pairs which is provided by the DependencyObject class. It also saves a lot of memory because it stores the property when changed. It also saves a lot of memory because it stores the property when changed. It can be bound in XAML as well. It can be bound in XAML as well. In .NET framework, custom dependency properties can also be defined. Here are the steps to define custom dependency property in C#. Declare and register your dependency property with system call register. Declare and register your dependency property with system call register. Provide the setter and getter for the property. Provide the setter and getter for the property. Define a static handler to handle any changes that occur globally. Define a static handler to handle any changes that occur globally. Define an instance handler to handle any changes that occur to that particular instance. Define an instance handler to handle any changes that occur to that particular instance. Given below is the code in C# for dependency property which defined to set the SetText property of the user control. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApplication3 { /// <summary> /// Interaction logic for UserControl1.xaml /// </summary> public partial class UserControl1 : UserControl { public UserControl1() { InitializeComponent(); } public static readonly DependencyProperty SetTextProperty = DependencyProperty.Register("SetText", typeof(string), typeof(UserControl1), new PropertyMetadata("", new PropertyChangedCallback(OnSetTextChanged))); public string SetText { get {return(string) GetValue(SetTextProperty); } set {SetValue(SetTextProperty, value);} } private static void OnSetTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { UserControl1 UserControl1Control = d as UserControl1; UserControl1Control.OnSetTextChanged(e); } private void OnSetTextChanged(DependencyPropertyChangedEventArgs e) { tbTest.Text = e.NewValue.ToString(); } } } Here is the XAML file in which the TextBlock is defined as a user control and the Text property will be assigned to it by the SetText dependency property. The following XAML code creates a user control with initializing its SetText dependency property and some other properties. <Window x:Class = "WpfApplication3.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:views = "clr-namespace:WpfApplication3" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <views:UserControl1 SetText = "Hellow World" /> </Grid> </Window> Let's run this application and you can see immediately in our MainWindow that dependency property for user control has been successfully used as a Text. Resources are normally definitions connected with some object that you just anticipate to use more often than once. It has the ability to store data locally for controls or for the current window or globally for the entire applications. Defining an object as a resource allows us to access it from another place. Hence, it allows reusability. Resources are defined in resource dictionaries and any object can be defined as a resource effectively making it a shareable asset. A unique key is specified to XAML resource and with that key, it can be referenced by using a StaticResource markup extension. Let’s have a look at a simple example again in which two text blocks are created with some properties and their foreground color is defined in Window.Resources. <Window x:Class = "XAMLResources.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Window.Resources> <SolidColorBrush Color = "Blue" x:Key = "myBrush"></SolidColorBrush> </Window.Resources> <StackPanel Orientation = "Vertical"> <TextBlock Foreground = "{StaticResource myBrush}" Text = "First Name" Width = "100" Margin = "10" /> <TextBlock Foreground = "{StaticResource myBrush}" Text = "Last Name" Width = "100" Margin = "10" /> </StackPanel> </Window> When the above code is compiled and executed, it will produce the following MainWindow. You can see two text blocks with blue foreground color. The advantage of the resource is that if there are multiple text blocks and you want to change their background color, then you will need just to change it in the resource dictionary. Resources are defined in resource dictionaries, but there are numerous places where a resource dictionary can be defined. In the above example, a resource dictionary is defined on Window/page level. In what dictionary a resource is defined immediately limits the scope of that resource. So the scope, i.e. where you can use the resource, depends on where you've defined it. Define the resource in the resource dictionary of a grid and it's accessible by that grid and by its child elements only. Define the resource in the resource dictionary of a grid and it's accessible by that grid and by its child elements only. Define it on a window/page and it's accessible by all elements on that window/page. Define it on a window/page and it's accessible by all elements on that window/page. The App root can be found in App.xaml resources dictionary. It's the root of our application, so the resources defined here are scoped to the complete application. The App root can be found in App.xaml resources dictionary. It's the root of our application, so the resources defined here are scoped to the complete application. As far as the scope of the resource is concerned, the most often are application level, page level, and a specific element level like a Grid, StackPanel, etc. Resource dictionaries in XAML apps imply resource dictionaries in separate files. It is followed in almost all XAML apps. Defining resources in separate files can have the following advantages − Separation between defining resources in the resource dictionary and UI related code. Separation between defining resources in the resource dictionary and UI related code. Defining all the resources in a separate file such as App.xaml would make them available across the App. Defining all the resources in a separate file such as App.xaml would make them available across the App. So, how we can define our resources in a resource dictionary in a separate file? Well, it is very easy, just add a new resource dictionary through Visual Studio by the following steps − In your solution, add a new folder and name it ResourceDictionaries. In your solution, add a new folder and name it ResourceDictionaries. Right-click on this folder and select Resource Dictionary from Add submenu item and name it DictionaryWithBrush.xaml Right-click on this folder and select Resource Dictionary from Add submenu item and name it DictionaryWithBrush.xaml Let’s have a look at the same application; just the resource dictionary is now defined in App level. Here is the XAML code for MainWindow.xaml. <Window x:Class = "XAMLResources.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <StackPanel Orientation = "Vertical"> <TextBlock Foreground = "{StaticResource myBrush}" Text = "First Name" Width = "100" Margin = "10" /> <TextBlock Foreground = "{StaticResource myBrush}" Text = "Last Name" Width = "100" Margin = "10"/> </StackPanel> </Window> Here is the implementation in DictionaryWithBrush.xaml − <ResourceDictionary xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"> <SolidColorBrush Color = "Blue" x:Key = "myBrush"></SolidColorBrush> </ResourceDictionary> Here is the implementation in app.xaml − <Application x:Class = "XAMLResources.App" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" StartupUri = "MainWindow.xaml"> <Application.Resources> <ResourceDictionary Source = " XAMLResources\ResourceDictionaries\DictionaryWithBrush.xaml" /> </Application.Resources> </Application> When the above code is compiled and executed, it will produce the following output − We recommend you to execute the above code and experiment with some more resources such as background color, etc. A template describes the overall look and visual appearance of a control. For each control, there is a default template associated with it which gives the appearance to that control. In XAML, you can easily create your own templates when you want to customize the visual behavior and visual appearance of a control. Connectivity between the logic and template can be achieved by data binding. The main difference between styles and templates are − Styles can only change the appearance of your control with default properties of that control. Styles can only change the appearance of your control with default properties of that control. With templates, you can access more parts of a control than in styles. You can also specify both existing and new behavior of a control. With templates, you can access more parts of a control than in styles. You can also specify both existing and new behavior of a control. There are two types of templates which are most commonly used. Control Template Data Template The Control Template defines or specifies the visual appearance and structure of a control. All of the UI elements have some kind of appearance as well as behavior, e.g., Button has an appearance and behavior. Click event or mouse hover events are the behaviors which are fired in response to a click and hover, and there is also a default appearance of button which can be changed by the Control template. Let’s have a look at a simple example again in which two buttons are created with some properties. One is with template and the other one is with the default button. <Window x:Class = "TemplateDemo.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Window.Resources> <ControlTemplate x:Key = "ButtonTemplate" TargetType = "Button"> <Grid> <Ellipse x:Name = "ButtonEllipse" Height = "100" Width = "150" > <Ellipse.Fill> <LinearGradientBrush StartPoint = "0,0.2" EndPoint = "0.2,1.4"> <GradientStop Offset = "0" Color = "Red"/> <GradientStop Offset = "1" Color = "Orange"/> </LinearGradientBrush> </Ellipse.Fill> </Ellipse> <ContentPresenter Content = "{TemplateBinding Content}" HorizontalAlignment = "Center" VerticalAlignment = "Center" /> </Grid> <ControlTemplate.Triggers> <Trigger Property = "IsMouseOver" Value = "True"> <Setter TargetName = "ButtonEllipse" Property = "Fill" > <Setter.Value> <LinearGradientBrush StartPoint = "0,0.2" EndPoint="0.2,1.4"> <GradientStop Offset = "0" Color = "YellowGreen"/> <GradientStop Offset = "1" Color = "Gold"/> </LinearGradientBrush> </Setter.Value> </Setter> </Trigger> <Trigger Property = "IsPressed" Value = "True"> <Setter Property = "RenderTransform"> <Setter.Value> <ScaleTransform ScaleX = "0.8" ScaleY = "0.8" CenterX = "0" CenterY = "0" /> </Setter.Value> </Setter> <Setter Property = "RenderTransformOrigin" Value = "0.5,0.5" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Window.Resources> <StackPanel> <Button Content = "Round Button!" Template = "{StaticResource ButtonTemplate}" Width = "150" Margin = "50" /> <Button Content = "Default Button!" Height = "40" Width = "150" Margin = "5" /> </StackPanel> </Window> When the above code is compiled and executed, it will produce the following MainWindow − When you hover the mouse over the button with custom template, then it also changes the color as shown below − A Data Template defines and specifies the appearance and structure of the collection of data. It provides the flexibility to format and define the presentation of the data on any UI element. It is mostly used on data related Item controls such as ComboBox, ListBox, etc. Let’s have a look at a simple example of data template. The following XAML code creates a combobox with Data Template and text blocks. <Window x:Class = "XAMLDataTemplate.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Grid VerticalAlignment = "Top"> <ComboBox Name = "Presidents" ItemsSource = "{Binding}" Height = "30" Width = "400"> <ComboBox.ItemTemplate> <DataTemplate> <StackPanel Orientation = "Horizontal" Margin = "2"> <TextBlock Text = "Name: " Width = "95" Background = "Aqua" Margin = "2" /> <TextBlock Text = "{Binding Name}" Width = "95" Background = "AliceBlue" Margin = "2" /> <TextBlock Text = "Title: " Width = "95" Background = "Aqua" Margin = "10,2,0,2" /> <TextBlock Text = "{Binding Title}" Width = "95" Background = "AliceBlue" Margin = "2" /> </StackPanel> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> </Grid> </Window> Here is the implementation in C# in which the employee object is assigned to DataContext − using System; using System.Windows; using System.Windows.Controls; namespace XAMLDataTemplate { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = Employee.GetEmployees(); } } } Here is the implementation in C# for Employee class − using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace XAMLDataTemplate { public class Employee : INotifyPropertyChanged { private string name; public string Name { get { return name; } set { name = value; RaiseProperChanged(); } } private string title; public string Title { get { return title; } set { title = value; RaiseProperChanged(); } } public static Employee GetEmployee() { var emp = new Employee() { Name = "Waqas", Title = "Software Engineer" }; return emp; } public event PropertyChangedEventHandler PropertyChanged; private void RaiseProperChanged( [CallerMemberName] string caller = ""){ if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(caller)); } } public static ObservableCollection<Employee> GetEmployees() { var employees = new ObservableCollection<Employee>(); employees.Add(new Employee() { Name = "Ali", Title = "Developer" }); employees.Add(new Employee() { Name = "Ahmed", Title = "Programmer" }); employees.Add(new Employee() { Name = "Amjad", Title = "Desiner" }); employees.Add(new Employee() { Name = "Waqas", Title = "Programmer" }); employees.Add(new Employee() { Name = "Bilal", Title = "Engineer" }); employees.Add(new Employee() { Name = "Waqar", Title = "Manager" }); return employees; } } } When the above code is compiled and executed, it will produce the following output. It contains a combobox and when you click on the combobox, you see that the collection of data which are created in the Employee class is listed as the combobox items. We recommend you to execute the above code and experiment with it. XAML framework provides several strategies to personalize and customize the appearance of an application. Styles give us the flexibility to set some properties of an object and reuse these specific settings across multiple objects for a consistent look. In styles, you can set only the existing properties of an object such as Height, Width, and Font size. In styles, you can set only the existing properties of an object such as Height, Width, and Font size. Only default behavior of a control can be specified. Only default behavior of a control can be specified. Multiple properties can be added into a single style. Multiple properties can be added into a single style. Styles are used to give a uniform look to a set of controls. Implicit Styles are used to apply an appearance to all controls of a given type and simplify the application. Imagine we have three buttons and all of them have to look the same − same width and height, same font size, and same foreground color. We can set all those properties on the button elements themselves and that's still quite okay for all of the buttons as shown in the following diagram. But in a real-life App, you'll typically have a lot more of these that need to look exactly the same. And not only buttons of course, you'll typically want your text blocks, text boxes, and combo boxes, etc., to look the same across your App. Surely there must be a better way to achieve this − it is known as styling. You can think of a style as a convenient way to apply a set of property values to more than one element as shown in the following diagram. Let’s have look at the example which contains three buttons which are created in XAML with some properties. <Window x:Class = "XAMLStyle.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local = "clr-namespace:XAMLStyle" mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604"> <StackPanel> <Button Content = "Button1" Height = "30" Width = "80" Foreground = "Blue" FontSize = "12" Margin = "10"/> <Button Content = "Button2" Height = "30" Width = "80" Foreground = "Blue" FontSize = "12" Margin = "10"/> <Button Content = "Button3" Height = "30" Width = "80" Foreground = "Blue" FontSize = "12" Margin = "10"/> </StackPanel> </Window> When you look at the above code, you will see that for all the buttons, height, width, foreground color, font size, and margin properties remain same. When the above code is compiled and executed, it will display the following output − Now let’s have a look at the same example, but this time, we will be using style. <Window x:Class = "XAMLStyle.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local = "clr-namespace:XAMLStyle" mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604"> <Window.Resources> <Style x:Key = "myButtonStyle" TargetType = "Button"> <Setter Property = "Height" Value = "30"/> <Setter Property = "Width" Value = "80"/> <Setter Property = "Foreground" Value = "Blue"/> <Setter Property = "FontSize" Value = "12"/> <Setter Property = "Margin" Value = "10"/> </Style> </Window.Resources> <StackPanel> <Button Content = "Button1" Style = "{StaticResource myButtonStyle}"/> <Button Content = "Button2" Style = "{StaticResource myButtonStyle}"/> <Button Content = "Button3" Style = "{StaticResource myButtonStyle}"/> </StackPanel> </Window> Styles are defined in the resource dictionary and each style has a unique key identifier and a target type. Inside <style>, you can see that multiple setter tags are defined for each property which will be included in the style. In the above example, all of the common properties of each button are now defined in style and then the style are assigned to each button with a unique key by setting the style property through the StaticResource markup extension. When the above code is compiled and executed, it will produce the following window which is the same output. The advantage of doing it like this is immediately obvious. We can reuse that style anywhere in its scope, and if we need to change it, we simply change it once in the style definition instead of on each element. In what level a style is defined instantaneously limits the scope of that style. So the scope, i.e. where you can use the style, depends on where you've defined it. Style can be defined on the following levels − Defining a style on control level can only be applied to that particular control. Defining a style on any layout level can only be accessible by that layout and by its child elements only. Defining a style on a window level can be accessible by all the elements on that window. Defining a style on App level makes it accessible in entire application. Basically, a trigger enables you to change property values or take actions based on the value of a property. So, it basically allows you to dynamically change the appearance and/or behavior of your control without having to create a new one. Triggers are used to change the value of any given property, when certain conditions are satisfied. Triggers are usually defined in a style or in the root of a document which are applied to that specific control. There are three types of triggers − Property Triggers Data Triggers Event Triggers In property triggers, when a change occurs in one property, it will bring either an immediate or an animated change in another property. For example, you can use a property trigger if you want to change the button appearance when the mouse is over the button. The following example demonstrates how to change the foreground color of a button when the mouse enters its region. <Window x:Class = "XAMLPropertyTriggers.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Window.Resources> <Style x:Key = "TriggerStyle" TargetType = "Button"> <Setter Property = "Foreground" Value = "Blue" /> <Style.Triggers> <Trigger Property = "IsMouseOver" Value = "True"> <Setter Property = "Foreground" Value = "Green" /> </Trigger> </Style.Triggers> </Style> </Window.Resources> <Grid> <Button Width = "100" Height = "70" Style = "{StaticResource TriggerStyle}" Content = "Trigger"/> </Grid> </Window> When you compile and execute the above code, it will produce the following output − When the mouse enters the region of button, the foreground color will change to green. A data trigger performs some action when the bound data satisfies some condition. Let’s have a look at the following XAML code in which a checkbox and a text block are created with some properties. When the checkbox is checked, it will change the foreground color to red. <Window x:Class = "XAMLDataTrigger.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "Data Trigger" Height = "350" Width = "604"> <StackPanel HorizontalAlignment = "Center"> <CheckBox x:Name = "redColorCheckBox" Content = "Set red as foreground color" Margin = "20"/> <TextBlock Name = "txtblock" VerticalAlignment = "Center" Text = "Event Trigger" FontSize = "24" Margin = "20"> <TextBlock.Style> <Style> <Style.Triggers> <DataTrigger Binding = "{Binding ElementName = redColorCheckBox, Path = IsChecked}" Value = "true"> <Setter Property = "TextBlock.Foreground" Value = "Red"/> <Setter Property = "TextBlock.Cursor" Value = "Hand" /> </DataTrigger> </Style.Triggers> </Style> </TextBlock.Style> </TextBlock> </StackPanel> </Window> When you compile and execute the above code, it will produce the following output − When the checkbox is checked, the foreground color of the text block will change to red. An event trigger performs some action when a specific event is fired. It is usually used to accomplish some animation such DoubleAnimation, ColorAnimation, etc. The following code block creates a simple button. When the click event is fired, it will expand the width and height of the button. <Window x:Class = "XAMLEventTrigger.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <Button Content = "Click Me" Width = "60" Height = "30"> <Button.Triggers> <EventTrigger RoutedEvent = "Button.Click"> <EventTrigger.Actions> <BeginStoryboard> <Storyboard> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty = "Width" Duration = "0:0:4"> <LinearDoubleKeyFrame Value = "60" KeyTime = "0:0:0"/> <LinearDoubleKeyFrame Value = "120" KeyTime = "0:0:1"/> <LinearDoubleKeyFrame Value = "200" KeyTime = "0:0:2"/> <LinearDoubleKeyFrame Value = "300" KeyTime = "0:0:3"/> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty = "Height" Duration = "0:0:4"> <LinearDoubleKeyFrame Value = "30" KeyTime = "0:0:0"/> <LinearDoubleKeyFrame Value = "40" KeyTime = "0:0:1"/> <LinearDoubleKeyFrame Value = "80" KeyTime = "0:0:2"/> <LinearDoubleKeyFrame Value = "150" KeyTime = "0:0:3"/> </DoubleAnimationUsingKeyFrames> </Storyboard> </BeginStoryboard> </EventTrigger.Actions> </EventTrigger> </Button.Triggers> </Button> </Grid> </Window> When you compile and execute the above code, it will produce the following output − Now, click on the button and you will observe that it will start expanding in both dimensions. If you are familiar with debugging in any procedural language (such as C#, C/C++ etc.) and you know the usage of break and are expecting the same kind of debugging in XAML, then you will be surprised to know that it is not possible yet to debug an XAML code like the way you used to debug any other procedural language code. Debugging an XAML app means trying to find an error; In data binding, your data doesn't show up on screen and you don't know why In data binding, your data doesn't show up on screen and you don't know why Or an issue is related to complex layouts. Or an issue is related to complex layouts. Or an alignment issue or issues in margin color, overlays, etc. with some extensive templates like ListBox and combo box. Or an alignment issue or issues in margin color, overlays, etc. with some extensive templates like ListBox and combo box. Debugging in XAML is something you typically do to check if your bindings work, and if it is not working, then to check what's wrong. Unfortunately, setting breakpoints in XAML bindings isn't possible except in Silverlight, but we can use the Output window to check for data binding errors. Let's have a look at the following XAML code to find the error in data binding. <Window x:Class = "DataBindingOneWay.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <StackPanel Name = "Display"> <StackPanel Orientation = "Horizontal" Margin = "50, 50, 0, 0"> <TextBlock Text = "Name: " Margin = "10" Width = "100"/> <TextBlock Margin = "10" Width = "100" Text = "{Binding FirstName}"/> </StackPanel> <StackPanel Orientation = "Horizontal" Margin = "50,0,50,0"> <TextBlock Text = "Title: " Margin = "10" Width = "100"/> <TextBlock Margin = "10" Width="100" Text = "{Binding Title}" /> </StackPanel> </StackPanel> </Grid> </Window> Text properties of the two text blocks are set to “Name” and “Title” statically, while the other two text block’s Text properties are bound to “FirstName” and “Title”. But the class variables are intentionally taken as Name and Title in the Employee class which are incorrect variable names. Let us now try to understand where we can find this type of mistake when the desired output is not shown. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataBindingOneWay { public class Employee { public string Name { get; set; } public string Title { get; set; } public static Employee GetEmployee() { var emp = new Employee() { Name = "Ali Ahmed", Title = "Developer" }; return emp; } } } Here is the implementation of MainWindow class in C# code − using System; using System.Windows; using System.Windows.Controls; namespace DataBindingOneWay { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = Employee.GetEmployee(); } } } Let's run this application and you can see immediately in our MainWindow that we have successfully bound to the Title of that Employee object but the name is not bound. To check what happened with the name, let’s look at the output window where a lot of log is generated. The easiest way to find an error is to just search for error and you will find the below mentioned error which says “BindingExpression path error: 'FirstName' property not found on 'object' ''Employe” System.Windows.Data Error: 40 : BindingExpression path error: 'FirstName' property not found on 'object' ''Employee' (HashCode = 11611730)'. BindingExpression:Path = FirstName; DataItem = 'Employee' (HashCode = 11611730); target element is 'TextBlock' (Name = ''); target property is 'Text' (type 'String') Which clearly indicate that FirstName is not a member of Employee class, so it helps to fix this type of issues in your application. When you change the FirstName to Name again, you will see the desired output. UI debugging tools for XAML are introduced with Visual Studio 2015 to inspect the XAML code at runtime. With the help of these tools, XAML code is presented in the form of visual tree of your running WPF application and also the different UI element properties in the tree. To enable this tool, follow the steps given below. Step 1 − Go to the Tools menu and select Options from the Tools menu. Step 1 − Go to the Tools menu and select Options from the Tools menu. Step 2 − You will get to see the following dialog box. Step 2 − You will get to see the following dialog box. Step 3 − Go to the General Options under Debugging item on the left side. Step 3 − Go to the General Options under Debugging item on the left side. Step 4 − Check the highlighted option, i.e, “Enable UI Debugging Tools for XAML” Step 4 − Check the highlighted option, i.e, “Enable UI Debugging Tools for XAML” Step 5 − Press the OK button. Step 5 − Press the OK button. Now run any XAML application or use the following XAML code − <Window x:Class = "XAMLTestBinding.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <StackPanel> <ComboBox Name = "comboBox" Margin = "50" Width = "100"> <ComboBoxItem Content = "Green"/> <ComboBoxItem Content = "Yellow" IsSelected = "True"/> <ComboBoxItem Content = "Orange" /> </ComboBox> <TextBox Name = "textBox" Margin = "50" Width = "100" Height = "23" VerticalAlignment = "Top" Text = "{ Binding ElementName = comboBox, Path = SelectedItem.Content, Mode = TwoWay, UpdateSourceTrigger = PropertyChanged}" Background = "{Binding ElementName = comboBox, Path = SelectedItem.Content}"> </TextBox> </StackPanel> </Window> When the application executes, it will show the Live Visual Tree where all the elements are shown in a tree. This Live Visual Tree shows the complete layout structure to understand where the UI elements are placed. But this option is only available in Visual Studio 2015. If you are using an older version of Visual studio, then you can’t use this tool; however there is another tool which can be integrated with Visual Studio such as XAML Spy for Visual Studio. You can download it from http://xamlspy.com/download. We recommend you to download this tool if you are using an older version of Visual Studio. XAML has one of the most powerful features provided to create custom controls which make it very easy to create feature-rich and customizable controls. Custom controls are used when all the built-in controls provided by Microsoft are not fulfilling your criteria or you don’t want to pay for 3rd party controls. In this chapter, you will learn how to create custom controls. Before we start taking a look at Custom Controls, let's take a quick look at a User Control first. User Controls provide a technique to collect and combine different built-in controls together and package them into re-usable XAML. User controls are used in the following scenarios − If the control consists of existing controls, i.e., you can create a single control of multiple, already existing controls. If the control consists of existing controls, i.e., you can create a single control of multiple, already existing controls. If the control don't need support for theming. User Controls do not support complex customization, control templates, and also difficult to style. If the control don't need support for theming. User Controls do not support complex customization, control templates, and also difficult to style. If a developer prefers to write controls using the code-behind model where a view and then a direct code is written behind for event handlers. If a developer prefers to write controls using the code-behind model where a view and then a direct code is written behind for event handlers. You won't be sharing your control across applications. You won't be sharing your control across applications. Let’s take an example of User control and follow the steps given below − Step 1 − Create a new WPF project and then right-click on your solution and select Add > New Item... Step 1 − Create a new WPF project and then right-click on your solution and select Add > New Item... Step 2 − The following dialog will open, now select User Control (WPF) and name it MyUserControl. Step 2 − The following dialog will open, now select User Control (WPF) and name it MyUserControl. Step 3 − Click on the Add button and you will see that two new files (MyUserControl.xaml and MyUserControl.cs) will be added in your solution. Step 3 − Click on the Add button and you will see that two new files (MyUserControl.xaml and MyUserControl.cs) will be added in your solution. Given below is the XAML code in which a button and a textbox is created with some properties in MyUserControl.xaml file. <UserControl x:Class = "XAMLUserControl.MyUserControl" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable = "d" d:DesignHeight = "300" d:DesignWidth = "300"> <Grid> <TextBox Height = "23" HorizontalAlignment = "Left" Margin = "80,49,0,0" Name = "txtBox" VerticalAlignment = "Top" Width = "200" /> <Button Content = "Click Me" Height = "23" HorizontalAlignment = "Left" Margin = "96,88,0,0" Name = "button" VerticalAlignment = "Top" Width = "75" Click = "button_Click" /> </Grid> </UserControl> Given below is the C# code for button click event in MyUserControl.cs file which updates the textbox. using System; using System.Windows; using System.Windows.Controls; namespace XAMLUserControl { /// <summary> /// Interaction logic for MyUserControl.xaml /// </summary> public partial class MyUserControl : UserControl { public MyUserControl() { InitializeComponent(); } private void button_Click(object sender, RoutedEventArgs e) { txtBox.Text = "You have just clicked the button"; } } } Here is implementation in MainWindow.xaml to add the user control. <Window x:Class = "XAMLUserControl.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:control = "clr-namespace:XAMLUserControl" Title = "MainWindow" Height = "350" Width = "525"> <Grid> <control:MyUserControl/> </Grid> </Window> When you compile and execute the above code, it will produce the following output − Now click on the "Click Me" button and you will see that the textbox text is updated. A custom control is a class which offers its own style and template which are normally defined in generic.xaml. Custom controls are used in following scenarios, If the control doesn't exist and you have to create it from scratch. If the control doesn't exist and you have to create it from scratch. If you want to extend or add functionality to a preexisting control by adding an extra property or an extra functionality to fit your specific scenario. If you want to extend or add functionality to a preexisting control by adding an extra property or an extra functionality to fit your specific scenario. If your controls need to support theming and styling. If your controls need to support theming and styling. If you want to share you control across applications. If you want to share you control across applications. Let’s take an example of custom control and follow the steps given below. Step 1 − Create a new WPF project and then right-click on your solution and select Add > New Item... Step 1 − Create a new WPF project and then right-click on your solution and select Add > New Item... Step 2 − The following dialog box will open. Now select Custom Control (WPF) and name it MyCustomControl. Step 2 − The following dialog box will open. Now select Custom Control (WPF) and name it MyCustomControl. Step 3 − Click on the Add button and you will see that two new files (Themes/Generic.xaml and MyCustomControl.cs) will be added in your solution. Step 3 − Click on the Add button and you will see that two new files (Themes/Generic.xaml and MyCustomControl.cs) will be added in your solution. Given below is the XAML code in which style is set for the custom control in Generic.xaml file. <ResourceDictionary xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local = "clr-namespace:XAMLCustomControls"> <Style TargetType = "{x:Type local:MyCustomControl}" BasedOn = "{StaticResource {x:Type Button}}"> <Setter Property = "Background" Value = "LightSalmon"/> <Setter Property = "Foreground" Value = "Blue"/> </Style> </ResourceDictionary> Given below is the C# code for MyCustomControl class which is inherited from the button class and in the constructor, it overrides the metadata. using System; using System.Windows; using System.Windows.Controls; namespace XAMLCustomControls { public class MyCustomControl : Button { static MyCustomControl() { DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl))); } } } Given below is the custom control click event implementation in C# which updates the text of the text block. using System; using System.Windows; using System.Windows.Controls; namespace XAMLCustomControls { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void customControl_Click(object sender, RoutedEventArgs e) { txtBlock.Text = "You have just click your custom control"; } } } Here is the implementation in MainWindow.xaml to add the custom control and a TextBlock. <Window x:Class = "XAMLCustomControls.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:control = "clr-namespace:XAMLCustomControls" Title = "MainWindow" Height = "350" Width = "604"> <StackPanel> <control:MyCustomControl x:Name = "customControl" Content = "Click Me" Width = "70" Margin = "10" Click = "customControl_Click"/> <TextBlock Name = "txtBlock" Width = "250" Height = "30"/> </StackPanel> </Window> When you compile and execute the above code, it will produce the following output. Observe the output contains a custom control which is a customized button. Now click on the customized button. You will see that the text block text is updated. Print Add Notes Bookmark this page
[ { "code": null, "e": 2032, "s": 1923, "text": "XAML stands for Extensible Application Markup Language. It’s a simple and declarative language based on XML." }, { "code": null, "e": 2138, "s": 2032, "text": "In XAML, it very easy to create, initialize, and set properties of an object with hierarchical relations." }, { "code": null, "e": 2244, "s": 2138, "text": "In XAML, it very easy to create, initialize, and set properties of an object with hierarchical relations." }, { "code": null, "e": 2282, "s": 2244, "text": "It is mainly used for designing GUIs." }, { "code": null, "e": 2320, "s": 2282, "text": "It is mainly used for designing GUIs." }, { "code": null, "e": 2413, "s": 2320, "text": "It can be used for other purposes as well, e.g., to declare workflow in Workflow Foundation." }, { "code": null, "e": 2506, "s": 2413, "text": "It can be used for other purposes as well, e.g., to declare workflow in Workflow Foundation." }, { "code": null, "e": 2740, "s": 2506, "text": "XAML can be used in different platforms such as WPF (Windows Presentation Foundation), Silverlight, Mobile Development, and Windows Store App. It can be used across different .Net framework and CLR (common language runtime) versions." }, { "code": null, "e": 2968, "s": 2740, "text": "XAML is a declarative language in the sense it defines the WHAT and HOW you want to do. XAML processor is responsible for the HOW part to find out. Let's have a look at the following schema. It sums up the XAML side of things −" }, { "code": null, "e": 3015, "s": 2968, "text": "The figure illustrates the following actions −" }, { "code": null, "e": 3083, "s": 3015, "text": "The XAML file is interpreted by a platform-specific XAML processor." }, { "code": null, "e": 3151, "s": 3083, "text": "The XAML file is interpreted by a platform-specific XAML processor." }, { "code": null, "e": 3238, "s": 3151, "text": "The XAML processor transforms the XAML to internal code that describes the UI element." }, { "code": null, "e": 3325, "s": 3238, "text": "The XAML processor transforms the XAML to internal code that describes the UI element." }, { "code": null, "e": 3458, "s": 3325, "text": "The internal code and the C# code are linked together through partial classes definitions and then the .NET compiler builds the app." }, { "code": null, "e": 3591, "s": 3458, "text": "The internal code and the C# code are linked together through partial classes definitions and then the .NET compiler builds the app." }, { "code": null, "e": 3757, "s": 3591, "text": "One of the longstanding problems that all of us face with GUI design can be solved by using XAML. It can be used to design UI elements in Windows Forms applications." }, { "code": null, "e": 4072, "s": 3757, "text": "In the earlier GUI frameworks, there was no real separation between how an application looks like and how it behaves. Both the GUI and its behavior were created in the same language, e.g. C# or VB.net, which would require more effort from the developer to implement both the UI and the behavior associated with it." }, { "code": null, "e": 4263, "s": 4072, "text": "With XAML, it is very easy to separate the behavior from the designer code. Hence, the XAML programmer and the designer can work in parallel. XAML codes are very easy to read and understand." }, { "code": null, "e": 4313, "s": 4263, "text": "Microsoft provides two important tools for XAML −" }, { "code": null, "e": 4327, "s": 4313, "text": "Visual Studio" }, { "code": null, "e": 4344, "s": 4327, "text": "Expression Blend" }, { "code": null, "e": 4511, "s": 4344, "text": "Currently, both the tools can create XAML, but the fact is that Visual Studio is used more by developers while Expression Blend is still used more often by designers." }, { "code": null, "e": 4667, "s": 4511, "text": "Microsoft provides a free version of Visual Studio which can be downloaded from https://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx" }, { "code": null, "e": 4898, "s": 4667, "text": "Note − For this tutorial, we will mostly be using WPF projects and Windows Store App. But the free version of Visual Studio doesn’t support Windows Store App. So for that purpose, you will need a licensed version of Visual Studio." }, { "code": null, "e": 4969, "s": 4898, "text": "Follow the steps given below to install Visual Studio on your system −" }, { "code": null, "e": 5061, "s": 4969, "text": "After downloading the files, run the installer. The following dialog box will be displayed." }, { "code": null, "e": 5153, "s": 5061, "text": "After downloading the files, run the installer. The following dialog box will be displayed." }, { "code": null, "e": 5225, "s": 5153, "text": "Click on the Install button and it will start the installation process." }, { "code": null, "e": 5297, "s": 5225, "text": "Click on the Install button and it will start the installation process." }, { "code": null, "e": 5386, "s": 5297, "text": "Once the installation process completes successfully, you will see the following screen." }, { "code": null, "e": 5475, "s": 5386, "text": "Once the installation process completes successfully, you will see the following screen." }, { "code": null, "e": 5536, "s": 5475, "text": "Close this dialog box and restart your computer if required." }, { "code": null, "e": 5597, "s": 5536, "text": "Close this dialog box and restart your computer if required." }, { "code": null, "e": 5747, "s": 5597, "text": "Now open Visual studio from the Start Menu which will show the following dialog box. It will take some time for the first time, only for preparation." }, { "code": null, "e": 5897, "s": 5747, "text": "Now open Visual studio from the Start Menu which will show the following dialog box. It will take some time for the first time, only for preparation." }, { "code": null, "e": 5962, "s": 5897, "text": "Once all is done, you will see the main window of Visual Studio." }, { "code": null, "e": 6036, "s": 5962, "text": "Let us start with a simple implementation. Follow the steps given below −" }, { "code": null, "e": 6079, "s": 6036, "text": "Click on File → New → Project menu option." }, { "code": null, "e": 6122, "s": 6079, "text": "Click on File → New → Project menu option." }, { "code": null, "e": 6167, "s": 6122, "text": "The following dialog box will be displayed −" }, { "code": null, "e": 6212, "s": 6167, "text": "The following dialog box will be displayed −" }, { "code": null, "e": 6326, "s": 6212, "text": "Under Templates, select Visual C# and select WPF Application. Give a name to the project and click the OK button." }, { "code": null, "e": 6440, "s": 6326, "text": "Under Templates, select Visual C# and select WPF Application. Give a name to the project and click the OK button." }, { "code": null, "e": 6576, "s": 6440, "text": "In the mainwindow.xaml file, the following XAML tags are written by default. You will understand all these tags later in this tutorial." }, { "code": null, "e": 6712, "s": 6576, "text": "In the mainwindow.xaml file, the following XAML tags are written by default. You will understand all these tags later in this tutorial." }, { "code": null, "e": 7199, "s": 6712, "text": "<Window x:Class = \"FirstStepDemo.MainWindow\"\n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\"\n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:local = \"clr-namespace:FirstStepDemo\" \n mc:Ignorable = \"d\" Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Grid> \n \n </Grid> \n</Window> " }, { "code": null, "e": 7258, "s": 7199, "text": "By default, a grid is set as the first element after page." }, { "code": null, "e": 7677, "s": 7258, "text": "Let's add a button and a text block under the Grid element. This is called object element syntax, a left angle bracket followed by the name of what we want to instantiate, for example a button, then define a content property. The string assigned to the Content will be displayed on the button. Now set the height and width of the button as 30 and 50 respectively. Similarly initialize the properties of the Text block." }, { "code": null, "e": 7778, "s": 7677, "text": "Now look at the design window. You will get to see a button. Now press F5 to execute this XAML code." }, { "code": null, "e": 8469, "s": 7778, "text": "<Window x:Class = \"FirstStepDemo.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:local = \"clr-namespace:FirstStepDemo\" \n mc:Ignorable = \"d\" Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Grid> \n <Button Content = \"First Button\" Height = \"30\" Width = \"80\"/> \n <TextBlock Text = \"Congratulations you have successfully build your first app\" \n Height = \"30\" Margin = \"162,180,122,109\"/> \n </Grid> \n\t\n</Window> " }, { "code": null, "e": 8549, "s": 8469, "text": "When you compile and execute the above code, you will see the following window." }, { "code": null, "e": 8602, "s": 8549, "text": "Congratulation! You have designed your First Button." }, { "code": null, "e": 8927, "s": 8602, "text": "XAML applications can be developed on Mac as well. On Mac, XAML can be used as iOS and Android applications. To setup the environment on Mac, go to www.xamarin.com. Click on Products and select the Xamarin Platform. Download Xamarin Studio and install it. It will allow you to develop applications for the various platforms." }, { "code": null, "e": 9056, "s": 8927, "text": "In this chapter, you will learn the basic XAML syntax/rules to write XAML applications. Let’s have a look at a simple XAML file." }, { "code": null, "e": 9328, "s": 9056, "text": "<Window x:Class = \"Resources.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" Title = \"MainWindow\" Height = \"350\" Width = \"525\"> \n\t\n <Grid> \n \n </Grid> \n</Window> " }, { "code": null, "e": 9471, "s": 9328, "text": "As you can see in the above XAML file, there are different kinds of tags and elements. The following table briefly describes all the elements." }, { "code": null, "e": 9479, "s": 9471, "text": "<Window" }, { "code": null, "e": 9538, "s": 9479, "text": "It is the opening object element or container of the root." }, { "code": null, "e": 9569, "s": 9538, "text": "x:Class=\"Resources.MainWindow\"" }, { "code": null, "e": 9679, "s": 9569, "text": "It is the partial class declaration which connects the markup to the partial class code behind defined in it." }, { "code": null, "e": 9686, "s": 9679, "text": "xmlns " }, { "code": null, "e": 9743, "s": 9686, "text": "Maps the default XAML namespace for WPF client/framework" }, { "code": null, "e": 9752, "s": 9743, "text": "xmlns:x " }, { "code": null, "e": 9812, "s": 9752, "text": "XAML namespace for XAML language which maps it to x: prefix" }, { "code": null, "e": 9814, "s": 9812, "text": ">" }, { "code": null, "e": 9849, "s": 9814, "text": "End of object element of the root." }, { "code": null, "e": 9856, "s": 9849, "text": "<Grid>" }, { "code": null, "e": 9864, "s": 9856, "text": "</Grid>" }, { "code": null, "e": 9915, "s": 9864, "text": "Starting and closing tags of an empty grid object." }, { "code": null, "e": 9925, "s": 9915, "text": "</Window>" }, { "code": null, "e": 9952, "s": 9925, "text": "Closing the object element" }, { "code": null, "e": 10304, "s": 9952, "text": "Syntax rules for XAML is almost similar to XML. If you take a look at an XAML document, then you will notice that actually it is a valid XML file. However, an XML file cannot be a valid XAML file. It is because in XML, the value of the attributes must be a string, while in XAML, it can be a different object which is known as Property element syntax." }, { "code": null, "e": 10422, "s": 10304, "text": "The syntax of an Object element starts with a left angle bracket (<) followed by the name of the object, e.g. Button." }, { "code": null, "e": 10540, "s": 10422, "text": "The syntax of an Object element starts with a left angle bracket (<) followed by the name of the object, e.g. Button." }, { "code": null, "e": 10602, "s": 10540, "text": "Define some Properties and attributes of that object element." }, { "code": null, "e": 10664, "s": 10602, "text": "Define some Properties and attributes of that object element." }, { "code": null, "e": 10772, "s": 10664, "text": "The Object element must be closed by a forward slash (/) followed immediately by a right angle bracket (>)." }, { "code": null, "e": 10880, "s": 10772, "text": "The Object element must be closed by a forward slash (/) followed immediately by a right angle bracket (>)." }, { "code": null, "e": 10929, "s": 10880, "text": "Example of simple object with no child element −" }, { "code": null, "e": 10940, "s": 10929, "text": "<Button/>\n" }, { "code": null, "e": 10989, "s": 10940, "text": "Example of object element with some attributes −" }, { "code": null, "e": 11049, "s": 10989, "text": "<Button Content = \"Click Me\" Height = \"30\" Width = \"60\"/> \n" }, { "code": null, "e": 11129, "s": 11049, "text": "Example of an alternate syntax to define properties (Property element syntax) −" }, { "code": null, "e": 11270, "s": 11129, "text": "<Button> \n <Button.Content>Click Me</Button.Content> \n <Button.Height>30</Button.Height> \n <Button.Width>60</Button.Width> \n</Button>\n" }, { "code": null, "e": 11356, "s": 11270, "text": "Example of Object with Child Element − StackPanel contains Textblock as child element" }, { "code": null, "e": 11445, "s": 11356, "text": "<StackPanel Orientation = \"Horizontal\"> \n <TextBlock Text = \"Hello\"/> \n</StackPanel> \n" }, { "code": null, "e": 11586, "s": 11445, "text": "You can use XAML to create, initialize, and set the properties of objects. The same activities can also be performed using programming code." }, { "code": null, "e": 11759, "s": 11586, "text": "XAML is just another simple and easy way to design UI elements. With XAML, it is up to you to decide whether you want to declare objects in XAML or declare them using code." }, { "code": null, "e": 11825, "s": 11759, "text": "Let’s take a simple example to demonstrate how to write in XAML −" }, { "code": null, "e": 12266, "s": 11825, "text": "<Window x:Class = \"XAMLVsCode.MainWindow\"\n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" Title = \"MainWindow\" Height = \"350\" Width = \"525\"> \n\t\n <StackPanel> \n <TextBlock Text = \"Welcome to XAML Tutorial\" Height = \"20\" Width = \"200\" Margin = \"5\"/>\n <Button Content = \"Ok\" Height = \"20\" Width = \"60\" Margin = \"5\"/> \n </StackPanel> \n\t\n</Window> " }, { "code": null, "e": 12524, "s": 12266, "text": "In this example, we have created a stack panel with a Button and a Text block and defined some of the properties of button and text block such as Height, Width, and Margin. When the above code is compiled and executed, it will produce the following output −" }, { "code": null, "e": 12574, "s": 12524, "text": "Now look at the same code which is written in C#." }, { "code": null, "e": 13592, "s": 12574, "text": "using System; \nusing System.Text; \nusing System.Windows; \nusing System.Windows.Controls; \n\nnamespace XAMLVsCode { \n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary> \n\t\n public partial class MainWindow : Window {\n public MainWindow() { \n InitializeComponent(); \n \n // Create the StackPanel \n StackPanel stackPanel = new StackPanel();\n this.Content = stackPanel; \n\t\t\t\n // Create the TextBlock \n TextBlock textBlock = new TextBlock(); \n textBlock.Text = \"Welcome to XAML Tutorial\"; \n textBlock.Height = 20;\n textBlock.Width = 200; \n textBlock.Margin = new Thickness(5); \n stackPanel.Children.Add(textBlock); \n\t\t\t\n // Create the Button \n Button button = new Button(); \n button.Content = \"OK\"; \n button.Height = 20; \n button.Width = 50; \n button.Margin = new Thickness(20); \n stackPanel.Children.Add(button); \n } \n }\n}" }, { "code": null, "e": 13737, "s": 13592, "text": "When the above code is compiled and executed, it will produce the following output. Note that it is exactly the same as the output of XAML code." }, { "code": null, "e": 13803, "s": 13737, "text": "Now you can see that how simple it is to use and understand XAML." }, { "code": null, "e": 13948, "s": 13803, "text": "In this chapter, we will write the same example in VB.Net so that those who are familiar with VB.Net can also understand the advantages of XAML." }, { "code": null, "e": 14023, "s": 13948, "text": "Let’s take a look at the the same example again which is written in XAML −" }, { "code": null, "e": 14479, "s": 14023, "text": "<Window x:Class = \"XAMLVsCode.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <StackPanel> \n <TextBlock Text = \"Welcome to XAML Tutorial with VB.net\" Height = \"20\" Width = \"220\" Margin = \"5\"/> \n <Button Content = \"Ok\" Height = \"20\" Width = \"60\" Margin = \"5\"/> \n </StackPanel> \n\t\n</Window> " }, { "code": null, "e": 14745, "s": 14479, "text": "In this example, we have created a stack panel with a button and a Text block and defined some of the properties of the button and the text block such as Height, Width, and Margin. When the above code is compiled and executed, it will produce the following output −" }, { "code": null, "e": 14800, "s": 14745, "text": "Now look at the same code which is written in VB.Net −" }, { "code": null, "e": 15442, "s": 14800, "text": "Public Class MainWindow\n Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs) \n Dim panel As New StackPanel() \n panel.Orientation = Orientation.Vertical \n Me.Content = panel \n Dim txtInput As New TextBlock \n\t\t\n txtInput.Text = \"Welcome to XAML Tutorial with VB.net\" \n txtInput.Width = 220 \n txtInput.Height = 20 \n txtInput.Margin = New Thickness(5) \n\t\t\n panel.Children.Add(txtInput) \n Dim btn As New Button()\n\t\t\n btn.Content = \"Ok\" \n btn.Width = 60 \n btn.Height = 20 \n btn.Margin = New Thickness(5) \n\t\t\n panel.Children.Add(btn)\n End Sub \nEnd Class " }, { "code": null, "e": 15546, "s": 15442, "text": "When the above code is compiled and executed the output is exactly the same as the output of XAML code." }, { "code": null, "e": 15626, "s": 15546, "text": "You can now visualize how simple it is to work with XAML as compared to VB.Net." }, { "code": null, "e": 15759, "s": 15626, "text": "In the above example, we have seen that what we can do in XAML can also be done in other procedural languages such as C# and VB.Net." }, { "code": null, "e": 15916, "s": 15759, "text": "Let’s have a look at another example in which we will use both XAML and VB.Net. We will design a GUI in XAML and the behavior will be implemented in VB.Net." }, { "code": null, "e": 16131, "s": 15916, "text": "In this example, a button is added to the main window. When the user clicks this button, it displays a message on the message box. Here is the code in XAML in which a Button Object is declared with some properties." }, { "code": null, "e": 16493, "s": 16131, "text": "<Window x:Class=\"MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Grid> \n <Button Name = \"btn\" HorizontalAlignment = \"Center\" Width = \"60\" Height = \"30\" Content = \"Click Me\" /> \n </Grid> \n\t\n</Window> " }, { "code": null, "e": 16605, "s": 16493, "text": "In VB.Net, the button click event (behavior) is implemented. This event displays the message on the messagebox." }, { "code": null, "e": 16780, "s": 16605, "text": "Public Class MainWindow\n Private Sub btn_Click(sender As Object, e As RoutedEventArgs) Handles btn.Click \n MessageBox.Show(\"Button is Clicked\") \n End Sub \nEnd Class " }, { "code": null, "e": 16865, "s": 16780, "text": "When the above code is compiled and executed, it will display the following screen −" }, { "code": null, "e": 16957, "s": 16865, "text": "Now click on the above button that says \"Click Me\". It will display the following message −" }, { "code": null, "e": 17074, "s": 16957, "text": "This chapter will describe some of the basic and important building blocks of XAML applications. It will explain how" }, { "code": null, "e": 17110, "s": 17074, "text": "to create and initialize an object," }, { "code": null, "e": 17186, "s": 17110, "text": "an object can be modified easily by using resources, styles, and templates," }, { "code": null, "e": 17257, "s": 17186, "text": "to make an object interactive by using transformations and animations." }, { "code": null, "e": 17516, "s": 17257, "text": "XAML is a typically declarative language which can create and instantiate objects. It is another way to describe objects based on XML, i.e., which objects need to be created and how they should be initialized before the execution of a program. Objects can be" }, { "code": null, "e": 17553, "s": 17516, "text": "Containers (Stack Panel, Dock Panel)" }, { "code": null, "e": 17600, "s": 17553, "text": "UI Elements / Controls (Button, TextBox, etc.)" }, { "code": null, "e": 17622, "s": 17600, "text": "Resource Dictionaries" }, { "code": null, "e": 17858, "s": 17622, "text": "Resources are normally definitions connected with some object that you just anticipate to use more often than once. It is the ability to store data locally for controls or for the current window or globally for the entire applications." }, { "code": null, "e": 18112, "s": 17858, "text": "XAML framework provides several strategies to personalize and customize the appearance of an application. Styles give us the flexibility to set some properties of an object and reuse these specific settings across multiple objects for a consistent look." }, { "code": null, "e": 18216, "s": 18112, "text": "In styles, you can set only the existing properties of an object such as Height, Width, Font size, etc." }, { "code": null, "e": 18273, "s": 18216, "text": "Only the default behavior of a control can be specified." }, { "code": null, "e": 18320, "s": 18273, "text": "Multiple properties can be added into a style." }, { "code": null, "e": 18609, "s": 18320, "text": "In the first diagram, you can see the same height and width properties are set for all the three button separately; but in the second diagram, you can see that height and width which are same for all the buttons are added to a style and then this style is associated with all the buttons." }, { "code": null, "e": 18925, "s": 18609, "text": "A template describes the overall look and visual appearance of a control. For each control, there is a default template associated with it which gives the appearance to that control. In XAML, you can easily create your own templates when you want to customize the visual behavior and visual appearance of a control." }, { "code": null, "e": 19039, "s": 18925, "text": "In the following screenshot, there are two buttons, one is with template and the other one is the default button." }, { "code": null, "e": 19127, "s": 19039, "text": "Now when you hover the mouse over the button, it also changes the color as shown below." }, { "code": null, "e": 19259, "s": 19127, "text": "With templates, you can access more parts of a control than in styles. You can specify both existing and new behavior of a control." }, { "code": null, "e": 19555, "s": 19259, "text": "Animations and transformations inside the Windows Runtime can improve your XAML application by building interactivity and movement. You can easily integrate the interactive look and feel in your XAML application by using the animations from Windows Runtime animation library. Animations are used" }, { "code": null, "e": 19616, "s": 19555, "text": "to enhance the user interface or to make it more attractive." }, { "code": null, "e": 19666, "s": 19616, "text": "to attract the attention of the user to a change." }, { "code": null, "e": 19718, "s": 19666, "text": "In the following screenshot, you can see a square −" }, { "code": null, "e": 19810, "s": 19718, "text": "When you hover the mouse over this square, it will expend in all directions as shown below." }, { "code": null, "e": 20177, "s": 19810, "text": "The XAML User Interface framework offers an extensive library of controls that supports UI development for Windows. Some of them have a visual representation such Button, Textbox, TextBlock, etc.; while other controls are used as containers for other controls or content, for example, images. All the XAML controls are inherited from System.Windows.Controls.Control." }, { "code": null, "e": 20240, "s": 20177, "text": "The complete inheritance hierarchy of controls is as follows −" }, { "code": null, "e": 20319, "s": 20240, "text": "Here is the list of controls which we will discuss one by one in this chapter." }, { "code": null, "e": 20358, "s": 20319, "text": "A control that responds to user input." }, { "code": null, "e": 20452, "s": 20358, "text": "Represents a control that enables a user to select a date by using a visual calendar display." }, { "code": null, "e": 20495, "s": 20452, "text": "A control that a user can select or clear." }, { "code": null, "e": 20545, "s": 20495, "text": "A drop-down list of items a user can select from." }, { "code": null, "e": 20697, "s": 20545, "text": "Gets or sets the context menu element that should appear whenever the context menu is requested through a user interface (UI) from within this element." }, { "code": null, "e": 20761, "s": 20697, "text": "Represents a control that displays data in a customizable grid." }, { "code": null, "e": 20803, "s": 20761, "text": "A control that lets a user select a date." }, { "code": null, "e": 20910, "s": 20803, "text": "An application may also display additional windows to the user to gather or display important information." }, { "code": null, "e": 21006, "s": 20910, "text": "A control that presents a collection of items in rows and columns that can scroll horizontally." }, { "code": null, "e": 21040, "s": 21006, "text": "A control that presents an image." }, { "code": null, "e": 21119, "s": 21040, "text": "A control that presents an inline list of items that the user can select from." }, { "code": null, "e": 21251, "s": 21119, "text": "Represents a Windows menu control that enables you to hierarchically organize elements associated with commands and event handlers." }, { "code": null, "e": 21285, "s": 21251, "text": "A control for entering passwords." }, { "code": null, "e": 21375, "s": 21285, "text": "Displays content on top of existing content, within the bounds of the application window." }, { "code": null, "e": 21430, "s": 21375, "text": "A control that indicates progress by displaying a bar." }, { "code": null, "e": 21500, "s": 21430, "text": "A control that indicates indeterminate progress by displaying a ring." }, { "code": null, "e": 21580, "s": 21500, "text": "A control that allows a user to select a single option from a group of options." }, { "code": null, "e": 21690, "s": 21580, "text": "A control that lets a user edit rich text documents with content like formatted text, hyperlinks, and images." }, { "code": null, "e": 21755, "s": 21690, "text": "A container control that lets the user pan and zoom its content." }, { "code": null, "e": 21804, "s": 21755, "text": "A control that lets a user enter search queries." }, { "code": null, "e": 21904, "s": 21804, "text": "A control that lets the user select from a range of values by moving a Thumb control along a track." }, { "code": null, "e": 21934, "s": 21904, "text": "A control that displays text." }, { "code": null, "e": 21979, "s": 21934, "text": "A control that lets a user set a time value." }, { "code": null, "e": 22026, "s": 21979, "text": "A button that can be toggled between 2 states." }, { "code": null, "e": 22084, "s": 22026, "text": "A pop-up window that displays information for an element." }, { "code": null, "e": 22177, "s": 22084, "text": "The root window which provides minimize/maximize option, Title bar, border and close button." }, { "code": null, "e": 22249, "s": 22177, "text": "In this chapter we will discuss all these controls with implementation." }, { "code": null, "e": 22479, "s": 22249, "text": "The layout of controls is very important and critical for application usability. It is required to arrange a group of GUI elements in your application. There are certain important points to consider while selecting layout panels;" }, { "code": null, "e": 22512, "s": 22479, "text": "Positions of the child elements." }, { "code": null, "e": 22541, "s": 22512, "text": "Sizes of the child elements." }, { "code": null, "e": 22602, "s": 22541, "text": "Layering of overlapping child elements on top of each other." }, { "code": null, "e": 22890, "s": 22602, "text": "Fixed pixel arrangement of controls doesn’t work when an application has been used on different screen resolutions. XAML provides a rich set of built-in layout panels to arrange GUI elements in an appropriate way. Some of the most commonly used and popular layout panels are as follows −" }, { "code": null, "e": 23084, "s": 22890, "text": "Stack panel is a simple and useful layout panel in XAML. In a stack panel, child elements can be arranged in a single line, either horizontally or vertically, based on the orientation property." }, { "code": null, "e": 23226, "s": 23084, "text": "In WrapPanel, child elements are positioned in a sequential order from left to right or from top to bottom based on the orientation property." }, { "code": null, "e": 23448, "s": 23226, "text": "DockPanel defines an area to arrange child elements relative to each other, either horizontally or vertically. With DockPanel, you can easily dock child elements to top, bottom, right, left, and center with Dock property." }, { "code": null, "e": 23637, "s": 23448, "text": "Canvas panel is the basic layout panel in which child elements can be positioned explicitly using coordinates that are relative to the Canvas any side such as left, right, top, and bottom." }, { "code": null, "e": 23772, "s": 23637, "text": "A Grid panel provides a flexible area which consists of rows and columns. In a Grid, child elements can be arranged in a tabular form." }, { "code": null, "e": 23994, "s": 23772, "text": "The general concept of events in XAML is similar to events in other popular programming languages such as .NET and C++. In XAML, all of the controls expose some events so that they can be subscribed for specific purposes." }, { "code": null, "e": 24141, "s": 23994, "text": "Whenever an event takes place, the application will be notified and the program can react to them, e.g., close buttons are used to close a dialog." }, { "code": null, "e": 24376, "s": 24141, "text": "There are many types of events that can be subscribed for different behaviors of an application based on the requirement of that application, but the most commonly used events are those which are related to mouse and keyboard such as," }, { "code": null, "e": 24382, "s": 24376, "text": "Click" }, { "code": null, "e": 24392, "s": 24382, "text": "MouseDown" }, { "code": null, "e": 24403, "s": 24392, "text": "MouseEnter" }, { "code": null, "e": 24414, "s": 24403, "text": "MouseLeave" }, { "code": null, "e": 24422, "s": 24414, "text": "MouseUp" }, { "code": null, "e": 24430, "s": 24422, "text": "KeyDown" }, { "code": null, "e": 24436, "s": 24430, "text": "KeyUp" }, { "code": null, "e": 24703, "s": 24436, "text": "In this chapter, we will use some of the basic and most commonly used events to understand how an event of a specific control can be linked to the code behind where the behavior will be implemented depending on what the user wants to do when a specific event occurs." }, { "code": null, "e": 24915, "s": 24703, "text": "Let’s have a look at a simple example of a button click event. Given below is the XAML implementation for Button control which is created and initialized with some properties and a Click event (Click=\"OnClick\")." }, { "code": null, "e": 25334, "s": 24915, "text": "<Window x:Class = \"XAMLEventHandling.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Grid> \n <Button x:Name = \"button1\" Content = \"Click\" Click = \"OnClick\" \n Width = \"150\" Height = \"30\" HorizontalAlignment = \"Center\" /> \n </Grid>\n \n</Window> " }, { "code": null, "e": 25571, "s": 25334, "text": "Whenever this button is clicked, it will fire an OnClick event and you can add any type of behavior as a response to the Click. Let’s have a look at the OnClick event implementation which will show a message when this button is clicked." }, { "code": null, "e": 26006, "s": 25571, "text": "using System; \nusing System.Windows; \nusing System.Windows.Controls; \n\nnamespace XAMLEventHandling {\n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary> \n\t\n public partial class MainWindow : Window {\n public MainWindow() { \n InitializeComponent(); \n }\n private void OnClick(object sender, RoutedEventArgs e) { \n MessageBox.Show(\"Button is clicked!\"); \n } \n }\n}" }, { "code": null, "e": 26090, "s": 26006, "text": "When you compile and execute the above code, it will produce the following output −" }, { "code": null, "e": 26205, "s": 26090, "text": "When you click on the button, the click (OnClick) event will be fired and the following message will be displayed." }, { "code": null, "e": 26294, "s": 26205, "text": "Now let’s have a look at a little bit complex example where multiple events are handled." }, { "code": null, "e": 26399, "s": 26294, "text": "The following example contains a textbox with ContextMenu which manipulates the text within the textbox." }, { "code": null, "e": 26542, "s": 26399, "text": "The following XAML code creates a TextBox, a ContextMenu, and MenuItems with some properties and events such as Checked, Unchecked, and Click." }, { "code": null, "e": 27580, "s": 26542, "text": "<Window x:Class = \"XAMLContextMenu.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Grid> \n <TextBox Name = \"textBox1\" TextWrapping = \"Wrap\" Margin = \"10\" Grid.Row = \"7\"> \n Hi, this is XAML tutorial. \n <TextBox.ContextMenu>\n \n <ContextMenu>\n <MenuItem Header = \"_Bold\" IsCheckable = \"True\" \n Checked = \"Bold_Checked\" Unchecked = \"Bold_Unchecked\" /> \n <MenuItem Header = \"_Italic\" IsCheckable = \"True\" \n Checked = \"Italic_Checked\" Unchecked = \"Italic_Unchecked\" /> \n <Separator /> \n <MenuItem Header = \"Increase Font Size\" Click = \"IncreaseFont_Click\" />\n <MenuItem Header = \"_Decrease Font Size\" Click = \"DecreaseFont_Click\" /> \n </ContextMenu> \n\t\t\t\t\n </TextBox.ContextMenu>\n </TextBox>\n </Grid> \n\t\n</Window> " }, { "code": null, "e": 27714, "s": 27580, "text": "Here is the implementation in C# for the different events which will be fired whenever a menu item is checked, unchecked, or clicked." }, { "code": null, "e": 29021, "s": 27714, "text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \nusing System.Threading.Tasks; \nusing System.Windows; \nusing System.Windows.Controls; \nusing System.Windows.Data; \n\nnamespace XAMLContextMenu { \n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary>\n\t\n public partial class MainWindow : Window {\n public MainWindow() { \n InitializeComponent(); \n }\n private void Bold_Checked(object sender, RoutedEventArgs e) { \n textBox1.FontWeight = FontWeights.Bold; \n }\n private void Bold_Unchecked(object sender, RoutedEventArgs e) { \n textBox1.FontWeight = FontWeights.Normal; \n }\n private void Italic_Checked(object sender, RoutedEventArgs e) { \n textBox1.FontStyle = FontStyles.Italic; \n }\n private void Italic_Unchecked(object sender, RoutedEventArgs e) { \n textBox1.FontStyle = FontStyles.Normal; \n }\n private void IncreaseFont_Click(object sender, RoutedEventArgs e) { \n if (textBox1.FontSize < 18) { \n textBox1.FontSize += 2; \n } \n }\n private void DecreaseFont_Click(object sender, RoutedEventArgs e) { \n if (textBox1.FontSize > 10) { \n textBox1.FontSize -= 2; \n } \n }\n }\n}" }, { "code": null, "e": 29105, "s": 29021, "text": "When you compile and execute the above code, it will produce the following output −" }, { "code": null, "e": 29195, "s": 29105, "text": "We recommend you to execute the above example code and experiment with some other events." }, { "code": null, "e": 29203, "s": 29195, "text": "Checked" }, { "code": null, "e": 29271, "s": 29203, "text": "Fires when a ToggleButton is checked. (Inherited from ToggleButton)" }, { "code": null, "e": 29277, "s": 29271, "text": "Click" }, { "code": null, "e": 29346, "s": 29277, "text": "Occurs when a button control is clicked. (Inherited from ButtonBase)" }, { "code": null, "e": 29365, "s": 29346, "text": "ContextMenuClosing" }, { "code": null, "e": 29462, "s": 29365, "text": "Occurs just before any context menu on the element is closed. (Inherited from FrameworkElement.)" }, { "code": null, "e": 29481, "s": 29462, "text": "ContextMenuOpening" }, { "code": null, "e": 29571, "s": 29481, "text": "Occurs when any context menu on the element is opened. (Inherited from FrameworkElement.)" }, { "code": null, "e": 29590, "s": 29571, "text": "DataContextChanged" }, { "code": null, "e": 29700, "s": 29590, "text": "Occurs when the value of the FrameworkElement.DataContext property changes. (Inherited from FrameworkElement)" }, { "code": null, "e": 29710, "s": 29700, "text": "DragEnter" }, { "code": null, "e": 29833, "s": 29710, "text": "Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement)." }, { "code": null, "e": 29843, "s": 29833, "text": "DragLeave" }, { "code": null, "e": 29965, "s": 29843, "text": "Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement)" }, { "code": null, "e": 29974, "s": 29965, "text": "DragOver" }, { "code": null, "e": 30111, "s": 29974, "text": "Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement)" }, { "code": null, "e": 30124, "s": 30111, "text": "DragStarting" }, { "code": null, "e": 30194, "s": 30124, "text": "Occurs when a drag operation is initiated. (Inherited from UIElement)" }, { "code": null, "e": 30208, "s": 30194, "text": "DropCompleted" }, { "code": null, "e": 30283, "s": 30208, "text": "Occurs when a drag-and-drop operation is ended. (Inherited from UIElement)" }, { "code": null, "e": 30298, "s": 30283, "text": "DropDownClosed" }, { "code": null, "e": 30356, "s": 30298, "text": "Occurs when the drop-down portion of the ComboBox closes." }, { "code": null, "e": 30371, "s": 30356, "text": "DropDownOpened" }, { "code": null, "e": 30428, "s": 30371, "text": "Occurs when the drop-down portion of the ComboBox opens." }, { "code": null, "e": 30437, "s": 30428, "text": "GotFocus" }, { "code": null, "e": 30504, "s": 30437, "text": "Occurs when a UIElement receives focus. (Inherited from UIElement)" }, { "code": null, "e": 30512, "s": 30504, "text": "Holding" }, { "code": null, "e": 30638, "s": 30512, "text": "Occurs when an otherwise unhandled Hold interaction occurs over the hit test area of this element. (Inherited from UIElement)" }, { "code": null, "e": 30651, "s": 30638, "text": "Intermediate" }, { "code": null, "e": 30760, "s": 30651, "text": "Fires when the state of a ToggleButton is switched to the indeterminate state. (Inherited from ToggleButton)" }, { "code": null, "e": 30777, "s": 30760, "text": "IsEnabledChanged" }, { "code": null, "e": 30846, "s": 30777, "text": "Occurs when the IsEnabled property changes. (Inherited from Control)" }, { "code": null, "e": 30854, "s": 30846, "text": "KeyDown" }, { "code": null, "e": 30950, "s": 30854, "text": "Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement)" }, { "code": null, "e": 30956, "s": 30950, "text": "KeyUp" }, { "code": null, "e": 31053, "s": 30956, "text": "Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement)" }, { "code": null, "e": 31063, "s": 31053, "text": "LostFocus" }, { "code": null, "e": 31127, "s": 31063, "text": "Occurs when a UIElement loses focus. (Inherited from UIElement)" }, { "code": null, "e": 31149, "s": 31127, "text": "ManipulationCompleted" }, { "code": null, "e": 31233, "s": 31149, "text": "Occurs when a manipulation on the UIElement is complete. (Inherited from UIElement)" }, { "code": null, "e": 31251, "s": 31233, "text": "ManipulationDelta" }, { "code": null, "e": 31347, "s": 31251, "text": "Occurs when the input device changes position during a manipulation. (Inherited from UIElement)" }, { "code": null, "e": 31375, "s": 31347, "text": "ManipulationInertiaStarting" }, { "code": null, "e": 31513, "s": 31375, "text": "Occurs when the input device loses contact with the UIElement object during a manipulation and inertia begins. (Inherited from UIElement)" }, { "code": null, "e": 31533, "s": 31513, "text": "ManipulationStarted" }, { "code": null, "e": 31628, "s": 31533, "text": "Occurs when an input device begins a manipulation on the UIElement. (Inherited from UIElement)" }, { "code": null, "e": 31649, "s": 31628, "text": "ManipulationStarting" }, { "code": null, "e": 31733, "s": 31649, "text": "Occurs when the manipulation processor is first created. (Inherited from UIElement)" }, { "code": null, "e": 31750, "s": 31733, "text": "SelectionChanged" }, { "code": null, "e": 31794, "s": 31750, "text": "Occurs when the text selection has changed." }, { "code": null, "e": 31806, "s": 31794, "text": "SizeChanged" }, { "code": null, "e": 31941, "s": 31806, "text": "Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement. (Inherited from FrameworkElement)" }, { "code": null, "e": 31951, "s": 31941, "text": "Unchecked" }, { "code": null, "e": 32022, "s": 31951, "text": "Occurs when a ToggleButton is unchecked. (Inherited from ToggleButton)" }, { "code": null, "e": 32035, "s": 32022, "text": "ValueChanged" }, { "code": null, "e": 32099, "s": 32035, "text": "Occurs when the range value changes. (Inherited from RangeBase)" }, { "code": null, "e": 32365, "s": 32099, "text": "Data binding is a mechanism in XAML applications that provides a simple and easy way for Windows Runtime Apps using partial classes to display and interact with data. The management of data is entirely separated from the way the data is displayed in this mechanism." }, { "code": null, "e": 32752, "s": 32365, "text": "Data binding allows the flow of data between UI elements and data object on user interface. When a binding is established and the data or your business model changes, then it will reflect the updates automatically to the UI elements and vice versa. It is also possible to bind, not to a standard data source, but rather to another element on the page. Data binding can be of two types −" }, { "code": null, "e": 32773, "s": 32752, "text": "One-way data binding" }, { "code": null, "e": 32794, "s": 32773, "text": "Two-way data binding" }, { "code": null, "e": 32944, "s": 32794, "text": "In one-way binding, data is bound from its source (that is the object that holds the data) to its target (that is the object that displays the data)." }, { "code": null, "e": 33078, "s": 32944, "text": "Let’s have a look at a simple example of one-way data binding. The following XAML code creates four text blocks with some properties." }, { "code": null, "e": 33905, "s": 33078, "text": "<Window x:Class = \"DataBindingOneWay.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Grid>\n <StackPanel Name = \"Display\">\n <StackPanel Orientation = \"Horizontal\" Margin = \"50, 50, 0, 0\"> \n <TextBlock Text = \"Name: \" Margin = \"10\" Width = \"100\" /> \n <TextBlock Margin = \"10\" Width = \"100\" Text = \"{Binding Name}\" />\n </StackPanel> \n\t\t\n <StackPanel Orientation = \"Horizontal\" Margin = \"50,0,50,0\"> \n <TextBlock Text = \"Title: \" Margin = \"10\" Width = \"100\" /> \n <TextBlock Margin = \"10\" Width = \"100\" Text = \"{Binding Title}\" /> \n </StackPanel>\n </StackPanel>\n </Grid> \n\t\n</Window> " }, { "code": null, "e": 34128, "s": 33905, "text": "Text properties of two text blocks are set to “Name” and “Title” statically, while the other two text blocks Text properties are bound to “Name” and “Title” which are class variables of Employee class which is shown below." }, { "code": null, "e": 34578, "s": 34128, "text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \nusing System.Threading.Tasks; \n \nnamespace DataBindingOneWay {\n public class Employee {\n public string Name { get; set; } \n public string Title { get; set; } \n\t\t\n public static Employee GetEmployee() {\n var emp = new Employee() { \n Name = \"Ali Ahmed\", Title = \"Developer\" \n }; \n return emp; \n }\n }\n}" }, { "code": null, "e": 34968, "s": 34578, "text": "In this class, we have just two variables, Name and Title, and one static method in which the Employee object is initialized which will return that employee object. So we are binding to a property, Name and Title, but we have not selected what object that property belongs to. The easiest way is to assign an object to DataContext whose properties we are binding in the following C# code −" }, { "code": null, "e": 35329, "s": 34968, "text": "using System; \nusing System.Windows; \nusing System.Windows.Controls;\n\nnamespace DataBindingOneWay { \n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary> \n\t\n public partial class MainWindow : Window {\n public MainWindow() { \n InitializeComponent(); \n DataContext = Employee.GetEmployee(); \n } \n }\n}" }, { "code": null, "e": 35481, "s": 35329, "text": "Let's run this application and you can see immediately in our MainWindow that we have successfully bound to the Name and Title of that Employee object." }, { "code": null, "e": 35695, "s": 35481, "text": "In two-way binding, the user can modify the data through the user interface and have that data updated in the source. If the source changes while the user is looking at the view, you would want to update the view." }, { "code": null, "e": 35945, "s": 35695, "text": "Let’s have a look at the following example in which one combobox with three combobox items and one textbox are created with some properties. In this example, we don’t have any standard data source, but the UI elements are bound to other UI elements." }, { "code": null, "e": 36836, "s": 35945, "text": "<Window x:Class = \"XAMLTestBinding.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <StackPanel>\n <ComboBox Name = \"comboBox\" Margin = \"50\" Width = \"100\"> \n <ComboBoxItem Content = \"Green\" /> \n <ComboBoxItem Content = \"Yellow\" IsSelected = \"True\" /> \n <ComboBoxItem Content = \"Orange\" /> \n </ComboBox>\n\t\t\n <TextBox Name = \"textBox\" Margin = \"50\" \n Width = \"100\" Height = \"23\" VerticalAlignment = \"Top\" \n Text = \"{Binding ElementName = comboBox, Path = SelectedItem.Content, \n Mode = TwoWay, UpdateSourceTrigger = PropertyChanged}\" \n Background = \"{Binding ElementName = comboBox, Path = SelectedItem.Content}\"> \n </TextBox>\n </StackPanel> \n\t\n</Window> " }, { "code": null, "e": 37039, "s": 36836, "text": "When you compile and execute the above code, it will produce the following output. When the user selects an item from the combobox, the textbox text and the background color will be updated accordingly." }, { "code": null, "e": 37178, "s": 37039, "text": "Similarly, when the user types a valid color name in the textbox, then the combobox and the textbox background color will also be updated." }, { "code": null, "e": 37463, "s": 37178, "text": "In XAML applications, markup extensions are a method/technique to gain a value that is neither a specific XAML object nor a primitive type. Markup extensions can be defined by opening and closing curly braces and inside that curly braces, the scope of the markup extension is defined." }, { "code": null, "e": 37603, "s": 37463, "text": "Data binding and static resources are markup extensions. There are some predefined XAML markup extensions in System.xaml which can be used." }, { "code": null, "e": 37733, "s": 37603, "text": "Let’s have a look at a simple example where StaticResources markup extension is used which is a predefined XAML markup extension." }, { "code": null, "e": 37855, "s": 37733, "text": "The following XAML code creates two text blocks with some properties and their foreground is defined in Window.Resources." }, { "code": null, "e": 38588, "s": 37855, "text": "<Window x:Class = \"XAMLStaticResourcesMarkupExtension.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"525\"> \n\t\n <Window.Resources> \n <SolidColorBrush Color = \"Blue\" x:Key = \"myBrush\"></SolidColorBrush> \n </Window.Resources> \n\t\n <Grid> \n <StackPanel Orientation = \"Vertical\"> \n <TextBlock Foreground = \"{StaticResource myBrush}\" Text = \"First Name\" \n Width = \"100\" Margin = \"10\" /> \n <TextBlock Foreground = \"{StaticResource myBrush}\" Text = \"Last Name\" \n Width = \"100\" Margin = \"10\" /> \n </StackPanel> \n </Grid> \n\t\n</Window> " }, { "code": null, "e": 38785, "s": 38588, "text": "In Window.Resources, you can see x:Key is used which uniquely identifies the elements that are created and referenced in an XAML defined dictionary to identify a resource in a resource dictionary." }, { "code": null, "e": 38932, "s": 38785, "text": "When you compile and execute the above code, it will produce the following MainWindow. You can see the two text blocks with blue foreground color." }, { "code": null, "e": 39119, "s": 38932, "text": "In XAML, custom markup extensions can also be defined by inheriting MarkupExtension class and overriding the ProvideValue method which is an abstract method in the MarkupExtension class." }, { "code": null, "e": 39185, "s": 39119, "text": "Let’s have a look at a simple example of custom markup extension." }, { "code": null, "e": 39645, "s": 39185, "text": "<Window x:Class = \"XAMLMarkupExtension.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:my = \"clr-namespace:XAMLMarkupExtension\" \n Title = \"MainWindow\" Height = \"350\" Width = \"525\"> \n\t\n <Grid> \n <Button Content = \"{my:MyMarkupExtension FirstStr = Markup, SecondStr = Extension}\" \n Width = \"200\" Height = \"20\" /> \n </Grid> \n\t\n</Window>" }, { "code": null, "e": 39900, "s": 39645, "text": "In the above XAML code, a button is created with some properties and for the content value, a custom markup extension (my:MyMarkupExtension) has been used with two values “Markup” and “Extension” which are assigned to FirstStr and SecondStr respectively." }, { "code": null, "e": 40187, "s": 39900, "text": "Actually, MyMarkupExtension is a class which is derived from MarkupExtension as shown below in the C# implementation. This class contains two string variables, FirstStr and SecondStr, which are concatenated and return that string from the ProvideValue method to the Content of a button." }, { "code": null, "e": 41185, "s": 40187, "text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \nusing System.Threading.Tasks;\n \nusing System.Windows; \nusing System.Windows.Controls; \nusing System.Windows.Data; \nusing System.Windows.Documents; \nusing System.Windows.Input; \nusing System.Windows.Markup; \nusing System.Windows.Media; \nusing System.Windows.Media.Imaging; \nusing System.Windows.Navigation; \nusing System.Windows.Shapes; \n\nnamespace XAMLMarkupExtension { \n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary> \n\t\n public partial class MainWindow : Window { \n public MainWindow() { \n InitializeComponent(); \n } \n }\n public class MyMarkupExtension : MarkupExtension { \n public MyMarkupExtension() { } \n public String FirstStr { get; set; } \n public String SecondStr { get; set; } \n\t\t\n public override object ProvideValue(IServiceProvider serviceProvider) { \n return FirstStr + \" \" + SecondStr; \n } \n }\n}" }, { "code": null, "e": 41339, "s": 41185, "text": "Let's run this application and you can see immediately in our MainWindow that \"markup extension\" has been successfully used as the content of the button." }, { "code": null, "e": 41590, "s": 41339, "text": "A dependency property is a specific type of property where the value is followed by a keen property system which is also a part of the Windows Runtime App. A class which defines a dependency property must be inherited from the DependencyObject class." }, { "code": null, "e": 41786, "s": 41590, "text": "Many of the UI control classes which are used in XAML are derived from the DependencyObject class and support dependency properties. The following XAML code creates a button with some properties." }, { "code": null, "e": 42577, "s": 41786, "text": "<Window x:Class = \"XAMLDependencyProperty.MainWindow\"\n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:local = \"clr-namespace:XAMLDependencyProperty\"\n Title = \"MainWindow\" Height = \"350\" Width = \"604\">\n\t\n <Grid>\n <Button Height = \"40\" Width = \"175\" Margin = \"10\" Content = \"Dependency Property\">\n <Button.Style>\n <Style TargetType = \"{x:Type Button}\">\n <Style.Triggers> \n <Trigger Property = \"IsMouseOver\" Value = \"True\">\n <Setter Property = \"Foreground\" Value = \"Red\" />\n </Trigger>\n </Style.Triggers>\n </Style>\n </Button.Style>\n </Button>\n </Grid>\n \n</Window>" }, { "code": null, "e": 42783, "s": 42577, "text": "The x:Type markup extension in XAML has a similar functionality like typeof() in C#. It is used when attributes are specified that take the type of the object such as <Style TargetType = \"{x:Type Button}\">" }, { "code": null, "e": 43033, "s": 42783, "text": "When you compile and execute the above code, it will produce the following MainWindow. When the mouse is over the button, it will change the foreground color of the button. When the mouse leaves the button, it will change back to its original color." }, { "code": null, "e": 43114, "s": 43033, "text": "The main difference between dependency properties and other CLR properties are −" }, { "code": null, "e": 43286, "s": 43114, "text": "CLR properties can directly read/write from the private member of a class by using getter and setter. In case of dependency properties, it is not stored in a local object." }, { "code": null, "e": 43458, "s": 43286, "text": "CLR properties can directly read/write from the private member of a class by using getter and setter. In case of dependency properties, it is not stored in a local object." }, { "code": null, "e": 43575, "s": 43458, "text": "Dependency properties are stored in a dictionary of key/value pairs which is provided by the DependencyObject class." }, { "code": null, "e": 43692, "s": 43575, "text": "Dependency properties are stored in a dictionary of key/value pairs which is provided by the DependencyObject class." }, { "code": null, "e": 43767, "s": 43692, "text": "It also saves a lot of memory because it stores the property when changed." }, { "code": null, "e": 43842, "s": 43767, "text": "It also saves a lot of memory because it stores the property when changed." }, { "code": null, "e": 43875, "s": 43842, "text": "It can be bound in XAML as well." }, { "code": null, "e": 43908, "s": 43875, "text": "It can be bound in XAML as well." }, { "code": null, "e": 44040, "s": 43908, "text": "In .NET framework, custom dependency properties can also be defined. Here are the steps to define custom dependency property in C#." }, { "code": null, "e": 44113, "s": 44040, "text": "Declare and register your dependency property with system call register." }, { "code": null, "e": 44186, "s": 44113, "text": "Declare and register your dependency property with system call register." }, { "code": null, "e": 44234, "s": 44186, "text": "Provide the setter and getter for the property." }, { "code": null, "e": 44282, "s": 44234, "text": "Provide the setter and getter for the property." }, { "code": null, "e": 44349, "s": 44282, "text": "Define a static handler to handle any changes that occur globally." }, { "code": null, "e": 44416, "s": 44349, "text": "Define a static handler to handle any changes that occur globally." }, { "code": null, "e": 44505, "s": 44416, "text": "Define an instance handler to handle any changes that occur to that particular instance." }, { "code": null, "e": 44594, "s": 44505, "text": "Define an instance handler to handle any changes that occur to that particular instance." }, { "code": null, "e": 44711, "s": 44594, "text": "Given below is the code in C# for dependency property which defined to set the SetText property of the user control." }, { "code": null, "e": 46089, "s": 44711, "text": "using System; \nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Documents;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing System.Windows.Navigation;\nusing System.Windows.Shapes;\n\nnamespace WpfApplication3 {\n /// <summary> \n /// Interaction logic for UserControl1.xaml \n /// </summary> \n\t\n public partial class UserControl1 : UserControl {\n public UserControl1() {\n InitializeComponent();\n }\n public static readonly DependencyProperty\n SetTextProperty = DependencyProperty.Register(\"SetText\", typeof(string), \n typeof(UserControl1), new PropertyMetadata(\"\", \n new PropertyChangedCallback(OnSetTextChanged)));\n public string SetText {\n get {return(string) GetValue(SetTextProperty); }\n set {SetValue(SetTextProperty, value);}\n }\n private static void OnSetTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {\n UserControl1 UserControl1Control = d as UserControl1;\n UserControl1Control.OnSetTextChanged(e);\n }\n private void OnSetTextChanged(DependencyPropertyChangedEventArgs e) {\n tbTest.Text = e.NewValue.ToString();\n }\n }\n}" }, { "code": null, "e": 46244, "s": 46089, "text": "Here is the XAML file in which the TextBlock is defined as a user control and the Text property will be assigned to it by the SetText dependency property." }, { "code": null, "e": 46368, "s": 46244, "text": "The following XAML code creates a user control with initializing its SetText dependency property and some other properties." }, { "code": null, "e": 46739, "s": 46368, "text": "<Window x:Class = \"WpfApplication3.MainWindow\"\n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:views = \"clr-namespace:WpfApplication3\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\">\n\t\n <Grid>\n <views:UserControl1 SetText = \"Hellow World\" />\n </Grid>\n\t\n</Window>" }, { "code": null, "e": 46892, "s": 46739, "text": "Let's run this application and you can see immediately in our MainWindow that dependency property for user control has been successfully used as a Text." }, { "code": null, "e": 47129, "s": 46892, "text": "Resources are normally definitions connected with some object that you just anticipate to use more often than once. It has the ability to store data locally for controls or for the current window or globally for the entire applications." }, { "code": null, "e": 47494, "s": 47129, "text": "Defining an object as a resource allows us to access it from another place. Hence, it allows reusability. Resources are defined in resource dictionaries and any object can be defined as a resource effectively making it a shareable asset. A unique key is specified to XAML resource and with that key, it can be referenced by using a StaticResource markup extension." }, { "code": null, "e": 47655, "s": 47494, "text": "Let’s have a look at a simple example again in which two text blocks are created with some properties and their foreground color is defined in Window.Resources." }, { "code": null, "e": 48327, "s": 47655, "text": "<Window x:Class = \"XAMLResources.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Window.Resources> \n <SolidColorBrush Color = \"Blue\" x:Key = \"myBrush\"></SolidColorBrush> \n </Window.Resources> \n\t\n <StackPanel Orientation = \"Vertical\"> \n <TextBlock Foreground = \"{StaticResource myBrush}\" \n Text = \"First Name\" Width = \"100\" Margin = \"10\" /> \n <TextBlock Foreground = \"{StaticResource myBrush}\" \n Text = \"Last Name\" Width = \"100\" Margin = \"10\" /> \n </StackPanel> \n\t\n</Window> " }, { "code": null, "e": 48655, "s": 48327, "text": "When the above code is compiled and executed, it will produce the following MainWindow. You can see two text blocks with blue foreground color. The advantage of the resource is that if there are multiple text blocks and you want to change their background color, then you will need just to change it in the resource dictionary." }, { "code": null, "e": 49029, "s": 48655, "text": "Resources are defined in resource dictionaries, but there are numerous places where a resource dictionary can be defined. In the above example, a resource dictionary is defined on Window/page level. In what dictionary a resource is defined immediately limits the scope of that resource. So the scope, i.e. where you can use the resource, depends on where you've defined it." }, { "code": null, "e": 49151, "s": 49029, "text": "Define the resource in the resource dictionary of a grid and it's accessible by that grid and by its child elements only." }, { "code": null, "e": 49273, "s": 49151, "text": "Define the resource in the resource dictionary of a grid and it's accessible by that grid and by its child elements only." }, { "code": null, "e": 49357, "s": 49273, "text": "Define it on a window/page and it's accessible by all elements on that window/page." }, { "code": null, "e": 49441, "s": 49357, "text": "Define it on a window/page and it's accessible by all elements on that window/page." }, { "code": null, "e": 49605, "s": 49441, "text": "The App root can be found in App.xaml resources dictionary. It's the root of our application, so the resources defined here are scoped to the complete application." }, { "code": null, "e": 49769, "s": 49605, "text": "The App root can be found in App.xaml resources dictionary. It's the root of our application, so the resources defined here are scoped to the complete application." }, { "code": null, "e": 49928, "s": 49769, "text": "As far as the scope of the resource is concerned, the most often are application level, page level, and a specific element level like a Grid, StackPanel, etc." }, { "code": null, "e": 50123, "s": 49928, "text": "Resource dictionaries in XAML apps imply resource dictionaries in separate files. It is followed in almost all XAML apps. Defining resources in separate files can have the following advantages −" }, { "code": null, "e": 50209, "s": 50123, "text": "Separation between defining resources in the resource dictionary and UI related code." }, { "code": null, "e": 50295, "s": 50209, "text": "Separation between defining resources in the resource dictionary and UI related code." }, { "code": null, "e": 50400, "s": 50295, "text": "Defining all the resources in a separate file such as App.xaml would make them available across the App." }, { "code": null, "e": 50505, "s": 50400, "text": "Defining all the resources in a separate file such as App.xaml would make them available across the App." }, { "code": null, "e": 50691, "s": 50505, "text": "So, how we can define our resources in a resource dictionary in a separate file? Well, it is very easy, just add a new resource dictionary through Visual Studio by the following steps −" }, { "code": null, "e": 50760, "s": 50691, "text": "In your solution, add a new folder and name it ResourceDictionaries." }, { "code": null, "e": 50829, "s": 50760, "text": "In your solution, add a new folder and name it ResourceDictionaries." }, { "code": null, "e": 50946, "s": 50829, "text": "Right-click on this folder and select Resource Dictionary from Add submenu item and name it DictionaryWithBrush.xaml" }, { "code": null, "e": 51063, "s": 50946, "text": "Right-click on this folder and select Resource Dictionary from Add submenu item and name it DictionaryWithBrush.xaml" }, { "code": null, "e": 51164, "s": 51063, "text": "Let’s have a look at the same application; just the resource dictionary is now defined in App level." }, { "code": null, "e": 51207, "s": 51164, "text": "Here is the XAML code for MainWindow.xaml." }, { "code": null, "e": 51752, "s": 51207, "text": "<Window x:Class = \"XAMLResources.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <StackPanel Orientation = \"Vertical\"> \n <TextBlock Foreground = \"{StaticResource myBrush}\" Text = \"First Name\" \n Width = \"100\" Margin = \"10\" /> \n <TextBlock Foreground = \"{StaticResource myBrush}\" Text = \"Last Name\" \n Width = \"100\" Margin = \"10\"/> \n </StackPanel> \n\t\n</Window> " }, { "code": null, "e": 51809, "s": 51752, "text": "Here is the implementation in DictionaryWithBrush.xaml −" }, { "code": null, "e": 52064, "s": 51809, "text": "<ResourceDictionary \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\"> \n\t\n <SolidColorBrush Color = \"Blue\" x:Key = \"myBrush\"></SolidColorBrush> \n\t\n</ResourceDictionary> " }, { "code": null, "e": 52105, "s": 52064, "text": "Here is the implementation in app.xaml −" }, { "code": null, "e": 52496, "s": 52105, "text": "<Application x:Class = \"XAMLResources.App\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n StartupUri = \"MainWindow.xaml\"> \n\t\n <Application.Resources> \n <ResourceDictionary Source = \" XAMLResources\\ResourceDictionaries\\DictionaryWithBrush.xaml\" /> \n </Application.Resources> \n\t\n</Application>" }, { "code": null, "e": 52581, "s": 52496, "text": "When the above code is compiled and executed, it will produce the following output −" }, { "code": null, "e": 52695, "s": 52581, "text": "We recommend you to execute the above code and experiment with some more resources such as background color, etc." }, { "code": null, "e": 52878, "s": 52695, "text": "A template describes the overall look and visual appearance of a control. For each control, there is a default template associated with it which gives the appearance to that control." }, { "code": null, "e": 53088, "s": 52878, "text": "In XAML, you can easily create your own templates when you want to customize the visual behavior and visual appearance of a control. Connectivity between the logic and template can be achieved by data binding." }, { "code": null, "e": 53143, "s": 53088, "text": "The main difference between styles and templates are −" }, { "code": null, "e": 53238, "s": 53143, "text": "Styles can only change the appearance of your control with default properties of that control." }, { "code": null, "e": 53333, "s": 53238, "text": "Styles can only change the appearance of your control with default properties of that control." }, { "code": null, "e": 53470, "s": 53333, "text": "With templates, you can access more parts of a control than in styles. You can also specify both existing and new behavior of a control." }, { "code": null, "e": 53607, "s": 53470, "text": "With templates, you can access more parts of a control than in styles. You can also specify both existing and new behavior of a control." }, { "code": null, "e": 53670, "s": 53607, "text": "There are two types of templates which are most commonly used." }, { "code": null, "e": 53687, "s": 53670, "text": "Control Template" }, { "code": null, "e": 53701, "s": 53687, "text": "Data Template" }, { "code": null, "e": 54108, "s": 53701, "text": "The Control Template defines or specifies the visual appearance and structure of a control. All of the UI elements have some kind of appearance as well as behavior, e.g., Button has an appearance and behavior. Click event or mouse hover events are the behaviors which are fired in response to a click and hover, and there is also a default appearance of button which can be changed by the Control template." }, { "code": null, "e": 54274, "s": 54108, "text": "Let’s have a look at a simple example again in which two buttons are created with some properties. One is with template and the other one is with the default button." }, { "code": null, "e": 56530, "s": 54274, "text": "<Window x:Class = \"TemplateDemo.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Window.Resources>\n <ControlTemplate x:Key = \"ButtonTemplate\" TargetType = \"Button\">\n <Grid>\n <Ellipse x:Name = \"ButtonEllipse\" Height = \"100\" Width = \"150\" >\n <Ellipse.Fill> \n <LinearGradientBrush StartPoint = \"0,0.2\" EndPoint = \"0.2,1.4\"> \n <GradientStop Offset = \"0\" Color = \"Red\"/>\n <GradientStop Offset = \"1\" Color = \"Orange\"/>\n </LinearGradientBrush> \n </Ellipse.Fill>\n </Ellipse>\n <ContentPresenter Content = \"{TemplateBinding Content}\"\n HorizontalAlignment = \"Center\" VerticalAlignment = \"Center\" />\n </Grid>\n <ControlTemplate.Triggers> \n <Trigger Property = \"IsMouseOver\" Value = \"True\">\n <Setter TargetName = \"ButtonEllipse\" Property = \"Fill\" >\n <Setter.Value> \n <LinearGradientBrush StartPoint = \"0,0.2\" EndPoint=\"0.2,1.4\"> \n <GradientStop Offset = \"0\" Color = \"YellowGreen\"/>\n <GradientStop Offset = \"1\" Color = \"Gold\"/>\n </LinearGradientBrush> \n </Setter.Value> \n </Setter>\n </Trigger> \n\t\t\t\t\n <Trigger Property = \"IsPressed\" Value = \"True\"> \n <Setter Property = \"RenderTransform\"> \n <Setter.Value> \n <ScaleTransform ScaleX = \"0.8\" ScaleY = \"0.8\" CenterX = \"0\" CenterY = \"0\" /> \n </Setter.Value> \n </Setter> \n\t\t\t\t\t\n <Setter Property = \"RenderTransformOrigin\" Value = \"0.5,0.5\" /> \n </Trigger>\n </ControlTemplate.Triggers>\n </ControlTemplate> \n </Window.Resources>\n\t\n <StackPanel> \n <Button Content = \"Round Button!\" Template = \"{StaticResource ButtonTemplate}\" \n Width = \"150\" Margin = \"50\" />\n <Button Content = \"Default Button!\" Height = \"40\" Width = \"150\" Margin = \"5\" /> \n </StackPanel> \n\t\n</Window>" }, { "code": null, "e": 56619, "s": 56530, "text": "When the above code is compiled and executed, it will produce the following MainWindow −" }, { "code": null, "e": 56730, "s": 56619, "text": "When you hover the mouse over the button with custom template, then it also changes the color as shown below −" }, { "code": null, "e": 57001, "s": 56730, "text": "A Data Template defines and specifies the appearance and structure of the collection of data. It provides the flexibility to format and define the presentation of the data on any UI element. It is mostly used on data related Item controls such as ComboBox, ListBox, etc." }, { "code": null, "e": 57136, "s": 57001, "text": "Let’s have a look at a simple example of data template. The following XAML code creates a combobox with Data Template and text blocks." }, { "code": null, "e": 58181, "s": 57136, "text": "<Window x:Class = \"XAMLDataTemplate.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Grid VerticalAlignment = \"Top\">\n <ComboBox Name = \"Presidents\" ItemsSource = \"{Binding}\" Height = \"30\" Width = \"400\"> \n <ComboBox.ItemTemplate> \n <DataTemplate>\n <StackPanel Orientation = \"Horizontal\" Margin = \"2\">\n <TextBlock Text = \"Name: \" Width = \"95\" Background = \"Aqua\" Margin = \"2\" /> \n <TextBlock Text = \"{Binding Name}\" Width = \"95\" Background = \"AliceBlue\" Margin = \"2\" /> \n <TextBlock Text = \"Title: \" Width = \"95\" Background = \"Aqua\" Margin = \"10,2,0,2\" />\n <TextBlock Text = \"{Binding Title}\" Width = \"95\" Background = \"AliceBlue\" Margin = \"2\" /> \n </StackPanel>\n </DataTemplate>\n </ComboBox.ItemTemplate> \n </ComboBox> \n </Grid>\n \n</Window>" }, { "code": null, "e": 58272, "s": 58181, "text": "Here is the implementation in C# in which the employee object is assigned to DataContext −" }, { "code": null, "e": 58631, "s": 58272, "text": "using System; \nusing System.Windows; \nusing System.Windows.Controls;\n\nnamespace XAMLDataTemplate { \n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary> \n\t\n public partial class MainWindow : Window {\n public MainWindow() {\n InitializeComponent(); \n DataContext = Employee.GetEmployees(); \n }\n }\n}" }, { "code": null, "e": 58685, "s": 58631, "text": "Here is the implementation in C# for Employee class −" }, { "code": null, "e": 60385, "s": 58685, "text": "using System; \nusing System.Collections.Generic; \nusing System.Collections.ObjectModel; \nusing System.ComponentModel; \nusing System.Linq; \nusing System.Runtime.CompilerServices; \nusing System.Text; \nusing System.Threading.Tasks;\n\nnamespace XAMLDataTemplate { \n public class Employee : INotifyPropertyChanged {\n private string name; public string Name {\n get { return name; } \n set { name = value; RaiseProperChanged(); } \n }\n private string title; public string Title { \n get { return title; } \n set { title = value; RaiseProperChanged(); } \n }\n public static Employee GetEmployee() {\n var emp = new Employee() { \n Name = \"Waqas\", Title = \"Software Engineer\" };\n return emp; \n }\n public event PropertyChangedEventHandler PropertyChanged;\n private void RaiseProperChanged( [CallerMemberName] string caller = \"\"){\n if (PropertyChanged != null) { \n PropertyChanged(this, new PropertyChangedEventArgs(caller)); \n } \n }\n public static ObservableCollection<Employee> GetEmployees() {\n var employees = new ObservableCollection<Employee>();\n employees.Add(new Employee() { Name = \"Ali\", Title = \"Developer\" }); \n employees.Add(new Employee() { Name = \"Ahmed\", Title = \"Programmer\" });\n employees.Add(new Employee() { Name = \"Amjad\", Title = \"Desiner\" });\n employees.Add(new Employee() { Name = \"Waqas\", Title = \"Programmer\" }); \n employees.Add(new Employee() { Name = \"Bilal\", Title = \"Engineer\" });\n employees.Add(new Employee() { Name = \"Waqar\", Title = \"Manager\" }); \n return employees; \n }\n }\n}" }, { "code": null, "e": 60637, "s": 60385, "text": "When the above code is compiled and executed, it will produce the following output. It contains a combobox and when you click on the combobox, you see that the collection of data which are created in the Employee class is listed as the combobox items." }, { "code": null, "e": 60704, "s": 60637, "text": "We recommend you to execute the above code and experiment with it." }, { "code": null, "e": 60958, "s": 60704, "text": "XAML framework provides several strategies to personalize and customize the appearance of an application. Styles give us the flexibility to set some properties of an object and reuse these specific settings across multiple objects for a consistent look." }, { "code": null, "e": 61061, "s": 60958, "text": "In styles, you can set only the existing properties of an object such as Height, Width, and Font size." }, { "code": null, "e": 61164, "s": 61061, "text": "In styles, you can set only the existing properties of an object such as Height, Width, and Font size." }, { "code": null, "e": 61217, "s": 61164, "text": "Only default behavior of a control can be specified." }, { "code": null, "e": 61270, "s": 61217, "text": "Only default behavior of a control can be specified." }, { "code": null, "e": 61324, "s": 61270, "text": "Multiple properties can be added into a single style." }, { "code": null, "e": 61378, "s": 61324, "text": "Multiple properties can be added into a single style." }, { "code": null, "e": 61549, "s": 61378, "text": "Styles are used to give a uniform look to a set of controls. Implicit Styles are used to apply an appearance to all controls of a given type and simplify the application." }, { "code": null, "e": 61837, "s": 61549, "text": "Imagine we have three buttons and all of them have to look the same − same width and height, same font size, and same foreground color. We can set all those properties on the button elements themselves and that's still quite okay for all of the buttons as shown in the following diagram." }, { "code": null, "e": 62295, "s": 61837, "text": "But in a real-life App, you'll typically have a lot more of these that need to look exactly the same. And not only buttons of course, you'll typically want your text blocks, text boxes, and combo boxes, etc., to look the same across your App. Surely there must be a better way to achieve this − it is known as styling. You can think of a style as a convenient way to apply a set of property values to more than one element as shown in the following diagram." }, { "code": null, "e": 62403, "s": 62295, "text": "Let’s have look at the example which contains three buttons which are created in XAML with some properties." }, { "code": null, "e": 63271, "s": 62403, "text": "<Window x:Class = \"XAMLStyle.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\"\n xmlns:local = \"clr-namespace:XAMLStyle\" mc:Ignorable = \"d\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <StackPanel> \n <Button Content = \"Button1\" Height = \"30\" Width = \"80\" Foreground = \"Blue\" \n FontSize = \"12\" Margin = \"10\"/>\n \n <Button Content = \"Button2\" Height = \"30\" Width = \"80\" Foreground = \"Blue\" \n FontSize = \"12\" Margin = \"10\"/>\n \n <Button Content = \"Button3\" Height = \"30\" Width = \"80\" Foreground = \"Blue\" \n FontSize = \"12\" Margin = \"10\"/> \n </StackPanel> \n\t\n</Window>" }, { "code": null, "e": 63507, "s": 63271, "text": "When you look at the above code, you will see that for all the buttons, height, width, foreground color, font size, and margin properties remain same. When the above code is compiled and executed, it will display the following output −" }, { "code": null, "e": 63589, "s": 63507, "text": "Now let’s have a look at the same example, but this time, we will be using style." }, { "code": null, "e": 64698, "s": 63589, "text": "<Window x:Class = \"XAMLStyle.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\"\n xmlns:local = \"clr-namespace:XAMLStyle\" mc:Ignorable = \"d\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\">\n\t\n <Window.Resources> \n <Style x:Key = \"myButtonStyle\" TargetType = \"Button\">\n <Setter Property = \"Height\" Value = \"30\"/> \n <Setter Property = \"Width\" Value = \"80\"/> \n <Setter Property = \"Foreground\" Value = \"Blue\"/> \n <Setter Property = \"FontSize\" Value = \"12\"/> \n <Setter Property = \"Margin\" Value = \"10\"/> \n </Style>\n </Window.Resources> \n\t\n <StackPanel> \n <Button Content = \"Button1\" Style = \"{StaticResource myButtonStyle}\"/>\n <Button Content = \"Button2\" Style = \"{StaticResource myButtonStyle}\"/>\n <Button Content = \"Button3\" Style = \"{StaticResource myButtonStyle}\"/>\n </StackPanel>\n\t\n</Window>" }, { "code": null, "e": 64927, "s": 64698, "text": "Styles are defined in the resource dictionary and each style has a unique key identifier and a target type. Inside <style>, you can see that multiple setter tags are defined for each property which will be included in the style." }, { "code": null, "e": 65158, "s": 64927, "text": "In the above example, all of the common properties of each button are now defined in style and then the style are assigned to each button with a unique key by setting the style property through the StaticResource markup extension." }, { "code": null, "e": 65267, "s": 65158, "text": "When the above code is compiled and executed, it will produce the following window which is the same output." }, { "code": null, "e": 65480, "s": 65267, "text": "The advantage of doing it like this is immediately obvious. We can reuse that style anywhere in its scope, and if we need to change it, we simply change it once in the style definition instead of on each element." }, { "code": null, "e": 65692, "s": 65480, "text": "In what level a style is defined instantaneously limits the scope of that style. So the scope, i.e. where you can use the style, depends on where you've defined it. Style can be defined on the following levels −" }, { "code": null, "e": 65774, "s": 65692, "text": "Defining a style on control level can only be applied to that particular control." }, { "code": null, "e": 65881, "s": 65774, "text": "Defining a style on any layout level can only be accessible by that layout and by its child elements only." }, { "code": null, "e": 65971, "s": 65881, "text": "Defining a style on a window level can be accessible by all the elements on that window. " }, { "code": null, "e": 66044, "s": 65971, "text": "Defining a style on App level makes it accessible in entire application." }, { "code": null, "e": 66286, "s": 66044, "text": "Basically, a trigger enables you to change property values or take actions based on the value of a property. So, it basically allows you to dynamically change the appearance and/or behavior of your control without having to create a new one." }, { "code": null, "e": 66535, "s": 66286, "text": "Triggers are used to change the value of any given property, when certain conditions are satisfied. Triggers are usually defined in a style or in the root of a document which are applied to that specific control. There are three types of triggers −" }, { "code": null, "e": 66553, "s": 66535, "text": "Property Triggers" }, { "code": null, "e": 66567, "s": 66553, "text": "Data Triggers" }, { "code": null, "e": 66582, "s": 66567, "text": "Event Triggers" }, { "code": null, "e": 66842, "s": 66582, "text": "In property triggers, when a change occurs in one property, it will bring either an immediate or an animated change in another property. For example, you can use a property trigger if you want to change the button appearance when the mouse is over the button." }, { "code": null, "e": 66958, "s": 66842, "text": "The following example demonstrates how to change the foreground color of a button when the mouse enters its region." }, { "code": null, "e": 67731, "s": 66958, "text": "<Window x:Class = \"XAMLPropertyTriggers.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\">\n\t\n <Window.Resources>\n <Style x:Key = \"TriggerStyle\" TargetType = \"Button\">\n <Setter Property = \"Foreground\" Value = \"Blue\" />\n <Style.Triggers>\n <Trigger Property = \"IsMouseOver\" Value = \"True\">\n <Setter Property = \"Foreground\" Value = \"Green\" />\n </Trigger> \n </Style.Triggers>\n </Style>\n </Window.Resources>\n\t\n <Grid>\n <Button Width = \"100\" Height = \"70\" Style = \"{StaticResource TriggerStyle}\" \n Content = \"Trigger\"/>\n </Grid>\n\t\n</Window>" }, { "code": null, "e": 67815, "s": 67731, "text": "When you compile and execute the above code, it will produce the following output −" }, { "code": null, "e": 67902, "s": 67815, "text": "When the mouse enters the region of button, the foreground color will change to green." }, { "code": null, "e": 68174, "s": 67902, "text": "A data trigger performs some action when the bound data satisfies some condition. Let’s have a look at the following XAML code in which a checkbox and a text block are created with some properties. When the checkbox is checked, it will change the foreground color to red." }, { "code": null, "e": 69230, "s": 68174, "text": "<Window x:Class = \"XAMLDataTrigger.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"Data Trigger\" Height = \"350\" Width = \"604\">\n\t\n <StackPanel HorizontalAlignment = \"Center\">\n <CheckBox x:Name = \"redColorCheckBox\" Content = \"Set red as foreground color\" Margin = \"20\"/>\n\t\t\n <TextBlock Name = \"txtblock\" VerticalAlignment = \"Center\" \n Text = \"Event Trigger\" FontSize = \"24\" Margin = \"20\">\n <TextBlock.Style>\n <Style>\n <Style.Triggers>\n <DataTrigger Binding = \"{Binding ElementName = redColorCheckBox, Path = IsChecked}\" \n Value = \"true\">\n <Setter Property = \"TextBlock.Foreground\" Value = \"Red\"/>\n <Setter Property = \"TextBlock.Cursor\" Value = \"Hand\" />\n </DataTrigger>\n </Style.Triggers>\n </Style>\n </TextBlock.Style>\n </TextBlock>\n </StackPanel>\n\t\n</Window>\t\t" }, { "code": null, "e": 69314, "s": 69230, "text": "When you compile and execute the above code, it will produce the following output −" }, { "code": null, "e": 69403, "s": 69314, "text": "When the checkbox is checked, the foreground color of the text block will change to red." }, { "code": null, "e": 69696, "s": 69403, "text": "An event trigger performs some action when a specific event is fired. It is usually used to accomplish some animation such DoubleAnimation, ColorAnimation, etc. The following code block creates a simple button. When the click event is fired, it will expand the width and height of the button." }, { "code": null, "e": 71435, "s": 69696, "text": "<Window x:Class = \"XAMLEventTrigger.MainWindow\"\n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\">\n\t\n <Grid>\n <Button Content = \"Click Me\" Width = \"60\" Height = \"30\">\n <Button.Triggers>\n <EventTrigger RoutedEvent = \"Button.Click\">\n <EventTrigger.Actions>\n <BeginStoryboard>\n <Storyboard>\n \n <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty = \"Width\" Duration = \"0:0:4\">\n <LinearDoubleKeyFrame Value = \"60\" KeyTime = \"0:0:0\"/>\n <LinearDoubleKeyFrame Value = \"120\" KeyTime = \"0:0:1\"/>\n <LinearDoubleKeyFrame Value = \"200\" KeyTime = \"0:0:2\"/>\n <LinearDoubleKeyFrame Value = \"300\" KeyTime = \"0:0:3\"/>\n </DoubleAnimationUsingKeyFrames>\n\t\t\t\t\t\t\t\n <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty = \"Height\" Duration = \"0:0:4\">\n <LinearDoubleKeyFrame Value = \"30\" KeyTime = \"0:0:0\"/>\n <LinearDoubleKeyFrame Value = \"40\" KeyTime = \"0:0:1\"/>\n <LinearDoubleKeyFrame Value = \"80\" KeyTime = \"0:0:2\"/>\n <LinearDoubleKeyFrame Value = \"150\" KeyTime = \"0:0:3\"/>\n </DoubleAnimationUsingKeyFrames>\n\t\t\t\t\t\t\t\n </Storyboard>\n </BeginStoryboard>\n </EventTrigger.Actions>\n </EventTrigger>\n </Button.Triggers>\n </Button>\n </Grid>\n</Window>" }, { "code": null, "e": 71519, "s": 71435, "text": "When you compile and execute the above code, it will produce the following output −" }, { "code": null, "e": 71614, "s": 71519, "text": "Now, click on the button and you will observe that it will start expanding in both dimensions." }, { "code": null, "e": 71992, "s": 71614, "text": "If you are familiar with debugging in any procedural language (such as C#, C/C++ etc.) and you know the usage of break and are expecting the same kind of debugging in XAML, then you will be surprised to know that it is not possible yet to debug an XAML code like the way you used to debug any other procedural language code. Debugging an XAML app means trying to find an error;" }, { "code": null, "e": 72068, "s": 71992, "text": "In data binding, your data doesn't show up on screen and you don't know why" }, { "code": null, "e": 72144, "s": 72068, "text": "In data binding, your data doesn't show up on screen and you don't know why" }, { "code": null, "e": 72187, "s": 72144, "text": "Or an issue is related to complex layouts." }, { "code": null, "e": 72230, "s": 72187, "text": "Or an issue is related to complex layouts." }, { "code": null, "e": 72352, "s": 72230, "text": "Or an alignment issue or issues in margin color, overlays, etc. with some extensive templates like ListBox and combo box." }, { "code": null, "e": 72474, "s": 72352, "text": "Or an alignment issue or issues in margin color, overlays, etc. with some extensive templates like ListBox and combo box." }, { "code": null, "e": 72845, "s": 72474, "text": "Debugging in XAML is something you typically do to check if your bindings work, and if it is not working, then to check what's wrong. Unfortunately, setting breakpoints in XAML bindings isn't possible except in Silverlight, but we can use the Output window to check for data binding errors. Let's have a look at the following XAML code to find the error in data binding." }, { "code": null, "e": 73663, "s": 72845, "text": "<Window x:Class = \"DataBindingOneWay.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\">\n\t\n <Grid>\n <StackPanel Name = \"Display\">\n <StackPanel Orientation = \"Horizontal\" Margin = \"50, 50, 0, 0\">\n <TextBlock Text = \"Name: \" Margin = \"10\" Width = \"100\"/>\n <TextBlock Margin = \"10\" Width = \"100\" Text = \"{Binding FirstName}\"/>\n </StackPanel>\n\t\t\t\n <StackPanel Orientation = \"Horizontal\" Margin = \"50,0,50,0\">\n <TextBlock Text = \"Title: \" Margin = \"10\" Width = \"100\"/>\n <TextBlock Margin = \"10\" Width=\"100\" Text = \"{Binding Title}\" />\n </StackPanel>\n </StackPanel>\n </Grid>\n\t\n</Window>" }, { "code": null, "e": 74061, "s": 73663, "text": "Text properties of the two text blocks are set to “Name” and “Title” statically, while the other two text block’s Text properties are bound to “FirstName” and “Title”. But the class variables are intentionally taken as Name and Title in the Employee class which are incorrect variable names. Let us now try to understand where we can find this type of mistake when the desired output is not shown." }, { "code": null, "e": 74517, "s": 74061, "text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \nusing System.Threading.Tasks;\n\nnamespace DataBindingOneWay {\n public class Employee {\n public string Name { get; set; } \n public string Title { get; set; }\n\t\t\n public static Employee GetEmployee() {\n var emp = new Employee() {\n Name = \"Ali Ahmed\", \n Title = \"Developer\"\n };\n return emp; \n }\n }\n}" }, { "code": null, "e": 74577, "s": 74517, "text": "Here is the implementation of MainWindow class in C# code −" }, { "code": null, "e": 74935, "s": 74577, "text": "using System; \nusing System.Windows; \nusing System.Windows.Controls;\n\nnamespace DataBindingOneWay {\n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary> \n\t\n public partial class MainWindow : Window {\n public MainWindow() {\n InitializeComponent(); \n DataContext = Employee.GetEmployee(); \n }\n }\n}" }, { "code": null, "e": 75104, "s": 74935, "text": "Let's run this application and you can see immediately in our MainWindow that we have successfully bound to the Title of that Employee object but the name is not bound." }, { "code": null, "e": 75207, "s": 75104, "text": "To check what happened with the name, let’s look at the output window where a lot of log is generated." }, { "code": null, "e": 75408, "s": 75207, "text": "The easiest way to find an error is to just search for error and you will find the below mentioned error which says “BindingExpression path error: 'FirstName' property not found on 'object' ''Employe”" }, { "code": null, "e": 75720, "s": 75408, "text": "System.Windows.Data Error: 40 : BindingExpression path error: 'FirstName'\n property not found on 'object' ''Employee' (HashCode = 11611730)'.\nBindingExpression:Path = FirstName; \nDataItem = 'Employee' (HashCode = 11611730); target element is 'TextBlock' (Name = ''); \ntarget property is 'Text' (type 'String')" }, { "code": null, "e": 75853, "s": 75720, "text": "Which clearly indicate that FirstName is not a member of Employee class, so it helps to fix this type of issues in your application." }, { "code": null, "e": 75931, "s": 75853, "text": "When you change the FirstName to Name again, you will see the desired output." }, { "code": null, "e": 76256, "s": 75931, "text": "UI debugging tools for XAML are introduced with Visual Studio 2015 to inspect the XAML code at runtime. With the help of these tools, XAML code is presented in the form of visual tree of your running WPF application and also the different UI element properties in the tree. To enable this tool, follow the steps given below." }, { "code": null, "e": 76326, "s": 76256, "text": "Step 1 − Go to the Tools menu and select Options from the Tools menu." }, { "code": null, "e": 76396, "s": 76326, "text": "Step 1 − Go to the Tools menu and select Options from the Tools menu." }, { "code": null, "e": 76451, "s": 76396, "text": "Step 2 − You will get to see the following dialog box." }, { "code": null, "e": 76506, "s": 76451, "text": "Step 2 − You will get to see the following dialog box." }, { "code": null, "e": 76580, "s": 76506, "text": "Step 3 − Go to the General Options under Debugging item on the left side." }, { "code": null, "e": 76654, "s": 76580, "text": "Step 3 − Go to the General Options under Debugging item on the left side." }, { "code": null, "e": 76735, "s": 76654, "text": "Step 4 − Check the highlighted option, i.e, “Enable UI Debugging Tools for XAML”" }, { "code": null, "e": 76816, "s": 76735, "text": "Step 4 − Check the highlighted option, i.e, “Enable UI Debugging Tools for XAML”" }, { "code": null, "e": 76846, "s": 76816, "text": "Step 5 − Press the OK button." }, { "code": null, "e": 76876, "s": 76846, "text": "Step 5 − Press the OK button." }, { "code": null, "e": 76938, "s": 76876, "text": "Now run any XAML application or use the following XAML code −" }, { "code": null, "e": 77816, "s": 76938, "text": "<Window x:Class = \"XAMLTestBinding.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\">\n\t\n <StackPanel>\n <ComboBox Name = \"comboBox\" Margin = \"50\" Width = \"100\">\n <ComboBoxItem Content = \"Green\"/>\n <ComboBoxItem Content = \"Yellow\" IsSelected = \"True\"/>\n <ComboBoxItem Content = \"Orange\" />\n </ComboBox>\n\t\t\n <TextBox Name = \"textBox\" Margin = \"50\" Width = \"100\" \n Height = \"23\" VerticalAlignment = \"Top\" Text = \"{\n Binding ElementName = comboBox, Path = SelectedItem.Content, \n Mode = TwoWay, UpdateSourceTrigger = PropertyChanged}\" \n Background = \"{Binding ElementName = comboBox, Path = SelectedItem.Content}\"> \n </TextBox>\n </StackPanel>\n\t\n</Window>" }, { "code": null, "e": 77925, "s": 77816, "text": "When the application executes, it will show the Live Visual Tree where all the elements are shown in a tree." }, { "code": null, "e": 78424, "s": 77925, "text": "This Live Visual Tree shows the complete layout structure to understand where the UI elements are placed. But this option is only available in Visual Studio 2015. If you are using an older version of Visual studio, then you can’t use this tool; however there is another tool which can be integrated with Visual Studio such as XAML Spy for Visual Studio. You can download it from http://xamlspy.com/download. We recommend you to download this tool if you are using an older version of Visual Studio." }, { "code": null, "e": 78736, "s": 78424, "text": "XAML has one of the most powerful features provided to create custom controls which make it very easy to create feature-rich and customizable controls. Custom controls are used when all the built-in controls provided by Microsoft are not fulfilling your criteria or you don’t want to pay for 3rd party controls." }, { "code": null, "e": 78898, "s": 78736, "text": "In this chapter, you will learn how to create custom controls. Before we start taking a look at Custom Controls, let's take a quick look at a User Control first." }, { "code": null, "e": 79082, "s": 78898, "text": "User Controls provide a technique to collect and combine different built-in controls together and package them into re-usable XAML. User controls are used in the following scenarios −" }, { "code": null, "e": 79206, "s": 79082, "text": "If the control consists of existing controls, i.e., you can create a single control of multiple, already existing controls." }, { "code": null, "e": 79330, "s": 79206, "text": "If the control consists of existing controls, i.e., you can create a single control of multiple, already existing controls." }, { "code": null, "e": 79477, "s": 79330, "text": "If the control don't need support for theming. User Controls do not support complex customization, control templates, and also difficult to style." }, { "code": null, "e": 79624, "s": 79477, "text": "If the control don't need support for theming. User Controls do not support complex customization, control templates, and also difficult to style." }, { "code": null, "e": 79767, "s": 79624, "text": "If a developer prefers to write controls using the code-behind model where a view and then a direct code is written behind for event handlers." }, { "code": null, "e": 79910, "s": 79767, "text": "If a developer prefers to write controls using the code-behind model where a view and then a direct code is written behind for event handlers." }, { "code": null, "e": 79965, "s": 79910, "text": "You won't be sharing your control across applications." }, { "code": null, "e": 80020, "s": 79965, "text": "You won't be sharing your control across applications." }, { "code": null, "e": 80093, "s": 80020, "text": "Let’s take an example of User control and follow the steps given below −" }, { "code": null, "e": 80194, "s": 80093, "text": "Step 1 − Create a new WPF project and then right-click on your solution and select Add > New Item..." }, { "code": null, "e": 80295, "s": 80194, "text": "Step 1 − Create a new WPF project and then right-click on your solution and select Add > New Item..." }, { "code": null, "e": 80393, "s": 80295, "text": "Step 2 − The following dialog will open, now select User Control (WPF) and name it MyUserControl." }, { "code": null, "e": 80491, "s": 80393, "text": "Step 2 − The following dialog will open, now select User Control (WPF) and name it MyUserControl." }, { "code": null, "e": 80634, "s": 80491, "text": "Step 3 − Click on the Add button and you will see that two new files (MyUserControl.xaml and MyUserControl.cs) will be added in your solution." }, { "code": null, "e": 80777, "s": 80634, "text": "Step 3 − Click on the Add button and you will see that two new files (MyUserControl.xaml and MyUserControl.cs) will be added in your solution." }, { "code": null, "e": 80898, "s": 80777, "text": "Given below is the XAML code in which a button and a textbox is created with some properties in MyUserControl.xaml file." }, { "code": null, "e": 81684, "s": 80898, "text": "<UserControl x:Class = \"XAMLUserControl.MyUserControl\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\"\n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\"\n mc:Ignorable = \"d\" d:DesignHeight = \"300\" d:DesignWidth = \"300\">\n\t\n <Grid>\n <TextBox Height = \"23\" HorizontalAlignment = \"Left\" \n Margin = \"80,49,0,0\" Name = \"txtBox\" VerticalAlignment = \"Top\" Width = \"200\" />\n <Button Content = \"Click Me\" Height = \"23\" \n HorizontalAlignment = \"Left\" Margin = \"96,88,0,0\" Name = \"button\" \n VerticalAlignment = \"Top\" Width = \"75\" Click = \"button_Click\" />\n </Grid>\n\t\n</UserControl>" }, { "code": null, "e": 81786, "s": 81684, "text": "Given below is the C# code for button click event in MyUserControl.cs file which updates the textbox." }, { "code": null, "e": 82245, "s": 81786, "text": "using System; \nusing System.Windows; \nusing System.Windows.Controls;\n\nnamespace XAMLUserControl {\n /// <summary> \n /// Interaction logic for MyUserControl.xaml\n /// </summary> \n\t\n public partial class MyUserControl : UserControl {\n public MyUserControl() {\n InitializeComponent(); \n }\n private void button_Click(object sender, RoutedEventArgs e) { \n txtBox.Text = \"You have just clicked the button\"; \n } \n }\n}" }, { "code": null, "e": 82312, "s": 82245, "text": "Here is implementation in MainWindow.xaml to add the user control." }, { "code": null, "e": 82663, "s": 82312, "text": "<Window x:Class = \"XAMLUserControl.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:control = \"clr-namespace:XAMLUserControl\" \n Title = \"MainWindow\" Height = \"350\" Width = \"525\">\n\t\n <Grid>\n <control:MyUserControl/>\n </Grid>\n\t\n</Window>" }, { "code": null, "e": 82747, "s": 82663, "text": "When you compile and execute the above code, it will produce the following output −" }, { "code": null, "e": 82833, "s": 82747, "text": "Now click on the \"Click Me\" button and you will see that the textbox text is updated." }, { "code": null, "e": 82994, "s": 82833, "text": "A custom control is a class which offers its own style and template which are normally defined in generic.xaml. Custom controls are used in following scenarios," }, { "code": null, "e": 83063, "s": 82994, "text": "If the control doesn't exist and you have to create it from scratch." }, { "code": null, "e": 83132, "s": 83063, "text": "If the control doesn't exist and you have to create it from scratch." }, { "code": null, "e": 83285, "s": 83132, "text": "If you want to extend or add functionality to a preexisting control by adding an extra property or an extra functionality to fit your specific scenario." }, { "code": null, "e": 83438, "s": 83285, "text": "If you want to extend or add functionality to a preexisting control by adding an extra property or an extra functionality to fit your specific scenario." }, { "code": null, "e": 83492, "s": 83438, "text": "If your controls need to support theming and styling." }, { "code": null, "e": 83546, "s": 83492, "text": "If your controls need to support theming and styling." }, { "code": null, "e": 83600, "s": 83546, "text": "If you want to share you control across applications." }, { "code": null, "e": 83654, "s": 83600, "text": "If you want to share you control across applications." }, { "code": null, "e": 83728, "s": 83654, "text": "Let’s take an example of custom control and follow the steps given below." }, { "code": null, "e": 83829, "s": 83728, "text": "Step 1 − Create a new WPF project and then right-click on your solution and select Add > New Item..." }, { "code": null, "e": 83930, "s": 83829, "text": "Step 1 − Create a new WPF project and then right-click on your solution and select Add > New Item..." }, { "code": null, "e": 84036, "s": 83930, "text": "Step 2 − The following dialog box will open. Now select Custom Control (WPF) and name it MyCustomControl." }, { "code": null, "e": 84142, "s": 84036, "text": "Step 2 − The following dialog box will open. Now select Custom Control (WPF) and name it MyCustomControl." }, { "code": null, "e": 84288, "s": 84142, "text": "Step 3 − Click on the Add button and you will see that two new files (Themes/Generic.xaml and MyCustomControl.cs) will be added in your solution." }, { "code": null, "e": 84434, "s": 84288, "text": "Step 3 − Click on the Add button and you will see that two new files (Themes/Generic.xaml and MyCustomControl.cs) will be added in your solution." }, { "code": null, "e": 84530, "s": 84434, "text": "Given below is the XAML code in which style is set for the custom control in Generic.xaml file." }, { "code": null, "e": 84999, "s": 84530, "text": "<ResourceDictionary \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:local = \"clr-namespace:XAMLCustomControls\">\n\t\n <Style TargetType = \"{x:Type local:MyCustomControl}\"\n BasedOn = \"{StaticResource {x:Type Button}}\"> \n <Setter Property = \"Background\" Value = \"LightSalmon\"/>\n <Setter Property = \"Foreground\" Value = \"Blue\"/>\n </Style>\n\t\n</ResourceDictionary>" }, { "code": null, "e": 85144, "s": 84999, "text": "Given below is the C# code for MyCustomControl class which is inherited from the button class and in the constructor, it overrides the metadata." }, { "code": null, "e": 85481, "s": 85144, "text": "using System; \nusing System.Windows; \nusing System.Windows.Controls;\n\nnamespace XAMLCustomControls {\n public class MyCustomControl : Button {\n static MyCustomControl() {\n DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), \n new FrameworkPropertyMetadata(typeof(MyCustomControl)));\n }\n }\n}" }, { "code": null, "e": 85590, "s": 85481, "text": "Given below is the custom control click event implementation in C# which updates the text of the text block." }, { "code": null, "e": 86055, "s": 85590, "text": "using System; \nusing System.Windows; \nusing System.Windows.Controls;\n\nnamespace XAMLCustomControls {\n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary> \n\t\n public partial class MainWindow : Window {\n public MainWindow() { \n InitializeComponent(); \n }\n private void customControl_Click(object sender, RoutedEventArgs e) {\n txtBlock.Text = \"You have just click your custom control\"; \n } \n }\n}" }, { "code": null, "e": 86144, "s": 86055, "text": "Here is the implementation in MainWindow.xaml to add the custom control and a TextBlock." }, { "code": null, "e": 86692, "s": 86144, "text": "<Window x:Class = \"XAMLCustomControls.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:control = \"clr-namespace:XAMLCustomControls\" Title = \"MainWindow\"\n Height = \"350\" Width = \"604\">\n\t\n <StackPanel>\n <control:MyCustomControl x:Name = \"customControl\" \n Content = \"Click Me\" Width = \"70\" Margin = \"10\" Click = \"customControl_Click\"/>\n <TextBlock Name = \"txtBlock\" Width = \"250\" Height = \"30\"/>\n </StackPanel>\n\t\n</Window>" }, { "code": null, "e": 86850, "s": 86692, "text": "When you compile and execute the above code, it will produce the following output. Observe the output contains a custom control which is a customized button." }, { "code": null, "e": 86936, "s": 86850, "text": "Now click on the customized button. You will see that the text block text is updated." }, { "code": null, "e": 86943, "s": 86936, "text": " Print" }, { "code": null, "e": 86954, "s": 86943, "text": " Add Notes" } ]
Basic SQL Commands - GeeksforGeeks
26 Apr, 2021 QUESTION: Consider the following table ITEM given below, write the commands in SQL for 1 – 10 and output for 11 – 20 TABLE: ITEM Write the SQL commands for 1. to 10. 1. To display the name of the item and cost of those items which were purchased after ‘2010-08-05’. Select Item_Name,Cost from ITEM where DOP>"2010-08-05"; 2. To display information of those items whose purchase quantity is more than 10 arranged by Date of Purchase. Select * from ITEM where Purchase_Qty>10 ORDER BY DOP; 3. To display the average cost price of the items of ‘JKL’ Company. Select avg(cost) from ITEM where Company="JKL"; 4. To display all the information of those items whose name starts with letter ‘M’. Select * from ITEM where Item_Name like "M%"; 5. To display maximum cost price of the items which contain letter ‘J’ in the company name. Select max(Cost) from ITEM where Company like '%J%; 6. To display all details of items whose purchase quantity is more than 5 arranged in decreasing order of Date of Purchase. Select * from ITEM where Purchase_Qty>5 order by DOP desc; 7. To display S_No, Item_Name and cost of all those items where Item_Name has the letter ‘o’ in second position. Select S_No,Item_Name,Cost from ITEM where instr(Item_Name,'o')=2; 8. To display Company, minimum of Purchase_Qty grouped by the month of purchase. Select Company,min(Purchase_Qty) from ITEM group by month(DOP); 9. To show the structure of the table ITEM. Desc ITEM; 10. To set Purchase_Qty as 31 of ‘JKL’ company. Update ITEM set Purchase_Qty=31 where Company='JKL'; Write the Output for the following SQL queries 11 – 20. 11. Select count(*) from item where cost>6000 and Purchase_Qty<25; OUTPUT: 12. Select max(Purchase_Qty) from item where cost<5000; OUTPUT: 13. Select avg(Cost) from item where Purchase_Qty>25; OUTPUT: 14. Select cost+200 as ‘Selling_Price’ from item where Item_Name=’Scanner’; OUTPUT: 15. Select S_No,Item_Name,Purchase_Qty from ITEM where Purchase_Qty>=10; OUTPUT: 16. Select Ucase(Item_Name), Lcase(Company) from ITEM; OUTPUT: 17. Select S_No, DOP from ITEM where month(DOP)=8; OUTPUT: 18. Select avg(Cost), Max(Purchase_Qty) from ITEM; OUTPUT: 19. Select Item_Name from ITEM where Item_Name like “%e%”; OUTPUT: 20. Select * from ITEM where length(Item_Name)=3; OUTPUT: DBMS-SQL DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS Introduction of Relational Algebra in DBMS What is Temporary Table in SQL? Two Phase Locking Protocol KDD Process in Data Mining SQL | DDL, DQL, DML, DCL and TCL Commands How to find Nth highest salary from a table SQL | ALTER (RENAME) How to Update Multiple Columns in Single Update Statement in SQL? MySQL | Group_CONCAT() Function
[ { "code": null, "e": 24328, "s": 24300, "text": "\n26 Apr, 2021" }, { "code": null, "e": 24445, "s": 24328, "text": "QUESTION: Consider the following table ITEM given below, write the commands in SQL for 1 – 10 and output for 11 – 20" }, { "code": null, "e": 24544, "s": 24445, "text": " TABLE: ITEM" }, { "code": null, "e": 24581, "s": 24544, "text": "Write the SQL commands for 1. to 10." }, { "code": null, "e": 24681, "s": 24581, "text": "1. To display the name of the item and cost of those items which were purchased after ‘2010-08-05’." }, { "code": null, "e": 24737, "s": 24681, "text": "Select Item_Name,Cost from ITEM where DOP>\"2010-08-05\";" }, { "code": null, "e": 24848, "s": 24737, "text": "2. To display information of those items whose purchase quantity is more than 10 arranged by Date of Purchase." }, { "code": null, "e": 24903, "s": 24848, "text": "Select * from ITEM where Purchase_Qty>10 ORDER BY DOP;" }, { "code": null, "e": 24971, "s": 24903, "text": "3. To display the average cost price of the items of ‘JKL’ Company." }, { "code": null, "e": 25019, "s": 24971, "text": "Select avg(cost) from ITEM where Company=\"JKL\";" }, { "code": null, "e": 25103, "s": 25019, "text": "4. To display all the information of those items whose name starts with letter ‘M’." }, { "code": null, "e": 25149, "s": 25103, "text": "Select * from ITEM where Item_Name like \"M%\";" }, { "code": null, "e": 25241, "s": 25149, "text": "5. To display maximum cost price of the items which contain letter ‘J’ in the company name." }, { "code": null, "e": 25293, "s": 25241, "text": "Select max(Cost) from ITEM where Company like '%J%;" }, { "code": null, "e": 25417, "s": 25293, "text": "6. To display all details of items whose purchase quantity is more than 5 arranged in decreasing order of Date of Purchase." }, { "code": null, "e": 25476, "s": 25417, "text": "Select * from ITEM where Purchase_Qty>5 order by DOP desc;" }, { "code": null, "e": 25589, "s": 25476, "text": "7. To display S_No, Item_Name and cost of all those items where Item_Name has the letter ‘o’ in second position." }, { "code": null, "e": 25656, "s": 25589, "text": "Select S_No,Item_Name,Cost from ITEM where instr(Item_Name,'o')=2;" }, { "code": null, "e": 25737, "s": 25656, "text": "8. To display Company, minimum of Purchase_Qty grouped by the month of purchase." }, { "code": null, "e": 25801, "s": 25737, "text": "Select Company,min(Purchase_Qty) from ITEM group by month(DOP);" }, { "code": null, "e": 25845, "s": 25801, "text": "9. To show the structure of the table ITEM." }, { "code": null, "e": 25856, "s": 25845, "text": "Desc ITEM;" }, { "code": null, "e": 25905, "s": 25856, "text": "10. To set Purchase_Qty as 31 of ‘JKL’ company. " }, { "code": null, "e": 25959, "s": 25905, "text": "Update ITEM set Purchase_Qty=31 where Company='JKL'; " }, { "code": null, "e": 26015, "s": 25959, "text": "Write the Output for the following SQL queries 11 – 20." }, { "code": null, "e": 26096, "s": 26015, "text": "11. Select count(*) from item where cost>6000 and Purchase_Qty<25; OUTPUT:" }, { "code": null, "e": 26166, "s": 26096, "text": "12. Select max(Purchase_Qty) from item where cost<5000; OUTPUT:" }, { "code": null, "e": 26233, "s": 26166, "text": "13. Select avg(Cost) from item where Purchase_Qty>25; OUTPUT:" }, { "code": null, "e": 26323, "s": 26233, "text": "14. Select cost+200 as ‘Selling_Price’ from item where Item_Name=’Scanner’; OUTPUT:" }, { "code": null, "e": 26409, "s": 26323, "text": "15. Select S_No,Item_Name,Purchase_Qty from ITEM where Purchase_Qty>=10; OUTPUT:" }, { "code": null, "e": 26476, "s": 26409, "text": "16. Select Ucase(Item_Name), Lcase(Company) from ITEM; OUTPUT:" }, { "code": null, "e": 26540, "s": 26476, "text": "17. Select S_No, DOP from ITEM where month(DOP)=8; OUTPUT:" }, { "code": null, "e": 26605, "s": 26540, "text": "18. Select avg(Cost), Max(Purchase_Qty) from ITEM; OUTPUT:" }, { "code": null, "e": 26678, "s": 26605, "text": "19. Select Item_Name from ITEM where Item_Name like “%e%”; OUTPUT:" }, { "code": null, "e": 26741, "s": 26678, "text": "20. Select * from ITEM where length(Item_Name)=3; OUTPUT:" }, { "code": null, "e": 26750, "s": 26741, "text": "DBMS-SQL" }, { "code": null, "e": 26755, "s": 26750, "text": "DBMS" }, { "code": null, "e": 26759, "s": 26755, "text": "SQL" }, { "code": null, "e": 26764, "s": 26759, "text": "DBMS" }, { "code": null, "e": 26768, "s": 26764, "text": "SQL" }, { "code": null, "e": 26866, "s": 26768, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26907, "s": 26866, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 26950, "s": 26907, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 26982, "s": 26950, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27009, "s": 26982, "text": "Two Phase Locking Protocol" }, { "code": null, "e": 27036, "s": 27009, "text": "KDD Process in Data Mining" }, { "code": null, "e": 27078, "s": 27036, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 27122, "s": 27078, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 27143, "s": 27122, "text": "SQL | ALTER (RENAME)" }, { "code": null, "e": 27209, "s": 27143, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" } ]
Here’s what I’ve learnt about Sklearn.resample | by Samson Afolabi | Towards Data Science
Working with imbalanced dataset can be a tough nut to crack for data scientist. One of the ways at which you deal with imbalanced datasets is by resampling with sklearn.resample i.e. upsampling the minority class or downsampling the majority class. Sklearn.resample is Scikit learn’s function for upsampling/downsampling. From sklearn documentation, the function sklearn.resample, resamples arrays or sparse matrices in a consistent way and the default strategy implements one step of the bootstrapping procedure. In simple terms, sklearn.resample doesn’t just generate extra data points to the datasets by magic, it basically creates a random resampling(with/without replacement) of your dataset. This equalization procedure prevents the Machine Learning model from inclining towards the majority class in the dataset. Next, I show upsampling in an example. In the example below we create a dataframe with 3 columns: age, sex and store. #import librariesimport pandas as pdfrom sklearn.utils import resample,shuffle#create a dataframedf = {'age':['a','b','c','a','b'],'sex':['e','f','g','f','e'],'store':[1,2,3,3,2]}df = pd.DataFrame(df)df.head() We first, separate the minority class and then the upsample the minority class. The size of the minority class is upsampled to the size of the other classes. #set the minority class to a seperate dataframedf_1 = df[df['store'] == 1]#set other classes to another dataframeother_df = df[df['store'] != 1] #upsample the minority classdf_1_upsampled = resample(df_1,random_state=42,n_samples=2,replace=True)#concatenate the upsampled dataframedf_upsampled = pd.concat([df_1_upsampled,other_df])df_upsampled How cool is that! 😉 😊 Now we have more data to train our model with. Also each of the 3 store categories (1,2 and 3) in the data can be observed in equal amounts when we train the model. However, when you upsample or downsample, avoid these mistakes! In a Machine Learning problem, make sure to upsample/downsample ONLY AFTER you split into train, test (and validate if you wish). If you do upsample your dataset before you split into train and test, there is a high possibility that your model is exposed to data leakage. See an Example below. In a Machine Learning problem, make sure to upsample/downsample ONLY AFTER you split into train, test (and validate if you wish). If you do upsample your dataset before you split into train and test, there is a high possibility that your model is exposed to data leakage. See an Example below. from sklearn.model_selection import train_test_splitX = df_upsampled.drop('store',axis=1)y = df_upsampled.storeX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1,shuffle=True)X_train.head() X_test.head() Notice the data leakage! We have exactly the same data point in X_train as well as X_test. Doing this might give us a wrong sense of what our Machine Learning model is really performing. 2. After your Machine Learning Model is built, it is advisable to test your metric on your NOT-UPSAMPLED train dataset. Testing your metric on the NOT-UPSAMPLED data set gives you a more realistic estimate of your model than testing it on the UPSAMPLED dataset. Personally, I always like to keep a version of the train dataset that wasn’t upsampled. Conclusion:Upsampling/downsampling are very good approaches in handling unbalanced data. However it is important to understand how they work, so as to be able to use them correctly. Note also that the upsampling mechanism introduces bias into your system because of the additional information. You can also read about the SMOTE operator of the imbean library. It works based on the KNearestNeighbours algorithm, synthetically generating data points that fall in the proximity of the already existing outnumbered group. Read more about it here. I hope this was helpful for you. Looking forward to your comments here, meanwhile you can also follow me on twitter and Linkedin.
[ { "code": null, "e": 420, "s": 171, "text": "Working with imbalanced dataset can be a tough nut to crack for data scientist. One of the ways at which you deal with imbalanced datasets is by resampling with sklearn.resample i.e. upsampling the minority class or downsampling the majority class." }, { "code": null, "e": 493, "s": 420, "text": "Sklearn.resample is Scikit learn’s function for upsampling/downsampling." }, { "code": null, "e": 991, "s": 493, "text": "From sklearn documentation, the function sklearn.resample, resamples arrays or sparse matrices in a consistent way and the default strategy implements one step of the bootstrapping procedure. In simple terms, sklearn.resample doesn’t just generate extra data points to the datasets by magic, it basically creates a random resampling(with/without replacement) of your dataset. This equalization procedure prevents the Machine Learning model from inclining towards the majority class in the dataset." }, { "code": null, "e": 1109, "s": 991, "text": "Next, I show upsampling in an example. In the example below we create a dataframe with 3 columns: age, sex and store." }, { "code": null, "e": 1319, "s": 1109, "text": "#import librariesimport pandas as pdfrom sklearn.utils import resample,shuffle#create a dataframedf = {'age':['a','b','c','a','b'],'sex':['e','f','g','f','e'],'store':[1,2,3,3,2]}df = pd.DataFrame(df)df.head()" }, { "code": null, "e": 1477, "s": 1319, "text": "We first, separate the minority class and then the upsample the minority class. The size of the minority class is upsampled to the size of the other classes." }, { "code": null, "e": 1823, "s": 1477, "text": "#set the minority class to a seperate dataframedf_1 = df[df['store'] == 1]#set other classes to another dataframeother_df = df[df['store'] != 1] #upsample the minority classdf_1_upsampled = resample(df_1,random_state=42,n_samples=2,replace=True)#concatenate the upsampled dataframedf_upsampled = pd.concat([df_1_upsampled,other_df])df_upsampled" }, { "code": null, "e": 2010, "s": 1823, "text": "How cool is that! 😉 😊 Now we have more data to train our model with. Also each of the 3 store categories (1,2 and 3) in the data can be observed in equal amounts when we train the model." }, { "code": null, "e": 2074, "s": 2010, "text": "However, when you upsample or downsample, avoid these mistakes!" }, { "code": null, "e": 2368, "s": 2074, "text": "In a Machine Learning problem, make sure to upsample/downsample ONLY AFTER you split into train, test (and validate if you wish). If you do upsample your dataset before you split into train and test, there is a high possibility that your model is exposed to data leakage. See an Example below." }, { "code": null, "e": 2662, "s": 2368, "text": "In a Machine Learning problem, make sure to upsample/downsample ONLY AFTER you split into train, test (and validate if you wish). If you do upsample your dataset before you split into train and test, there is a high possibility that your model is exposed to data leakage. See an Example below." }, { "code": null, "e": 2889, "s": 2662, "text": "from sklearn.model_selection import train_test_splitX = df_upsampled.drop('store',axis=1)y = df_upsampled.storeX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1,shuffle=True)X_train.head()" }, { "code": null, "e": 2903, "s": 2889, "text": "X_test.head()" }, { "code": null, "e": 3090, "s": 2903, "text": "Notice the data leakage! We have exactly the same data point in X_train as well as X_test. Doing this might give us a wrong sense of what our Machine Learning model is really performing." }, { "code": null, "e": 3440, "s": 3090, "text": "2. After your Machine Learning Model is built, it is advisable to test your metric on your NOT-UPSAMPLED train dataset. Testing your metric on the NOT-UPSAMPLED data set gives you a more realistic estimate of your model than testing it on the UPSAMPLED dataset. Personally, I always like to keep a version of the train dataset that wasn’t upsampled." }, { "code": null, "e": 3734, "s": 3440, "text": "Conclusion:Upsampling/downsampling are very good approaches in handling unbalanced data. However it is important to understand how they work, so as to be able to use them correctly. Note also that the upsampling mechanism introduces bias into your system because of the additional information." }, { "code": null, "e": 3984, "s": 3734, "text": "You can also read about the SMOTE operator of the imbean library. It works based on the KNearestNeighbours algorithm, synthetically generating data points that fall in the proximity of the already existing outnumbered group. Read more about it here." } ]
Find Nth term of the series 0, 2, 4, 8, 12, 18... - GeeksforGeeks
15 Mar, 2021 Given a number N. The task is to write a program to find the Nth term in the below series: 0, 2, 4, 8, 12, 18... Examples: Input: 3 Output: 4 For N = 3 Nth term = ( 3 + ( 3 - 1 ) * 3 ) / 2 = 4 Input: 5 Output: 12 On observing carefully, the Nth term in the above series can be generalized as: Nth term = ( N + ( N - 1 ) * N ) / 2 Below is the implementation of the above approach: C++ Java Python 3 C# PHP Javascript // CPP program to find N-th term of the series:// 0, 2, 4, 8, 12, 18...#include <iostream>using namespace std; // Calculate Nth term of seriesint nthTerm(int N){ return (N + N * (N - 1)) / 2;} // Driver Functionint main(){ int N = 5; cout << nthTerm(N); return 0;} // Java program to find N-th term of the series:// 0, 2, 4, 8, 12, 18...import java.io.*; // Main class for main methodclass GFG { public static int nthTerm(int N) { // By using above formula return (N + (N - 1) * N) / 2; } // Driver code public static void main(String[] args) { int N = 5; // 5th term is 12 System.out.println(nthTerm(N)); }} # Python 3 program to find N-th term of the series:# 0, 2, 4, 8, 12, 18. # Calculate Nth term of seriesdef nthTerm(N) : return (N + N * (N - 1)) // 2 # Driver Codeif __name__ == "__main__" : N = 5 print(nthTerm(N)) # This code is contributed by ANKITRAI1 // C# program to find N-th term of the series:// 0, 2, 4, 8, 12, 18...using System;class gfg{ // Calculate Nth term of series public int nthTerm(int N) { int n = ((N + N * (N - 1)) / 2); return n; } //Driver program static void Main(string[] args) { gfg p = new gfg(); int a = p.nthTerm(5); Console.WriteLine(a); Console.Read(); }}//This code is contributed by SoumikMondal <?php// PHP program to find// N-th term of the series:// 0, 2, 4, 8, 12, 18... // Calculate Nth term of seriesfunction nthTerm($N){ return (int)(($N + $N * ($N - 1)) / 2);} // Driver Code$N = 5; echo nthTerm($N); // This code is contributed by mits?> <script> // JavaScript program to find N-th term of the series:// 0, 2, 4, 8, 12, 18... // Calculate Nth term of seriesfunction nthTerm(N){ return parseInt((N + N * (N - 1)) / 2);}// Driver Function let N = 5; document.write(nthTerm(N)); // This code contributed by Rajput-Ji </script> 12 Time Complexity: O(1) Mithun Kumar ankthon SoumikMondal Rajput-Ji C++ Java Pattern Searching Java Pattern Searching CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects Bitwise Operators in C/C++ Operator Overloading in C++ For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 25255, "s": 25227, "text": "\n15 Mar, 2021" }, { "code": null, "e": 25348, "s": 25255, "text": "Given a number N. The task is to write a program to find the Nth term in the below series: " }, { "code": null, "e": 25370, "s": 25348, "text": "0, 2, 4, 8, 12, 18..." }, { "code": null, "e": 25382, "s": 25370, "text": "Examples: " }, { "code": null, "e": 25482, "s": 25382, "text": "Input: 3\nOutput: 4\nFor N = 3\nNth term = ( 3 + ( 3 - 1 ) * 3 ) / 2\n = 4\nInput: 5 \nOutput: 12" }, { "code": null, "e": 25566, "s": 25484, "text": "On observing carefully, the Nth term in the above series can be generalized as: " }, { "code": null, "e": 25603, "s": 25566, "text": "Nth term = ( N + ( N - 1 ) * N ) / 2" }, { "code": null, "e": 25655, "s": 25603, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25659, "s": 25655, "text": "C++" }, { "code": null, "e": 25664, "s": 25659, "text": "Java" }, { "code": null, "e": 25673, "s": 25664, "text": "Python 3" }, { "code": null, "e": 25676, "s": 25673, "text": "C#" }, { "code": null, "e": 25680, "s": 25676, "text": "PHP" }, { "code": null, "e": 25691, "s": 25680, "text": "Javascript" }, { "code": "// CPP program to find N-th term of the series:// 0, 2, 4, 8, 12, 18...#include <iostream>using namespace std; // Calculate Nth term of seriesint nthTerm(int N){ return (N + N * (N - 1)) / 2;} // Driver Functionint main(){ int N = 5; cout << nthTerm(N); return 0;}", "e": 25970, "s": 25691, "text": null }, { "code": "// Java program to find N-th term of the series:// 0, 2, 4, 8, 12, 18...import java.io.*; // Main class for main methodclass GFG { public static int nthTerm(int N) { // By using above formula return (N + (N - 1) * N) / 2; } // Driver code public static void main(String[] args) { int N = 5; // 5th term is 12 System.out.println(nthTerm(N)); }}", "e": 26380, "s": 25970, "text": null }, { "code": "# Python 3 program to find N-th term of the series:# 0, 2, 4, 8, 12, 18. # Calculate Nth term of seriesdef nthTerm(N) : return (N + N * (N - 1)) // 2 # Driver Codeif __name__ == \"__main__\" : N = 5 print(nthTerm(N)) # This code is contributed by ANKITRAI1", "e": 26651, "s": 26380, "text": null }, { "code": "// C# program to find N-th term of the series:// 0, 2, 4, 8, 12, 18...using System;class gfg{ // Calculate Nth term of series public int nthTerm(int N) { int n = ((N + N * (N - 1)) / 2); return n; } //Driver program static void Main(string[] args) { gfg p = new gfg(); int a = p.nthTerm(5); Console.WriteLine(a); Console.Read(); }}//This code is contributed by SoumikMondal", "e": 27094, "s": 26651, "text": null }, { "code": "<?php// PHP program to find// N-th term of the series:// 0, 2, 4, 8, 12, 18... // Calculate Nth term of seriesfunction nthTerm($N){ return (int)(($N + $N * ($N - 1)) / 2);} // Driver Code$N = 5; echo nthTerm($N); // This code is contributed by mits?>", "e": 27364, "s": 27094, "text": null }, { "code": "<script> // JavaScript program to find N-th term of the series:// 0, 2, 4, 8, 12, 18... // Calculate Nth term of seriesfunction nthTerm(N){ return parseInt((N + N * (N - 1)) / 2);}// Driver Function let N = 5; document.write(nthTerm(N)); // This code contributed by Rajput-Ji </script>", "e": 27664, "s": 27364, "text": null }, { "code": null, "e": 27667, "s": 27664, "text": "12" }, { "code": null, "e": 27692, "s": 27669, "text": "Time Complexity: O(1) " }, { "code": null, "e": 27705, "s": 27692, "text": "Mithun Kumar" }, { "code": null, "e": 27713, "s": 27705, "text": "ankthon" }, { "code": null, "e": 27726, "s": 27713, "text": "SoumikMondal" }, { "code": null, "e": 27736, "s": 27726, "text": "Rajput-Ji" }, { "code": null, "e": 27740, "s": 27736, "text": "C++" }, { "code": null, "e": 27745, "s": 27740, "text": "Java" }, { "code": null, "e": 27763, "s": 27745, "text": "Pattern Searching" }, { "code": null, "e": 27768, "s": 27763, "text": "Java" }, { "code": null, "e": 27786, "s": 27768, "text": "Pattern Searching" }, { "code": null, "e": 27790, "s": 27786, "text": "CPP" }, { "code": null, "e": 27888, "s": 27790, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27907, "s": 27888, "text": "Inheritance in C++" }, { "code": null, "e": 27950, "s": 27907, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 27974, "s": 27950, "text": "C++ Classes and Objects" }, { "code": null, "e": 28001, "s": 27974, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 28029, "s": 28001, "text": "Operator Overloading in C++" }, { "code": null, "e": 28051, "s": 28029, "text": "For-each loop in Java" }, { "code": null, "e": 28087, "s": 28051, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 28112, "s": 28087, "text": "Reverse a string in Java" }, { "code": null, "e": 28144, "s": 28112, "text": "Initialize an ArrayList in Java" } ]
Tryit Editor v3.7
Tryit: Another text shadow effect
[]
Gaussian Filter Generation in C++
As we know the Gaussian Filtering is very much useful applied in the field of image processing. It is used to reduce the noise of an image. In this section we will see how to generate a 2D Gaussian Kernel. Gaussian Distribution for generating 2D kernel is as follows. G(x,y)=12Πσ2ex2+y22σ2 Let us see the following implementation to get better understanding − Live Demo #include <cmath> #include <iomanip> #include <iostream> #define PI 3.1415 using namespace std; void calc_filter(double kernel[][5]) { double sigma = 1.0; double p, q = 2.0 * sigma * sigma; double sum = 0.0; for (int x = -2; x <= 2; x++) { for (int y = -2; y <= 2; y++) { p = sqrt(x * x + y * y); kernel[x + 2][y + 2] = (exp(-(p * p) / q)) / (PI * q); sum += kernel[x + 2][y + 2]; } } for (int i = 0; i < 5; i++) for (int j = 0; j < 5; j++) kernel[i][j] /= sum; } int main() { double kernel[5][5]; calc_filter(kernel); for (int i = 0; i < 5; ++i) { for (int j = 0; j < 5; ++j) cout << kernel[i][j] << " "; cout << endl; } } 0.00296902 0.0133062 0.0219382 0.0133062 0.00296902 0.0133062 0.0596343 0.0983203 0.0596343 0.0133062 0.0219382 0.0983203 0.162103 0.0983203 0.0219382 0.0133062 0.0596343 0.0983203 0.0596343 0.0133062 0.00296902 0.0133062 0.0219382 0.0133062 0.00296902
[ { "code": null, "e": 1330, "s": 1062, "text": "As we know the Gaussian Filtering is very much useful applied in the field of image processing. It is used to reduce the noise of an image. In this section we will see how to generate a 2D Gaussian Kernel. Gaussian Distribution for generating 2D kernel is as follows." }, { "code": null, "e": 1352, "s": 1330, "text": "G(x,y)=12Πσ2ex2+y22σ2" }, { "code": null, "e": 1422, "s": 1352, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1433, "s": 1422, "text": " Live Demo" }, { "code": null, "e": 2161, "s": 1433, "text": "#include <cmath>\n#include <iomanip>\n#include <iostream>\n#define PI 3.1415\nusing namespace std;\nvoid calc_filter(double kernel[][5]) {\n double sigma = 1.0;\n double p, q = 2.0 * sigma * sigma;\n double sum = 0.0;\n for (int x = -2; x <= 2; x++) {\n for (int y = -2; y <= 2; y++) {\n p = sqrt(x * x + y * y);\n kernel[x + 2][y + 2] = (exp(-(p * p) / q)) / (PI * q);\n sum += kernel[x + 2][y + 2];\n }\n }\n for (int i = 0; i < 5; i++)\n for (int j = 0; j < 5; j++)\n kernel[i][j] /= sum;\n}\nint main() {\n double kernel[5][5];\n calc_filter(kernel);\n for (int i = 0; i < 5; ++i) {\n for (int j = 0; j < 5; ++j)\n cout << kernel[i][j] << \" \";\n cout << endl;\n }\n}" }, { "code": null, "e": 2414, "s": 2161, "text": "0.00296902 0.0133062 0.0219382 0.0133062 0.00296902\n0.0133062 0.0596343 0.0983203 0.0596343 0.0133062\n0.0219382 0.0983203 0.162103 0.0983203 0.0219382\n0.0133062 0.0596343 0.0983203 0.0596343 0.0133062\n0.00296902 0.0133062 0.0219382 0.0133062 0.00296902" } ]
Difference Between wait() and notify() in Java - GeeksforGeeks
04 Apr, 2022 The wait() and notify() are methods of the Object class. They were introduced to part ways with polling, which is the process of repeatedly checking for a condition to be fulfilled. Polling wastes CPU resources considerably, hence it is not preferred. wait() method is a part of java.lang.Object class. When wait() method is called, the calling thread stops its execution until notify() or notifyAll() method is invoked by some other Thread. The wait() method has 3 variations: 1. wait(): This is a basic version of the wait() method which does not take any argument. It will cause the thread to wait till notify is called. public final void wait() 2. wait(long timeout): This version of the wait() method takes a single timeout argument. It will cause the thread to wait either till notify is called or till timeout (One which occurs earlier). public final void wait(long timeout) 3. wait(long timeout, int nanoseconds): This version of the wait() method takes a timeout argument as well as a nanosecond argument for extra precision. public final void wait(long timeout, int nanoseconds) The notify() method is defined in the Object class, which is Java’s top-level class. It’s used to wake up only one thread that’s waiting for an object, and that thread then begins execution. The thread class notify() method is used to wake up a single thread. public final void notify() One of the waiting threads is randomly selected and notified about the same. The notified thread then exits the waiting state and enters the blocked state where it waits till the previous thread has given up the lock and this thread has acquired it. Once it acquires the lock, it enters the runnable state where it waits for CPU time and then it starts running. Below is demonstration of wait() and notify() method: Java // Java Program to demonstrate usage of wait() and notify() class demo { // variable to check if part1 has returned // volatile used to prevent threads from // storing local copies of variable volatile boolean part1done = false; // method synchronized on this // i.e. current object of demo synchronized void part1() { System.out.println("Welcome to India"); part1done = true; System.out.println( "Thread t1 about to surrender lock"); // notify the waiting thread, if any notify(); } // method synchronized on this // i.e. current object of demo synchronized void part2() { // loop to prevent spurious wake-up while (!part1done) { try { System.out.println("Thread t2 waiting"); // wait till notify is called wait(); System.out.println( "Thread t2 running again"); } catch (Exception e) { System.out.println(e.getClass()); } } System.out.println("Do visit Taj Mahal"); }} public class Main { public static void main(String[] args) { // Make an instance of demo class demo obj = new demo(); // Thread t1 will call part1() Thread t1 = new Thread(new Runnable() { public void run() { obj.part1(); } }); // Thread t2 will call part2() Thread t2 = new Thread(new Runnable() { public void run() { obj.part2(); } }); // Start t2 and then t1 t2.start(); t1.start(); }} Thread t2 waiting Welcome to India Thread t1 about to surrender lock Thread t2 running again Do visit Taj Mahal 1. wait() It is mandatory to enclose wait() in a try-catch block because if a thread present in the waiting state gets interrupted, then it will throw InterruptedException. The other two variations of wait housing parameters will throw IllegalArgumentException if the value of timeout is negative or the value of nanoseconds is not in the range 0 to 9,99,999. Below is the implementation for the exception handling. Java // Program demonstrating occurrence of InterruptedException class demo { volatile boolean part1done = false; synchronized void part1() { System.out.println("Welcome to India"); part1done = true; // notify() has been commented, waiting // thread remains waiting forever notify(); } synchronized void part2() { while (!part1done) { try { wait(); } catch (Exception e) { System.out.println("Exception : " + e.getClass()); // quit program after exception is thrown System.exit(-1); } } System.out.println("Do visit Taj Mahal"); }} public class Main { public static void main(String[] args) { // Make an instance of demo class demo obj = new demo(); // Thread t1 will call part1() Thread t1 = new Thread(new Runnable() { public void run() { obj.part1(); } }); // Thread t2 will call part2() Thread t2 = new Thread(new Runnable() { public void run() { obj.part2(); } }); // Start t2 and then t1 t2.start(); t1.start(); // This is a counter which will // interrupt Thread t2 after 3 seconds long startTime = System.currentTimeMillis(); while (true) { if (System.currentTimeMillis() - startTime > 3000) t2.interrupt(); } }} Welcome to India Exception : class java.lang.InterruptedException 2. notify() Unlike wait(), the notify method does not throw an InterruptedException hence it is not mandatory to house it inside a try-catch block Note: wait() and notify() both have a tendency to throw IllegalMonitorStateException This occurs when a thread is holding the monitor lock of object A and tries to call wait or notify on object B. In all the preceding examples, the methods were synchronized on “this” i.e. the object used to call those methods (obj). Also, the wait() & notify() were being called as this.wait() and this.notify() (usage of this was redundant). Hence, there was no issue. In the below example, the methods part1 and part2 are now synchronized on an Integer object, but wait() & notify() are still being called on the object which called these methods (obj). This causes an IllegalMonitorStateException Below is the implementation of the exception handling. Java // Program to demonstrate IllegalMonitorStateException class demo { volatile boolean part1done = false; // Made an Integer object a // and set it randomly to 5 Integer a = 5; void part1() { // Synchronized code on a synchronized (a) { System.out.println("Welcome to India"); part1done = true; // calling this.notify() notify(); } } void part2() { // Synchronized code on a synchronized (a) { while (!part1done) { try { // calling this.wait() wait(); } catch (Exception e) { System.out.println("Exception: "+e.getClass()); System.exit(-1); } } System.out.println("Do visit Taj Mahal"); } }} public class Main { public static void main(String[] args) { // Make an instance of demo class demo obj = new demo(); // Thread t1 will call part1() Thread t1 = new Thread(new Runnable() { public void run() { obj.part1(); } }); // Thread t2 will call part2() Thread t2 = new Thread(new Runnable() { public void run() { obj.part2(); } }); // Start t2 and then t1 t2.start(); t1.start(); }} Exception: class java.lang.IllegalMonitorStateException Note: To fix the above code, just replace notify() with a.notify() on line 17 and wait() with a.wait() on line 29. arorakashish0911 germanshephered48 nishkarshgandhi mayank007rawa Picked Technical Scripter 2020 Difference Between Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference Between Spark DataFrame and Pandas DataFrame Difference between Internal and External fragmentation Difference between Top down parsing and Bottom up parsing Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 24804, "s": 24776, "text": "\n04 Apr, 2022" }, { "code": null, "e": 25056, "s": 24804, "text": "The wait() and notify() are methods of the Object class. They were introduced to part ways with polling, which is the process of repeatedly checking for a condition to be fulfilled. Polling wastes CPU resources considerably, hence it is not preferred." }, { "code": null, "e": 25246, "s": 25056, "text": "wait() method is a part of java.lang.Object class. When wait() method is called, the calling thread stops its execution until notify() or notifyAll() method is invoked by some other Thread." }, { "code": null, "e": 25282, "s": 25246, "text": "The wait() method has 3 variations:" }, { "code": null, "e": 25428, "s": 25282, "text": "1. wait(): This is a basic version of the wait() method which does not take any argument. It will cause the thread to wait till notify is called." }, { "code": null, "e": 25453, "s": 25428, "text": "public final void wait()" }, { "code": null, "e": 25649, "s": 25453, "text": "2. wait(long timeout): This version of the wait() method takes a single timeout argument. It will cause the thread to wait either till notify is called or till timeout (One which occurs earlier)." }, { "code": null, "e": 25686, "s": 25649, "text": "public final void wait(long timeout)" }, { "code": null, "e": 25839, "s": 25686, "text": "3. wait(long timeout, int nanoseconds): This version of the wait() method takes a timeout argument as well as a nanosecond argument for extra precision." }, { "code": null, "e": 25893, "s": 25839, "text": "public final void wait(long timeout, int nanoseconds)" }, { "code": null, "e": 26153, "s": 25893, "text": "The notify() method is defined in the Object class, which is Java’s top-level class. It’s used to wake up only one thread that’s waiting for an object, and that thread then begins execution. The thread class notify() method is used to wake up a single thread." }, { "code": null, "e": 26180, "s": 26153, "text": "public final void notify()" }, { "code": null, "e": 26542, "s": 26180, "text": "One of the waiting threads is randomly selected and notified about the same. The notified thread then exits the waiting state and enters the blocked state where it waits till the previous thread has given up the lock and this thread has acquired it. Once it acquires the lock, it enters the runnable state where it waits for CPU time and then it starts running." }, { "code": null, "e": 26596, "s": 26542, "text": "Below is demonstration of wait() and notify() method:" }, { "code": null, "e": 26601, "s": 26596, "text": "Java" }, { "code": "// Java Program to demonstrate usage of wait() and notify() class demo { // variable to check if part1 has returned // volatile used to prevent threads from // storing local copies of variable volatile boolean part1done = false; // method synchronized on this // i.e. current object of demo synchronized void part1() { System.out.println(\"Welcome to India\"); part1done = true; System.out.println( \"Thread t1 about to surrender lock\"); // notify the waiting thread, if any notify(); } // method synchronized on this // i.e. current object of demo synchronized void part2() { // loop to prevent spurious wake-up while (!part1done) { try { System.out.println(\"Thread t2 waiting\"); // wait till notify is called wait(); System.out.println( \"Thread t2 running again\"); } catch (Exception e) { System.out.println(e.getClass()); } } System.out.println(\"Do visit Taj Mahal\"); }} public class Main { public static void main(String[] args) { // Make an instance of demo class demo obj = new demo(); // Thread t1 will call part1() Thread t1 = new Thread(new Runnable() { public void run() { obj.part1(); } }); // Thread t2 will call part2() Thread t2 = new Thread(new Runnable() { public void run() { obj.part2(); } }); // Start t2 and then t1 t2.start(); t1.start(); }}", "e": 28230, "s": 26601, "text": null }, { "code": null, "e": 28342, "s": 28230, "text": "Thread t2 waiting\nWelcome to India\nThread t1 about to surrender lock\nThread t2 running again\nDo visit Taj Mahal" }, { "code": null, "e": 28352, "s": 28342, "text": "1. wait()" }, { "code": null, "e": 28515, "s": 28352, "text": "It is mandatory to enclose wait() in a try-catch block because if a thread present in the waiting state gets interrupted, then it will throw InterruptedException." }, { "code": null, "e": 28702, "s": 28515, "text": "The other two variations of wait housing parameters will throw IllegalArgumentException if the value of timeout is negative or the value of nanoseconds is not in the range 0 to 9,99,999." }, { "code": null, "e": 28758, "s": 28702, "text": "Below is the implementation for the exception handling." }, { "code": null, "e": 28763, "s": 28758, "text": "Java" }, { "code": "// Program demonstrating occurrence of InterruptedException class demo { volatile boolean part1done = false; synchronized void part1() { System.out.println(\"Welcome to India\"); part1done = true; // notify() has been commented, waiting // thread remains waiting forever notify(); } synchronized void part2() { while (!part1done) { try { wait(); } catch (Exception e) { System.out.println(\"Exception : \" + e.getClass()); // quit program after exception is thrown System.exit(-1); } } System.out.println(\"Do visit Taj Mahal\"); }} public class Main { public static void main(String[] args) { // Make an instance of demo class demo obj = new demo(); // Thread t1 will call part1() Thread t1 = new Thread(new Runnable() { public void run() { obj.part1(); } }); // Thread t2 will call part2() Thread t2 = new Thread(new Runnable() { public void run() { obj.part2(); } }); // Start t2 and then t1 t2.start(); t1.start(); // This is a counter which will // interrupt Thread t2 after 3 seconds long startTime = System.currentTimeMillis(); while (true) { if (System.currentTimeMillis() - startTime > 3000) t2.interrupt(); } }}", "e": 30278, "s": 28763, "text": null }, { "code": null, "e": 30344, "s": 30278, "text": "Welcome to India\nException : class java.lang.InterruptedException" }, { "code": null, "e": 30356, "s": 30344, "text": "2. notify()" }, { "code": null, "e": 30491, "s": 30356, "text": "Unlike wait(), the notify method does not throw an InterruptedException hence it is not mandatory to house it inside a try-catch block" }, { "code": null, "e": 30497, "s": 30491, "text": "Note:" }, { "code": null, "e": 30576, "s": 30497, "text": "wait() and notify() both have a tendency to throw IllegalMonitorStateException" }, { "code": null, "e": 30688, "s": 30576, "text": "This occurs when a thread is holding the monitor lock of object A and tries to call wait or notify on object B." }, { "code": null, "e": 30946, "s": 30688, "text": "In all the preceding examples, the methods were synchronized on “this” i.e. the object used to call those methods (obj). Also, the wait() & notify() were being called as this.wait() and this.notify() (usage of this was redundant). Hence, there was no issue." }, { "code": null, "e": 31132, "s": 30946, "text": "In the below example, the methods part1 and part2 are now synchronized on an Integer object, but wait() & notify() are still being called on the object which called these methods (obj)." }, { "code": null, "e": 31176, "s": 31132, "text": "This causes an IllegalMonitorStateException" }, { "code": null, "e": 31231, "s": 31176, "text": "Below is the implementation of the exception handling." }, { "code": null, "e": 31236, "s": 31231, "text": "Java" }, { "code": "// Program to demonstrate IllegalMonitorStateException class demo { volatile boolean part1done = false; // Made an Integer object a // and set it randomly to 5 Integer a = 5; void part1() { // Synchronized code on a synchronized (a) { System.out.println(\"Welcome to India\"); part1done = true; // calling this.notify() notify(); } } void part2() { // Synchronized code on a synchronized (a) { while (!part1done) { try { // calling this.wait() wait(); } catch (Exception e) { System.out.println(\"Exception: \"+e.getClass()); System.exit(-1); } } System.out.println(\"Do visit Taj Mahal\"); } }} public class Main { public static void main(String[] args) { // Make an instance of demo class demo obj = new demo(); // Thread t1 will call part1() Thread t1 = new Thread(new Runnable() { public void run() { obj.part1(); } }); // Thread t2 will call part2() Thread t2 = new Thread(new Runnable() { public void run() { obj.part2(); } }); // Start t2 and then t1 t2.start(); t1.start(); }}", "e": 32629, "s": 31236, "text": null }, { "code": null, "e": 32685, "s": 32629, "text": "Exception: class java.lang.IllegalMonitorStateException" }, { "code": null, "e": 32800, "s": 32685, "text": "Note: To fix the above code, just replace notify() with a.notify() on line 17 and wait() with a.wait() on line 29." }, { "code": null, "e": 32817, "s": 32800, "text": "arorakashish0911" }, { "code": null, "e": 32835, "s": 32817, "text": "germanshephered48" }, { "code": null, "e": 32851, "s": 32835, "text": "nishkarshgandhi" }, { "code": null, "e": 32865, "s": 32851, "text": "mayank007rawa" }, { "code": null, "e": 32872, "s": 32865, "text": "Picked" }, { "code": null, "e": 32896, "s": 32872, "text": "Technical Scripter 2020" }, { "code": null, "e": 32915, "s": 32896, "text": "Difference Between" }, { "code": null, "e": 32920, "s": 32915, "text": "Java" }, { "code": null, "e": 32939, "s": 32920, "text": "Technical Scripter" }, { "code": null, "e": 32944, "s": 32939, "text": "Java" }, { "code": null, "e": 33042, "s": 32944, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33051, "s": 33042, "text": "Comments" }, { "code": null, "e": 33064, "s": 33051, "text": "Old Comments" }, { "code": null, "e": 33125, "s": 33064, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 33193, "s": 33125, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 33249, "s": 33193, "text": "Difference Between Spark DataFrame and Pandas DataFrame" }, { "code": null, "e": 33304, "s": 33249, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 33362, "s": 33304, "text": "Difference between Top down parsing and Bottom up parsing" }, { "code": null, "e": 33377, "s": 33362, "text": "Arrays in Java" }, { "code": null, "e": 33421, "s": 33377, "text": "Split() String method in Java with examples" }, { "code": null, "e": 33443, "s": 33421, "text": "For-each loop in Java" }, { "code": null, "e": 33468, "s": 33443, "text": "Reverse a string in Java" } ]
Insert a node after the n-th node from the end - GeeksforGeeks
29 Mar, 2022 Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 <= n. Examples: Input : list: 1->3->4->5 n = 4, x = 2 Output : 1->2->3->4->5 4th node from the end is 1 and insertion has been done after this node. Input : list: 10->8->3->12->5->18 n = 2, x = 11 Output : 10->8->3->12->5->11->18 Method 1 (Using length of the list):Find the length of the linked list, i.e, the number of nodes in the list. Let it be len. Now traverse the list from the 1st node upto the (len-n+1)th node from the beginning and insert the new node after this node. This method requires two traversals of the list. C++ Java Python3 C# Javascript // C++ implementation to insert a node after// the n-th node from the end#include <bits/stdc++.h>using namespace std; // structure of a nodestruct Node { int data; Node* next;}; // function to get a new nodeNode* getNode(int data){ // allocate memory for the node Node* newNode = (Node*)malloc(sizeof(Node)); // put in the data newNode->data = data; newNode->next = NULL; return newNode;} // function to insert a node after the// nth node from the endvoid insertAfterNthNode(Node* head, int n, int x){ // if list is empty if (head == NULL) return; // get a new node for the value 'x' Node* newNode = getNode(x); Node* ptr = head; int len = 0, i; // find length of the list, i.e, the // number of nodes in the list while (ptr != NULL) { len++; ptr = ptr->next; } // traverse up to the nth node from the end ptr = head; for (i = 1; i <= (len - n); i++) ptr = ptr->next; // insert the 'newNode' by making the // necessary adjustment in the links newNode->next = ptr->next; ptr->next = newNode;} // function to print the listvoid printList(Node* head){ while (head != NULL) { cout << head->data << " "; head = head->next; }} // Driver program to test aboveint main(){ // Creating list 1->3->4->5 Node* head = getNode(1); head->next = getNode(3); head->next->next = getNode(4); head->next->next->next = getNode(5); int n = 4, x = 2; cout << "Original Linked List: "; printList(head); insertAfterNthNode(head, n, x); cout << "\nLinked List After Insertion: "; printList(head); return 0;} // Java implementation to insert a node after// the n-th node from the endclass GfG{ // structure of a nodestatic class Node{ int data; Node next;} // function to get a new nodestatic Node getNode(int data){ // allocate memory for the node Node newNode = new Node(); // put in the data newNode.data = data; newNode.next = null; return newNode;} // function to insert a node after the// nth node from the endstatic void insertAfterNthNode(Node head, int n, int x){ // if list is empty if (head == null) return; // get a new node for the value 'x' Node newNode = getNode(x); Node ptr = head; int len = 0, i; // find length of the list, i.e, the // number of nodes in the list while (ptr != null) { len++; ptr = ptr.next; } // traverse up to the nth node from the end ptr = head; for (i = 1; i <= (len - n); i++) ptr = ptr.next; // insert the 'newNode' by making the // necessary adjustment in the links newNode.next = ptr.next; ptr.next = newNode;} // function to print the liststatic void printList(Node head){ while (head != null) { System.out.print(head.data + " "); head = head.next; }} // Driver codepublic static void main(String[] args){ // Creating list 1->3->4->5 Node head = getNode(1); head.next = getNode(3); head.next.next = getNode(4); head.next.next.next = getNode(5); int n = 4, x = 2; System.out.print("Original Linked List: "); printList(head); insertAfterNthNode(head, n, x); System.out.println(); System.out.print("Linked List After Insertion: "); printList(head);}} // This code is contributed by prerna saini # Python implementation to insert a node after# the n-th node from the end # Linked List nodeclass Node: def __init__(self, data): self.data = data self.next = None # function to get a new nodedef getNode(data) : # allocate memory for the node newNode = Node(0) # put in the data newNode.data = data newNode.next = None return newNode # function to insert a node after the# nth node from the enddef insertAfterNthNode(head, n, x) : # if list is empty if (head == None) : return # get a new node for the value 'x' newNode = getNode(x) ptr = head len = 0 i = 0 # find length of the list, i.e, the # number of nodes in the list while (ptr != None) : len = len + 1 ptr = ptr.next # traverse up to the nth node from the end ptr = head i = 1 while ( i <= (len - n) ) : ptr = ptr.next i = i + 1 # insert the 'newNode' by making the # necessary adjustment in the links newNode.next = ptr.next ptr.next = newNode # function to print the listdef printList( head) : while (head != None): print(head.data ,end = " ") head = head.next # Driver code # Creating list 1->3->4->5head = getNode(1)head.next = getNode(3)head.next.next = getNode(4)head.next.next.next = getNode(5) n = 4x = 2 print("Original Linked List: ")printList(head) insertAfterNthNode(head, n, x)print()print("Linked List After Insertion: ")printList(head) # This code is contributed by Arnab Kundu // C# implementation to insert a node after// the n-th node from the endusing System; class GfG{ // structure of a nodepublic class Node{ public int data; public Node next;} // function to get a new nodestatic Node getNode(int data){ // allocate memory for the node Node newNode = new Node(); // put in the data newNode.data = data; newNode.next = null; return newNode;} // function to insert a node after the// nth node from the endstatic void insertAfterNthNode(Node head, int n, int x){ // if list is empty if (head == null) return; // get a new node for the value 'x' Node newNode = getNode(x); Node ptr = head; int len = 0, i; // find length of the list, i.e, the // number of nodes in the list while (ptr != null) { len++; ptr = ptr.next; } // traverse up to the nth node from the end ptr = head; for (i = 1; i <= (len - n); i++) ptr = ptr.next; // insert the 'newNode' by making the // necessary adjustment in the links newNode.next = ptr.next; ptr.next = newNode;} // function to print the liststatic void printList(Node head){ while (head != null) { Console.Write(head.data + " "); head = head.next; }} // Driver codepublic static void Main(String[] args){ // Creating list 1->3->4->5 Node head = getNode(1); head.next = getNode(3); head.next.next = getNode(4); head.next.next.next = getNode(5); int n = 4, x = 2; Console.Write("Original Linked List: "); printList(head); insertAfterNthNode(head, n, x); Console.WriteLine(); Console.Write("Linked List After Insertion: "); printList(head);}} // This code has been contributed by 29AjayKumar <script> // JavaScript implementation to// insert a node after// the n-th node from the end // structure of a node class Node { constructor() { this.data = 0; this.next = null; } } // function to get a new node function getNode(data) { // allocate memory for the nodevar newNode = new Node(); // put in the data newNode.data = data; newNode.next = null; return newNode; } // function to insert a node after the // nth node from the end function insertAfterNthNode(head , n , x) { // if list is empty if (head == null) return; // get a new node for the value 'x'var newNode = getNode(x);var ptr = head; var len = 0, i; // find length of the list, i.e, the // number of nodes in the list while (ptr != null) { len++; ptr = ptr.next; } // traverse up to the nth node from the end ptr = head; for (i = 1; i <= (len - n); i++) ptr = ptr.next; // insert the 'newNode' by making the // necessary adjustment in the links newNode.next = ptr.next; ptr.next = newNode; } // function to print the list function printList(head) { while (head != null) { document.write(head.data + " "); head = head.next; } } // Driver code // Creating list 1->3->4->5var head = getNode(1); head.next = getNode(3); head.next.next = getNode(4); head.next.next.next = getNode(5); var n = 4, x = 2; document.write("Original Linked List: "); printList(head); insertAfterNthNode(head, n, x); document.write(); document.write("<br/>Linked List After Insertion: "); printList(head); // This code contributed by gauravrajput1 </script> Original Linked List: 1 3 4 5 Linked List After Insertion: 1 2 3 4 5 Time Complexity: O(n), where n is the number of nodes in the list. Method 2 (Single traversal):This method uses two pointers, one is slow_ptr and the other is fast_ptr. First move the fast_ptr up to the nth node from the beginning. Make the slow_ptr point to the 1st node of the list. Now, simultaneously move both the pointers until fast_ptr points to the last node. At this point the slow_ptr will be pointing to the nth node from the end. Insert the new node after this node. This method requires single traversal of the list. C++ Java Python3 C# Javascript // C++ implementation to insert a node after the// nth node from the end#include <bits/stdc++.h> using namespace std; // structure of a nodestruct Node { int data; Node* next;}; // function to get a new nodeNode* getNode(int data){ // allocate memory for the node Node* newNode = (Node*)malloc(sizeof(Node)); // put in the data newNode->data = data; newNode->next = NULL; return newNode;} // function to insert a node after the// nth node from the endvoid insertAfterNthNode(Node* head, int n, int x){ // if list is empty if (head == NULL) return; // get a new node for the value 'x' Node* newNode = getNode(x); // Initializing the slow and fast pointers Node* slow_ptr = head; Node* fast_ptr = head; // move 'fast_ptr' to point to the nth node // from the beginning for (int i = 1; i <= n - 1; i++) fast_ptr = fast_ptr->next; // iterate until 'fast_ptr' points to the // last node while (fast_ptr->next != NULL) { // move both the pointers to the // respective next nodes slow_ptr = slow_ptr->next; fast_ptr = fast_ptr->next; } // insert the 'newNode' by making the // necessary adjustment in the links newNode->next = slow_ptr->next; slow_ptr->next = newNode;} // function to print the listvoid printList(Node* head){ while (head != NULL) { cout << head->data << " "; head = head->next; }} // Driver program to test aboveint main(){ // Creating list 1->3->4->5 Node* head = getNode(1); head->next = getNode(3); head->next->next = getNode(4); head->next->next->next = getNode(5); int n = 4, x = 2; cout << "Original Linked List: "; printList(head); insertAfterNthNode(head, n, x); cout << "\nLinked List After Insertion: "; printList(head); return 0;} // Java implementation to// insert a node after the// nth node from the endclass GfG{ // structure of a nodestatic class Node{ int data; Node next;} // function to get a new nodestatic Node getNode(int data){ // allocate memory for the node Node newNode = new Node(); // put in the data newNode.data = data; newNode.next = null; return newNode;} // function to insert a node after// the nth node from the endstatic void insertAfterNthNode(Node head, int n, int x){ // if list is empty if (head == null) return; // get a new node for the value 'x' Node newNode = getNode(x); // Initializing the slow // and fast pointers Node slow_ptr = head; Node fast_ptr = head; // move 'fast_ptr' to point to the // nth node from the beginning for (int i = 1; i <= n - 1; i++) fast_ptr = fast_ptr.next; // iterate until 'fast_ptr' points // to the last node while (fast_ptr.next != null) { // move both the pointers to the // respective next nodes slow_ptr = slow_ptr.next; fast_ptr = fast_ptr.next; } // insert the 'newNode' by making the // necessary adjustment in the links newNode.next = slow_ptr.next; slow_ptr.next = newNode;} // function to print the liststatic void printList(Node head){ while (head != null) { System.out.print(head.data + " "); head = head.next; }} // Driver codepublic static void main(String[] args){ // Creating list 1->3->4->5 Node head = getNode(1); head.next = getNode(3); head.next.next = getNode(4); head.next.next.next = getNode(5); int n = 4, x = 2; System.out.println("Original Linked List: "); printList(head); insertAfterNthNode(head, n, x); System.out.println(); System.out.println("Linked List After Insertion: "); printList(head);}} // This code is contributed by// Prerna Saini. # Python3 implementation to insert a# node after the nth node from the end # Structure of a nodeclass Node: def __init__(self, data): self.data = data self.next = None # Function to get a new nodedef getNode(data): # Allocate memory for the node newNode = Node(data) return newNode # Function to insert a node after the# nth node from the enddef insertAfterNthNode(head, n, x): # If list is empty if (head == None): return # Get a new node for the value 'x' newNode = getNode(x) # Initializing the slow and fast pointers slow_ptr = head fast_ptr = head # Move 'fast_ptr' to point to the nth # node from the beginning for i in range(1, n): fast_ptr = fast_ptr.next # Iterate until 'fast_ptr' points to the # last node while (fast_ptr.next != None): # Move both the pointers to the # respective next nodes slow_ptr = slow_ptr.next fast_ptr = fast_ptr.next # Insert the 'newNode' by making the # necessary adjustment in the links newNode.next = slow_ptr.next slow_ptr.next = newNode # Function to print the listdef printList(head): while (head != None): print(head.data, end = ' ') head = head.next # Driver codeif __name__=='__main__': # Creating list 1.3.4.5 head = getNode(1) head.next = getNode(3) head.next.next = getNode(4) head.next.next.next = getNode(5) n = 4 x = 2 print("Original Linked List: ", end = '') printList(head) insertAfterNthNode(head, n, x) print("\nLinked List After Insertion: ", end = '') printList(head) # This code is contributed by rutvik_56 // C# implementation to// insert a node after the// nth node from the endusing System; class GfG{ // structure of a node public class Node { public int data; public Node next; } // function to get a new node static Node getNode(int data) { // allocate memory for the node Node newNode = new Node(); // put in the data newNode.data = data; newNode.next = null; return newNode; } // function to insert a node after // the nth node from the end static void insertAfterNthNode(Node head, int n, int x) { // if list is empty if (head == null) return; // get a new node for the value 'x' Node newNode = getNode(x); // Initializing the slow // and fast pointers Node slow_ptr = head; Node fast_ptr = head; // move 'fast_ptr' to point to the // nth node from the beginning for (int i = 1; i <= n - 1; i++) fast_ptr = fast_ptr.next; // iterate until 'fast_ptr' points // to the last node while (fast_ptr.next != null) { // move both the pointers to the // respective next nodes slow_ptr = slow_ptr.next; fast_ptr = fast_ptr.next; } // insert the 'newNode' by making the // necessary adjustment in the links newNode.next = slow_ptr.next; slow_ptr.next = newNode; } // function to print the list static void printList(Node head) { while (head != null) { Console.Write(head.data + " "); head = head.next; } } // Driver code public static void Main() { // Creating list 1->3->4->5 Node head = getNode(1); head.next = getNode(3); head.next.next = getNode(4); head.next.next.next = getNode(5); int n = 4, x = 2; Console.WriteLine("Original Linked List: "); printList(head); insertAfterNthNode(head, n, x); Console.WriteLine(); Console.WriteLine("Linked List After Insertion: "); printList(head); }} /* This code contributed by PrinciRaj1992 */ <script> // JavaScript implementation to // insert a node after the // nth node from the end // structure of a node class Node { constructor() { this.data = 0; this.next = null; } } // function to get a new node function getNode(data) { // allocate memory for the node var newNode = new Node(); // put in the data newNode.data = data; newNode.next = null; return newNode; } // function to insert a node after // the nth node from the end function insertAfterNthNode(head, n, x) { // if list is empty if (head == null) return; // get a new node for the value 'x' var newNode = getNode(x); // Initializing the slow // and fast pointers var slow_ptr = head; var fast_ptr = head; // move 'fast_ptr' to point to the // nth node from the beginning for (var i = 1; i <= n - 1; i++) fast_ptr = fast_ptr.next; // iterate until 'fast_ptr' points // to the last node while (fast_ptr.next != null) { // move both the pointers to the // respective next nodes slow_ptr = slow_ptr.next; fast_ptr = fast_ptr.next; } // insert the 'newNode' by making the // necessary adjustment in the links newNode.next = slow_ptr.next; slow_ptr.next = newNode; } // function to print the list function printList(head) { while (head != null) { document.write(head.data + " "); head = head.next; } } // Driver code // Creating list 1->3->4->5 var head = getNode(1); head.next = getNode(3); head.next.next = getNode(4); head.next.next.next = getNode(5); var n = 4, x = 2; document.write("Original Linked List: "); printList(head); insertAfterNthNode(head, n, x); document.write("<br>"); document.write("Linked List After Insertion:"); printList(head); </script> Original Linked List: 1 3 4 5 Linked List After Insertion: 1 2 3 4 5 Time Complexity: O(n), where n is the number of nodes in the list. Method 3 (Recursive Approach): Traverse the list recursively till we reach the last node. while back tracking insert the node at desired position. C++ // C++ implementation to insert a node after the// nth node from the end#include <bits/stdc++.h>using namespace std; // structure of a nodestruct Node { int data; Node* next;}; // function to get a new nodeNode* getNode(int data){ // allocate memory for the node Node* newNode = new Node(); newNode->data = data; newNode->next = NULL; return newNode;} // function to insert a node after the// nth node from the endvoid insertAfterNthNode(Node* head, int x, int& n){ // Base case if (head == NULL) return; // recursively traverse till the last node insertAfterNthNode(head->next, x, n); // condition to insert the node after nth node from end if (--n == 0) { // create a node with the given value Node* temp = getNode(x); // update the next pointer to point next node in the // list temp->next = head->next; // make sure head points to newly inserted node head->next = temp; }} // function to print the listvoid printList(Node* head){ while (head != NULL) { cout << head->data << " "; head = head->next; }} // Driver program to test above functionsint main(){ // Creating list 1->3->4->5 Node* head = getNode(1); head->next = getNode(3); head->next->next = getNode(4); head->next->next->next = getNode(5); int n = 4, x = 2; cout << "Original Linked List: "; printList(head); insertAfterNthNode(head, x, n); cout << "\nLinked List After Insertion: "; printList(head); return 0;}// This code is contributed by Upendra Original Linked List: 1 3 4 5 Linked List After Insertion: 1 2 3 4 5 Time Complexity: O(n), where n is the number of nodes in the list. This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. prerna saini princiraj1992 29AjayKumar andrew1234 rutvik_56 GauravRajput1 rdtank upendra200223 Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Swap nodes in a linked list without swapping data Circular Linked List | Set 2 (Traversal) Delete a node in a Doubly Linked List Given a linked list which is sorted, how will you insert in sorted way Circular Singly Linked List | Insertion Insertion Sort for Singly Linked List Program to implement Singly Linked List in C++ using class Priority Queue using Linked List Insert a node at a specific position in a linked list Remove last node of the linked list
[ { "code": null, "e": 24878, "s": 24850, "text": "\n29 Mar, 2022" }, { "code": null, "e": 25039, "s": 24878, "text": "Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 <= n." }, { "code": null, "e": 25050, "s": 25039, "text": "Examples: " }, { "code": null, "e": 25281, "s": 25050, "text": "Input : list: 1->3->4->5\n n = 4, x = 2\nOutput : 1->2->3->4->5\n4th node from the end is 1 and\ninsertion has been done after this node.\n\nInput : list: 10->8->3->12->5->18\n n = 2, x = 11\nOutput : 10->8->3->12->5->11->18" }, { "code": null, "e": 25582, "s": 25281, "text": "Method 1 (Using length of the list):Find the length of the linked list, i.e, the number of nodes in the list. Let it be len. Now traverse the list from the 1st node upto the (len-n+1)th node from the beginning and insert the new node after this node. This method requires two traversals of the list. " }, { "code": null, "e": 25586, "s": 25582, "text": "C++" }, { "code": null, "e": 25591, "s": 25586, "text": "Java" }, { "code": null, "e": 25599, "s": 25591, "text": "Python3" }, { "code": null, "e": 25602, "s": 25599, "text": "C#" }, { "code": null, "e": 25613, "s": 25602, "text": "Javascript" }, { "code": "// C++ implementation to insert a node after// the n-th node from the end#include <bits/stdc++.h>using namespace std; // structure of a nodestruct Node { int data; Node* next;}; // function to get a new nodeNode* getNode(int data){ // allocate memory for the node Node* newNode = (Node*)malloc(sizeof(Node)); // put in the data newNode->data = data; newNode->next = NULL; return newNode;} // function to insert a node after the// nth node from the endvoid insertAfterNthNode(Node* head, int n, int x){ // if list is empty if (head == NULL) return; // get a new node for the value 'x' Node* newNode = getNode(x); Node* ptr = head; int len = 0, i; // find length of the list, i.e, the // number of nodes in the list while (ptr != NULL) { len++; ptr = ptr->next; } // traverse up to the nth node from the end ptr = head; for (i = 1; i <= (len - n); i++) ptr = ptr->next; // insert the 'newNode' by making the // necessary adjustment in the links newNode->next = ptr->next; ptr->next = newNode;} // function to print the listvoid printList(Node* head){ while (head != NULL) { cout << head->data << \" \"; head = head->next; }} // Driver program to test aboveint main(){ // Creating list 1->3->4->5 Node* head = getNode(1); head->next = getNode(3); head->next->next = getNode(4); head->next->next->next = getNode(5); int n = 4, x = 2; cout << \"Original Linked List: \"; printList(head); insertAfterNthNode(head, n, x); cout << \"\\nLinked List After Insertion: \"; printList(head); return 0;}", "e": 27264, "s": 25613, "text": null }, { "code": "// Java implementation to insert a node after// the n-th node from the endclass GfG{ // structure of a nodestatic class Node{ int data; Node next;} // function to get a new nodestatic Node getNode(int data){ // allocate memory for the node Node newNode = new Node(); // put in the data newNode.data = data; newNode.next = null; return newNode;} // function to insert a node after the// nth node from the endstatic void insertAfterNthNode(Node head, int n, int x){ // if list is empty if (head == null) return; // get a new node for the value 'x' Node newNode = getNode(x); Node ptr = head; int len = 0, i; // find length of the list, i.e, the // number of nodes in the list while (ptr != null) { len++; ptr = ptr.next; } // traverse up to the nth node from the end ptr = head; for (i = 1; i <= (len - n); i++) ptr = ptr.next; // insert the 'newNode' by making the // necessary adjustment in the links newNode.next = ptr.next; ptr.next = newNode;} // function to print the liststatic void printList(Node head){ while (head != null) { System.out.print(head.data + \" \"); head = head.next; }} // Driver codepublic static void main(String[] args){ // Creating list 1->3->4->5 Node head = getNode(1); head.next = getNode(3); head.next.next = getNode(4); head.next.next.next = getNode(5); int n = 4, x = 2; System.out.print(\"Original Linked List: \"); printList(head); insertAfterNthNode(head, n, x); System.out.println(); System.out.print(\"Linked List After Insertion: \"); printList(head);}} // This code is contributed by prerna saini", "e": 28966, "s": 27264, "text": null }, { "code": "# Python implementation to insert a node after# the n-th node from the end # Linked List nodeclass Node: def __init__(self, data): self.data = data self.next = None # function to get a new nodedef getNode(data) : # allocate memory for the node newNode = Node(0) # put in the data newNode.data = data newNode.next = None return newNode # function to insert a node after the# nth node from the enddef insertAfterNthNode(head, n, x) : # if list is empty if (head == None) : return # get a new node for the value 'x' newNode = getNode(x) ptr = head len = 0 i = 0 # find length of the list, i.e, the # number of nodes in the list while (ptr != None) : len = len + 1 ptr = ptr.next # traverse up to the nth node from the end ptr = head i = 1 while ( i <= (len - n) ) : ptr = ptr.next i = i + 1 # insert the 'newNode' by making the # necessary adjustment in the links newNode.next = ptr.next ptr.next = newNode # function to print the listdef printList( head) : while (head != None): print(head.data ,end = \" \") head = head.next # Driver code # Creating list 1->3->4->5head = getNode(1)head.next = getNode(3)head.next.next = getNode(4)head.next.next.next = getNode(5) n = 4x = 2 print(\"Original Linked List: \")printList(head) insertAfterNthNode(head, n, x)print()print(\"Linked List After Insertion: \")printList(head) # This code is contributed by Arnab Kundu", "e": 30485, "s": 28966, "text": null }, { "code": "// C# implementation to insert a node after// the n-th node from the endusing System; class GfG{ // structure of a nodepublic class Node{ public int data; public Node next;} // function to get a new nodestatic Node getNode(int data){ // allocate memory for the node Node newNode = new Node(); // put in the data newNode.data = data; newNode.next = null; return newNode;} // function to insert a node after the// nth node from the endstatic void insertAfterNthNode(Node head, int n, int x){ // if list is empty if (head == null) return; // get a new node for the value 'x' Node newNode = getNode(x); Node ptr = head; int len = 0, i; // find length of the list, i.e, the // number of nodes in the list while (ptr != null) { len++; ptr = ptr.next; } // traverse up to the nth node from the end ptr = head; for (i = 1; i <= (len - n); i++) ptr = ptr.next; // insert the 'newNode' by making the // necessary adjustment in the links newNode.next = ptr.next; ptr.next = newNode;} // function to print the liststatic void printList(Node head){ while (head != null) { Console.Write(head.data + \" \"); head = head.next; }} // Driver codepublic static void Main(String[] args){ // Creating list 1->3->4->5 Node head = getNode(1); head.next = getNode(3); head.next.next = getNode(4); head.next.next.next = getNode(5); int n = 4, x = 2; Console.Write(\"Original Linked List: \"); printList(head); insertAfterNthNode(head, n, x); Console.WriteLine(); Console.Write(\"Linked List After Insertion: \"); printList(head);}} // This code has been contributed by 29AjayKumar", "e": 32208, "s": 30485, "text": null }, { "code": "<script> // JavaScript implementation to// insert a node after// the n-th node from the end // structure of a node class Node { constructor() { this.data = 0; this.next = null; } } // function to get a new node function getNode(data) { // allocate memory for the nodevar newNode = new Node(); // put in the data newNode.data = data; newNode.next = null; return newNode; } // function to insert a node after the // nth node from the end function insertAfterNthNode(head , n , x) { // if list is empty if (head == null) return; // get a new node for the value 'x'var newNode = getNode(x);var ptr = head; var len = 0, i; // find length of the list, i.e, the // number of nodes in the list while (ptr != null) { len++; ptr = ptr.next; } // traverse up to the nth node from the end ptr = head; for (i = 1; i <= (len - n); i++) ptr = ptr.next; // insert the 'newNode' by making the // necessary adjustment in the links newNode.next = ptr.next; ptr.next = newNode; } // function to print the list function printList(head) { while (head != null) { document.write(head.data + \" \"); head = head.next; } } // Driver code // Creating list 1->3->4->5var head = getNode(1); head.next = getNode(3); head.next.next = getNode(4); head.next.next.next = getNode(5); var n = 4, x = 2; document.write(\"Original Linked List: \"); printList(head); insertAfterNthNode(head, n, x); document.write(); document.write(\"<br/>Linked List After Insertion: \"); printList(head); // This code contributed by gauravrajput1 </script>", "e": 34119, "s": 32208, "text": null }, { "code": null, "e": 34190, "s": 34119, "text": "Original Linked List: 1 3 4 5 \nLinked List After Insertion: 1 2 3 4 5 " }, { "code": null, "e": 34257, "s": 34190, "text": "Time Complexity: O(n), where n is the number of nodes in the list." }, { "code": null, "e": 34720, "s": 34257, "text": "Method 2 (Single traversal):This method uses two pointers, one is slow_ptr and the other is fast_ptr. First move the fast_ptr up to the nth node from the beginning. Make the slow_ptr point to the 1st node of the list. Now, simultaneously move both the pointers until fast_ptr points to the last node. At this point the slow_ptr will be pointing to the nth node from the end. Insert the new node after this node. This method requires single traversal of the list." }, { "code": null, "e": 34724, "s": 34720, "text": "C++" }, { "code": null, "e": 34729, "s": 34724, "text": "Java" }, { "code": null, "e": 34737, "s": 34729, "text": "Python3" }, { "code": null, "e": 34740, "s": 34737, "text": "C#" }, { "code": null, "e": 34751, "s": 34740, "text": "Javascript" }, { "code": "// C++ implementation to insert a node after the// nth node from the end#include <bits/stdc++.h> using namespace std; // structure of a nodestruct Node { int data; Node* next;}; // function to get a new nodeNode* getNode(int data){ // allocate memory for the node Node* newNode = (Node*)malloc(sizeof(Node)); // put in the data newNode->data = data; newNode->next = NULL; return newNode;} // function to insert a node after the// nth node from the endvoid insertAfterNthNode(Node* head, int n, int x){ // if list is empty if (head == NULL) return; // get a new node for the value 'x' Node* newNode = getNode(x); // Initializing the slow and fast pointers Node* slow_ptr = head; Node* fast_ptr = head; // move 'fast_ptr' to point to the nth node // from the beginning for (int i = 1; i <= n - 1; i++) fast_ptr = fast_ptr->next; // iterate until 'fast_ptr' points to the // last node while (fast_ptr->next != NULL) { // move both the pointers to the // respective next nodes slow_ptr = slow_ptr->next; fast_ptr = fast_ptr->next; } // insert the 'newNode' by making the // necessary adjustment in the links newNode->next = slow_ptr->next; slow_ptr->next = newNode;} // function to print the listvoid printList(Node* head){ while (head != NULL) { cout << head->data << \" \"; head = head->next; }} // Driver program to test aboveint main(){ // Creating list 1->3->4->5 Node* head = getNode(1); head->next = getNode(3); head->next->next = getNode(4); head->next->next->next = getNode(5); int n = 4, x = 2; cout << \"Original Linked List: \"; printList(head); insertAfterNthNode(head, n, x); cout << \"\\nLinked List After Insertion: \"; printList(head); return 0;}", "e": 36592, "s": 34751, "text": null }, { "code": "// Java implementation to// insert a node after the// nth node from the endclass GfG{ // structure of a nodestatic class Node{ int data; Node next;} // function to get a new nodestatic Node getNode(int data){ // allocate memory for the node Node newNode = new Node(); // put in the data newNode.data = data; newNode.next = null; return newNode;} // function to insert a node after// the nth node from the endstatic void insertAfterNthNode(Node head, int n, int x){ // if list is empty if (head == null) return; // get a new node for the value 'x' Node newNode = getNode(x); // Initializing the slow // and fast pointers Node slow_ptr = head; Node fast_ptr = head; // move 'fast_ptr' to point to the // nth node from the beginning for (int i = 1; i <= n - 1; i++) fast_ptr = fast_ptr.next; // iterate until 'fast_ptr' points // to the last node while (fast_ptr.next != null) { // move both the pointers to the // respective next nodes slow_ptr = slow_ptr.next; fast_ptr = fast_ptr.next; } // insert the 'newNode' by making the // necessary adjustment in the links newNode.next = slow_ptr.next; slow_ptr.next = newNode;} // function to print the liststatic void printList(Node head){ while (head != null) { System.out.print(head.data + \" \"); head = head.next; }} // Driver codepublic static void main(String[] args){ // Creating list 1->3->4->5 Node head = getNode(1); head.next = getNode(3); head.next.next = getNode(4); head.next.next.next = getNode(5); int n = 4, x = 2; System.out.println(\"Original Linked List: \"); printList(head); insertAfterNthNode(head, n, x); System.out.println(); System.out.println(\"Linked List After Insertion: \"); printList(head);}} // This code is contributed by// Prerna Saini.", "e": 38522, "s": 36592, "text": null }, { "code": "# Python3 implementation to insert a# node after the nth node from the end # Structure of a nodeclass Node: def __init__(self, data): self.data = data self.next = None # Function to get a new nodedef getNode(data): # Allocate memory for the node newNode = Node(data) return newNode # Function to insert a node after the# nth node from the enddef insertAfterNthNode(head, n, x): # If list is empty if (head == None): return # Get a new node for the value 'x' newNode = getNode(x) # Initializing the slow and fast pointers slow_ptr = head fast_ptr = head # Move 'fast_ptr' to point to the nth # node from the beginning for i in range(1, n): fast_ptr = fast_ptr.next # Iterate until 'fast_ptr' points to the # last node while (fast_ptr.next != None): # Move both the pointers to the # respective next nodes slow_ptr = slow_ptr.next fast_ptr = fast_ptr.next # Insert the 'newNode' by making the # necessary adjustment in the links newNode.next = slow_ptr.next slow_ptr.next = newNode # Function to print the listdef printList(head): while (head != None): print(head.data, end = ' ') head = head.next # Driver codeif __name__=='__main__': # Creating list 1.3.4.5 head = getNode(1) head.next = getNode(3) head.next.next = getNode(4) head.next.next.next = getNode(5) n = 4 x = 2 print(\"Original Linked List: \", end = '') printList(head) insertAfterNthNode(head, n, x) print(\"\\nLinked List After Insertion: \", end = '') printList(head) # This code is contributed by rutvik_56", "e": 40217, "s": 38522, "text": null }, { "code": "// C# implementation to// insert a node after the// nth node from the endusing System; class GfG{ // structure of a node public class Node { public int data; public Node next; } // function to get a new node static Node getNode(int data) { // allocate memory for the node Node newNode = new Node(); // put in the data newNode.data = data; newNode.next = null; return newNode; } // function to insert a node after // the nth node from the end static void insertAfterNthNode(Node head, int n, int x) { // if list is empty if (head == null) return; // get a new node for the value 'x' Node newNode = getNode(x); // Initializing the slow // and fast pointers Node slow_ptr = head; Node fast_ptr = head; // move 'fast_ptr' to point to the // nth node from the beginning for (int i = 1; i <= n - 1; i++) fast_ptr = fast_ptr.next; // iterate until 'fast_ptr' points // to the last node while (fast_ptr.next != null) { // move both the pointers to the // respective next nodes slow_ptr = slow_ptr.next; fast_ptr = fast_ptr.next; } // insert the 'newNode' by making the // necessary adjustment in the links newNode.next = slow_ptr.next; slow_ptr.next = newNode; } // function to print the list static void printList(Node head) { while (head != null) { Console.Write(head.data + \" \"); head = head.next; } } // Driver code public static void Main() { // Creating list 1->3->4->5 Node head = getNode(1); head.next = getNode(3); head.next.next = getNode(4); head.next.next.next = getNode(5); int n = 4, x = 2; Console.WriteLine(\"Original Linked List: \"); printList(head); insertAfterNthNode(head, n, x); Console.WriteLine(); Console.WriteLine(\"Linked List After Insertion: \"); printList(head); }} /* This code contributed by PrinciRaj1992 */", "e": 42443, "s": 40217, "text": null }, { "code": "<script> // JavaScript implementation to // insert a node after the // nth node from the end // structure of a node class Node { constructor() { this.data = 0; this.next = null; } } // function to get a new node function getNode(data) { // allocate memory for the node var newNode = new Node(); // put in the data newNode.data = data; newNode.next = null; return newNode; } // function to insert a node after // the nth node from the end function insertAfterNthNode(head, n, x) { // if list is empty if (head == null) return; // get a new node for the value 'x' var newNode = getNode(x); // Initializing the slow // and fast pointers var slow_ptr = head; var fast_ptr = head; // move 'fast_ptr' to point to the // nth node from the beginning for (var i = 1; i <= n - 1; i++) fast_ptr = fast_ptr.next; // iterate until 'fast_ptr' points // to the last node while (fast_ptr.next != null) { // move both the pointers to the // respective next nodes slow_ptr = slow_ptr.next; fast_ptr = fast_ptr.next; } // insert the 'newNode' by making the // necessary adjustment in the links newNode.next = slow_ptr.next; slow_ptr.next = newNode; } // function to print the list function printList(head) { while (head != null) { document.write(head.data + \" \"); head = head.next; } } // Driver code // Creating list 1->3->4->5 var head = getNode(1); head.next = getNode(3); head.next.next = getNode(4); head.next.next.next = getNode(5); var n = 4, x = 2; document.write(\"Original Linked List: \"); printList(head); insertAfterNthNode(head, n, x); document.write(\"<br>\"); document.write(\"Linked List After Insertion:\"); printList(head); </script>", "e": 44524, "s": 42443, "text": null }, { "code": null, "e": 44595, "s": 44524, "text": "Original Linked List: 1 3 4 5 \nLinked List After Insertion: 1 2 3 4 5 " }, { "code": null, "e": 44662, "s": 44595, "text": "Time Complexity: O(n), where n is the number of nodes in the list." }, { "code": null, "e": 44693, "s": 44662, "text": "Method 3 (Recursive Approach):" }, { "code": null, "e": 44752, "s": 44693, "text": "Traverse the list recursively till we reach the last node." }, { "code": null, "e": 44809, "s": 44752, "text": "while back tracking insert the node at desired position." }, { "code": null, "e": 44813, "s": 44809, "text": "C++" }, { "code": "// C++ implementation to insert a node after the// nth node from the end#include <bits/stdc++.h>using namespace std; // structure of a nodestruct Node { int data; Node* next;}; // function to get a new nodeNode* getNode(int data){ // allocate memory for the node Node* newNode = new Node(); newNode->data = data; newNode->next = NULL; return newNode;} // function to insert a node after the// nth node from the endvoid insertAfterNthNode(Node* head, int x, int& n){ // Base case if (head == NULL) return; // recursively traverse till the last node insertAfterNthNode(head->next, x, n); // condition to insert the node after nth node from end if (--n == 0) { // create a node with the given value Node* temp = getNode(x); // update the next pointer to point next node in the // list temp->next = head->next; // make sure head points to newly inserted node head->next = temp; }} // function to print the listvoid printList(Node* head){ while (head != NULL) { cout << head->data << \" \"; head = head->next; }} // Driver program to test above functionsint main(){ // Creating list 1->3->4->5 Node* head = getNode(1); head->next = getNode(3); head->next->next = getNode(4); head->next->next->next = getNode(5); int n = 4, x = 2; cout << \"Original Linked List: \"; printList(head); insertAfterNthNode(head, x, n); cout << \"\\nLinked List After Insertion: \"; printList(head); return 0;}// This code is contributed by Upendra", "e": 46395, "s": 44813, "text": null }, { "code": null, "e": 46466, "s": 46395, "text": "Original Linked List: 1 3 4 5 \nLinked List After Insertion: 1 2 3 4 5 " }, { "code": null, "e": 46533, "s": 46466, "text": "Time Complexity: O(n), where n is the number of nodes in the list." }, { "code": null, "e": 46955, "s": 46533, "text": "This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 46968, "s": 46955, "text": "prerna saini" }, { "code": null, "e": 46982, "s": 46968, "text": "princiraj1992" }, { "code": null, "e": 46994, "s": 46982, "text": "29AjayKumar" }, { "code": null, "e": 47005, "s": 46994, "text": "andrew1234" }, { "code": null, "e": 47015, "s": 47005, "text": "rutvik_56" }, { "code": null, "e": 47029, "s": 47015, "text": "GauravRajput1" }, { "code": null, "e": 47036, "s": 47029, "text": "rdtank" }, { "code": null, "e": 47050, "s": 47036, "text": "upendra200223" }, { "code": null, "e": 47062, "s": 47050, "text": "Linked List" }, { "code": null, "e": 47074, "s": 47062, "text": "Linked List" }, { "code": null, "e": 47172, "s": 47074, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47181, "s": 47172, "text": "Comments" }, { "code": null, "e": 47194, "s": 47181, "text": "Old Comments" }, { "code": null, "e": 47244, "s": 47194, "text": "Swap nodes in a linked list without swapping data" }, { "code": null, "e": 47285, "s": 47244, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 47323, "s": 47285, "text": "Delete a node in a Doubly Linked List" }, { "code": null, "e": 47394, "s": 47323, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 47434, "s": 47394, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 47472, "s": 47434, "text": "Insertion Sort for Singly Linked List" }, { "code": null, "e": 47531, "s": 47472, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 47564, "s": 47531, "text": "Priority Queue using Linked List" }, { "code": null, "e": 47618, "s": 47564, "text": "Insert a node at a specific position in a linked list" } ]
DRY (Don’t Repeat Yourself) Principle in Java with Examples - GeeksforGeeks
08 May, 2021 DRY is simply an approach, or we can say a different perceptive to programmers. DRY stands for Don’t Repeat Yourself. In Java, it means don’t write the same code repeatedly. Suppose you are having the same code at many places in your program, then It is known as DRY, You are repeating the same code repeatedly at different places. Hence, the solution is obtained using the DRY concept by placing the methods in place of all repeated codes and define the code in one method. So By calling methods, we will reach the principle DRY. Applications: Online marketing applications education financial applications Illustration: Consider the scenario of the college student system. The college contains many departments. So each department has different people, but the college name is the same. So no need to specify the college name for each department by writing the code for the display of the college name. Implementation: Without DRY approach Example: Java // Java Program without DRY approach // Main classpublic class GFG { // Method 1 // For cse department public void CSE() { System.out.println("This is computer science"); } // Method 2 // For cse dept. college public void college() { System.out.println("IIT - Madras"); } // Method 3 // ece dept method public void ECE() { System.out.println("This is electronics"); } // Method 4 // For ece dept college 1 public void college1() { System.out.println("IIT - Madras"); } // Method 5 // For IT dept public void IT() { System.out.println( "This is Information Technology"); } // Method 6 // For IT dept college 2 public void college2() { System.out.println("IIT - Madras"); } // Method 7 // Main driver method public static void main(String[] args) { // Creating object of class in main() method GFG s = new GFG(); // Calling above methods one by one // as created above s.CSE(); s.college(); s.ECE(); s.college1(); s.IT(); s.college2(); }} This is computer science IIT - Madras This is electronics IIT - Madras This is Information Technology IIT - Madras Implementation: Applying the DRY principle Here we create only one method named college and then call the method in all the departments. Example 1: Java // Java Program with Use of DRY Concept // Importing input output classesimport java.util.*; // Main classpublic class GFG { // Method 1 // For cse department public void CSE() { // Print statement System.out.println("This is computer science"); // Calling method college(); } // Method 2 // For ece dept method public void ECE() { System.out.println("This is electronics"); // Calling method college(); } // Method 3 // For IT dept public void IT() { // Print statement System.out.println( "This is Information Technology"); // Callling method college(); } // Method 4 // For college dept public void college() { // Print statement System.out.println("IIT - Madras"); } // Method 5 // Main driver method public static void main(String[] args) { // Creating object of class in main() method GFG s = new GFG(); // Calling the methods one by one // as created above s.CSE(); s.ECE(); s.IT(); }} This is computer science IIT - Madras This is electronics IIT - Madras This is Information Technology IIT - Madras Implementation: Bank names of a person related to one bank after applying the DRY approach Example 2: Java // Java Program with Use of DRY Concept // Importing input output classesimport java.util.*; // Main classpublic class GFG { // Method 1 // For person1 public void person1() { // Print statement System.out.println("sravan"); // Calling Method 3 bank(); } // Method 2 // For person 2 public void person2() { // Print statement System.out.println("ramya"); // Calling method 3 bank(); } // Method 3 // For bank public void bank() { // Print statement System.out.println("SBI"); } // Method 4 // Main driver method public static void main(String[] args) { // Creating objectof class in main() method GFG s = new GFG(); // Calling the methods one by one s.person1(); s.person2(); }} sravan SBI ramya SBI Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Different ways of Reading a text file in Java Constructors in Java Stream In Java Exceptions in Java StringBuilder Class in Java with Examples Comparator Interface in Java with Examples Generics in Java Functional Interfaces in Java Java Programming Examples HashMap get() Method in Java
[ { "code": null, "e": 23868, "s": 23840, "text": "\n08 May, 2021" }, { "code": null, "e": 24399, "s": 23868, "text": "DRY is simply an approach, or we can say a different perceptive to programmers. DRY stands for Don’t Repeat Yourself. In Java, it means don’t write the same code repeatedly. Suppose you are having the same code at many places in your program, then It is known as DRY, You are repeating the same code repeatedly at different places. Hence, the solution is obtained using the DRY concept by placing the methods in place of all repeated codes and define the code in one method. So By calling methods, we will reach the principle DRY." }, { "code": null, "e": 24413, "s": 24399, "text": "Applications:" }, { "code": null, "e": 24443, "s": 24413, "text": "Online marketing applications" }, { "code": null, "e": 24453, "s": 24443, "text": "education" }, { "code": null, "e": 24476, "s": 24453, "text": "financial applications" }, { "code": null, "e": 24490, "s": 24476, "text": "Illustration:" }, { "code": null, "e": 24773, "s": 24490, "text": "Consider the scenario of the college student system. The college contains many departments. So each department has different people, but the college name is the same. So no need to specify the college name for each department by writing the code for the display of the college name." }, { "code": null, "e": 24810, "s": 24773, "text": "Implementation: Without DRY approach" }, { "code": null, "e": 24819, "s": 24810, "text": "Example:" }, { "code": null, "e": 24824, "s": 24819, "text": "Java" }, { "code": "// Java Program without DRY approach // Main classpublic class GFG { // Method 1 // For cse department public void CSE() { System.out.println(\"This is computer science\"); } // Method 2 // For cse dept. college public void college() { System.out.println(\"IIT - Madras\"); } // Method 3 // ece dept method public void ECE() { System.out.println(\"This is electronics\"); } // Method 4 // For ece dept college 1 public void college1() { System.out.println(\"IIT - Madras\"); } // Method 5 // For IT dept public void IT() { System.out.println( \"This is Information Technology\"); } // Method 6 // For IT dept college 2 public void college2() { System.out.println(\"IIT - Madras\"); } // Method 7 // Main driver method public static void main(String[] args) { // Creating object of class in main() method GFG s = new GFG(); // Calling above methods one by one // as created above s.CSE(); s.college(); s.ECE(); s.college1(); s.IT(); s.college2(); }}", "e": 26004, "s": 24824, "text": null }, { "code": null, "e": 26120, "s": 26004, "text": "This is computer science\nIIT - Madras\nThis is electronics\nIIT - Madras\nThis is Information Technology\nIIT - Madras\n" }, { "code": null, "e": 26163, "s": 26120, "text": "Implementation: Applying the DRY principle" }, { "code": null, "e": 26257, "s": 26163, "text": "Here we create only one method named college and then call the method in all the departments." }, { "code": null, "e": 26268, "s": 26257, "text": "Example 1:" }, { "code": null, "e": 26273, "s": 26268, "text": "Java" }, { "code": "// Java Program with Use of DRY Concept // Importing input output classesimport java.util.*; // Main classpublic class GFG { // Method 1 // For cse department public void CSE() { // Print statement System.out.println(\"This is computer science\"); // Calling method college(); } // Method 2 // For ece dept method public void ECE() { System.out.println(\"This is electronics\"); // Calling method college(); } // Method 3 // For IT dept public void IT() { // Print statement System.out.println( \"This is Information Technology\"); // Callling method college(); } // Method 4 // For college dept public void college() { // Print statement System.out.println(\"IIT - Madras\"); } // Method 5 // Main driver method public static void main(String[] args) { // Creating object of class in main() method GFG s = new GFG(); // Calling the methods one by one // as created above s.CSE(); s.ECE(); s.IT(); }}", "e": 27420, "s": 26273, "text": null }, { "code": null, "e": 27536, "s": 27420, "text": "This is computer science\nIIT - Madras\nThis is electronics\nIIT - Madras\nThis is Information Technology\nIIT - Madras\n" }, { "code": null, "e": 27628, "s": 27536, "text": "Implementation: Bank names of a person related to one bank after applying the DRY approach " }, { "code": null, "e": 27639, "s": 27628, "text": "Example 2:" }, { "code": null, "e": 27644, "s": 27639, "text": "Java" }, { "code": "// Java Program with Use of DRY Concept // Importing input output classesimport java.util.*; // Main classpublic class GFG { // Method 1 // For person1 public void person1() { // Print statement System.out.println(\"sravan\"); // Calling Method 3 bank(); } // Method 2 // For person 2 public void person2() { // Print statement System.out.println(\"ramya\"); // Calling method 3 bank(); } // Method 3 // For bank public void bank() { // Print statement System.out.println(\"SBI\"); } // Method 4 // Main driver method public static void main(String[] args) { // Creating objectof class in main() method GFG s = new GFG(); // Calling the methods one by one s.person1(); s.person2(); }}", "e": 28512, "s": 27644, "text": null }, { "code": null, "e": 28534, "s": 28512, "text": "sravan\nSBI\nramya\nSBI\n" }, { "code": null, "e": 28541, "s": 28534, "text": "Picked" }, { "code": null, "e": 28546, "s": 28541, "text": "Java" }, { "code": null, "e": 28551, "s": 28546, "text": "Java" }, { "code": null, "e": 28649, "s": 28551, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28658, "s": 28649, "text": "Comments" }, { "code": null, "e": 28671, "s": 28658, "text": "Old Comments" }, { "code": null, "e": 28717, "s": 28671, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28738, "s": 28717, "text": "Constructors in Java" }, { "code": null, "e": 28753, "s": 28738, "text": "Stream In Java" }, { "code": null, "e": 28772, "s": 28753, "text": "Exceptions in Java" }, { "code": null, "e": 28814, "s": 28772, "text": "StringBuilder Class in Java with Examples" }, { "code": null, "e": 28857, "s": 28814, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 28874, "s": 28857, "text": "Generics in Java" }, { "code": null, "e": 28904, "s": 28874, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28930, "s": 28904, "text": "Java Programming Examples" } ]
Python | Pretty Print a dictionary with dictionary value - GeeksforGeeks
28 Aug, 2019 This article just provides a quick way to pretty print a dictionary which has dictionary as values. This is required many times now days as the advent of NoSQL databases. Lets code a way to perform this particular task. Method : Using loopsWe just loop through each dictionary element and it’s corresponding values using brute manner of loops. # Python3 code to demonstrate working of# Pretty Print a dictionary with dictionary value# Using loops # initializing dictionarytest_dict = {'gfg' : {'rate' : 5, 'remark' : 'good'}, 'cs' : {'rate' : 3}} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # using loops to Pretty Printprint("The Pretty Print dictionary is : ")for sub in test_dict: print (sub) for sub_nest in test_dict[sub]: print (sub_nest, ':', test_dict[sub][sub_nest]) The original dictionary is : {'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} The Pretty Print dictionary is : gfg remark : good rate : 5 cs rate : 3 Python list-programs Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Pandas dataframe.groupby() Create a directory in Python Defaultdict in Python Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n28 Aug, 2019" }, { "code": null, "e": 25867, "s": 25647, "text": "This article just provides a quick way to pretty print a dictionary which has dictionary as values. This is required many times now days as the advent of NoSQL databases. Lets code a way to perform this particular task." }, { "code": null, "e": 25991, "s": 25867, "text": "Method : Using loopsWe just loop through each dictionary element and it’s corresponding values using brute manner of loops." }, { "code": "# Python3 code to demonstrate working of# Pretty Print a dictionary with dictionary value# Using loops # initializing dictionarytest_dict = {'gfg' : {'rate' : 5, 'remark' : 'good'}, 'cs' : {'rate' : 3}} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # using loops to Pretty Printprint(\"The Pretty Print dictionary is : \")for sub in test_dict: print (sub) for sub_nest in test_dict[sub]: print (sub_nest, ':', test_dict[sub][sub_nest])", "e": 26482, "s": 25991, "text": null }, { "code": null, "e": 26643, "s": 26482, "text": "The original dictionary is : {'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}}\nThe Pretty Print dictionary is : \ngfg\nremark : good\nrate : 5\ncs\nrate : 3\n" }, { "code": null, "e": 26664, "s": 26643, "text": "Python list-programs" }, { "code": null, "e": 26671, "s": 26664, "text": "Python" }, { "code": null, "e": 26769, "s": 26671, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26801, "s": 26769, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26843, "s": 26801, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26885, "s": 26843, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26941, "s": 26885, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26968, "s": 26941, "text": "Python Classes and Objects" }, { "code": null, "e": 26999, "s": 26968, "text": "Python | os.path.join() method" }, { "code": null, "e": 27035, "s": 26999, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 27064, "s": 27035, "text": "Create a directory in Python" }, { "code": null, "e": 27086, "s": 27064, "text": "Defaultdict in Python" } ]
How to describe “object” arguments in jsdoc? - GeeksforGeeks
19 Jul, 2019 There are various different ways to describe “object” parameters in JSDoc. We will look into 4 different ways, each with their own uses, in this article. To document objects with specified properties:Syntax:/** * @param {{a: string, b: number}} Obj description */ This syntax is good practice for objects that will only be used as arguments for the given method without needing further documentation of each property. This can also be used for @returns.Example:<html> <head> <title> GeeksforGeeks </title></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <button onclick="Hello(a, b)"> Hello </button> <script> /** * @param {{a: string, b: number}} obj User information */ function Hello(a, b) { alert('User: ' + a + ', number:' + b); }; var a = "Adarsh"; var b = 973; </script> </center></body> </html>Output:Before:After:To document objects with specified properties (type 2):Syntax:/** * @param {Object} Obj Description * @param {string} Obj.a Description * @param {number} Obj.b Description */ This syntax is good practice for objects that will only be used as arguments for the given method and need further documentation of each property. This cannot be used for @returns.Example:<html> <head> <title> GeeksforGeeks </title></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <button onclick="Hello(a, b)"> Hello </button> <script> /** * @param {Object} Obj User information * @param {string} Obj.a name of user * @param {number} Obj.b number of user */ function Hello(a, b) { alert('User: ' + a + ', number:' + b); }; var a = "name"; var b = 001; </script> </center></body> </html>Output:Before:After:To document objects that will be used more than once in source:@typedef is useful in this situation. Once the type is defined in source, you can use it as a type for JSDoc tags like @param or @returns that make use of a type.Syntax:/** * @typedef {Object} Person * @property {number} age Length of time the person has lived * @property {string} name The word by which the person is addressed */ Can also be used in a @param tag:Syntax:/** * @param {Person} p - Description of p */ Can also be used in a @returns tag:Syntax:/** * @returns {Person} Description */ Example:<!DOCTYPE html><html> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <button onclick="Hello()"> Hello </button> <p id="demo"></p> <script> /** * @typedef {Object} Person * @property {number} age Length of time the person has lived * @property {string} name The word by which the person is addressed */ function Hello() { document.getElementById( "demo").innerHTML = person.name + " " + person.age; } var person = { name: "John", lastName: "Doe", age: 50, }; </script> </center> </body> </html>Output:Before:After:To document objects that have values of the same type:Syntax:/** * @param {Object.} Dict */ This syntax is good practice for objects whose values are all the same type. In this case, the first type i.e. string describes the type of JavaScript property (keys) that always remains of string type. The second type i.e. number describes the type of value, which can be of any type.This can also be used for @returns. To document objects with specified properties:Syntax:/** * @param {{a: string, b: number}} Obj description */ This syntax is good practice for objects that will only be used as arguments for the given method without needing further documentation of each property. This can also be used for @returns.Example:<html> <head> <title> GeeksforGeeks </title></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <button onclick="Hello(a, b)"> Hello </button> <script> /** * @param {{a: string, b: number}} obj User information */ function Hello(a, b) { alert('User: ' + a + ', number:' + b); }; var a = "Adarsh"; var b = 973; </script> </center></body> </html>Output:Before:After: Syntax: /** * @param {{a: string, b: number}} Obj description */ This syntax is good practice for objects that will only be used as arguments for the given method without needing further documentation of each property. This can also be used for @returns. Example: <html> <head> <title> GeeksforGeeks </title></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <button onclick="Hello(a, b)"> Hello </button> <script> /** * @param {{a: string, b: number}} obj User information */ function Hello(a, b) { alert('User: ' + a + ', number:' + b); }; var a = "Adarsh"; var b = 973; </script> </center></body> </html> Output:Before:After: To document objects with specified properties (type 2):Syntax:/** * @param {Object} Obj Description * @param {string} Obj.a Description * @param {number} Obj.b Description */ This syntax is good practice for objects that will only be used as arguments for the given method and need further documentation of each property. This cannot be used for @returns.Example:<html> <head> <title> GeeksforGeeks </title></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <button onclick="Hello(a, b)"> Hello </button> <script> /** * @param {Object} Obj User information * @param {string} Obj.a name of user * @param {number} Obj.b number of user */ function Hello(a, b) { alert('User: ' + a + ', number:' + b); }; var a = "name"; var b = 001; </script> </center></body> </html>Output:Before:After: Syntax: /** * @param {Object} Obj Description * @param {string} Obj.a Description * @param {number} Obj.b Description */ This syntax is good practice for objects that will only be used as arguments for the given method and need further documentation of each property. This cannot be used for @returns. Example: <html> <head> <title> GeeksforGeeks </title></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <button onclick="Hello(a, b)"> Hello </button> <script> /** * @param {Object} Obj User information * @param {string} Obj.a name of user * @param {number} Obj.b number of user */ function Hello(a, b) { alert('User: ' + a + ', number:' + b); }; var a = "name"; var b = 001; </script> </center></body> </html> Output:Before:After: To document objects that will be used more than once in source:@typedef is useful in this situation. Once the type is defined in source, you can use it as a type for JSDoc tags like @param or @returns that make use of a type.Syntax:/** * @typedef {Object} Person * @property {number} age Length of time the person has lived * @property {string} name The word by which the person is addressed */ Can also be used in a @param tag:Syntax:/** * @param {Person} p - Description of p */ Can also be used in a @returns tag:Syntax:/** * @returns {Person} Description */ Example:<!DOCTYPE html><html> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <button onclick="Hello()"> Hello </button> <p id="demo"></p> <script> /** * @typedef {Object} Person * @property {number} age Length of time the person has lived * @property {string} name The word by which the person is addressed */ function Hello() { document.getElementById( "demo").innerHTML = person.name + " " + person.age; } var person = { name: "John", lastName: "Doe", age: 50, }; </script> </center> </body> </html>Output:Before:After: Syntax: /** * @typedef {Object} Person * @property {number} age Length of time the person has lived * @property {string} name The word by which the person is addressed */ Can also be used in a @param tag: Syntax: /** * @param {Person} p - Description of p */ Can also be used in a @returns tag: Syntax: /** * @returns {Person} Description */ Example: <!DOCTYPE html><html> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <button onclick="Hello()"> Hello </button> <p id="demo"></p> <script> /** * @typedef {Object} Person * @property {number} age Length of time the person has lived * @property {string} name The word by which the person is addressed */ function Hello() { document.getElementById( "demo").innerHTML = person.name + " " + person.age; } var person = { name: "John", lastName: "Doe", age: 50, }; </script> </center> </body> </html> Output:Before:After: To document objects that have values of the same type:Syntax:/** * @param {Object.} Dict */ This syntax is good practice for objects whose values are all the same type. In this case, the first type i.e. string describes the type of JavaScript property (keys) that always remains of string type. The second type i.e. number describes the type of value, which can be of any type.This can also be used for @returns. Syntax: /** * @param {Object.} Dict */ This syntax is good practice for objects whose values are all the same type. In this case, the first type i.e. string describes the type of JavaScript property (keys) that always remains of string type. The second type i.e. number describes the type of value, which can be of any type. This can also be used for @returns. 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 append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25941, "s": 25913, "text": "\n19 Jul, 2019" }, { "code": null, "e": 26095, "s": 25941, "text": "There are various different ways to describe “object” parameters in JSDoc. We will look into 4 different ways, each with their own uses, in this article." }, { "code": null, "e": 29723, "s": 26095, "text": "To document objects with specified properties:Syntax:/**\n * @param {{a: string, b: number}} Obj description\n */\nThis syntax is good practice for objects that will only be used as arguments for the given method without needing further documentation of each property. This can also be used for @returns.Example:<html> <head> <title> GeeksforGeeks </title></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <button onclick=\"Hello(a, b)\"> Hello </button> <script> /** * @param {{a: string, b: number}} obj User information */ function Hello(a, b) { alert('User: ' + a + ', number:' + b); }; var a = \"Adarsh\"; var b = 973; </script> </center></body> </html>Output:Before:After:To document objects with specified properties (type 2):Syntax:/**\n * @param {Object} Obj Description\n * @param {string} Obj.a Description\n * @param {number} Obj.b Description\n */\nThis syntax is good practice for objects that will only be used as arguments for the given method and need further documentation of each property. This cannot be used for @returns.Example:<html> <head> <title> GeeksforGeeks </title></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <button onclick=\"Hello(a, b)\"> Hello </button> <script> /** * @param {Object} Obj User information * @param {string} Obj.a name of user * @param {number} Obj.b number of user */ function Hello(a, b) { alert('User: ' + a + ', number:' + b); }; var a = \"name\"; var b = 001; </script> </center></body> </html>Output:Before:After:To document objects that will be used more than once in source:@typedef is useful in this situation. Once the type is defined in source, you can use it as a type for JSDoc tags like @param or @returns that make use of a type.Syntax:/**\n * @typedef {Object} Person\n * @property {number} age Length of time the person has lived\n * @property {string} name The word by which the person is addressed\n */\nCan also be used in a @param tag:Syntax:/**\n * @param {Person} p - Description of p\n */\nCan also be used in a @returns tag:Syntax:/**\n * @returns {Person} Description\n */\nExample:<!DOCTYPE html><html> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <button onclick=\"Hello()\"> Hello </button> <p id=\"demo\"></p> <script> /** * @typedef {Object} Person * @property {number} age Length of time the person has lived * @property {string} name The word by which the person is addressed */ function Hello() { document.getElementById( \"demo\").innerHTML = person.name + \" \" + person.age; } var person = { name: \"John\", lastName: \"Doe\", age: 50, }; </script> </center> </body> </html>Output:Before:After:To document objects that have values of the same type:Syntax:/**\n * @param {Object.} Dict\n */\nThis syntax is good practice for objects whose values are all the same type. In this case, the first type i.e. string describes the type of JavaScript property (keys) that always remains of string type. The second type i.e. number describes the type of value, which can be of any type.This can also be used for @returns." }, { "code": null, "e": 30586, "s": 29723, "text": "To document objects with specified properties:Syntax:/**\n * @param {{a: string, b: number}} Obj description\n */\nThis syntax is good practice for objects that will only be used as arguments for the given method without needing further documentation of each property. This can also be used for @returns.Example:<html> <head> <title> GeeksforGeeks </title></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <button onclick=\"Hello(a, b)\"> Hello </button> <script> /** * @param {{a: string, b: number}} obj User information */ function Hello(a, b) { alert('User: ' + a + ', number:' + b); }; var a = \"Adarsh\"; var b = 973; </script> </center></body> </html>Output:Before:After:" }, { "code": null, "e": 30594, "s": 30586, "text": "Syntax:" }, { "code": null, "e": 30654, "s": 30594, "text": "/**\n * @param {{a: string, b: number}} Obj description\n */\n" }, { "code": null, "e": 30844, "s": 30654, "text": "This syntax is good practice for objects that will only be used as arguments for the given method without needing further documentation of each property. This can also be used for @returns." }, { "code": null, "e": 30853, "s": 30844, "text": "Example:" }, { "code": "<html> <head> <title> GeeksforGeeks </title></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <button onclick=\"Hello(a, b)\"> Hello </button> <script> /** * @param {{a: string, b: number}} obj User information */ function Hello(a, b) { alert('User: ' + a + ', number:' + b); }; var a = \"Adarsh\"; var b = 973; </script> </center></body> </html>", "e": 31387, "s": 30853, "text": null }, { "code": null, "e": 31408, "s": 31387, "text": "Output:Before:After:" }, { "code": null, "e": 32417, "s": 31408, "text": "To document objects with specified properties (type 2):Syntax:/**\n * @param {Object} Obj Description\n * @param {string} Obj.a Description\n * @param {number} Obj.b Description\n */\nThis syntax is good practice for objects that will only be used as arguments for the given method and need further documentation of each property. This cannot be used for @returns.Example:<html> <head> <title> GeeksforGeeks </title></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <button onclick=\"Hello(a, b)\"> Hello </button> <script> /** * @param {Object} Obj User information * @param {string} Obj.a name of user * @param {number} Obj.b number of user */ function Hello(a, b) { alert('User: ' + a + ', number:' + b); }; var a = \"name\"; var b = 001; </script> </center></body> </html>Output:Before:After:" }, { "code": null, "e": 32425, "s": 32417, "text": "Syntax:" }, { "code": null, "e": 32546, "s": 32425, "text": "/**\n * @param {Object} Obj Description\n * @param {string} Obj.a Description\n * @param {number} Obj.b Description\n */\n" }, { "code": null, "e": 32727, "s": 32546, "text": "This syntax is good practice for objects that will only be used as arguments for the given method and need further documentation of each property. This cannot be used for @returns." }, { "code": null, "e": 32736, "s": 32727, "text": "Example:" }, { "code": "<html> <head> <title> GeeksforGeeks </title></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <button onclick=\"Hello(a, b)\"> Hello </button> <script> /** * @param {Object} Obj User information * @param {string} Obj.a name of user * @param {number} Obj.b number of user */ function Hello(a, b) { alert('User: ' + a + ', number:' + b); }; var a = \"name\"; var b = 001; </script> </center></body> </html>", "e": 33355, "s": 32736, "text": null }, { "code": null, "e": 33376, "s": 33355, "text": "Output:Before:After:" }, { "code": null, "e": 34720, "s": 33376, "text": "To document objects that will be used more than once in source:@typedef is useful in this situation. Once the type is defined in source, you can use it as a type for JSDoc tags like @param or @returns that make use of a type.Syntax:/**\n * @typedef {Object} Person\n * @property {number} age Length of time the person has lived\n * @property {string} name The word by which the person is addressed\n */\nCan also be used in a @param tag:Syntax:/**\n * @param {Person} p - Description of p\n */\nCan also be used in a @returns tag:Syntax:/**\n * @returns {Person} Description\n */\nExample:<!DOCTYPE html><html> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <button onclick=\"Hello()\"> Hello </button> <p id=\"demo\"></p> <script> /** * @typedef {Object} Person * @property {number} age Length of time the person has lived * @property {string} name The word by which the person is addressed */ function Hello() { document.getElementById( \"demo\").innerHTML = person.name + \" \" + person.age; } var person = { name: \"John\", lastName: \"Doe\", age: 50, }; </script> </center> </body> </html>Output:Before:After:" }, { "code": null, "e": 34728, "s": 34720, "text": "Syntax:" }, { "code": null, "e": 34896, "s": 34728, "text": "/**\n * @typedef {Object} Person\n * @property {number} age Length of time the person has lived\n * @property {string} name The word by which the person is addressed\n */\n" }, { "code": null, "e": 34930, "s": 34896, "text": "Can also be used in a @param tag:" }, { "code": null, "e": 34938, "s": 34930, "text": "Syntax:" }, { "code": null, "e": 34987, "s": 34938, "text": "/**\n * @param {Person} p - Description of p\n */\n" }, { "code": null, "e": 35023, "s": 34987, "text": "Can also be used in a @returns tag:" }, { "code": null, "e": 35031, "s": 35023, "text": "Syntax:" }, { "code": null, "e": 35073, "s": 35031, "text": "/**\n * @returns {Person} Description\n */\n" }, { "code": null, "e": 35082, "s": 35073, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <button onclick=\"Hello()\"> Hello </button> <p id=\"demo\"></p> <script> /** * @typedef {Object} Person * @property {number} age Length of time the person has lived * @property {string} name The word by which the person is addressed */ function Hello() { document.getElementById( \"demo\").innerHTML = person.name + \" \" + person.age; } var person = { name: \"John\", lastName: \"Doe\", age: 50, }; </script> </center> </body> </html>", "e": 35828, "s": 35082, "text": null }, { "code": null, "e": 35849, "s": 35828, "text": "Output:Before:After:" }, { "code": null, "e": 36264, "s": 35849, "text": "To document objects that have values of the same type:Syntax:/**\n * @param {Object.} Dict\n */\nThis syntax is good practice for objects whose values are all the same type. In this case, the first type i.e. string describes the type of JavaScript property (keys) that always remains of string type. The second type i.e. number describes the type of value, which can be of any type.This can also be used for @returns." }, { "code": null, "e": 36272, "s": 36264, "text": "Syntax:" }, { "code": null, "e": 36306, "s": 36272, "text": "/**\n * @param {Object.} Dict\n */\n" }, { "code": null, "e": 36592, "s": 36306, "text": "This syntax is good practice for objects whose values are all the same type. In this case, the first type i.e. string describes the type of JavaScript property (keys) that always remains of string type. The second type i.e. number describes the type of value, which can be of any type." }, { "code": null, "e": 36628, "s": 36592, "text": "This can also be used for @returns." }, { "code": null, "e": 36635, "s": 36628, "text": "Picked" }, { "code": null, "e": 36646, "s": 36635, "text": "JavaScript" }, { "code": null, "e": 36663, "s": 36646, "text": "Web Technologies" }, { "code": null, "e": 36761, "s": 36663, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36801, "s": 36761, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 36846, "s": 36801, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 36907, "s": 36846, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 36979, "s": 36907, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 37031, "s": 36979, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 37071, "s": 37031, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 37104, "s": 37071, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 37149, "s": 37104, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 37192, "s": 37149, "text": "How to fetch data from an API in ReactJS ?" } ]
C# | How to change the WindowWidth of the Console - GeeksforGeeks
28 Jan, 2019 Given the normal Console in C#, the task is to change the WindowWidth of the Console. Approach: This can be done using the WindowWidth property in the Console class of the System package in C#. The WindowWidth refers to the Width of the console window measured in columns. Program 1: Getting the value of WindowWidth // C# program to illustrate the// Console.WindowWidth Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Get the WindowWidth Console.WriteLine("Current WindowWidth: {0}", Console.WindowWidth); }}} Output: Program 2: Setting the value of WindowWidth // C# program to illustrate the// Console.WindowWidth Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Get the WindowWidth Console.WriteLine("Current WindowWidth: {0}", Console.WindowWidth); // Set the WindowWidth Console.WindowWidth = 150; // Get the WindowWidth Console.Write("Current WindowWidth: {0}", Console.WindowWidth); }}} Output: Note: See the Width of the Window in both the images. CSharp-Console-Class C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Delegates C# | Abstract Classes Extension Method in C# Difference between Ref and Out keywords in C# C# | Replace() Method C# | Class and Object C# | Constructors C# | String.IndexOf( ) Method | Set - 1 Introduction to .NET Framework C# | Data Types
[ { "code": null, "e": 26361, "s": 26333, "text": "\n28 Jan, 2019" }, { "code": null, "e": 26447, "s": 26361, "text": "Given the normal Console in C#, the task is to change the WindowWidth of the Console." }, { "code": null, "e": 26634, "s": 26447, "text": "Approach: This can be done using the WindowWidth property in the Console class of the System package in C#. The WindowWidth refers to the Width of the console window measured in columns." }, { "code": null, "e": 26678, "s": 26634, "text": "Program 1: Getting the value of WindowWidth" }, { "code": "// C# program to illustrate the// Console.WindowWidth Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Get the WindowWidth Console.WriteLine(\"Current WindowWidth: {0}\", Console.WindowWidth); }}}", "e": 27073, "s": 26678, "text": null }, { "code": null, "e": 27081, "s": 27073, "text": "Output:" }, { "code": null, "e": 27125, "s": 27081, "text": "Program 2: Setting the value of WindowWidth" }, { "code": "// C# program to illustrate the// Console.WindowWidth Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Get the WindowWidth Console.WriteLine(\"Current WindowWidth: {0}\", Console.WindowWidth); // Set the WindowWidth Console.WindowWidth = 150; // Get the WindowWidth Console.Write(\"Current WindowWidth: {0}\", Console.WindowWidth); }}}", "e": 27716, "s": 27125, "text": null }, { "code": null, "e": 27724, "s": 27716, "text": "Output:" }, { "code": null, "e": 27778, "s": 27724, "text": "Note: See the Width of the Window in both the images." }, { "code": null, "e": 27799, "s": 27778, "text": "CSharp-Console-Class" }, { "code": null, "e": 27802, "s": 27799, "text": "C#" }, { "code": null, "e": 27900, "s": 27802, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27915, "s": 27900, "text": "C# | Delegates" }, { "code": null, "e": 27937, "s": 27915, "text": "C# | Abstract Classes" }, { "code": null, "e": 27960, "s": 27937, "text": "Extension Method in C#" }, { "code": null, "e": 28006, "s": 27960, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28028, "s": 28006, "text": "C# | Replace() Method" }, { "code": null, "e": 28050, "s": 28028, "text": "C# | Class and Object" }, { "code": null, "e": 28068, "s": 28050, "text": "C# | Constructors" }, { "code": null, "e": 28108, "s": 28068, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 28139, "s": 28108, "text": "Introduction to .NET Framework" } ]
How to convert a super class variable into a sub class type in Java
Inheritance is a relation between two classes where one class inherits the properties of the other class. This relation can be defined using the extends keyword as − public class A extends B{} public class A extends B{ The class which inherits the properties is known as sub class or, child class and the class whose properties are inherited is super class or, parent class. In inheritance a copy of super class members is created in the sub class object. Therefore, using the sub class object you can access the members of the both classes. You can try to convert the super class variable to the sub class type by simply using the cast operator. But, first of all you need to create the super class reference using the sub class object and then, convert this (super) reference type to sub class type using the cast operator. Live Demo class Person{ public String name; public int age; public Person(String name, int age){ this.name = name; this.age = age; } public void displayPerson() { System.out.println("Data of the Person class: "); System.out.println("Name: "+this.name); System.out.println("Age: "+this.age); } } public class Sample extends Person { public String branch; public int Student_id; public Sample(String name, int age, String branch, int Student_id){ super(name, age); this.branch = branch; this.Student_id = Student_id; } public void displayStudent() { System.out.println("Data of the Student class: "); System.out.println("Name: "+super.name); System.out.println("Age: "+super.age); System.out.println("Branch: "+this.branch); System.out.println("Student ID: "+this.Student_id); } public static void main(String[] args) { Person person = new Sample("Krishna", 20, "IT", 1256); //Converting super class variable to sub class type Sample obj = (Sample) person; obj.displayPerson(); obj.displayStudent(); } } Data of the Person class: Name: Krishna Age: 20 Data of the Student class: Name: Krishna Age: 20 Branch: IT Student ID: 1256 Live Demo class Super{ public Super(){ System.out.println("Constructor of the super class"); } public void superMethod() { System.out.println("Method of the super class "); } } public class Test extends Super { public Test(){ System.out.println("Constructor of the sub class"); } public void subMethod() { System.out.println("Method of the sub class "); } public static void main(String[] args) { Super sup = new Test(); //Converting super class variable to sub class type Test obj = (Test) sup; obj.superMethod(); obj.subMethod(); } } Constructor of the super class Constructor of the sub class Method of the super class Method of the sub class
[ { "code": null, "e": 1228, "s": 1062, "text": "Inheritance is a relation between two classes where one class inherits the properties of the other class. This relation can be defined using the extends keyword as −" }, { "code": null, "e": 1255, "s": 1228, "text": "public class A extends B{}" }, { "code": null, "e": 1281, "s": 1255, "text": "public class A extends B{" }, { "code": null, "e": 1437, "s": 1281, "text": "The class which inherits the properties is known as sub class or, child class and the class whose properties are inherited is super class or, parent class." }, { "code": null, "e": 1604, "s": 1437, "text": "In inheritance a copy of super class members is created in the sub class object. Therefore, using the sub class object you can access the members of the both classes." }, { "code": null, "e": 1888, "s": 1604, "text": "You can try to convert the super class variable to the sub class type by simply using the cast operator. But, first of all you need to create the super class reference using the sub class object and then, convert this (super) reference type to sub class type using the cast operator." }, { "code": null, "e": 1898, "s": 1888, "text": "Live Demo" }, { "code": null, "e": 3058, "s": 1898, "text": "class Person{\n public String name;\n public int age;\n public Person(String name, int age){\n this.name = name;\n this.age = age;\n }\n public void displayPerson() {\n System.out.println(\"Data of the Person class: \");\n System.out.println(\"Name: \"+this.name);\n System.out.println(\"Age: \"+this.age);\n }\n}\npublic class Sample extends Person {\n public String branch;\n public int Student_id;\n\n public Sample(String name, int age, String branch, int Student_id){\n super(name, age);\n this.branch = branch;\n this.Student_id = Student_id;\n }\n public void displayStudent() {\n System.out.println(\"Data of the Student class: \");\n System.out.println(\"Name: \"+super.name);\n System.out.println(\"Age: \"+super.age);\n System.out.println(\"Branch: \"+this.branch);\n System.out.println(\"Student ID: \"+this.Student_id);\n }\n public static void main(String[] args) { \n Person person = new Sample(\"Krishna\", 20, \"IT\", 1256); \n //Converting super class variable to sub class type\n Sample obj = (Sample) person; \n obj.displayPerson();\n obj.displayStudent();\n }\n}" }, { "code": null, "e": 3183, "s": 3058, "text": "Data of the Person class:\nName: Krishna\nAge: 20\nData of the Student class:\nName: Krishna\nAge: 20\nBranch: IT\nStudent ID: 1256" }, { "code": null, "e": 3193, "s": 3183, "text": "Live Demo" }, { "code": null, "e": 3823, "s": 3193, "text": "class Super{\n public Super(){\n System.out.println(\"Constructor of the super class\");\n }\n public void superMethod() {\n System.out.println(\"Method of the super class \");\n }\n}\npublic class Test extends Super {\n public Test(){\n System.out.println(\"Constructor of the sub class\");\n }\n public void subMethod() {\n System.out.println(\"Method of the sub class \");\n }\n public static void main(String[] args) { \n Super sup = new Test(); \n //Converting super class variable to sub class type\n Test obj = (Test) sup; \n obj.superMethod();\n obj.subMethod();\n }\n}" }, { "code": null, "e": 3933, "s": 3823, "text": "Constructor of the super class\nConstructor of the sub class\nMethod of the super class\nMethod of the sub class" } ]
LEAST() Function in MySQL - GeeksforGeeks
29 Sep, 2020 LEAST() function in MySQL is used to find smallest values from given arguments respectively. If any given value is NULL, it return NULLs. Otherwise it returns the smallest value. Syntax : LEAST(X1, X2, X3, ...) Parameter : This method accepts N parameter as mentioned above and described below : X1, X2, X3... : The list of values from which smallest to be evaluated. Returns : It returns the smallest value. Example-1 : Finding Smallest number between given numbers using LEAST() function. SELECT LEAST(10, 20, 30, 40) AS Least_Value; Output : +-------------+ | Least_Value | +-------------+ | 10 | +-------------+ Example-2 : Finding Smallest value between given string using LEAST() function. SELECT LEAST( 'MySQL', 'MS ACCESS', 'SQL') AS LeastValue_String; Output : +-------------------+ | LeastValue_String | +-------------------+ | MS ACCESS | +-------------------+ Example-3 : The LEAST function can also be used to find the Smallest value of a column data . To demonstrate create a table named. Student : CREATE TABLE Student( Student_id INT AUTO_INCREMENT, Student_name VARCHAR(100) NOT NULL, Student_Class VARCHAR(20) NOT NULL, Subject1 INT NOT NULL, Subject2 INT NOT NULL, Subject3 INT NOT NULL, Subject4 INT NOT NULL, PRIMARY KEY(Student_id ) ); Now inserting some data to the Student table : INSERT INTO Student(Student_name, Student_Class, Subject1, Subject2, Subject3, Subject4) VALUES ('Sayan', 'X', 81, 90, 86, 98 ), ('Nitin', 'X', 90, 84, 88, 90 ), ('Aniket', 'X', 81, 80, 87, 90 ), ('Abdur', 'X', 85, 90, 80, 90 ), ('Sanjoy', 'X', 88, 82, 84, 90 ) ; So, Our table looks like : +------------+--------------+---------------+----------+----------+----------+----------+ | Student_id | Student_name | Student_Class | Subject1 | Subject2 | Subject3 | Subject4 | +------------+--------------+---------------+----------+----------+----------+----------+ | 1 | Sayan | X | 81 | 90 | 86 | 98 | | 2 | Nitin | X | 90 | 84 | 88 | 90 | | 3 | Aniket | X | 81 | 80 | 87 | 90 | | 4 | Abdur | X | 85 | 90 | 80 | 90 | | 5 | Sanjoy | X | 88 | 82 | 84 | 90 | +------------+--------------+---------------+----------+----------+----------+----------+ Now, we are going to find least marks for every student among all subjects. Select Student_id, Student_name, LEAST(Subject1, Subject2, Subject3, Subject4) as Least_Mark FROM Student; Output : +------------+--------------+------------+ | Student_id | Student_name | Least_Mark | +------------+--------------+------------+ | 1 | Sayan | 81 | | 2 | Nitin | 84 | | 3 | Aniket | 80 | | 4 | Abdur | 80 | | 5 | Sanjoy | 82 | +------------+--------------+------------+ DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL | Subquery SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL using Python How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25623, "s": 25595, "text": "\n29 Sep, 2020" }, { "code": null, "e": 25802, "s": 25623, "text": "LEAST() function in MySQL is used to find smallest values from given arguments respectively. If any given value is NULL, it return NULLs. Otherwise it returns the smallest value." }, { "code": null, "e": 25811, "s": 25802, "text": "Syntax :" }, { "code": null, "e": 25836, "s": 25811, "text": "LEAST(X1, X2, X3, ...) \n" }, { "code": null, "e": 25921, "s": 25836, "text": "Parameter : This method accepts N parameter as mentioned above and described below :" }, { "code": null, "e": 25993, "s": 25921, "text": "X1, X2, X3... : The list of values from which smallest to be evaluated." }, { "code": null, "e": 26034, "s": 25993, "text": "Returns : It returns the smallest value." }, { "code": null, "e": 26116, "s": 26034, "text": "Example-1 : Finding Smallest number between given numbers using LEAST() function." }, { "code": null, "e": 26162, "s": 26116, "text": "SELECT LEAST(10, 20, 30, 40) AS Least_Value;\n" }, { "code": null, "e": 26171, "s": 26162, "text": "Output :" }, { "code": null, "e": 26252, "s": 26171, "text": "+-------------+\n| Least_Value |\n+-------------+\n| 10 |\n+-------------+\n" }, { "code": null, "e": 26332, "s": 26252, "text": "Example-2 : Finding Smallest value between given string using LEAST() function." }, { "code": null, "e": 26398, "s": 26332, "text": "SELECT LEAST( 'MySQL', 'MS ACCESS', 'SQL') AS LeastValue_String;\n" }, { "code": null, "e": 26407, "s": 26398, "text": "Output :" }, { "code": null, "e": 26518, "s": 26407, "text": "+-------------------+\n| LeastValue_String |\n+-------------------+\n| MS ACCESS |\n+-------------------+\n" }, { "code": null, "e": 26649, "s": 26518, "text": "Example-3 : The LEAST function can also be used to find the Smallest value of a column data . To demonstrate create a table named." }, { "code": null, "e": 26659, "s": 26649, "text": "Student :" }, { "code": null, "e": 26946, "s": 26659, "text": "CREATE TABLE Student(\n\n Student_id INT AUTO_INCREMENT, \n Student_name VARCHAR(100) NOT NULL,\n Student_Class VARCHAR(20) NOT NULL,\n Subject1 INT NOT NULL,\n Subject2 INT NOT NULL,\n Subject3 INT NOT NULL,\n Subject4 INT NOT NULL,\n\n PRIMARY KEY(Student_id )\n\n);\n" }, { "code": null, "e": 26993, "s": 26946, "text": "Now inserting some data to the Student table :" }, { "code": null, "e": 27286, "s": 26993, "text": "INSERT INTO \n Student(Student_name, Student_Class, Subject1, Subject2, Subject3, Subject4)\n\nVALUES\n ('Sayan', 'X', 81, 90, 86, 98 ),\n ('Nitin', 'X', 90, 84, 88, 90 ),\n ('Aniket', 'X', 81, 80, 87, 90 ),\n ('Abdur', 'X', 85, 90, 80, 90 ),\n ('Sanjoy', 'X', 88, 82, 84, 90 ) ;\n" }, { "code": null, "e": 27313, "s": 27286, "text": "So, Our table looks like :" }, { "code": null, "e": 28124, "s": 27313, "text": "+------------+--------------+---------------+----------+----------+----------+----------+\n| Student_id | Student_name | Student_Class | Subject1 | Subject2 | Subject3 | Subject4 |\n+------------+--------------+---------------+----------+----------+----------+----------+\n| 1 | Sayan | X | 81 | 90 | 86 | 98 |\n| 2 | Nitin | X | 90 | 84 | 88 | 90 |\n| 3 | Aniket | X | 81 | 80 | 87 | 90 |\n| 4 | Abdur | X | 85 | 90 | 80 | 90 |\n| 5 | Sanjoy | X | 88 | 82 | 84 | 90 |\n+------------+--------------+---------------+----------+----------+----------+----------+\n" }, { "code": null, "e": 28200, "s": 28124, "text": "Now, we are going to find least marks for every student among all subjects." }, { "code": null, "e": 28314, "s": 28200, "text": "Select \n Student_id, Student_name, LEAST(Subject1, Subject2, Subject3, Subject4) as Least_Mark \nFROM Student;\n" }, { "code": null, "e": 28323, "s": 28314, "text": "Output :" }, { "code": null, "e": 28711, "s": 28323, "text": "+------------+--------------+------------+\n| Student_id | Student_name | Least_Mark |\n+------------+--------------+------------+\n| 1 | Sayan | 81 |\n| 2 | Nitin | 84 |\n| 3 | Aniket | 80 |\n| 4 | Abdur | 80 |\n| 5 | Sanjoy | 82 |\n+------------+--------------+------------+\n" }, { "code": null, "e": 28720, "s": 28711, "text": "DBMS-SQL" }, { "code": null, "e": 28726, "s": 28720, "text": "mysql" }, { "code": null, "e": 28730, "s": 28726, "text": "SQL" }, { "code": null, "e": 28734, "s": 28730, "text": "SQL" }, { "code": null, "e": 28832, "s": 28734, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28898, "s": 28832, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 28955, "s": 28898, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 28987, "s": 28955, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 29002, "s": 28987, "text": "SQL | Subquery" }, { "code": null, "e": 29080, "s": 29002, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 29116, "s": 29080, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 29133, "s": 29116, "text": "SQL using Python" }, { "code": null, "e": 29199, "s": 29133, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 29261, "s": 29199, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
What are integer literals in C#?
An integer literal can be a decimal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, and there is no prefix id for decimal. It can also have a suffix that is a combination of U and L, for unsigned and long, respectively. Here are some of the examples of integer literals − 200 // int 90u// unsigned int Let’s use the above literal while declaring and initializing a variable − // int int a =200; We will now print the values − Live Demo using System; namespace Demo { class Program { static void Main(string[] args) { // integer literal int a = 200; Console.WriteLine(a); } } } 200
[ { "code": null, "e": 1324, "s": 1062, "text": "An integer literal can be a decimal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, and there is no prefix id for decimal. It can also have a suffix that is a combination of U and L, for unsigned and long, respectively." }, { "code": null, "e": 1376, "s": 1324, "text": "Here are some of the examples of integer literals −" }, { "code": null, "e": 1406, "s": 1376, "text": "200 // int\n90u// unsigned int" }, { "code": null, "e": 1480, "s": 1406, "text": "Let’s use the above literal while declaring and initializing a variable −" }, { "code": null, "e": 1499, "s": 1480, "text": "// int\nint a =200;" }, { "code": null, "e": 1530, "s": 1499, "text": "We will now print the values −" }, { "code": null, "e": 1541, "s": 1530, "text": " Live Demo" }, { "code": null, "e": 1732, "s": 1541, "text": "using System;\n\nnamespace Demo {\n\n class Program {\n\n static void Main(string[] args) {\n\n // integer literal\n int a = 200;\n Console.WriteLine(a);\n\n }\n }\n}" }, { "code": null, "e": 1736, "s": 1732, "text": "200" } ]
Check if an array contains all elements of a given range - GeeksforGeeks
04 Oct, 2021 An array containing positive elements is given. ‘A’ and ‘B’ are two numbers defining a range. Write a function to check if the array contains all elements in the given range.Examples : Input : arr[] = {1 4 5 2 7 8 3} A : 2, B : 5 Output : Yes Input : arr[] = {1 4 5 2 7 8 3} A : 2, B : 6 Output : No Method 1 : (Intuitive) The most intuitive approach is to sort the array and check from the element greater than ‘A’ to the element greater than ‘B’. If these elements are in continuous order, all elements in the range exists in the array.Time complexity: O(n log n) Auxiliary space: O(1)Method 2 : (Hashing) We can maintain a count array or a hash table that stores the count of all numbers in the array that are in the range A...B. Then we can simply check if every number occurred at least once.Time complexity : O(n) Auxiliary space : O(max_element)Method 3 : (Best) Do a linear traversal of the array. If an element is found such that in the given range, i.e., |arr[i]| >= A and |arr[i]| <=B C++ Java Python3 C# PHP Javascript #include <iostream>using namespace std; // Function to check the array for elements in// given rangebool check_elements(int arr[], int n, int A, int B){ // Range is the no. of elements that are // to be checked int range = B - A; // Traversing the array for (int i = 0; i < n; i++) { // If an element is in range if (abs(arr[i]) >= A && abs(arr[i]) <= B) { // Negating at index ‘element – A’ int z = abs(arr[i]) - A; if (arr[z] > 0) { arr[z] = arr[z] * -1; } } } // Checking whether elements in range 0-range // are negative int count=0; for (int i = 0; i <= range && i<n; i++) { // Element from range is missing from array if (arr[i] > 0) return false; else count++; } if(count!= (range+1)) return false; // All range elements are present return true;} // Driver codeint main(){ // Defining Array and size int arr[] = { 1, 4, 5, 2, 7, 8, 3 }; int n = sizeof(arr) / sizeof(arr[0]); // A is lower limit and B is the upper limit // of range int A = 2, B = 5; // True denotes all elements were present if (check_elements(arr, n, A, B)) cout << "Yes"; // False denotes any element was not present else cout << "No"; return 0;} // JAVA Code for Check if an array contains// all elements of a given rangeimport java.util.*; class GFG { // Function to check the array for elements in // given range public static boolean check_elements(int arr[], int n, int A, int B) { // Range is the no. of elements that are // to be checked int range = B - A; // Traversing the array for (int i = 0; i < n; i++) { // If an element is in range if (Math.abs(arr[i]) >= A && Math.abs(arr[i]) <= B) { int z = Math.abs(arr[i]) - A; if (arr[z] > 0) { arr[z] = arr[z] * -1; } } } // Checking whether elements in range 0-range // are negative int count=0; for (int i = 0; i <= range && i<n; i++) { // Element from range is missing from array if (arr[i] > 0) return false; else count++; } if(count!= (range+1)) return false; // All range elements are present return true; } /* Driver program to test above function */ public static void main(String[] args) { // Defining Array and size int arr[] = { 1, 4, 5, 2, 7, 8, 3 }; int n = arr.length; // A is lower limit and B is the upper limit // of range int A = 2, B = 5; // True denotes all elements were present if (check_elements(arr, n, A, B)) System.out.println("Yes"); // False denotes any element was not present else System.out.println("No"); }}// This code is contributed by Arnav Kr. Mandal. # Function to check the array for# elements in given rangedef check_elements(arr, n, A, B) : # Range is the no. of elements # that are to be checked rangeV = B - A # Traversing the array for i in range(0, n): # If an element is in range if (abs(arr[i]) >= A and abs(arr[i]) <= B) : # Negating at index ‘element – A’ z = abs(arr[i]) - A if (arr[z] > 0) : arr[z] = arr[z] * -1 # Checking whether elements in # range 0-range are negative count = 0 for i in range(0, rangeV + 1): if i >= n: break # Element from range is # missing from array if (arr[i] > 0): return False else: count = count + 1 if(count != (rangeV + 1)): return False # All range elements are present return True # Driver code # Defining Array and sizearr = [ 1, 4, 5, 2, 7, 8, 3 ]n = len(arr) # A is lower limit and B is# the upper limit of rangeA = 2B = 5 # True denotes all elements# were presentif (check_elements(arr, n, A, B)) : print("Yes") # False denotes any element# was not presentelse: print("No") # This code is contributed# by Yatin Gupta // C# Code for Check if an array contains// all elements of a given rangeusing System; class GFG { // Function to check the array for // elements in given range public static bool check_elements(int []arr, int n, int A, int B) { // Range is the no. of elements // that are to be checked int range = B - A; // Traversing the array for (int i = 0; i < n; i++) { // If an element is in range if (Math.Abs(arr[i]) >= A && Math.Abs(arr[i]) <= B) { int z = Math.Abs(arr[i]) - A; if (arr[z] > 0) { arr[z] = arr[z] * - 1; } } } // Checking whether elements in // range 0-range are negative int count=0; for (int i = 0; i <= range && i < n; i++) { // Element from range is // missing from array if (arr[i] > 0) return false; else count++; } if(count != (range + 1)) return false; // All range elements are present return true; } // Driver Code public static void Main(String []args) { // Defining Array and size int []arr = {1, 4, 5, 2, 7, 8, 3}; int n = arr.Length; // A is lower limit and B is // the upper limit of range int A = 2, B = 5; // True denotes all elements were present if (check_elements(arr, n, A, B)) Console.WriteLine("Yes"); // False denotes any element was not present else Console.WriteLine("No"); }} // This code is contributed by vt_m. <?php// Function to check the// array for elements in// given rangefunction check_elements($arr, $n, $A, $B){ // Range is the no. of // elements that are to // be checked $range = $B - $A; // Traversing the array for ($i = 0; $i < $n; $i++) { // If an element is in range if (abs($arr[$i]) >= $A && abs($arr[$i]) <= $B) { // Negating at index // ‘element – A’ $z = abs($arr[$i]) - $A; if ($arr[$z] > 0) { $arr[$z] = $arr[$z] * -1; } } } // Checking whether elements // in range 0-range are negative $count = 0; for ($i = 0; $i <= $range && $i< $n; $i++) { // Element from range is // missing from array if ($arr[$i] > 0) return -1; else $count++; } if($count!= ($range + 1)) return -1; // All range elements // are present return true;} // Driver code // Defining Array and size$arr = array(1, 4, 5, 2, 7, 8, 3);$n = sizeof($arr); // A is lower limit and// B is the upper limit// of range$A = 2; $B = 5; // True denotes all// elements were presentif ((check_elements($arr, $n, $A, $B)) == true) echo "Yes"; // False denotes any// element was not presentelse echo "No"; // This code is contributed by aj_36?> <script> // Javascript Code for Check // if an array contains // all elements of a given range // Function to check the array for // elements in given range function check_elements(arr, n, A, B) { // Range is the no. of elements // that are to be checked let range = B - A; // Traversing the array for (let i = 0; i < n; i++) { // If an element is in range if (Math.abs(arr[i]) >= A && Math.abs(arr[i]) <= B) { let z = Math.abs(arr[i]) - A; if (arr[z] > 0) { arr[z] = arr[z] * - 1; } } } // Checking whether elements in // range 0-range are negative let count=0; for (let i = 0; i <= range && i < n; i++) { // Element from range is // missing from array if (arr[i] > 0) return false; else count++; } if(count != (range + 1)) return false; // All range elements are present return true; } // Defining Array and size let arr = [1, 4, 5, 2, 7, 8, 3]; let n = arr.length; // A is lower limit and B is // the upper limit of range let A = 2, B = 5; // True denotes all elements were present if (check_elements(arr, n, A, B)) document.write("Yes"); // False denotes any element was not present else document.write("No"); </script> Output : Yes Time complexity : O(n) Auxiliary space : O(1)This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m jit_t YatinGupta divyeshrabadiya07 Mithlesh Upadhyay Arrays Searching Arrays Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search Search an element in a sorted and rotated array Find the Missing Number
[ { "code": null, "e": 26567, "s": 26539, "text": "\n04 Oct, 2021" }, { "code": null, "e": 26754, "s": 26567, "text": "An array containing positive elements is given. ‘A’ and ‘B’ are two numbers defining a range. Write a function to check if the array contains all elements in the given range.Examples : " }, { "code": null, "e": 26891, "s": 26754, "text": "Input : arr[] = {1 4 5 2 7 8 3}\n A : 2, B : 5\nOutput : Yes\n\nInput : arr[] = {1 4 5 2 7 8 3}\n A : 2, B : 6\nOutput : No" }, { "code": null, "e": 27591, "s": 26893, "text": "Method 1 : (Intuitive) The most intuitive approach is to sort the array and check from the element greater than ‘A’ to the element greater than ‘B’. If these elements are in continuous order, all elements in the range exists in the array.Time complexity: O(n log n) Auxiliary space: O(1)Method 2 : (Hashing) We can maintain a count array or a hash table that stores the count of all numbers in the array that are in the range A...B. Then we can simply check if every number occurred at least once.Time complexity : O(n) Auxiliary space : O(max_element)Method 3 : (Best) Do a linear traversal of the array. If an element is found such that in the given range, i.e., |arr[i]| >= A and |arr[i]| <=B " }, { "code": null, "e": 27595, "s": 27591, "text": "C++" }, { "code": null, "e": 27600, "s": 27595, "text": "Java" }, { "code": null, "e": 27608, "s": 27600, "text": "Python3" }, { "code": null, "e": 27611, "s": 27608, "text": "C#" }, { "code": null, "e": 27615, "s": 27611, "text": "PHP" }, { "code": null, "e": 27626, "s": 27615, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; // Function to check the array for elements in// given rangebool check_elements(int arr[], int n, int A, int B){ // Range is the no. of elements that are // to be checked int range = B - A; // Traversing the array for (int i = 0; i < n; i++) { // If an element is in range if (abs(arr[i]) >= A && abs(arr[i]) <= B) { // Negating at index ‘element – A’ int z = abs(arr[i]) - A; if (arr[z] > 0) { arr[z] = arr[z] * -1; } } } // Checking whether elements in range 0-range // are negative int count=0; for (int i = 0; i <= range && i<n; i++) { // Element from range is missing from array if (arr[i] > 0) return false; else count++; } if(count!= (range+1)) return false; // All range elements are present return true;} // Driver codeint main(){ // Defining Array and size int arr[] = { 1, 4, 5, 2, 7, 8, 3 }; int n = sizeof(arr) / sizeof(arr[0]); // A is lower limit and B is the upper limit // of range int A = 2, B = 5; // True denotes all elements were present if (check_elements(arr, n, A, B)) cout << \"Yes\"; // False denotes any element was not present else cout << \"No\"; return 0;}", "e": 28988, "s": 27626, "text": null }, { "code": "// JAVA Code for Check if an array contains// all elements of a given rangeimport java.util.*; class GFG { // Function to check the array for elements in // given range public static boolean check_elements(int arr[], int n, int A, int B) { // Range is the no. of elements that are // to be checked int range = B - A; // Traversing the array for (int i = 0; i < n; i++) { // If an element is in range if (Math.abs(arr[i]) >= A && Math.abs(arr[i]) <= B) { int z = Math.abs(arr[i]) - A; if (arr[z] > 0) { arr[z] = arr[z] * -1; } } } // Checking whether elements in range 0-range // are negative int count=0; for (int i = 0; i <= range && i<n; i++) { // Element from range is missing from array if (arr[i] > 0) return false; else count++; } if(count!= (range+1)) return false; // All range elements are present return true; } /* Driver program to test above function */ public static void main(String[] args) { // Defining Array and size int arr[] = { 1, 4, 5, 2, 7, 8, 3 }; int n = arr.length; // A is lower limit and B is the upper limit // of range int A = 2, B = 5; // True denotes all elements were present if (check_elements(arr, n, A, B)) System.out.println(\"Yes\"); // False denotes any element was not present else System.out.println(\"No\"); }}// This code is contributed by Arnav Kr. Mandal.", "e": 30829, "s": 28988, "text": null }, { "code": "# Function to check the array for# elements in given rangedef check_elements(arr, n, A, B) : # Range is the no. of elements # that are to be checked rangeV = B - A # Traversing the array for i in range(0, n): # If an element is in range if (abs(arr[i]) >= A and abs(arr[i]) <= B) : # Negating at index ‘element – A’ z = abs(arr[i]) - A if (arr[z] > 0) : arr[z] = arr[z] * -1 # Checking whether elements in # range 0-range are negative count = 0 for i in range(0, rangeV + 1): if i >= n: break # Element from range is # missing from array if (arr[i] > 0): return False else: count = count + 1 if(count != (rangeV + 1)): return False # All range elements are present return True # Driver code # Defining Array and sizearr = [ 1, 4, 5, 2, 7, 8, 3 ]n = len(arr) # A is lower limit and B is# the upper limit of rangeA = 2B = 5 # True denotes all elements# were presentif (check_elements(arr, n, A, B)) : print(\"Yes\") # False denotes any element# was not presentelse: print(\"No\") # This code is contributed# by Yatin Gupta", "e": 32108, "s": 30829, "text": null }, { "code": "// C# Code for Check if an array contains// all elements of a given rangeusing System; class GFG { // Function to check the array for // elements in given range public static bool check_elements(int []arr, int n, int A, int B) { // Range is the no. of elements // that are to be checked int range = B - A; // Traversing the array for (int i = 0; i < n; i++) { // If an element is in range if (Math.Abs(arr[i]) >= A && Math.Abs(arr[i]) <= B) { int z = Math.Abs(arr[i]) - A; if (arr[z] > 0) { arr[z] = arr[z] * - 1; } } } // Checking whether elements in // range 0-range are negative int count=0; for (int i = 0; i <= range && i < n; i++) { // Element from range is // missing from array if (arr[i] > 0) return false; else count++; } if(count != (range + 1)) return false; // All range elements are present return true; } // Driver Code public static void Main(String []args) { // Defining Array and size int []arr = {1, 4, 5, 2, 7, 8, 3}; int n = arr.Length; // A is lower limit and B is // the upper limit of range int A = 2, B = 5; // True denotes all elements were present if (check_elements(arr, n, A, B)) Console.WriteLine(\"Yes\"); // False denotes any element was not present else Console.WriteLine(\"No\"); }} // This code is contributed by vt_m.", "e": 33932, "s": 32108, "text": null }, { "code": "<?php// Function to check the// array for elements in// given rangefunction check_elements($arr, $n, $A, $B){ // Range is the no. of // elements that are to // be checked $range = $B - $A; // Traversing the array for ($i = 0; $i < $n; $i++) { // If an element is in range if (abs($arr[$i]) >= $A && abs($arr[$i]) <= $B) { // Negating at index // ‘element – A’ $z = abs($arr[$i]) - $A; if ($arr[$z] > 0) { $arr[$z] = $arr[$z] * -1; } } } // Checking whether elements // in range 0-range are negative $count = 0; for ($i = 0; $i <= $range && $i< $n; $i++) { // Element from range is // missing from array if ($arr[$i] > 0) return -1; else $count++; } if($count!= ($range + 1)) return -1; // All range elements // are present return true;} // Driver code // Defining Array and size$arr = array(1, 4, 5, 2, 7, 8, 3);$n = sizeof($arr); // A is lower limit and// B is the upper limit// of range$A = 2; $B = 5; // True denotes all// elements were presentif ((check_elements($arr, $n, $A, $B)) == true) echo \"Yes\"; // False denotes any// element was not presentelse echo \"No\"; // This code is contributed by aj_36?>", "e": 35353, "s": 33932, "text": null }, { "code": "<script> // Javascript Code for Check // if an array contains // all elements of a given range // Function to check the array for // elements in given range function check_elements(arr, n, A, B) { // Range is the no. of elements // that are to be checked let range = B - A; // Traversing the array for (let i = 0; i < n; i++) { // If an element is in range if (Math.abs(arr[i]) >= A && Math.abs(arr[i]) <= B) { let z = Math.abs(arr[i]) - A; if (arr[z] > 0) { arr[z] = arr[z] * - 1; } } } // Checking whether elements in // range 0-range are negative let count=0; for (let i = 0; i <= range && i < n; i++) { // Element from range is // missing from array if (arr[i] > 0) return false; else count++; } if(count != (range + 1)) return false; // All range elements are present return true; } // Defining Array and size let arr = [1, 4, 5, 2, 7, 8, 3]; let n = arr.length; // A is lower limit and B is // the upper limit of range let A = 2, B = 5; // True denotes all elements were present if (check_elements(arr, n, A, B)) document.write(\"Yes\"); // False denotes any element was not present else document.write(\"No\"); </script>", "e": 36964, "s": 35353, "text": null }, { "code": null, "e": 36975, "s": 36964, "text": "Output : " }, { "code": null, "e": 36979, "s": 36975, "text": "Yes" }, { "code": null, "e": 37448, "s": 36979, "text": "Time complexity : O(n) Auxiliary space : O(1)This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 37453, "s": 37448, "text": "vt_m" }, { "code": null, "e": 37459, "s": 37453, "text": "jit_t" }, { "code": null, "e": 37470, "s": 37459, "text": "YatinGupta" }, { "code": null, "e": 37488, "s": 37470, "text": "divyeshrabadiya07" }, { "code": null, "e": 37506, "s": 37488, "text": "Mithlesh Upadhyay" }, { "code": null, "e": 37513, "s": 37506, "text": "Arrays" }, { "code": null, "e": 37523, "s": 37513, "text": "Searching" }, { "code": null, "e": 37530, "s": 37523, "text": "Arrays" }, { "code": null, "e": 37540, "s": 37530, "text": "Searching" }, { "code": null, "e": 37638, "s": 37540, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37706, "s": 37638, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 37750, "s": 37706, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 37798, "s": 37750, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 37821, "s": 37798, "text": "Introduction to Arrays" }, { "code": null, "e": 37853, "s": 37821, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 37867, "s": 37853, "text": "Binary Search" }, { "code": null, "e": 37935, "s": 37867, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 37949, "s": 37935, "text": "Linear Search" }, { "code": null, "e": 37997, "s": 37949, "text": "Search an element in a sorted and rotated array" } ]
String with maximum number of unique characters - GeeksforGeeks
07 Mar, 2022 Given a list of strings, find the largest string among all. The largest string is the string with the largest number of unique characters. Example: Input : "AN KOW", "LO JO", "ZEW DO RO" Output : "ZEW DO RO" Explanation : "ZEW DO RO" has maximum distinct letters. Input : "ROMEO", "EMINEM", "RADO" Output : "ROMEO" Explanation : In case of tie, we can print any of the strings. We iterate over the strings and take a boolean array to check the presence of letters. Also, keep track of the maximum unique letters. Return the string with the maximum number of distinct characters. C++ Java Python3 C# PHP Javascript // C++ code to find// the largest string#include <bits/stdc++.h>using namespace std; // Function to find string// with maximum number of// unique characters.void LargestString(string *na){ int N = sizeof(na) / sizeof(na[0]); int c[N]; // Index of string with // maximum unique characters int m = 1; // iterate through // all strings for (int j = 0; j < N; j++) { // array indicating any // alphabet included or // not included bool character[26]; // count number of unique // alphabets in each string for (int k = 0; k < na[j].size(); k++) { int x = (int)(na[j][k] - 'A'); if (na[j][k] != ' ' && character[x] == false) { c[j]++; character[x] = true; } } // keep track of maximum // number of alphabets if (c[j] > c[m]) m = j; } // print result cout << na[m] << endl;} // Driver codeint main(){ string na[] = {"BOB", "A AB C JOHNSON", "ANJALI","ASKRIT", "ARMAN MALLIK"}; LargestString(na);} // This code is contributed by// Manish Shaw(manishshaw1) // Java code to find the largest stringimport java.lang.*;import java.io.*;import java.util.Arrays; class Geek { // Function to find string with maximum // number of unique characters. public static void LargestString(String na[]) { int N = na.length; int c[] = new int[N]; // Index of string with maximum unique // characters int m = 0; // iterate through all strings for (int j = 0; j < N; j++) { // array indicating any alphabet // included or not included boolean character[] = new boolean[26]; // count number of unique alphabets in each string for (int k = 0; k < na[j].length(); k++) { int x = na[j].charAt(k) - 'A'; if ((na[j].charAt(k) != ' ') && (character[x] == false)) { c[j]++; character[x] = true; } } // keep track of maximum number of alphabets if (c[j] > c[m]) m = j; } // print result System.out.println(na[m]); } // Driver code public static void main(String[] args) { String na[] = {"BOB", "A AB C JOHNSON","ANJALI", "ASKRIT", "ARMAN MALLIK"}; LargestString(na); }} # Python3 code to find the largest string # Function to find string with maximum# number of unique characters.def LargestString(na): N = len(na) c = [0] * N # Index of string with # maximum unique characters m = 0 # Iterate through all strings for j in range(N): # Array indicating any alphabet # included or not included character = [False] * 26 # count number of unique # alphabets in each string for k in range(len(na[j])): x = ord(na[j][k]) - ord('A') if ((na[j][k] != ' ') and (character[x] == False)): c[j] += 1 character[x] = True # keep track of maximum # number of alphabets if (c[j] > c[m]): m = j # print result print(na[m]) # Driver codena = ["BOB", "A AB C JOHNSON","ANJALI", "ASKRIT", "ARMAN MALLIK"]LargestString(na) # This article is Contributed by Sharad Bhardwaj. // C# code to find the largest stringusing System; class GFG { // Function to find string with maximum // number of unique characters. public static void LargestString(string []na) { int N = na.Length; int []c = new int[N]; // Index of string with maximum unique // characters int m = 0; // iterate through all strings for (int j = 0; j < N; j++) { // array indicating any alphabet // included or not included bool []character = new bool[26]; // count number of unique alphabets // in each string for (int k = 0; k < na[j].Length; k++) { int x = na[j][k] - 'A'; if ((na[j][k] != ' ') && (character[x] == false)) { c[j]++; character[x] = true; } } // keep track of maximum number of // alphabets if (c[j] > c[m]) m = j; } // print result Console.Write(na[m]); } // Driver code public static void Main() { string []na = {"BOB", "A AB C JOHNSON", "ANJALI", "ASKRIT", "ARMAN MALLIK"}; LargestString(na); }} // This code is contributed by nitin mittal. <?php// PHP implementation to// find the largest string // Function to find string with maximum// number of unique charactersfunction LargestString($na){ $N = sizeof($na); $c = array_fill(0, $N, 0); // Index of string with maximum unique // characters $m = 0; // iterate through all strings for ($j = 0; $j < $N; $j++) { // array indicating any alphabet // included or not included $character = array_fill(0, 26, false); // count number of unique // alphabets in each string for ($k = 0; $k < strlen($na[$j]); $k++) { $x = ord($na[$j][$k]) - 65; if (($na[$j][$k] != ' ') && ($character[$x] == false)) { $c[$j]++; $character[$x] = true; } } // keep track of maximum // number of alphabets if ($c[$j] > $c[$m]) $m = $j; } // print result echo $na[$m]."\n";} // Driver code$na = array("BOB", "A AB C JOHNSON", "ASKRIT", "ARMAN MALLIK", "ANJALI");LargestString($na); // This code is contributed by mits?> <script> // C# code to find the largest string // Function to find string with maximum// number of unique characters.function LargestString(na){ let N = na.length; let c = new Array(N); // Index of string with maximum unique // characters let m = 1; // iterate through all strings for (let j = 0; j < N; j++) { // array indicating any alphabet // included or not included let character = new Array(26,0); // count number of unique alphabets // in each string for (let k = 0; k < na[j].length; k++) { let x = na[j][k].charCodeAt(0)-65; if ((na[j][k] != ' ') && (character[x] == 0)) { c[j]++; character[x] = 1; } } // keep track of maximum number of // alphabets if (c[j] > c[m]) m = j; } // print result document.write(na[m]);} // Driver code let na =["BOB", "A AB C JOHNSON","ANJALI", "ASKRIT", "ARMAN MALLIK"]; LargestString(na); </script> Output: A AB C JOHNSON YouTubeGeeksforGeeks507K subscribersString with maximum number of unique characters | 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:44•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=kjSuTowqkzI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Mithun Kumar nitin mittal manishshaw1 mohit kumar 29 arorakashish0911 frequency-counting Arrays Strings Arrays Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Reversal algorithm for array rotation Window Sliding Technique Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 Reverse a string in Java C++ Data Types Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 26177, "s": 26149, "text": "\n07 Mar, 2022" }, { "code": null, "e": 26317, "s": 26177, "text": "Given a list of strings, find the largest string among all. The largest string is the string with the largest number of unique characters. " }, { "code": null, "e": 26327, "s": 26317, "text": "Example: " }, { "code": null, "e": 26562, "s": 26327, "text": "Input : \"AN KOW\", \"LO JO\", \"ZEW DO RO\" \nOutput : \"ZEW DO RO\" \nExplanation : \n\"ZEW DO RO\" has maximum distinct letters.\n\nInput : \"ROMEO\", \"EMINEM\", \"RADO\"\nOutput : \"ROMEO\" \nExplanation : In case of tie, we can print\nany of the strings." }, { "code": null, "e": 26766, "s": 26564, "text": "We iterate over the strings and take a boolean array to check the presence of letters. Also, keep track of the maximum unique letters. Return the string with the maximum number of distinct characters. " }, { "code": null, "e": 26770, "s": 26766, "text": "C++" }, { "code": null, "e": 26775, "s": 26770, "text": "Java" }, { "code": null, "e": 26783, "s": 26775, "text": "Python3" }, { "code": null, "e": 26786, "s": 26783, "text": "C#" }, { "code": null, "e": 26790, "s": 26786, "text": "PHP" }, { "code": null, "e": 26801, "s": 26790, "text": "Javascript" }, { "code": "// C++ code to find// the largest string#include <bits/stdc++.h>using namespace std; // Function to find string// with maximum number of// unique characters.void LargestString(string *na){ int N = sizeof(na) / sizeof(na[0]); int c[N]; // Index of string with // maximum unique characters int m = 1; // iterate through // all strings for (int j = 0; j < N; j++) { // array indicating any // alphabet included or // not included bool character[26]; // count number of unique // alphabets in each string for (int k = 0; k < na[j].size(); k++) { int x = (int)(na[j][k] - 'A'); if (na[j][k] != ' ' && character[x] == false) { c[j]++; character[x] = true; } } // keep track of maximum // number of alphabets if (c[j] > c[m]) m = j; } // print result cout << na[m] << endl;} // Driver codeint main(){ string na[] = {\"BOB\", \"A AB C JOHNSON\", \"ANJALI\",\"ASKRIT\", \"ARMAN MALLIK\"}; LargestString(na);} // This code is contributed by// Manish Shaw(manishshaw1)", "e": 28027, "s": 26801, "text": null }, { "code": "// Java code to find the largest stringimport java.lang.*;import java.io.*;import java.util.Arrays; class Geek { // Function to find string with maximum // number of unique characters. public static void LargestString(String na[]) { int N = na.length; int c[] = new int[N]; // Index of string with maximum unique // characters int m = 0; // iterate through all strings for (int j = 0; j < N; j++) { // array indicating any alphabet // included or not included boolean character[] = new boolean[26]; // count number of unique alphabets in each string for (int k = 0; k < na[j].length(); k++) { int x = na[j].charAt(k) - 'A'; if ((na[j].charAt(k) != ' ') && (character[x] == false)) { c[j]++; character[x] = true; } } // keep track of maximum number of alphabets if (c[j] > c[m]) m = j; } // print result System.out.println(na[m]); } // Driver code public static void main(String[] args) { String na[] = {\"BOB\", \"A AB C JOHNSON\",\"ANJALI\", \"ASKRIT\", \"ARMAN MALLIK\"}; LargestString(na); }}", "e": 29396, "s": 28027, "text": null }, { "code": "# Python3 code to find the largest string # Function to find string with maximum# number of unique characters.def LargestString(na): N = len(na) c = [0] * N # Index of string with # maximum unique characters m = 0 # Iterate through all strings for j in range(N): # Array indicating any alphabet # included or not included character = [False] * 26 # count number of unique # alphabets in each string for k in range(len(na[j])): x = ord(na[j][k]) - ord('A') if ((na[j][k] != ' ') and (character[x] == False)): c[j] += 1 character[x] = True # keep track of maximum # number of alphabets if (c[j] > c[m]): m = j # print result print(na[m]) # Driver codena = [\"BOB\", \"A AB C JOHNSON\",\"ANJALI\", \"ASKRIT\", \"ARMAN MALLIK\"]LargestString(na) # This article is Contributed by Sharad Bhardwaj.", "e": 30433, "s": 29396, "text": null }, { "code": "// C# code to find the largest stringusing System; class GFG { // Function to find string with maximum // number of unique characters. public static void LargestString(string []na) { int N = na.Length; int []c = new int[N]; // Index of string with maximum unique // characters int m = 0; // iterate through all strings for (int j = 0; j < N; j++) { // array indicating any alphabet // included or not included bool []character = new bool[26]; // count number of unique alphabets // in each string for (int k = 0; k < na[j].Length; k++) { int x = na[j][k] - 'A'; if ((na[j][k] != ' ') && (character[x] == false)) { c[j]++; character[x] = true; } } // keep track of maximum number of // alphabets if (c[j] > c[m]) m = j; } // print result Console.Write(na[m]); } // Driver code public static void Main() { string []na = {\"BOB\", \"A AB C JOHNSON\", \"ANJALI\", \"ASKRIT\", \"ARMAN MALLIK\"}; LargestString(na); }} // This code is contributed by nitin mittal.", "e": 31791, "s": 30433, "text": null }, { "code": "<?php// PHP implementation to// find the largest string // Function to find string with maximum// number of unique charactersfunction LargestString($na){ $N = sizeof($na); $c = array_fill(0, $N, 0); // Index of string with maximum unique // characters $m = 0; // iterate through all strings for ($j = 0; $j < $N; $j++) { // array indicating any alphabet // included or not included $character = array_fill(0, 26, false); // count number of unique // alphabets in each string for ($k = 0; $k < strlen($na[$j]); $k++) { $x = ord($na[$j][$k]) - 65; if (($na[$j][$k] != ' ') && ($character[$x] == false)) { $c[$j]++; $character[$x] = true; } } // keep track of maximum // number of alphabets if ($c[$j] > $c[$m]) $m = $j; } // print result echo $na[$m].\"\\n\";} // Driver code$na = array(\"BOB\", \"A AB C JOHNSON\", \"ASKRIT\", \"ARMAN MALLIK\", \"ANJALI\");LargestString($na); // This code is contributed by mits?>", "e": 33022, "s": 31791, "text": null }, { "code": "<script> // C# code to find the largest string // Function to find string with maximum// number of unique characters.function LargestString(na){ let N = na.length; let c = new Array(N); // Index of string with maximum unique // characters let m = 1; // iterate through all strings for (let j = 0; j < N; j++) { // array indicating any alphabet // included or not included let character = new Array(26,0); // count number of unique alphabets // in each string for (let k = 0; k < na[j].length; k++) { let x = na[j][k].charCodeAt(0)-65; if ((na[j][k] != ' ') && (character[x] == 0)) { c[j]++; character[x] = 1; } } // keep track of maximum number of // alphabets if (c[j] > c[m]) m = j; } // print result document.write(na[m]);} // Driver code let na =[\"BOB\", \"A AB C JOHNSON\",\"ANJALI\", \"ASKRIT\", \"ARMAN MALLIK\"]; LargestString(na); </script>", "e": 34097, "s": 33022, "text": null }, { "code": null, "e": 34106, "s": 34097, "text": "Output: " }, { "code": null, "e": 34121, "s": 34106, "text": "A AB C JOHNSON" }, { "code": null, "e": 34967, "s": 34121, "text": "YouTubeGeeksforGeeks507K subscribersString with maximum number of unique characters | 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:44•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=kjSuTowqkzI\" 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": 34982, "s": 34969, "text": "Mithun Kumar" }, { "code": null, "e": 34995, "s": 34982, "text": "nitin mittal" }, { "code": null, "e": 35007, "s": 34995, "text": "manishshaw1" }, { "code": null, "e": 35022, "s": 35007, "text": "mohit kumar 29" }, { "code": null, "e": 35039, "s": 35022, "text": "arorakashish0911" }, { "code": null, "e": 35058, "s": 35039, "text": "frequency-counting" }, { "code": null, "e": 35065, "s": 35058, "text": "Arrays" }, { "code": null, "e": 35073, "s": 35065, "text": "Strings" }, { "code": null, "e": 35080, "s": 35073, "text": "Arrays" }, { "code": null, "e": 35088, "s": 35080, "text": "Strings" }, { "code": null, "e": 35186, "s": 35088, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35217, "s": 35186, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 35255, "s": 35217, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 35280, "s": 35255, "text": "Window Sliding Technique" }, { "code": null, "e": 35301, "s": 35280, "text": "Next Greater Element" }, { "code": null, "e": 35359, "s": 35301, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 35384, "s": 35359, "text": "Reverse a string in Java" }, { "code": null, "e": 35399, "s": 35384, "text": "C++ Data Types" }, { "code": null, "e": 35433, "s": 35399, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 35493, "s": 35433, "text": "Write a program to print all permutations of a given string" } ]
How to use an HTML button to call a JavaScript function?
The simplest way to use an HTML button to call a JavaScript function is shown below − <input id = "Double Click here" type = "button" value = "clickme" ondblclick = "myFunction();" /> You can also use the following by adding to the DOM property − document.getElementById("Double Click here ").ondblclick = myFunction;
[ { "code": null, "e": 1148, "s": 1062, "text": "The simplest way to use an HTML button to call a JavaScript function is shown below −" }, { "code": null, "e": 1246, "s": 1148, "text": "<input id = \"Double Click here\" type = \"button\" value = \"clickme\" ondblclick = \"myFunction();\" />" }, { "code": null, "e": 1309, "s": 1246, "text": "You can also use the following by adding to the DOM property −" }, { "code": null, "e": 1380, "s": 1309, "text": "document.getElementById(\"Double Click here \").ondblclick = myFunction;" } ]
Sum of all the child nodes with even grandparents in a Binary Tree - GeeksforGeeks
22 Jun, 2021 Given a Binary Tree, calculate the sum of nodes with even valued Grandparents.Examples: Input: 22 / \ 3 8 / \ / \ 4 8 1 9 \ 2 Output: 24 Explanation The nodes 4, 8, 2, 1, 9 has even value grandparents. Hence sum = 4 + 8 + 1 + 9 + 2 = 24. Input: 1 / \ 2 3 / \ / \ 4 5 6 7 / 8 Output: 8 Explanation Only 8 has 2 as a grandparent. Approach: To solve the problem mentioned above, for each node that is not null, check if they have a grandparent and if their grandparent is even valued add the node’s data to the sum.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find sum// of all the child nodes with// even grandparents in a Binary Tree #include <bits/stdc++.h>using namespace std; /* A binary tree node has data andpointers to the right and left children*/struct TreeNode { int data; TreeNode *left, *right; TreeNode(int x) { data = x; left = right = NULL; }}; // Function to calculate the sumvoid getSum( TreeNode* curr, TreeNode* p, TreeNode* gp, int& sum){ // Base condition if (curr == NULL) return; // Check if node has a grandparent // if it does check // if they are even valued if (gp != NULL && gp->data % 2 == 0) sum += curr->data; // Recurse for left child getSum(curr->left, curr, p, sum); // Recurse for right child getSum(curr->right, curr, p, sum);} // Driver Programint main(){ TreeNode* root = new TreeNode(22); root->left = new TreeNode(3); root->right = new TreeNode(8); root->left->left = new TreeNode(4); root->left->right = new TreeNode(8); root->right->left = new TreeNode(1); root->right->right = new TreeNode(9); root->right->right->right = new TreeNode(2); int sum = 0; getSum(root, NULL, NULL, sum); cout << sum << '\n'; return 0;} // Java implementation to find sum// of all the child nodes with// even grandparents in a Binary Treeimport java.util.*;class GFG{ /* A binary tree node has data andpointers to the right and left children*/static class TreeNode{ int data; TreeNode left, right; TreeNode(int x) { data = x; left = right = null; }} static int sum = 0; // Function to calculate the sumstatic void getSum(TreeNode curr, TreeNode p, TreeNode gp){ // Base condition if (curr == null) return; // Check if node has // a grandparent // if it does check // if they are even valued if (gp != null && gp.data % 2 == 0) sum += curr.data; // Recurse for left child getSum(curr.left, curr, p); // Recurse for right child getSum(curr.right, curr, p);} // Driver Programpublic static void main(String[] args){ TreeNode root = new TreeNode(22); root.left = new TreeNode(3); root.right = new TreeNode(8); root.left.left = new TreeNode(4); root.left.right = new TreeNode(8); root.right.left = new TreeNode(1); root.right.right = new TreeNode(9); root.right.right.right = new TreeNode(2); getSum(root, null, null); System.out.println(sum);}} // This code is contributed by Rajput-Ji # Python3 implementation to find sum# of all the child nodes with# even grandparents in a Binary Tree # A binary tree node has data and# pointers to the right and left childrenclass TreeNode(): def __init__(self, data): self.data = data self.left = None self.right = None sum = 0 # Function to calculate the sumdef getSum(curr, p, gp): global sum # Base condition if (curr == None): return # Check if node has a grandparent # if it does check # if they are even valued if (gp != None and gp.data % 2 == 0): sum += curr.data # Recurse for left child getSum(curr.left, curr, p) # Recurse for right child getSum(curr.right, curr, p) # Driver codeif __name__=="__main__": root = TreeNode(22) root.left = TreeNode(3) root.right = TreeNode(8) root.left.left = TreeNode(4) root.left.right = TreeNode(8) root.right.left = TreeNode(1) root.right.right = TreeNode(9) root.right.right.right = TreeNode(2) getSum(root, None, None) print(sum) # This code is contributed by rutvik_56 // C# implementation to find sum// of all the child nodes with// even grandparents in a Binary Treeusing System;class GFG{ /* A binary tree nodehas data and pointers tothe right and left children*/class TreeNode{ public int data; public TreeNode left, right; public TreeNode(int x) { data = x; left = right = null; }} static int sum = 0; // Function to calculate the sumstatic void getSum(TreeNode curr, TreeNode p, TreeNode gp){ // Base condition if (curr == null) return; // Check if node has // a grandparent // if it does check // if they are even valued if (gp != null && gp.data % 2 == 0) sum += curr.data; // Recurse for left child getSum(curr.left, curr, p); // Recurse for right child getSum(curr.right, curr, p);} // Driver Programpublic static void Main(String[] args){ TreeNode root = new TreeNode(22); root.left = new TreeNode(3); root.right = new TreeNode(8); root.left.left = new TreeNode(4); root.left.right = new TreeNode(8); root.right.left = new TreeNode(1); root.right.right = new TreeNode(9); root.right.right.right = new TreeNode(2); getSum(root, null, null); Console.WriteLine(sum);}} // This code is contributed by Princi Singh <script> // JavaScript implementation to find sum // of all the child nodes with // even grandparents in a Binary Tree /* A binary tree node has data and pointers to the right and left children*/ class TreeNode { constructor(x) { this.left = null; this.right = null; this.data = x; } } let sum = 0; // Function to calculate the sum function getSum(curr, p, gp) { // Base condition if (curr == null) return; // Check if node has // a grandparent // if it does check // if they are even valued if (gp != null && gp.data % 2 == 0) sum += curr.data; // Recurse for left child getSum(curr.left, curr, p); // Recurse for right child getSum(curr.right, curr, p); } let root = new TreeNode(22); root.left = new TreeNode(3); root.right = new TreeNode(8); root.left.left = new TreeNode(4); root.left.right = new TreeNode(8); root.right.left = new TreeNode(1); root.right.right = new TreeNode(9); root.right.right.right = new TreeNode(2); getSum(root, null, null); document.write(sum); </script> 24 Time Complexity: O(N)Space Complexity: O(H), Used by recursion stack where H = height of the tree. Rajput-Ji princi singh rutvik_56 decode2207 Binary Tree tree-traversal Algorithms Data Structures Recursion Tree Data Structures Recursion Tree Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Introduction to Algorithms Playfair Cipher with Examples How to write a Pseudo Code? SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Doubly Linked List | Set 1 (Introduction and Insertion) Implementing a Linked List in Java using Class Abstract Data Types
[ { "code": null, "e": 25024, "s": 24996, "text": "\n22 Jun, 2021" }, { "code": null, "e": 25113, "s": 25024, "text": "Given a Binary Tree, calculate the sum of nodes with even valued Grandparents.Examples: " }, { "code": null, "e": 25458, "s": 25113, "text": "Input: \n 22\n / \\\n 3 8\n / \\ / \\\n 4 8 1 9\n \\\n 2\nOutput: 24\nExplanation \nThe nodes 4, 8, 2, 1, 9\nhas even value grandparents. \nHence sum = 4 + 8 + 1 + 9 + 2 = 24.\n\nInput:\n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n /\n 8\nOutput: 8\nExplanation \nOnly 8 has 2 as a grandparent." }, { "code": null, "e": 25694, "s": 25458, "text": "Approach: To solve the problem mentioned above, for each node that is not null, check if they have a grandparent and if their grandparent is even valued add the node’s data to the sum.Below is the implementation of the above approach: " }, { "code": null, "e": 25698, "s": 25694, "text": "C++" }, { "code": null, "e": 25703, "s": 25698, "text": "Java" }, { "code": null, "e": 25711, "s": 25703, "text": "Python3" }, { "code": null, "e": 25714, "s": 25711, "text": "C#" }, { "code": null, "e": 25725, "s": 25714, "text": "Javascript" }, { "code": "// C++ implementation to find sum// of all the child nodes with// even grandparents in a Binary Tree #include <bits/stdc++.h>using namespace std; /* A binary tree node has data andpointers to the right and left children*/struct TreeNode { int data; TreeNode *left, *right; TreeNode(int x) { data = x; left = right = NULL; }}; // Function to calculate the sumvoid getSum( TreeNode* curr, TreeNode* p, TreeNode* gp, int& sum){ // Base condition if (curr == NULL) return; // Check if node has a grandparent // if it does check // if they are even valued if (gp != NULL && gp->data % 2 == 0) sum += curr->data; // Recurse for left child getSum(curr->left, curr, p, sum); // Recurse for right child getSum(curr->right, curr, p, sum);} // Driver Programint main(){ TreeNode* root = new TreeNode(22); root->left = new TreeNode(3); root->right = new TreeNode(8); root->left->left = new TreeNode(4); root->left->right = new TreeNode(8); root->right->left = new TreeNode(1); root->right->right = new TreeNode(9); root->right->right->right = new TreeNode(2); int sum = 0; getSum(root, NULL, NULL, sum); cout << sum << '\\n'; return 0;}", "e": 26972, "s": 25725, "text": null }, { "code": "// Java implementation to find sum// of all the child nodes with// even grandparents in a Binary Treeimport java.util.*;class GFG{ /* A binary tree node has data andpointers to the right and left children*/static class TreeNode{ int data; TreeNode left, right; TreeNode(int x) { data = x; left = right = null; }} static int sum = 0; // Function to calculate the sumstatic void getSum(TreeNode curr, TreeNode p, TreeNode gp){ // Base condition if (curr == null) return; // Check if node has // a grandparent // if it does check // if they are even valued if (gp != null && gp.data % 2 == 0) sum += curr.data; // Recurse for left child getSum(curr.left, curr, p); // Recurse for right child getSum(curr.right, curr, p);} // Driver Programpublic static void main(String[] args){ TreeNode root = new TreeNode(22); root.left = new TreeNode(3); root.right = new TreeNode(8); root.left.left = new TreeNode(4); root.left.right = new TreeNode(8); root.right.left = new TreeNode(1); root.right.right = new TreeNode(9); root.right.right.right = new TreeNode(2); getSum(root, null, null); System.out.println(sum);}} // This code is contributed by Rajput-Ji", "e": 28202, "s": 26972, "text": null }, { "code": "# Python3 implementation to find sum# of all the child nodes with# even grandparents in a Binary Tree # A binary tree node has data and# pointers to the right and left childrenclass TreeNode(): def __init__(self, data): self.data = data self.left = None self.right = None sum = 0 # Function to calculate the sumdef getSum(curr, p, gp): global sum # Base condition if (curr == None): return # Check if node has a grandparent # if it does check # if they are even valued if (gp != None and gp.data % 2 == 0): sum += curr.data # Recurse for left child getSum(curr.left, curr, p) # Recurse for right child getSum(curr.right, curr, p) # Driver codeif __name__==\"__main__\": root = TreeNode(22) root.left = TreeNode(3) root.right = TreeNode(8) root.left.left = TreeNode(4) root.left.right = TreeNode(8) root.right.left = TreeNode(1) root.right.right = TreeNode(9) root.right.right.right = TreeNode(2) getSum(root, None, None) print(sum) # This code is contributed by rutvik_56", "e": 29325, "s": 28202, "text": null }, { "code": "// C# implementation to find sum// of all the child nodes with// even grandparents in a Binary Treeusing System;class GFG{ /* A binary tree nodehas data and pointers tothe right and left children*/class TreeNode{ public int data; public TreeNode left, right; public TreeNode(int x) { data = x; left = right = null; }} static int sum = 0; // Function to calculate the sumstatic void getSum(TreeNode curr, TreeNode p, TreeNode gp){ // Base condition if (curr == null) return; // Check if node has // a grandparent // if it does check // if they are even valued if (gp != null && gp.data % 2 == 0) sum += curr.data; // Recurse for left child getSum(curr.left, curr, p); // Recurse for right child getSum(curr.right, curr, p);} // Driver Programpublic static void Main(String[] args){ TreeNode root = new TreeNode(22); root.left = new TreeNode(3); root.right = new TreeNode(8); root.left.left = new TreeNode(4); root.left.right = new TreeNode(8); root.right.left = new TreeNode(1); root.right.right = new TreeNode(9); root.right.right.right = new TreeNode(2); getSum(root, null, null); Console.WriteLine(sum);}} // This code is contributed by Princi Singh", "e": 30562, "s": 29325, "text": null }, { "code": "<script> // JavaScript implementation to find sum // of all the child nodes with // even grandparents in a Binary Tree /* A binary tree node has data and pointers to the right and left children*/ class TreeNode { constructor(x) { this.left = null; this.right = null; this.data = x; } } let sum = 0; // Function to calculate the sum function getSum(curr, p, gp) { // Base condition if (curr == null) return; // Check if node has // a grandparent // if it does check // if they are even valued if (gp != null && gp.data % 2 == 0) sum += curr.data; // Recurse for left child getSum(curr.left, curr, p); // Recurse for right child getSum(curr.right, curr, p); } let root = new TreeNode(22); root.left = new TreeNode(3); root.right = new TreeNode(8); root.left.left = new TreeNode(4); root.left.right = new TreeNode(8); root.right.left = new TreeNode(1); root.right.right = new TreeNode(9); root.right.right.right = new TreeNode(2); getSum(root, null, null); document.write(sum); </script>", "e": 31754, "s": 30562, "text": null }, { "code": null, "e": 31757, "s": 31754, "text": "24" }, { "code": null, "e": 31859, "s": 31759, "text": "Time Complexity: O(N)Space Complexity: O(H), Used by recursion stack where H = height of the tree. " }, { "code": null, "e": 31869, "s": 31859, "text": "Rajput-Ji" }, { "code": null, "e": 31882, "s": 31869, "text": "princi singh" }, { "code": null, "e": 31892, "s": 31882, "text": "rutvik_56" }, { "code": null, "e": 31903, "s": 31892, "text": "decode2207" }, { "code": null, "e": 31915, "s": 31903, "text": "Binary Tree" }, { "code": null, "e": 31930, "s": 31915, "text": "tree-traversal" }, { "code": null, "e": 31941, "s": 31930, "text": "Algorithms" }, { "code": null, "e": 31957, "s": 31941, "text": "Data Structures" }, { "code": null, "e": 31967, "s": 31957, "text": "Recursion" }, { "code": null, "e": 31972, "s": 31967, "text": "Tree" }, { "code": null, "e": 31988, "s": 31972, "text": "Data Structures" }, { "code": null, "e": 31998, "s": 31988, "text": "Recursion" }, { "code": null, "e": 32003, "s": 31998, "text": "Tree" }, { "code": null, "e": 32014, "s": 32003, "text": "Algorithms" }, { "code": null, "e": 32112, "s": 32014, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32121, "s": 32112, "text": "Comments" }, { "code": null, "e": 32134, "s": 32121, "text": "Old Comments" }, { "code": null, "e": 32183, "s": 32134, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 32208, "s": 32183, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 32235, "s": 32208, "text": "Introduction to Algorithms" }, { "code": null, "e": 32265, "s": 32235, "text": "Playfair Cipher with Examples" }, { "code": null, "e": 32293, "s": 32265, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 32342, "s": 32293, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 32367, "s": 32342, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 32423, "s": 32367, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 32470, "s": 32423, "text": "Implementing a Linked List in Java using Class" } ]
How to do recursive SELECT query in MySQL?
For recursive select, let us see an example. First, we will create a table. The CREATE command is used to create a table. mysql> CREATE table tblSelectDemo - > ( - > id int, - > name varchar(100) - > ); Query OK, 0 rows affected (0.61 sec) Now, we will insert records in the table “tblSelectDemo”. mysql> insert into tblSelectDemo values(1,'John'); Query OK, 1 row affected (0.10 sec) mysql> insert into tblSelectDemo values(2,'Carol'); Query OK, 1 row affected (0.09 sec) mysql> insert into tblSelectDemo values(3,'Smith'); Query OK, 1 row affected (0.17 sec) mysql> insert into tblSelectDemo values(4,'David'); Query OK, 1 row affected (0.15 sec) mysql> insert into tblSelectDemo values(5,'Bob'); Query OK, 1 row affected (0.18 sec) To display all records. mysql> SELECT *from tblSelectDemo; Here is the output. +------+-------+ | id | name | +------+-------+ | 1 | John | | 2 | Carol | | 3 | Smith | | 4 | David | | 5 | Bob | +------+-------+ 6 rows in set (0.00 sec) The following is the syntax for recursive SELECT. mysql> SELECT var1.id as id, @sessionName:= var1.Name as NameofStudent - > from (select * from tblSelectDemo order by id desc) var1 - > join - > (select @sessionName:= 4)tmp - > where var1.id = @sessionName; Here is the output. +------+----------------+ | id | NameofStudent | +------+----------------+ | 4 | David | +------+----------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1184, "s": 1062, "text": "For recursive select, let us see an example. First, we will create a table. The CREATE command is used to create a table." }, { "code": null, "e": 1314, "s": 1184, "text": "mysql> CREATE table tblSelectDemo\n - > (\n - > id int,\n - > name varchar(100)\n - > );\nQuery OK, 0 rows affected (0.61 sec)" }, { "code": null, "e": 1372, "s": 1314, "text": "Now, we will insert records in the table “tblSelectDemo”." }, { "code": null, "e": 1813, "s": 1372, "text": "mysql> insert into tblSelectDemo values(1,'John');\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into tblSelectDemo values(2,'Carol');\nQuery OK, 1 row affected (0.09 sec)\n\nmysql> insert into tblSelectDemo values(3,'Smith');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into tblSelectDemo values(4,'David');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into tblSelectDemo values(5,'Bob');\nQuery OK, 1 row affected (0.18 sec)" }, { "code": null, "e": 1837, "s": 1813, "text": "To display all records." }, { "code": null, "e": 1872, "s": 1837, "text": "mysql> SELECT *from tblSelectDemo;" }, { "code": null, "e": 1892, "s": 1872, "text": "Here is the output." }, { "code": null, "e": 2071, "s": 1892, "text": "+------+-------+\n| id | name |\n+------+-------+\n| 1 | John |\n| 2 | Carol |\n| 3 | Smith |\n| 4 | David |\n| 5 | Bob |\n+------+-------+\n6 rows in set (0.00 sec)\n" }, { "code": null, "e": 2121, "s": 2071, "text": "The following is the syntax for recursive SELECT." }, { "code": null, "e": 2341, "s": 2121, "text": "mysql> SELECT var1.id as id, @sessionName:= var1.Name as NameofStudent\n - > from (select * from tblSelectDemo order by id desc) var1\n - > join\n - > (select @sessionName:= 4)tmp\n - > where var1.id = @sessionName;" }, { "code": null, "e": 2361, "s": 2341, "text": "Here is the output." }, { "code": null, "e": 2516, "s": 2361, "text": "+------+----------------+\n| id | NameofStudent |\n+------+----------------+\n| 4 | David |\n+------+----------------+\n1 row in set (0.00 sec)\n" } ]
Python Tricks: Check Multiple Variables against Single Value | by Louis Chan | Medium | Towards Data Science
Welcome to a series of short posts each with handy Python tricks that can help you become a better Python programmer. In this blog, we will look into variable comparisons. You have variables x, y, z, and you have also got a constant c that you would like to check whether it exists in any of the three variables. We can do it with a brute-force approach with the following logic, but are there better solutions? if (x == c) or (y == c) or (z == c): print("It exists!")else: print("It does not exist!") if any(i == c for i in (x, y, z)): print("It exists!")else: print("It does not exist!") If in case you would like to check whether all of x, y, z are of value c, you can also change any to all. The two functions check whether any/all of the provided iterator is evaluated as True. That means if we have a tuple of t = (0, 1, 2), all(t) will return False as the first element 0 will be evaluated as False. This also opens up a lot of flexibility as common values like 0, None, [], (), "", {} would all be evaluated as False. Note that x, y, z have been combined to a tuple rather than a list for marginally better memory performance. If you would like to read more about the memory usage of data structures, I have previously written a piece on it: towardsdatascience.com Instead of creating a tuple and iterate it through, we can also just do it with a membership test and skip the need of any. # Membership test with listif c in [x, y, z]: print("It exists!")else: print("It does not exist!")# Membership test with tupleif c in (x, y, z): print("It exists!")else: print("It does not exist!")# Membership test with setif c in {x, y, z}: print("It exists!")else: print("It does not exist!") Although both list, tuple, and set supports the membership test as they are all iterables in Python, there are minor differences when choosing which one to use. For example, using tuple will take up the least memory among the three assuming that the uniqueness of values within the tuple is high. On the other hand, implementation of set allows constant-cost membership test meaning that it has the least computational complexity among the three though constructing a set might outweigh the benefits of it. While for list, there just isn’t any edge of using variable-length arrays in this context so forget about it. That’s about it for this blog post! I hope you have found this useful. If you are interested in other Python tricks, I have put together a list of these short blogs for you: Python Tricks: Flattening Lists Python Tricks: Simplifying If Statements & Boolean Evaluation Python Tricks: How to Check Table Merging with Pandas If you want to learn more about Python, Data Science, or Machine Learning, you may want to check out these posts: 7 Easy Ways for Improving Your Data Science Workflow Efficient Conditional Logic on Pandas DataFrames Memory Efficiency of Common Python Data Structures Parallelism with Python Essential Jupyter Extension for Data Science Set Up Efficient Root Searching Algorithms in Python If you would like to learn more about how to apply machine learning to trading & investing, here are some other posts that may be of interest: Genetic Algorithm for Trading Strategy Optimization in Python Genetic Algorithm — Stop Overfitting Trading Strategies ANN Recommendation System for Stock Selection www.linkedin.com Special thanks to Sander Koelstra for pointing out some misleading statements.
[ { "code": null, "e": 343, "s": 171, "text": "Welcome to a series of short posts each with handy Python tricks that can help you become a better Python programmer. In this blog, we will look into variable comparisons." }, { "code": null, "e": 583, "s": 343, "text": "You have variables x, y, z, and you have also got a constant c that you would like to check whether it exists in any of the three variables. We can do it with a brute-force approach with the following logic, but are there better solutions?" }, { "code": null, "e": 679, "s": 583, "text": "if (x == c) or (y == c) or (z == c): print(\"It exists!\")else: print(\"It does not exist!\")" }, { "code": null, "e": 773, "s": 679, "text": "if any(i == c for i in (x, y, z)): print(\"It exists!\")else: print(\"It does not exist!\")" }, { "code": null, "e": 1209, "s": 773, "text": "If in case you would like to check whether all of x, y, z are of value c, you can also change any to all. The two functions check whether any/all of the provided iterator is evaluated as True. That means if we have a tuple of t = (0, 1, 2), all(t) will return False as the first element 0 will be evaluated as False. This also opens up a lot of flexibility as common values like 0, None, [], (), \"\", {} would all be evaluated as False." }, { "code": null, "e": 1433, "s": 1209, "text": "Note that x, y, z have been combined to a tuple rather than a list for marginally better memory performance. If you would like to read more about the memory usage of data structures, I have previously written a piece on it:" }, { "code": null, "e": 1456, "s": 1433, "text": "towardsdatascience.com" }, { "code": null, "e": 1580, "s": 1456, "text": "Instead of creating a tuple and iterate it through, we can also just do it with a membership test and skip the need of any." }, { "code": null, "e": 1893, "s": 1580, "text": "# Membership test with listif c in [x, y, z]: print(\"It exists!\")else: print(\"It does not exist!\")# Membership test with tupleif c in (x, y, z): print(\"It exists!\")else: print(\"It does not exist!\")# Membership test with setif c in {x, y, z}: print(\"It exists!\")else: print(\"It does not exist!\")" }, { "code": null, "e": 2510, "s": 1893, "text": "Although both list, tuple, and set supports the membership test as they are all iterables in Python, there are minor differences when choosing which one to use. For example, using tuple will take up the least memory among the three assuming that the uniqueness of values within the tuple is high. On the other hand, implementation of set allows constant-cost membership test meaning that it has the least computational complexity among the three though constructing a set might outweigh the benefits of it. While for list, there just isn’t any edge of using variable-length arrays in this context so forget about it." }, { "code": null, "e": 2684, "s": 2510, "text": "That’s about it for this blog post! I hope you have found this useful. If you are interested in other Python tricks, I have put together a list of these short blogs for you:" }, { "code": null, "e": 2716, "s": 2684, "text": "Python Tricks: Flattening Lists" }, { "code": null, "e": 2778, "s": 2716, "text": "Python Tricks: Simplifying If Statements & Boolean Evaluation" }, { "code": null, "e": 2832, "s": 2778, "text": "Python Tricks: How to Check Table Merging with Pandas" }, { "code": null, "e": 2946, "s": 2832, "text": "If you want to learn more about Python, Data Science, or Machine Learning, you may want to check out these posts:" }, { "code": null, "e": 2999, "s": 2946, "text": "7 Easy Ways for Improving Your Data Science Workflow" }, { "code": null, "e": 3048, "s": 2999, "text": "Efficient Conditional Logic on Pandas DataFrames" }, { "code": null, "e": 3099, "s": 3048, "text": "Memory Efficiency of Common Python Data Structures" }, { "code": null, "e": 3123, "s": 3099, "text": "Parallelism with Python" }, { "code": null, "e": 3175, "s": 3123, "text": "Essential Jupyter Extension for Data Science Set Up" }, { "code": null, "e": 3221, "s": 3175, "text": "Efficient Root Searching Algorithms in Python" }, { "code": null, "e": 3364, "s": 3221, "text": "If you would like to learn more about how to apply machine learning to trading & investing, here are some other posts that may be of interest:" }, { "code": null, "e": 3426, "s": 3364, "text": "Genetic Algorithm for Trading Strategy Optimization in Python" }, { "code": null, "e": 3482, "s": 3426, "text": "Genetic Algorithm — Stop Overfitting Trading Strategies" }, { "code": null, "e": 3528, "s": 3482, "text": "ANN Recommendation System for Stock Selection" }, { "code": null, "e": 3545, "s": 3528, "text": "www.linkedin.com" } ]
Booleans Class in Java
The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean. Following are the fields of the Boolean class − static Boolean FALSE − This is the Boolean object corresponding to the primitive value false. static Boolean TRUE − This is the Boolean object corresponding to the primitive value true. static Class<Boolean> TYPE − This is the Class object representing the primitive type boolean. Following are some of the methods of the Boolean class− Let us now see an example − Live Demo import java.lang.*; public class Demo { public static void main(String[] args){ Boolean val1, val2; val1 = new Boolean(true); val2 = new Boolean(true); boolean res = val1.equals(val2); System.out.println("Are both the Boolean values equal? = "+res); } } Are both the Boolean values equal? = true Let us now see another example− Live Demo import java.lang.*; public class Demo { public static void main(String[] args){ Boolean val1, val2; val1 = new Boolean(false); val2 = new Boolean(true); System.out.println("Value1 = "+val1); System.out.println("Value2 = "+val2); System.out.println("HashCode Value1 = "+val1.hashCode()); System.out.println("HashCode Value2 = "+val2.hashCode()); boolean res = val1.equals(val2); System.out.println("Are both the Boolean values equal? = "+res); } } Value1 = false Value2 = true HashCode Value1 = 1237 HashCode Value2 = 1231 Are both the Boolean values equal? = false
[ { "code": null, "e": 1211, "s": 1062, "text": "The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean." }, { "code": null, "e": 1259, "s": 1211, "text": "Following are the fields of the Boolean class −" }, { "code": null, "e": 1353, "s": 1259, "text": "static Boolean FALSE − This is the Boolean object corresponding to the primitive value false." }, { "code": null, "e": 1445, "s": 1353, "text": "static Boolean TRUE − This is the Boolean object corresponding to the primitive value true." }, { "code": null, "e": 1540, "s": 1445, "text": "static Class<Boolean> TYPE − This is the Class object representing the primitive type boolean." }, { "code": null, "e": 1596, "s": 1540, "text": "Following are some of the methods of the Boolean class−" }, { "code": null, "e": 1624, "s": 1596, "text": "Let us now see an example −" }, { "code": null, "e": 1635, "s": 1624, "text": " Live Demo" }, { "code": null, "e": 1925, "s": 1635, "text": "import java.lang.*;\npublic class Demo {\n public static void main(String[] args){\n Boolean val1, val2;\n val1 = new Boolean(true);\n val2 = new Boolean(true);\n boolean res = val1.equals(val2);\n System.out.println(\"Are both the Boolean values equal? = \"+res);\n }\n}" }, { "code": null, "e": 1967, "s": 1925, "text": "Are both the Boolean values equal? = true" }, { "code": null, "e": 1999, "s": 1967, "text": "Let us now see another example−" }, { "code": null, "e": 2010, "s": 1999, "text": " Live Demo" }, { "code": null, "e": 2517, "s": 2010, "text": "import java.lang.*;\npublic class Demo {\n public static void main(String[] args){\n Boolean val1, val2;\n val1 = new Boolean(false);\n val2 = new Boolean(true);\n System.out.println(\"Value1 = \"+val1);\n System.out.println(\"Value2 = \"+val2);\n System.out.println(\"HashCode Value1 = \"+val1.hashCode());\n System.out.println(\"HashCode Value2 = \"+val2.hashCode());\n boolean res = val1.equals(val2);\n System.out.println(\"Are both the Boolean values equal? = \"+res);\n }\n}" }, { "code": null, "e": 2635, "s": 2517, "text": "Value1 = false\nValue2 = true\nHashCode Value1 = 1237\nHashCode Value2 = 1231\nAre both the Boolean values equal? = false" } ]
Automatically filling multiple responses into a Google Form with Selenium and Python - GeeksforGeeks
19 Aug, 2021 Prerequisite: Selenium Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e. Python, Java, C#, etc.. we will be working with Python. Selenium Tutorial covers all topics such as– WebDriver, WebElement, Unit Testing with selenium. The Task here is to fill multiple responses with the same Google form using selenium in python. Link to the Google form used in this example is given below: Form link – Click Here GOOGLE FORM The form has five entries: Name Email Address Phone Number Comments Name, Email & Phone Number has same class name quantumWizTextinputPaperinputInput and Address & Comments has same class name quantumWizTextinputPapertextareaInput. Data is in the form of a list. The given program also uses count, reason being textboxes contain a list, whose class name is “quantumWizTextinputPaperinputInput” and textareaboxes contain a list, whose class name is “quantumWizTextinputPapertextareaInput” and when these two classes are added it results in a list. The data is also provided in a form of a list, thus count variable will be incremented with each data variable. Example: # values of data [name, email, phone number, address, comments]datas = [ [‘Mary D Joiner’,’MaryDJoiner@gmail.com’,’4079025063′,’2474 McDonald Avenue,Maitland’,’NA’], [‘Karen B Johnson’,’KarenBJohnson@gmail.com’,’3153437575′,’2143 Oak Street,GRAND ISLE’,’NA’],] To achieve our required functionality given steps needs to followed in a perfect order: Import selenium and time module Add chrome driver path and Form URL Add some delay, until page gets fully loaded Add data in the form of list Iterate through each data and fill detail Close the window Program: Python3 # Import Modulefrom selenium import webdriverfrom selenium.webdriver.common.keys import Keysimport time # open Chromedriver = webdriver.Chrome( 'C:/Users/HP/Desktop/Drivers/chromedriver_win32/chromedriver.exe') # Open URLdriver.get('https://forms.gle/vWVmojtWdfFvEj8V6') # wait for one second, until page gets fully loadedtime.sleep(1) # Datadatas = [ ['Mary D Joiner', 'MaryDJoiner@gmail.com', '4079025063', '2474 McDonald Avenue,Maitland', 'NA'], ['Karen B Johnson', 'KarenBJohnson@gmail.com', '3153437575', '2143 Oak Street,GRAND ISLE', 'NA'],] # Iterate through each datafor data in datas: # Initialize count is zero count = 0 # contain input boxes textboxes = driver.find_elements_by_class_name( "quantumWizTextinputPaperinputInput") # contain textareas textareaboxes = driver.find_elements_by_class_name( "quantumWizTextinputPapertextareaInput") # Iterate through all input boxes for value in textboxes: # enter value value.send_keys(data[count]) # increment count value count += 1 # Iterate through all textareas for value in textareaboxes: # enter value value.send_keys(data[count]) # increment count value count += 1 # click on submit button submit = driver.find_element_by_xpath( '//*[@id="mG61Hd"]/div[2]/div/div[3]/div[1]/div/div/span/span') submit.click() # fill another response another_response = driver.find_element_by_xpath( '/html/body/div[1]/div[2]/div[1]/div/div[4]/a') another_response.click() # close the windowdriver.close() Output: gulshankumarar231 Python Selenium-Exercises Python-selenium 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 How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Python Classes and Objects Create a directory in Python
[ { "code": null, "e": 23927, "s": 23899, "text": "\n19 Aug, 2021" }, { "code": null, "e": 23950, "s": 23927, "text": "Prerequisite: Selenium" }, { "code": null, "e": 24323, "s": 23950, "text": "Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e. Python, Java, C#, etc.. we will be working with Python. Selenium Tutorial covers all topics such as– WebDriver, WebElement, Unit Testing with selenium. " }, { "code": null, "e": 24480, "s": 24323, "text": "The Task here is to fill multiple responses with the same Google form using selenium in python. Link to the Google form used in this example is given below:" }, { "code": null, "e": 24503, "s": 24480, "text": "Form link – Click Here" }, { "code": null, "e": 24515, "s": 24503, "text": "GOOGLE FORM" }, { "code": null, "e": 24542, "s": 24515, "text": "The form has five entries:" }, { "code": null, "e": 24547, "s": 24542, "text": "Name" }, { "code": null, "e": 24553, "s": 24547, "text": "Email" }, { "code": null, "e": 24561, "s": 24553, "text": "Address" }, { "code": null, "e": 24574, "s": 24561, "text": "Phone Number" }, { "code": null, "e": 24583, "s": 24574, "text": "Comments" }, { "code": null, "e": 24778, "s": 24583, "text": "Name, Email & Phone Number has same class name quantumWizTextinputPaperinputInput and Address & Comments has same class name quantumWizTextinputPapertextareaInput. Data is in the form of a list." }, { "code": null, "e": 25174, "s": 24778, "text": "The given program also uses count, reason being textboxes contain a list, whose class name is “quantumWizTextinputPaperinputInput” and textareaboxes contain a list, whose class name is “quantumWizTextinputPapertextareaInput” and when these two classes are added it results in a list. The data is also provided in a form of a list, thus count variable will be incremented with each data variable." }, { "code": null, "e": 25183, "s": 25174, "text": "Example:" }, { "code": null, "e": 25200, "s": 25183, "text": "# values of data" }, { "code": null, "e": 25450, "s": 25200, "text": "[name, email, phone number, address, comments]datas = [ [‘Mary D Joiner’,’MaryDJoiner@gmail.com’,’4079025063′,’2474 McDonald Avenue,Maitland’,’NA’], [‘Karen B Johnson’,’KarenBJohnson@gmail.com’,’3153437575′,’2143 Oak Street,GRAND ISLE’,’NA’],]" }, { "code": null, "e": 25538, "s": 25450, "text": "To achieve our required functionality given steps needs to followed in a perfect order:" }, { "code": null, "e": 25570, "s": 25538, "text": "Import selenium and time module" }, { "code": null, "e": 25606, "s": 25570, "text": "Add chrome driver path and Form URL" }, { "code": null, "e": 25651, "s": 25606, "text": "Add some delay, until page gets fully loaded" }, { "code": null, "e": 25680, "s": 25651, "text": "Add data in the form of list" }, { "code": null, "e": 25722, "s": 25680, "text": "Iterate through each data and fill detail" }, { "code": null, "e": 25739, "s": 25722, "text": "Close the window" }, { "code": null, "e": 25748, "s": 25739, "text": "Program:" }, { "code": null, "e": 25756, "s": 25748, "text": "Python3" }, { "code": "# Import Modulefrom selenium import webdriverfrom selenium.webdriver.common.keys import Keysimport time # open Chromedriver = webdriver.Chrome( 'C:/Users/HP/Desktop/Drivers/chromedriver_win32/chromedriver.exe') # Open URLdriver.get('https://forms.gle/vWVmojtWdfFvEj8V6') # wait for one second, until page gets fully loadedtime.sleep(1) # Datadatas = [ ['Mary D Joiner', 'MaryDJoiner@gmail.com', '4079025063', '2474 McDonald Avenue,Maitland', 'NA'], ['Karen B Johnson', 'KarenBJohnson@gmail.com', '3153437575', '2143 Oak Street,GRAND ISLE', 'NA'],] # Iterate through each datafor data in datas: # Initialize count is zero count = 0 # contain input boxes textboxes = driver.find_elements_by_class_name( \"quantumWizTextinputPaperinputInput\") # contain textareas textareaboxes = driver.find_elements_by_class_name( \"quantumWizTextinputPapertextareaInput\") # Iterate through all input boxes for value in textboxes: # enter value value.send_keys(data[count]) # increment count value count += 1 # Iterate through all textareas for value in textareaboxes: # enter value value.send_keys(data[count]) # increment count value count += 1 # click on submit button submit = driver.find_element_by_xpath( '//*[@id=\"mG61Hd\"]/div[2]/div/div[3]/div[1]/div/div/span/span') submit.click() # fill another response another_response = driver.find_element_by_xpath( '/html/body/div[1]/div[2]/div[1]/div/div[4]/a') another_response.click() # close the windowdriver.close()", "e": 27367, "s": 25756, "text": null }, { "code": null, "e": 27375, "s": 27367, "text": "Output:" }, { "code": null, "e": 27393, "s": 27375, "text": "gulshankumarar231" }, { "code": null, "e": 27419, "s": 27393, "text": "Python Selenium-Exercises" }, { "code": null, "e": 27435, "s": 27419, "text": "Python-selenium" }, { "code": null, "e": 27442, "s": 27435, "text": "Python" }, { "code": null, "e": 27540, "s": 27442, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27549, "s": 27540, "text": "Comments" }, { "code": null, "e": 27562, "s": 27549, "text": "Old Comments" }, { "code": null, "e": 27594, "s": 27562, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27650, "s": 27594, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27692, "s": 27650, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27734, "s": 27692, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27770, "s": 27734, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 27809, "s": 27770, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27831, "s": 27809, "text": "Defaultdict in Python" }, { "code": null, "e": 27862, "s": 27831, "text": "Python | os.path.join() method" }, { "code": null, "e": 27889, "s": 27862, "text": "Python Classes and Objects" } ]
An Illustrative Introduction to Dynamic Time Warping | by Esmaeil Alizadeh | Towards Data Science
Dynamic Time Warping (DTW) is a way to compare two -usually temporal- sequences that do not sync up perfectly. It is a method to calculate the optimal matching between two sequences. DTW is useful in many domains such as speech recognition, data mining, financial markets, etc. It’s commonly used in data mining to measure the distance between two time-series. In this post, we will go over the mathematics behind DTW. Then, two illustrative examples are provided to better understand the concept. If you are not interested in the math behind it, please jump to examples. Let’s assume we have two sequences like the following: X=x[1], x[2], ..., x[i], ..., x[n] Y=y[1], y[2], ..., y[j], ..., y[m] The sequences X and Y can be arranged to form an n-by-m grid, where each point (i, j) is the alignment between x[i] and y[j]. A warping path W maps the elements of X and Y to minimize the distance between them. W is a sequence of grid points (i, j). We will see an example of the warping path later. The Optimal path to (i_k, j_k) can be computed by: where d is the Euclidean distance. Then, the overall path cost can be calculated as The warping path is found using a dynamic programming approach to align two sequences. Going through all possible paths is “combinatorically explosive” [1]. Therefore, for efficiency purposes, it’s important to limit the number of possible warping paths, and hence the following constraints are outlined: Boundary Condition: This constraint ensures that the warping path begins with the start points of both signals and terminates with their endpoints. Monotonicity condition: This constraint preserves the time-order of points (not going back in time). Continuity (step size) condition: This constraint limits the path transitions to adjacent points in time (not jumping in time). In addition to the above three constraints, there are other less frequent conditions for an allowable warping path: Warping window condition: Allowable points can be restricted to fall within a given warping window of width ω (a positive integer). Slope condition: The warping path can be constrained by restricting the slope, and consequently avoiding extreme movements in one direction. An acceptable warping path has combinations of chess king moves that are: Horizontal moves: (i, j) → (i, j+1) Vertical moves: (i, j) → (i+1, j) Diagonal moves: (i, j) → (i+1, j+1) Let’s import all python packages we need. import pandas as pdimport numpy as np# Plotting Packagesimport matplotlib.pyplot as pltimport seaborn as sbn# Configuring Matplotlibimport matplotlib as mplmpl.rcParams['figure.dpi'] = 300savefig_options = dict(format="png", dpi=300, bbox_inches="tight")# Computation packagesfrom scipy.spatial.distance import euclideanfrom fastdtw import fastdtw Let’s define a method to compute the accumulated cost matrix D for the warp path. The cost matrix uses the Euclidean distance to calculate the distance between every two points. The methods to compute the Euclidean distance matrix and accumulated cost matrix are defined below: In this example, we have two sequences x and y with different lengths. # Create two sequencesx = [3, 1, 2, 2, 1]y = [2, 0, 0, 3, 3, 1, 0] We cannot calculate the Euclidean distance between x and y since they don’t have equal lengths. Many Python packages calculate the DTW by just providing the sequences and the type of distance (usually Euclidean). Here, we use a popular Python implementation of DTW that is FastDTW which is an approximate DTW algorithm with lower time and memory complexities [2]. dtw_distance, warp_path = fastdtw(x, y, dist=euclidean) Note that we are using SciPy’s distance function Euclidean that we imported earlier. For a better understanding of the warp path, let’s first compute the accumulated cost matrix and then visualize the path on a grid. The following code will plot a heatmap of the accumulated cost matrix. cost_matrix = compute_accumulated_cost_matrix(x, y) The color bar shows the cost of each point in the grid. As can be seen, the warp path (blue line) is going through the lowest cost on the grid. Let’s see the DTW distance and the warping path by printing these two variables. >>> DTW distance: 6.0>>> Warp path: [(0, 0), (1, 1), (1, 2), (2, 3), (3, 4), (4, 5), (4, 6)] The warping path starts at point (0, 0) and ends at (4, 6) by 6 moves. Let’s also calculate the accumulated cost most using the functions we defined earlier and compare the values with the heatmap. cost_matrix = compute_accumulated_cost_matrix(x, y)print(np.flipud(cost_matrix)) # Flipping the cost matrix for easier comparison with heatmap values!>>> [[32. 12. 10. 10. 6.] [23. 11. 6. 6. 5.] [19. 11. 5. 5. 9.] [19. 7. 4. 5. 8.] [19. 3. 6. 10. 4.] [10. 2. 6. 6. 3.] [ 1. 2. 2. 2. 3.]] The cost matrix is printed above has similar values to the heatmap. Now let’s plot the two sequences and connect the mapping points. The code to plot the DTW distance between x and y is given below. In this example, we will use two sinusoidal signals and see how they will be matched by calculating the DTW distance between them. Just like Example 1, let’s calculate the DTW distance and the warp path for x1 and x2 signals using FastDTW package. distance, warp_path = fastdtw(x1, x2, dist=euclidean) As can be seen in above figure, the DTW distance between the two signals is particularly powerful when the signals have similar patterns. The extrema (maximum and minimum points) between the two signals are correctly mapped. Moreover, unlike Euclidean distance, we may see many-to-one mapping when DTW distance is used, particularly if the two signals have different lengths. You may spot an issue with dynamic time warping from the figure above. Can you guess what it is? The issue is around the head and tail of time-series that do not properly match. This is because the DTW algorithm cannot afford the warping invariance for at the endpoints. In short, the effect of this is that a small difference at the sequence endpoints will tend to contribute disproportionately to the estimated similarity[3]. DTW is an algorithm to find an optimal alignment between two sequences and a useful distance metric to have in our toolbox. This technique is useful when we are working with two non-linear sequences, particularly if one sequence is a non-linear stretched/shrunk version of the other. The warping path is a combination of “chess king” moves that starts from the head of two sequences and ends with their tails. You can find the Jupyter notebook for this blog post here. Thanks for reading! [1] Donald J. Berndt and James Clifford, Using Dynamic Time Warping to Find Patterns in Time Series, 3rd International Conference on Knowledge Discovery and Data Mining [2] Salvador, S. and P. Chan, FastDTW: Toward accurate dynamic time warping in linear time and space (2007), Intelligent Data Analysis [3] Diego Furtado Silva, et al., On the effect of endpoints on dynamic time warping (2016), SIGKDD Workshop on Mining and Learning from Time Series
[ { "code": null, "e": 533, "s": 172, "text": "Dynamic Time Warping (DTW) is a way to compare two -usually temporal- sequences that do not sync up perfectly. It is a method to calculate the optimal matching between two sequences. DTW is useful in many domains such as speech recognition, data mining, financial markets, etc. It’s commonly used in data mining to measure the distance between two time-series." }, { "code": null, "e": 744, "s": 533, "text": "In this post, we will go over the mathematics behind DTW. Then, two illustrative examples are provided to better understand the concept. If you are not interested in the math behind it, please jump to examples." }, { "code": null, "e": 799, "s": 744, "text": "Let’s assume we have two sequences like the following:" }, { "code": null, "e": 834, "s": 799, "text": "X=x[1], x[2], ..., x[i], ..., x[n]" }, { "code": null, "e": 869, "s": 834, "text": "Y=y[1], y[2], ..., y[j], ..., y[m]" }, { "code": null, "e": 995, "s": 869, "text": "The sequences X and Y can be arranged to form an n-by-m grid, where each point (i, j) is the alignment between x[i] and y[j]." }, { "code": null, "e": 1169, "s": 995, "text": "A warping path W maps the elements of X and Y to minimize the distance between them. W is a sequence of grid points (i, j). We will see an example of the warping path later." }, { "code": null, "e": 1220, "s": 1169, "text": "The Optimal path to (i_k, j_k) can be computed by:" }, { "code": null, "e": 1304, "s": 1220, "text": "where d is the Euclidean distance. Then, the overall path cost can be calculated as" }, { "code": null, "e": 1609, "s": 1304, "text": "The warping path is found using a dynamic programming approach to align two sequences. Going through all possible paths is “combinatorically explosive” [1]. Therefore, for efficiency purposes, it’s important to limit the number of possible warping paths, and hence the following constraints are outlined:" }, { "code": null, "e": 1757, "s": 1609, "text": "Boundary Condition: This constraint ensures that the warping path begins with the start points of both signals and terminates with their endpoints." }, { "code": null, "e": 1858, "s": 1757, "text": "Monotonicity condition: This constraint preserves the time-order of points (not going back in time)." }, { "code": null, "e": 1986, "s": 1858, "text": "Continuity (step size) condition: This constraint limits the path transitions to adjacent points in time (not jumping in time)." }, { "code": null, "e": 2102, "s": 1986, "text": "In addition to the above three constraints, there are other less frequent conditions for an allowable warping path:" }, { "code": null, "e": 2234, "s": 2102, "text": "Warping window condition: Allowable points can be restricted to fall within a given warping window of width ω (a positive integer)." }, { "code": null, "e": 2375, "s": 2234, "text": "Slope condition: The warping path can be constrained by restricting the slope, and consequently avoiding extreme movements in one direction." }, { "code": null, "e": 2449, "s": 2375, "text": "An acceptable warping path has combinations of chess king moves that are:" }, { "code": null, "e": 2485, "s": 2449, "text": "Horizontal moves: (i, j) → (i, j+1)" }, { "code": null, "e": 2519, "s": 2485, "text": "Vertical moves: (i, j) → (i+1, j)" }, { "code": null, "e": 2555, "s": 2519, "text": "Diagonal moves: (i, j) → (i+1, j+1)" }, { "code": null, "e": 2597, "s": 2555, "text": "Let’s import all python packages we need." }, { "code": null, "e": 2945, "s": 2597, "text": "import pandas as pdimport numpy as np# Plotting Packagesimport matplotlib.pyplot as pltimport seaborn as sbn# Configuring Matplotlibimport matplotlib as mplmpl.rcParams['figure.dpi'] = 300savefig_options = dict(format=\"png\", dpi=300, bbox_inches=\"tight\")# Computation packagesfrom scipy.spatial.distance import euclideanfrom fastdtw import fastdtw" }, { "code": null, "e": 3223, "s": 2945, "text": "Let’s define a method to compute the accumulated cost matrix D for the warp path. The cost matrix uses the Euclidean distance to calculate the distance between every two points. The methods to compute the Euclidean distance matrix and accumulated cost matrix are defined below:" }, { "code": null, "e": 3294, "s": 3223, "text": "In this example, we have two sequences x and y with different lengths." }, { "code": null, "e": 3361, "s": 3294, "text": "# Create two sequencesx = [3, 1, 2, 2, 1]y = [2, 0, 0, 3, 3, 1, 0]" }, { "code": null, "e": 3457, "s": 3361, "text": "We cannot calculate the Euclidean distance between x and y since they don’t have equal lengths." }, { "code": null, "e": 3725, "s": 3457, "text": "Many Python packages calculate the DTW by just providing the sequences and the type of distance (usually Euclidean). Here, we use a popular Python implementation of DTW that is FastDTW which is an approximate DTW algorithm with lower time and memory complexities [2]." }, { "code": null, "e": 3781, "s": 3725, "text": "dtw_distance, warp_path = fastdtw(x, y, dist=euclidean)" }, { "code": null, "e": 4069, "s": 3781, "text": "Note that we are using SciPy’s distance function Euclidean that we imported earlier. For a better understanding of the warp path, let’s first compute the accumulated cost matrix and then visualize the path on a grid. The following code will plot a heatmap of the accumulated cost matrix." }, { "code": null, "e": 4121, "s": 4069, "text": "cost_matrix = compute_accumulated_cost_matrix(x, y)" }, { "code": null, "e": 4346, "s": 4121, "text": "The color bar shows the cost of each point in the grid. As can be seen, the warp path (blue line) is going through the lowest cost on the grid. Let’s see the DTW distance and the warping path by printing these two variables." }, { "code": null, "e": 4440, "s": 4346, "text": ">>> DTW distance: 6.0>>> Warp path: [(0, 0), (1, 1), (1, 2), (2, 3), (3, 4), (4, 5), (4, 6)]" }, { "code": null, "e": 4638, "s": 4440, "text": "The warping path starts at point (0, 0) and ends at (4, 6) by 6 moves. Let’s also calculate the accumulated cost most using the functions we defined earlier and compare the values with the heatmap." }, { "code": null, "e": 4985, "s": 4638, "text": "cost_matrix = compute_accumulated_cost_matrix(x, y)print(np.flipud(cost_matrix)) # Flipping the cost matrix for easier comparison with heatmap values!>>> [[32. 12. 10. 10. 6.] [23. 11. 6. 6. 5.] [19. 11. 5. 5. 9.] [19. 7. 4. 5. 8.] [19. 3. 6. 10. 4.] [10. 2. 6. 6. 3.] [ 1. 2. 2. 2. 3.]]" }, { "code": null, "e": 5053, "s": 4985, "text": "The cost matrix is printed above has similar values to the heatmap." }, { "code": null, "e": 5184, "s": 5053, "text": "Now let’s plot the two sequences and connect the mapping points. The code to plot the DTW distance between x and y is given below." }, { "code": null, "e": 5315, "s": 5184, "text": "In this example, we will use two sinusoidal signals and see how they will be matched by calculating the DTW distance between them." }, { "code": null, "e": 5432, "s": 5315, "text": "Just like Example 1, let’s calculate the DTW distance and the warp path for x1 and x2 signals using FastDTW package." }, { "code": null, "e": 5486, "s": 5432, "text": "distance, warp_path = fastdtw(x1, x2, dist=euclidean)" }, { "code": null, "e": 5862, "s": 5486, "text": "As can be seen in above figure, the DTW distance between the two signals is particularly powerful when the signals have similar patterns. The extrema (maximum and minimum points) between the two signals are correctly mapped. Moreover, unlike Euclidean distance, we may see many-to-one mapping when DTW distance is used, particularly if the two signals have different lengths." }, { "code": null, "e": 5959, "s": 5862, "text": "You may spot an issue with dynamic time warping from the figure above. Can you guess what it is?" }, { "code": null, "e": 6290, "s": 5959, "text": "The issue is around the head and tail of time-series that do not properly match. This is because the DTW algorithm cannot afford the warping invariance for at the endpoints. In short, the effect of this is that a small difference at the sequence endpoints will tend to contribute disproportionately to the estimated similarity[3]." }, { "code": null, "e": 6700, "s": 6290, "text": "DTW is an algorithm to find an optimal alignment between two sequences and a useful distance metric to have in our toolbox. This technique is useful when we are working with two non-linear sequences, particularly if one sequence is a non-linear stretched/shrunk version of the other. The warping path is a combination of “chess king” moves that starts from the head of two sequences and ends with their tails." }, { "code": null, "e": 6779, "s": 6700, "text": "You can find the Jupyter notebook for this blog post here. Thanks for reading!" }, { "code": null, "e": 6948, "s": 6779, "text": "[1] Donald J. Berndt and James Clifford, Using Dynamic Time Warping to Find Patterns in Time Series, 3rd International Conference on Knowledge Discovery and Data Mining" }, { "code": null, "e": 7083, "s": 6948, "text": "[2] Salvador, S. and P. Chan, FastDTW: Toward accurate dynamic time warping in linear time and space (2007), Intelligent Data Analysis" } ]
D3.js - Delimiter-Separated Values API
A delimiter is a sequence of one or more characters used to specify the boundary between separate, independent regions in plain text or other data. A field delimiter is a sequence of comma-separated values. Well, delimiter-separated values are comma separated values (CSV) or tab-separated values (TSV). This chapter explains the delimiter separated values in detail. We can easily load the API using the following syntax. <script src = "https://d3js.org/d3-dsv.v1.min.js"></script> <script> var data = d3.csvParse(string); </script> Following are the various API methods of the delimiter-separated values. d3.csvParse(string[, row]) d3.csvParseRows(string[, row]) d3.csvFormat(rows[, columns]) d3.csvFormatRows(rows) d3.tsvParse(string[, row]) d3.tsvParseRows(string[, row]) d3.tsvFormat(rows[, columns]) d3.tsvFormatRows(rows) Let us go through each of these API methods in detail. This method is used to parse the csv format. Consider the file data.csv that is shown below. year,population 2006,40 2008,45 2010,48 2012,51 2014,53 2016,57 2017,62 Now, we can apply the above-given function. Example − Let us consider the following example. var data = d3.csvParse(string, function(d) { return { year: new Date(+d.Year, 0, 1), // lowercase and convert "Year" to Date population: d.population }; }); Here, it Parses the specified string in the delimiter-separated values. It returns an array of objects representing the parsed rows. This method is used to parse the csv format equivalent to rows. var data = d3.csvParseRows(string, function(d, i) { return { year: new Date(+d[0], 0, 1), // convert first colum column to Date population: d[1], }; }); It parses each row in the csv file. This method is used to format the csv rows and columns. Example − Let us consider the following example. var string = d3.csvFormat(data, ["year", "population"]); Here, if the columns are not specified, the list of the column names that forms the header row is determined by the union of all properties on all the objects in the rows. If columns are specified, it is an array of strings representing the column names. This method is used to format the csv rows. Example − Let us consider the following example. var string = d3.csvFormatRows(data.map(function(d, i) { return [ d.year.getFullYear(), // Assuming d.year is a Date object. d.population ]; })); Here, it formats the specified array of string rows as delimiter-separated values, returning a string. This method is used to parse the tsv format. It is similar to csvParse. This method is used to parse the tsv format equivalent to rows. It is similar to csvParseRows function. This method is used to format the tsv rows and columns. This method is used to format the tsv rows. Print Add Notes Bookmark this page
[ { "code": null, "e": 2498, "s": 2130, "text": "A delimiter is a sequence of one or more characters used to specify the boundary between separate, independent regions in plain text or other data. A field delimiter is a sequence of comma-separated values. Well, delimiter-separated values are comma separated values (CSV) or tab-separated values (TSV). This chapter explains the delimiter separated values in detail." }, { "code": null, "e": 2553, "s": 2498, "text": "We can easily load the API using the following syntax." }, { "code": null, "e": 2667, "s": 2553, "text": "<script src = \"https://d3js.org/d3-dsv.v1.min.js\"></script>\n<script>\n var data = d3.csvParse(string);\n</script>" }, { "code": null, "e": 2740, "s": 2667, "text": "Following are the various API methods of the delimiter-separated values." }, { "code": null, "e": 2767, "s": 2740, "text": "d3.csvParse(string[, row])" }, { "code": null, "e": 2798, "s": 2767, "text": "d3.csvParseRows(string[, row])" }, { "code": null, "e": 2828, "s": 2798, "text": "d3.csvFormat(rows[, columns])" }, { "code": null, "e": 2851, "s": 2828, "text": "d3.csvFormatRows(rows)" }, { "code": null, "e": 2878, "s": 2851, "text": "d3.tsvParse(string[, row])" }, { "code": null, "e": 2909, "s": 2878, "text": "d3.tsvParseRows(string[, row])" }, { "code": null, "e": 2939, "s": 2909, "text": "d3.tsvFormat(rows[, columns])" }, { "code": null, "e": 2962, "s": 2939, "text": "d3.tsvFormatRows(rows)" }, { "code": null, "e": 3017, "s": 2962, "text": "Let us go through each of these API methods in detail." }, { "code": null, "e": 3110, "s": 3017, "text": "This method is used to parse the csv format. Consider the file data.csv that is shown below." }, { "code": null, "e": 3183, "s": 3110, "text": "year,population\n2006,40\n2008,45\n2010,48\n2012,51\n2014,53\n2016,57\n2017,62\n" }, { "code": null, "e": 3227, "s": 3183, "text": "Now, we can apply the above-given function." }, { "code": null, "e": 3276, "s": 3227, "text": "Example − Let us consider the following example." }, { "code": null, "e": 3451, "s": 3276, "text": "var data = d3.csvParse(string, function(d) {\n return {\n year: new Date(+d.Year, 0, 1), // lowercase and convert \"Year\" to Date\n population: d.population\n };\n});" }, { "code": null, "e": 3584, "s": 3451, "text": "Here, it Parses the specified string in the delimiter-separated values. It returns an array of objects representing the parsed rows." }, { "code": null, "e": 3648, "s": 3584, "text": "This method is used to parse the csv format equivalent to rows." }, { "code": null, "e": 3819, "s": 3648, "text": "var data = d3.csvParseRows(string, function(d, i) {\n return {\n year: new Date(+d[0], 0, 1), // convert first colum column to Date\n population: d[1],\n };\n});" }, { "code": null, "e": 3855, "s": 3819, "text": "It parses each row in the csv file." }, { "code": null, "e": 3911, "s": 3855, "text": "This method is used to format the csv rows and columns." }, { "code": null, "e": 3960, "s": 3911, "text": "Example − Let us consider the following example." }, { "code": null, "e": 4017, "s": 3960, "text": "var string = d3.csvFormat(data, [\"year\", \"population\"]);" }, { "code": null, "e": 4272, "s": 4017, "text": "Here, if the columns are not specified, the list of the column names that forms the header row is determined by the union of all properties on all the objects in the rows. If columns are specified, it is an array of strings representing the column names." }, { "code": null, "e": 4316, "s": 4272, "text": "This method is used to format the csv rows." }, { "code": null, "e": 4365, "s": 4316, "text": "Example − Let us consider the following example." }, { "code": null, "e": 4528, "s": 4365, "text": "var string = d3.csvFormatRows(data.map(function(d, i) {\n return [\n d.year.getFullYear(), // Assuming d.year is a Date object.\n d.population\n ];\n}));" }, { "code": null, "e": 4631, "s": 4528, "text": "Here, it formats the specified array of string rows as delimiter-separated values, returning a string." }, { "code": null, "e": 4703, "s": 4631, "text": "This method is used to parse the tsv format. It is similar to csvParse." }, { "code": null, "e": 4807, "s": 4703, "text": "This method is used to parse the tsv format equivalent to rows. It is similar to csvParseRows function." }, { "code": null, "e": 4863, "s": 4807, "text": "This method is used to format the tsv rows and columns." }, { "code": null, "e": 4907, "s": 4863, "text": "This method is used to format the tsv rows." }, { "code": null, "e": 4914, "s": 4907, "text": " Print" }, { "code": null, "e": 4925, "s": 4914, "text": " Add Notes" } ]
How do we split a string with any whitespace chars as delimiters using java?
The split() method of the String class accepts a delimiter (in the form of the string), divides the current String into smaller strings based on the delimiter and returns the resulting strings as an array. If the String does not contain the specified delimiter this method returns an array which contains only the current string. If the String does not contain the specified delimiter this method returns an array containing the whole string as element. To split a String into an array of strings with white pace as delimiter − Read the source string. Read the source string. Invoke split() method by passing “ ” as a delimiter. Invoke split() method by passing “ ” as a delimiter. Print the resultant array. Print the resultant array. Following Java program reads the contents of a file into a Sting and splits it using the split() method with white space as delimiter − import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Scanner; public class SplitExample { public static void main(String args[]) throws FileNotFoundException { Scanner sc = new Scanner(new File("D:\\sample.txt")); StringBuffer sb = new StringBuffer(); String input = new String(); while (sc.hasNextLine()) { input = sc.nextLine(); sb.append(input); } String source = sb.toString(); String result[] = source.split(" "); for(int i = 0; i < result.length; i++) { System.out.println(result[i]); } } } Hello how are you
[ { "code": null, "e": 1392, "s": 1062, "text": "The split() method of the String class accepts a delimiter (in the form of the string), divides the current String into smaller strings based on the delimiter and returns the resulting strings as an array. If the String does not contain the specified delimiter this method returns an array which contains only the current string." }, { "code": null, "e": 1516, "s": 1392, "text": "If the String does not contain the specified delimiter this method returns an array containing the whole string as element." }, { "code": null, "e": 1590, "s": 1516, "text": "To split a String into an array of strings with white pace as delimiter −" }, { "code": null, "e": 1614, "s": 1590, "text": "Read the source string." }, { "code": null, "e": 1638, "s": 1614, "text": "Read the source string." }, { "code": null, "e": 1691, "s": 1638, "text": "Invoke split() method by passing “ ” as a delimiter." }, { "code": null, "e": 1744, "s": 1691, "text": "Invoke split() method by passing “ ” as a delimiter." }, { "code": null, "e": 1771, "s": 1744, "text": "Print the resultant array." }, { "code": null, "e": 1798, "s": 1771, "text": "Print the resultant array." }, { "code": null, "e": 1934, "s": 1798, "text": "Following Java program reads the contents of a file into a Sting and splits it using the split() method with white space as delimiter −" }, { "code": null, "e": 2566, "s": 1934, "text": "import java.io.File;\nimport java.io.FileNotFoundException;\nimport java.util.Arrays;\nimport java.util.Scanner;\npublic class SplitExample {\n public static void main(String args[]) throws FileNotFoundException {\n Scanner sc = new Scanner(new File(\"D:\\\\sample.txt\"));\n StringBuffer sb = new StringBuffer();\n String input = new String();\n while (sc.hasNextLine()) {\n input = sc.nextLine();\n sb.append(input);\n }\n String source = sb.toString();\n String result[] = source.split(\" \");\n for(int i = 0; i < result.length; i++) {\n System.out.println(result[i]);\n }\n }\n}" }, { "code": null, "e": 2584, "s": 2566, "text": "Hello\nhow\nare\nyou" } ]
Access remote code in a breeze with JupyterLab via SSH | by Chiawei Lim | Towards Data Science
During our daily development work, there’s a need for us to access a remote system to co-develop with peers in a shared workplace train deep learning models on a powerful machine deploy some scripts in production The remote server might be referring to the public cloud, the private data center of an organization, a personal workstation, or others. There is one common attribute with these remote servers — it is located in a fixed location, often with top-notch security and a good cooling system. Fundamentally, since the server is located remotely, the user would need to access the server via SSH or other UI-based remote desktop application. UI-based remote desktop applications such as Anydesk, Teamviewer might not be the preferred option due to a few reasons These applications might not be free for long term use The need to have the application always running in the background The remote server is headless Increase of networking latency with the inclusion of graphical interface Hence, the majority opt for SSH as a secured method to access a remote system. With SSH work solely works in the terminal, at times it might be difficult to edit configurations or code with just vim/vi. Here’s where forwarding the web-based IDE — JupyterLab to the local system comes into handy. Walkthrough of the workflow Run JupyterLab in the background Run JupyterLab as a root user But I’m using Jupyter Notebook To allow the running of JupyterLab in sync with the remote system, there are two main steps Initiate the running of JupyterLab without interface.Forward remote port to local port Initiate the running of JupyterLab without interface. Forward remote port to local port Step 1: Initiate the running of JupyterLab without an interface Ssh into the remote system in the form of ssh <remote-user>@<remote-host> With JupyterLab installed, run the following command jupyter lab --no-browser --port <port-number> To forward the port, open another terminal and run the following command ssh -N -L localhost:<local-port>:localhost:<remote-port> <remote-user>@<remote-host> -N: Used for port forwarding. This suppresses the execution of a remote command. -L: Bind remote port to local port. Go ahead and open http://localhost:<local-port>/ in the browser. Enter the token key by copying from the terminal window from step 1. There are three important points to take notes of: In the current setup, the terminal running JupyterLab in the remote system has to be kept open. Alternatively, check out Run JupyterLab in the background, allowing the terminal to be closed without killing the process. Likewise, the terminal forwarding the port has to be kept open during the whole operation. The port forwarding terminal will not generate any output message to prompt that operation was successful (due to the flag -N being used). There is an option to run JupyterLab in the background and allow the terminal to be closed without killing the JupyterLab process. Simply add an ampersand & at the end of the command. jupyter lab --no-browser --port <port-number> & To kill the process, use the following command to identify the process ps -ef | grep python | sort Kill the process with kill -9 <process-id> Running JupyterLab as a root user is not recommended. However, the workaround for it is by adding a flag to explicitly allow running in the root user mode. jupyter lab --no-browser --port <port-number> --allow-root There is still a vast community that opts for Jupyter Notebook as their go-to IDE. Fear not. All of the commands introduced in this article are compatible with Jupyter Notebook too. Simply swap the command of JupyterLab into Jupyter Notebook. Example: jupyter notebook --no-browser --port <port-number> The installation of the JupyterLab package also allows the running of the Jupyter Notebook too! Till next time!
[ { "code": null, "e": 258, "s": 172, "text": "During our daily development work, there’s a need for us to access a remote system to" }, { "code": null, "e": 302, "s": 258, "text": "co-develop with peers in a shared workplace" }, { "code": null, "e": 351, "s": 302, "text": "train deep learning models on a powerful machine" }, { "code": null, "e": 385, "s": 351, "text": "deploy some scripts in production" }, { "code": null, "e": 522, "s": 385, "text": "The remote server might be referring to the public cloud, the private data center of an organization, a personal workstation, or others." }, { "code": null, "e": 820, "s": 522, "text": "There is one common attribute with these remote servers — it is located in a fixed location, often with top-notch security and a good cooling system. Fundamentally, since the server is located remotely, the user would need to access the server via SSH or other UI-based remote desktop application." }, { "code": null, "e": 940, "s": 820, "text": "UI-based remote desktop applications such as Anydesk, Teamviewer might not be the preferred option due to a few reasons" }, { "code": null, "e": 995, "s": 940, "text": "These applications might not be free for long term use" }, { "code": null, "e": 1061, "s": 995, "text": "The need to have the application always running in the background" }, { "code": null, "e": 1091, "s": 1061, "text": "The remote server is headless" }, { "code": null, "e": 1164, "s": 1091, "text": "Increase of networking latency with the inclusion of graphical interface" }, { "code": null, "e": 1367, "s": 1164, "text": "Hence, the majority opt for SSH as a secured method to access a remote system. With SSH work solely works in the terminal, at times it might be difficult to edit configurations or code with just vim/vi." }, { "code": null, "e": 1460, "s": 1367, "text": "Here’s where forwarding the web-based IDE — JupyterLab to the local system comes into handy." }, { "code": null, "e": 1488, "s": 1460, "text": "Walkthrough of the workflow" }, { "code": null, "e": 1521, "s": 1488, "text": "Run JupyterLab in the background" }, { "code": null, "e": 1551, "s": 1521, "text": "Run JupyterLab as a root user" }, { "code": null, "e": 1582, "s": 1551, "text": "But I’m using Jupyter Notebook" }, { "code": null, "e": 1674, "s": 1582, "text": "To allow the running of JupyterLab in sync with the remote system, there are two main steps" }, { "code": null, "e": 1761, "s": 1674, "text": "Initiate the running of JupyterLab without interface.Forward remote port to local port" }, { "code": null, "e": 1815, "s": 1761, "text": "Initiate the running of JupyterLab without interface." }, { "code": null, "e": 1849, "s": 1815, "text": "Forward remote port to local port" }, { "code": null, "e": 1913, "s": 1849, "text": "Step 1: Initiate the running of JupyterLab without an interface" }, { "code": null, "e": 1955, "s": 1913, "text": "Ssh into the remote system in the form of" }, { "code": null, "e": 1987, "s": 1955, "text": "ssh <remote-user>@<remote-host>" }, { "code": null, "e": 2040, "s": 1987, "text": "With JupyterLab installed, run the following command" }, { "code": null, "e": 2086, "s": 2040, "text": "jupyter lab --no-browser --port <port-number>" }, { "code": null, "e": 2159, "s": 2086, "text": "To forward the port, open another terminal and run the following command" }, { "code": null, "e": 2244, "s": 2159, "text": "ssh -N -L localhost:<local-port>:localhost:<remote-port> <remote-user>@<remote-host>" }, { "code": null, "e": 2325, "s": 2244, "text": "-N: Used for port forwarding. This suppresses the execution of a remote command." }, { "code": null, "e": 2361, "s": 2325, "text": "-L: Bind remote port to local port." }, { "code": null, "e": 2426, "s": 2361, "text": "Go ahead and open http://localhost:<local-port>/ in the browser." }, { "code": null, "e": 2495, "s": 2426, "text": "Enter the token key by copying from the terminal window from step 1." }, { "code": null, "e": 2546, "s": 2495, "text": "There are three important points to take notes of:" }, { "code": null, "e": 2765, "s": 2546, "text": "In the current setup, the terminal running JupyterLab in the remote system has to be kept open. Alternatively, check out Run JupyterLab in the background, allowing the terminal to be closed without killing the process." }, { "code": null, "e": 2856, "s": 2765, "text": "Likewise, the terminal forwarding the port has to be kept open during the whole operation." }, { "code": null, "e": 2995, "s": 2856, "text": "The port forwarding terminal will not generate any output message to prompt that operation was successful (due to the flag -N being used)." }, { "code": null, "e": 3126, "s": 2995, "text": "There is an option to run JupyterLab in the background and allow the terminal to be closed without killing the JupyterLab process." }, { "code": null, "e": 3179, "s": 3126, "text": "Simply add an ampersand & at the end of the command." }, { "code": null, "e": 3227, "s": 3179, "text": "jupyter lab --no-browser --port <port-number> &" }, { "code": null, "e": 3298, "s": 3227, "text": "To kill the process, use the following command to identify the process" }, { "code": null, "e": 3326, "s": 3298, "text": "ps -ef | grep python | sort" }, { "code": null, "e": 3348, "s": 3326, "text": "Kill the process with" }, { "code": null, "e": 3369, "s": 3348, "text": "kill -9 <process-id>" }, { "code": null, "e": 3423, "s": 3369, "text": "Running JupyterLab as a root user is not recommended." }, { "code": null, "e": 3525, "s": 3423, "text": "However, the workaround for it is by adding a flag to explicitly allow running in the root user mode." }, { "code": null, "e": 3584, "s": 3525, "text": "jupyter lab --no-browser --port <port-number> --allow-root" }, { "code": null, "e": 3766, "s": 3584, "text": "There is still a vast community that opts for Jupyter Notebook as their go-to IDE. Fear not. All of the commands introduced in this article are compatible with Jupyter Notebook too." }, { "code": null, "e": 3827, "s": 3766, "text": "Simply swap the command of JupyterLab into Jupyter Notebook." }, { "code": null, "e": 3836, "s": 3827, "text": "Example:" }, { "code": null, "e": 3887, "s": 3836, "text": "jupyter notebook --no-browser --port <port-number>" }, { "code": null, "e": 3983, "s": 3887, "text": "The installation of the JupyterLab package also allows the running of the Jupyter Notebook too!" } ]
Python - Display images with PyGame
Pygame is a multimedia library for Python for making games and multimedia applications. In this article we will see how to use the pygame module to paint a picture on the screen taking into consideration, its height, width and position in the pygame window. In the below program we initialize the pygame module and then define the mode and the caption for the image. Next we load the image and define the coordinates. The screen.blit function paints the screen while the while loop keeps listening the end of the game is clicked. import pygame pygame.init() w = 300; h = 300 screen = pygame.display.set_mode((w, h)) pygame.display.set_caption('Tutorialspoint Logo') TPImage = pygame.image.load("E:\\Python3\\tutorialspoint.png").convert() # coordinates of the image x = 10; y = 20; screen.blit(TPImage, (x, y)) # paint screen one time pygame.display.flip() running = True while (running): # loop listening for end of game for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # loop over, quite pygame pygame.quit() Running the above code gives us the following result −
[ { "code": null, "e": 1320, "s": 1062, "text": "Pygame is a multimedia library for Python for making games and multimedia applications. In this article we will see how to use the pygame module to paint a picture on the screen taking into consideration, its height, width and position in the pygame window." }, { "code": null, "e": 1592, "s": 1320, "text": "In the below program we initialize the pygame module and then define the mode and the caption for the image. Next we load the image and define the coordinates. The screen.blit function paints the screen while the while loop keeps listening the end of the game is clicked." }, { "code": null, "e": 2122, "s": 1592, "text": "import pygame\npygame.init()\nw = 300;\nh = 300\nscreen = pygame.display.set_mode((w, h))\npygame.display.set_caption('Tutorialspoint Logo')\nTPImage = pygame.image.load(\"E:\\\\Python3\\\\tutorialspoint.png\").convert()\n# coordinates of the image\nx = 10;\ny = 20;\nscreen.blit(TPImage, (x, y))\n# paint screen one time\npygame.display.flip()\nrunning = True\nwhile (running): # loop listening for end of game\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n# loop over, quite pygame\npygame.quit()\n" }, { "code": null, "e": 2177, "s": 2122, "text": "Running the above code gives us the following result −" } ]
Tryit Editor v3.7
Tryit: Change the opacity on hover
[]
\intercal - Tex Command
\intercal - Used to draw intercal symbol. { \intercal } \intercal command draws intercal symbol. intercal ⊺ intercal ⊺ intercal 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8028, "s": 7986, "text": "\\intercal - Used to draw intercal symbol." }, { "code": null, "e": 8042, "s": 8028, "text": "{ \\intercal }" }, { "code": null, "e": 8083, "s": 8042, "text": "\\intercal command draws intercal symbol." }, { "code": null, "e": 8099, "s": 8083, "text": "\nintercal\n\n⊺\n\n\n" }, { "code": null, "e": 8113, "s": 8099, "text": "intercal\n\n⊺\n\n" }, { "code": null, "e": 8122, "s": 8113, "text": "intercal" }, { "code": null, "e": 8154, "s": 8122, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8167, "s": 8154, "text": " Ashraf Said" }, { "code": null, "e": 8200, "s": 8167, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8213, "s": 8200, "text": " Ashraf Said" }, { "code": null, "e": 8245, "s": 8213, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 8281, "s": 8245, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8316, "s": 8281, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8333, "s": 8316, "text": " Mohammad Nauman" }, { "code": null, "e": 8366, "s": 8333, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8380, "s": 8366, "text": " Daniel Stern" }, { "code": null, "e": 8412, "s": 8380, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 8427, "s": 8412, "text": " Nishant Kumar" }, { "code": null, "e": 8434, "s": 8427, "text": " Print" }, { "code": null, "e": 8445, "s": 8434, "text": " Add Notes" } ]
Python 3 - List pop() Method
The pop() method removes and returns last object or obj from the list. Following is the syntax for pop() method − list.pop(obj = list[-1]) obj − This is an optional parameter, index of the object to be removed from the list. This method returns the removed object from the list. The following example shows the usage of pop() method. #!/usr/bin/python3 list1 = ['physics', 'Biology', 'chemistry', 'maths'] list1.pop() print ("list now : ", list1) list1.pop(1) print ("list now : ", list1) When we run above program, it produces the following result − list now : ['physics', 'Biology', 'chemistry'] list now : ['physics', 'chemistry'] 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": 2411, "s": 2340, "text": "The pop() method removes and returns last object or obj from the list." }, { "code": null, "e": 2454, "s": 2411, "text": "Following is the syntax for pop() method −" }, { "code": null, "e": 2480, "s": 2454, "text": "list.pop(obj = list[-1])\n" }, { "code": null, "e": 2566, "s": 2480, "text": "obj − This is an optional parameter, index of the object to be removed from the list." }, { "code": null, "e": 2620, "s": 2566, "text": "This method returns the removed object from the list." }, { "code": null, "e": 2675, "s": 2620, "text": "The following example shows the usage of pop() method." }, { "code": null, "e": 2832, "s": 2675, "text": "#!/usr/bin/python3\n\nlist1 = ['physics', 'Biology', 'chemistry', 'maths']\nlist1.pop()\nprint (\"list now : \", list1)\n\nlist1.pop(1)\nprint (\"list now : \", list1)" }, { "code": null, "e": 2894, "s": 2832, "text": "When we run above program, it produces the following result −" }, { "code": null, "e": 2980, "s": 2894, "text": "list now : ['physics', 'Biology', 'chemistry']\nlist now : ['physics', 'chemistry']\n" }, { "code": null, "e": 3017, "s": 2980, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3033, "s": 3017, "text": " Malhar Lathkar" }, { "code": null, "e": 3066, "s": 3033, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3085, "s": 3066, "text": " Arnab Chakraborty" }, { "code": null, "e": 3120, "s": 3085, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3142, "s": 3120, "text": " In28Minutes Official" }, { "code": null, "e": 3176, "s": 3142, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3204, "s": 3176, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3239, "s": 3204, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3253, "s": 3239, "text": " Lets Kode It" }, { "code": null, "e": 3286, "s": 3253, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3303, "s": 3286, "text": " Abhilash Nelson" }, { "code": null, "e": 3310, "s": 3303, "text": " Print" }, { "code": null, "e": 3321, "s": 3310, "text": " Add Notes" } ]
How to Sort a DataFrame in R ? - GeeksforGeeks
30 May, 2021 In this article, we will discuss how to sort the dataframe in R Programming Language. Methods to sort a dataframe: order() function (increasing and decreasing order)arrange() function from dplyr packagesetorder() function from data.table package order() function (increasing and decreasing order) arrange() function from dplyr package setorder() function from data.table package This function is used to sort the dataframe based on the particular column in the dataframe Syntax: order(dataframe$column_name,decreasing = TRUE)) where dataframe is the input dataframe Column name is the column in the dataframe such that dataframe is sorted based on this column Decreasing parameter specifies the type of sorting order If it is TRUE dataframe is sorted in descending order. Otherwise, in increasing order return type: Index positions of the elements Example 1: R program to create dataframe with 2 columns and order based on particular columns in decreasing order. Displayed the Sorted dataframe based on subjects in decreasing order, displayed the Sorted dataframe based on rollno in decreasing order R # create dataframe with roll no and # subjects columnsdata = data.frame( rollno = c(1, 5, 4, 2, 3), subjects = c("java", "python", "php", "sql", "c")) print(data) print("sort the data in decreasing order based on subjects ")print(data[order(data$subjects, decreasing = TRUE), ] ) print("sort the data in decreasing order based on rollno ")print(data[order(data$rollno, decreasing = TRUE), ] ) Output: rollno subjects 1 1 java 2 5 python 3 4 php 4 2 sql 5 3 c [1] "sort the data in decreasing order based on subjects " rollno subjects 4 2 sql 2 5 python 3 4 php 1 1 java 5 3 c [1] "sort the data in decreasing order based on rollno " rollno subjects 2 5 python 3 4 php 5 3 c 4 2 sql 1 1 java Example 2: R program to create dataframe with 3 columns named rollno, names, and subjects with a vector, displayed the Sorted dataframe based on subjects in increasing order, displayed the Sorted dataframe based on rollno in increasing order, displayed the Sorted dataframe based on names in increasing order R # create dataframe with roll no, names# and subjects columnsdata=data.frame(rollno = c(1, 5, 4, 2, 3), names = c("sravan", "bobby", "pinkey", "rohith", "gnanesh"), subjects = c("java", "python", "php", "sql", "c")) print(data) print("sort the data in increasing order based on subjects") print(data[order(data$subjects, decreasing = FALSE), ] ) print("sort the data in increasing order based on rollno")print(data[order(data$rollno, decreasing = FALSE), ] ) print("sort the data in increasing order based on names")print(data[order(data$names,decreasing = FALSE), ] ) Output: rollno names subjects 1 1 sravan java 2 5 bobby python 3 4 pinkey php 4 2 rohith sql 5 3 gnanesh c [1] "sort the data in increasing order based on subjects" rollno names subjects 5 3 gnanesh c 1 1 sravan java 3 4 pinkey php 2 5 bobby python 4 2 rohith sql [1] "sort the data in increasing order based on rollno" rollno names subjects 1 1 sravan java 4 2 rohith sql 5 3 gnanesh c 3 4 pinkey php 2 5 bobby python [1] "sort the data in increasing order based on names" rollno names subjects 2 5 bobby python 5 3 gnanesh c 3 4 pinkey php 4 2 rohith sql 1 1 sravan java Arrange() is used to sort the dataframe in increasing order, it will also sort the dataframe based on the column in the dataframe Syntax: arrange(dataframe,column) where dataframe is the dataframe input column is the column name , based on this column dataframe is sorted We need to install dplyr package as it is available in that package Syntax: install.packages(“dplyr”) Example: R program to sort dataframe based on columns In this program, we created three columns using the vector and sorted the dataframe based on the subjects column Code: R # load the packagelibrary("dplyr") # create dataframe with roll no, names # and subjects columnsdata = data.frame(rollno = c(1, 5, 4, 2, 3), names = c("sravan", "bobby", "pinkey", "rohith", "gnanesh"), subjects = c("java", "python", "php", "sql", "c")) # sort the data based on subjectsprint(arrange(data, subjects)) Output: rollno names subjects 1 3 gnanesh c 2 1 sravan java 3 4 pinkey php 4 5 bobby python 5 2 rohith sql setorder is used to sort a dataframe in the set order format. Syntax: setorder(dataframe, column) Where dataframe is the input dataframe The column is the column name Example: R program to sort dataframe based on columns In this program, we created the dataframe with three columns using vector and sorted the dataframe using setorder function based on subjects column Code: R # load the librarylibrary("data.table") # create dataframe with roll no, names # and subjects columnsdata=data.frame(rollno = c(1, 5, 4, 2, 3), names = c("sravan", "bobby", "pinkey", "rohith", "gnanesh"), subjects = c("java", "python", "php", "sql", "c")) # sort the data based on subjectsprint(setorder(data,subjects)) Output: rollno names subjects 5 3 gnanesh c 1 1 sravan java 3 4 pinkey php 2 5 bobby python 4 2 rohith sql 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. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? Data Visualization in R How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? Convert Matrix to Dataframe in R
[ { "code": null, "e": 25162, "s": 25134, "text": "\n30 May, 2021" }, { "code": null, "e": 25249, "s": 25162, "text": "In this article, we will discuss how to sort the dataframe in R Programming Language. " }, { "code": null, "e": 25278, "s": 25249, "text": "Methods to sort a dataframe:" }, { "code": null, "e": 25409, "s": 25278, "text": "order() function (increasing and decreasing order)arrange() function from dplyr packagesetorder() function from data.table package" }, { "code": null, "e": 25460, "s": 25409, "text": "order() function (increasing and decreasing order)" }, { "code": null, "e": 25498, "s": 25460, "text": "arrange() function from dplyr package" }, { "code": null, "e": 25542, "s": 25498, "text": "setorder() function from data.table package" }, { "code": null, "e": 25634, "s": 25542, "text": "This function is used to sort the dataframe based on the particular column in the dataframe" }, { "code": null, "e": 25690, "s": 25634, "text": "Syntax: order(dataframe$column_name,decreasing = TRUE))" }, { "code": null, "e": 25697, "s": 25690, "text": "where " }, { "code": null, "e": 25730, "s": 25697, "text": "dataframe is the input dataframe" }, { "code": null, "e": 25824, "s": 25730, "text": "Column name is the column in the dataframe such that dataframe is sorted based on this column" }, { "code": null, "e": 25881, "s": 25824, "text": "Decreasing parameter specifies the type of sorting order" }, { "code": null, "e": 25967, "s": 25881, "text": "If it is TRUE dataframe is sorted in descending order. Otherwise, in increasing order" }, { "code": null, "e": 26012, "s": 25967, "text": "return type: Index positions of the elements" }, { "code": null, "e": 26264, "s": 26012, "text": "Example 1: R program to create dataframe with 2 columns and order based on particular columns in decreasing order. Displayed the Sorted dataframe based on subjects in decreasing order, displayed the Sorted dataframe based on rollno in decreasing order" }, { "code": null, "e": 26266, "s": 26264, "text": "R" }, { "code": "# create dataframe with roll no and # subjects columnsdata = data.frame( rollno = c(1, 5, 4, 2, 3), subjects = c(\"java\", \"python\", \"php\", \"sql\", \"c\")) print(data) print(\"sort the data in decreasing order based on subjects \")print(data[order(data$subjects, decreasing = TRUE), ] ) print(\"sort the data in decreasing order based on rollno \")print(data[order(data$rollno, decreasing = TRUE), ] )", "e": 26670, "s": 26266, "text": null }, { "code": null, "e": 26678, "s": 26670, "text": "Output:" }, { "code": null, "e": 27118, "s": 26678, "text": " rollno subjects\n1 1 java\n2 5 python\n3 4 php\n4 2 sql\n5 3 c\n[1] \"sort the data in decreasing order based on subjects \"\n rollno subjects\n4 2 sql\n2 5 python\n3 4 php\n1 1 java\n5 3 c\n[1] \"sort the data in decreasing order based on rollno \"\n rollno subjects\n2 5 python\n3 4 php\n5 3 c\n4 2 sql\n1 1 java" }, { "code": null, "e": 27427, "s": 27118, "text": "Example 2: R program to create dataframe with 3 columns named rollno, names, and subjects with a vector, displayed the Sorted dataframe based on subjects in increasing order, displayed the Sorted dataframe based on rollno in increasing order, displayed the Sorted dataframe based on names in increasing order" }, { "code": null, "e": 27429, "s": 27427, "text": "R" }, { "code": "# create dataframe with roll no, names# and subjects columnsdata=data.frame(rollno = c(1, 5, 4, 2, 3), names = c(\"sravan\", \"bobby\", \"pinkey\", \"rohith\", \"gnanesh\"), subjects = c(\"java\", \"python\", \"php\", \"sql\", \"c\")) print(data) print(\"sort the data in increasing order based on subjects\") print(data[order(data$subjects, decreasing = FALSE), ] ) print(\"sort the data in increasing order based on rollno\")print(data[order(data$rollno, decreasing = FALSE), ] ) print(\"sort the data in increasing order based on names\")print(data[order(data$names,decreasing = FALSE), ] )", "e": 28118, "s": 27429, "text": null }, { "code": null, "e": 28126, "s": 28118, "text": "Output:" }, { "code": null, "e": 28919, "s": 28126, "text": " rollno names subjects\n1 1 sravan java\n2 5 bobby python\n3 4 pinkey php\n4 2 rohith sql\n5 3 gnanesh c\n[1] \"sort the data in increasing order based on subjects\"\n rollno names subjects\n5 3 gnanesh c\n1 1 sravan java\n3 4 pinkey php\n2 5 bobby python\n4 2 rohith sql\n[1] \"sort the data in increasing order based on rollno\"\n rollno names subjects\n1 1 sravan java\n4 2 rohith sql\n5 3 gnanesh c\n3 4 pinkey php\n2 5 bobby python\n[1] \"sort the data in increasing order based on names\"\n rollno names subjects\n2 5 bobby python\n5 3 gnanesh c\n3 4 pinkey php\n4 2 rohith sql\n1 1 sravan java" }, { "code": null, "e": 29049, "s": 28919, "text": "Arrange() is used to sort the dataframe in increasing order, it will also sort the dataframe based on the column in the dataframe" }, { "code": null, "e": 29083, "s": 29049, "text": "Syntax: arrange(dataframe,column)" }, { "code": null, "e": 29089, "s": 29083, "text": "where" }, { "code": null, "e": 29122, "s": 29089, "text": "dataframe is the dataframe input" }, { "code": null, "e": 29191, "s": 29122, "text": "column is the column name , based on this column dataframe is sorted" }, { "code": null, "e": 29259, "s": 29191, "text": "We need to install dplyr package as it is available in that package" }, { "code": null, "e": 29293, "s": 29259, "text": "Syntax: install.packages(“dplyr”)" }, { "code": null, "e": 29347, "s": 29293, "text": "Example: R program to sort dataframe based on columns" }, { "code": null, "e": 29460, "s": 29347, "text": "In this program, we created three columns using the vector and sorted the dataframe based on the subjects column" }, { "code": null, "e": 29466, "s": 29460, "text": "Code:" }, { "code": null, "e": 29468, "s": 29466, "text": "R" }, { "code": "# load the packagelibrary(\"dplyr\") # create dataframe with roll no, names # and subjects columnsdata = data.frame(rollno = c(1, 5, 4, 2, 3), names = c(\"sravan\", \"bobby\", \"pinkey\", \"rohith\", \"gnanesh\"), subjects = c(\"java\", \"python\", \"php\", \"sql\", \"c\")) # sort the data based on subjectsprint(arrange(data, subjects))", "e": 29881, "s": 29468, "text": null }, { "code": null, "e": 29889, "s": 29881, "text": "Output:" }, { "code": null, "e": 30045, "s": 29889, "text": " rollno names subjects\n1 3 gnanesh c\n2 1 sravan java\n3 4 pinkey php\n4 5 bobby python\n5 2 rohith sql" }, { "code": null, "e": 30107, "s": 30045, "text": "setorder is used to sort a dataframe in the set order format." }, { "code": null, "e": 30143, "s": 30107, "text": "Syntax: setorder(dataframe, column)" }, { "code": null, "e": 30182, "s": 30143, "text": "Where dataframe is the input dataframe" }, { "code": null, "e": 30212, "s": 30182, "text": "The column is the column name" }, { "code": null, "e": 30266, "s": 30212, "text": "Example: R program to sort dataframe based on columns" }, { "code": null, "e": 30414, "s": 30266, "text": "In this program, we created the dataframe with three columns using vector and sorted the dataframe using setorder function based on subjects column" }, { "code": null, "e": 30420, "s": 30414, "text": "Code:" }, { "code": null, "e": 30422, "s": 30420, "text": "R" }, { "code": "# load the librarylibrary(\"data.table\") # create dataframe with roll no, names # and subjects columnsdata=data.frame(rollno = c(1, 5, 4, 2, 3), names = c(\"sravan\", \"bobby\", \"pinkey\", \"rohith\", \"gnanesh\"), subjects = c(\"java\", \"python\", \"php\", \"sql\", \"c\")) # sort the data based on subjectsprint(setorder(data,subjects))", "e": 30854, "s": 30422, "text": null }, { "code": null, "e": 30862, "s": 30854, "text": "Output:" }, { "code": null, "e": 31018, "s": 30862, "text": " rollno names subjects\n5 3 gnanesh c\n1 1 sravan java\n3 4 pinkey php\n2 5 bobby python\n4 2 rohith sql" }, { "code": null, "e": 31025, "s": 31018, "text": "Picked" }, { "code": null, "e": 31046, "s": 31025, "text": "R DataFrame-Programs" }, { "code": null, "e": 31058, "s": 31046, "text": "R-DataFrame" }, { "code": null, "e": 31069, "s": 31058, "text": "R Language" }, { "code": null, "e": 31080, "s": 31069, "text": "R Programs" }, { "code": null, "e": 31178, "s": 31080, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31187, "s": 31178, "text": "Comments" }, { "code": null, "e": 31200, "s": 31187, "text": "Old Comments" }, { "code": null, "e": 31252, "s": 31200, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 31290, "s": 31252, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 31325, "s": 31290, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 31383, "s": 31325, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 31407, "s": 31383, "text": "Data Visualization in R" }, { "code": null, "e": 31465, "s": 31407, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 31514, "s": 31465, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 31557, "s": 31514, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 31607, "s": 31557, "text": "How to filter R dataframe by multiple conditions?" } ]
What is Calloc in C language?
The C library memory allocation function void *calloc(size_t nitems, size_t size) allocates the requested memory and returns a pointer to it. The difference in malloc and calloc is that malloc does not set the memory to zero, whereas, calloc sets the allocated memory to zero. Memory can be allocated in two ways as explained below − Once memory is allocated at compile time, it cannot be changed during execution. There will be a problem of either insufficiency or else wastage of memory. The solution is to create memory dynamically i.e. as per the requirement of the user during execution of program. The standard library functions which are used for dynamic memory management are as follows − malloc ( ) calloc ( ) realloc ( ) free ( ) This function is used for allocating continuous blocks of memory at run time. This function is used for allocating continuous blocks of memory at run time. This is specially designed for arrays. This is specially designed for arrays. It returns a void pointer, which points to the base address of the allocated memory. It returns a void pointer, which points to the base address of the allocated memory. The syntax for calloc() function is given below − void *calloc ( numbers of elements, size in bytes) The following example shows the usage of calloc() function. int *ptr; ptr = (int * ) calloc (500,2); Here, 500 blocks of memory each of size 2 bytes will be allocated continuously. Total memory allocated = 1000 bytes. int *ptr; ptr = (int * ) calloc (n, sizeof (int)); Given below is a C Program to compute sum of even numbers and odd numbers in a set of elements using dynamic memory allocation functions Calloc. Live Demo #include<stdio.h> #include<stdlib.h> void main(){ //Declaring variables, pointers// int i,n; int *p; int even=0,odd=0; //Declaring base address p using Calloc// p = (int * ) calloc (n, sizeof (int)); //Reading number of elements// printf("Enter the number of elements : "); scanf("%d",&n); /*Printing O/p - We have to use if statement because we have to check if memory has been successfully allocated/reserved or not*/ if (p==NULL){ printf("Memory not available"); exit(0); } //Storing elements into location using for loop// printf("The elements are : \n"); for(i=0;i<n;i++){ scanf("%d",p+i); } for(i=0;i<n;i++){ if(*(p+i)%2==0){ even=even+*(p+i); } else { odd=odd+*(p+i); } } printf("The sum of even numbers is : %d\n",even); printf("The sum of odd numbers is : %d\n",odd); } When the above program is executed, it produces the following result − Enter the number of elements : 4 The elements are : 12 56 23 10 The sum of even numbers is : 78 The sum of odd numbers is : 23
[ { "code": null, "e": 1204, "s": 1062, "text": "The C library memory allocation function void *calloc(size_t nitems, size_t size) allocates the requested memory and returns a pointer to it." }, { "code": null, "e": 1339, "s": 1204, "text": "The difference in malloc and calloc is that malloc does not set the memory to zero, whereas, calloc sets the allocated memory to zero." }, { "code": null, "e": 1396, "s": 1339, "text": "Memory can be allocated in two ways as explained below −" }, { "code": null, "e": 1552, "s": 1396, "text": "Once memory is allocated at compile time, it cannot be changed during execution. There will be a problem of either insufficiency or else wastage of memory." }, { "code": null, "e": 1666, "s": 1552, "text": "The solution is to create memory dynamically i.e. as per the requirement of the user during execution of program." }, { "code": null, "e": 1759, "s": 1666, "text": "The standard library functions which are used for dynamic memory management are as follows −" }, { "code": null, "e": 1770, "s": 1759, "text": "malloc ( )" }, { "code": null, "e": 1781, "s": 1770, "text": "calloc ( )" }, { "code": null, "e": 1793, "s": 1781, "text": "realloc ( )" }, { "code": null, "e": 1802, "s": 1793, "text": "free ( )" }, { "code": null, "e": 1880, "s": 1802, "text": "This function is used for allocating continuous blocks of memory at run time." }, { "code": null, "e": 1958, "s": 1880, "text": "This function is used for allocating continuous blocks of memory at run time." }, { "code": null, "e": 1997, "s": 1958, "text": "This is specially designed for arrays." }, { "code": null, "e": 2036, "s": 1997, "text": "This is specially designed for arrays." }, { "code": null, "e": 2121, "s": 2036, "text": "It returns a void pointer, which points to the base address of the allocated memory." }, { "code": null, "e": 2206, "s": 2121, "text": "It returns a void pointer, which points to the base address of the allocated memory." }, { "code": null, "e": 2256, "s": 2206, "text": "The syntax for calloc() function is given below −" }, { "code": null, "e": 2307, "s": 2256, "text": "void *calloc ( numbers of elements, size in bytes)" }, { "code": null, "e": 2367, "s": 2307, "text": "The following example shows the usage of calloc() function." }, { "code": null, "e": 2408, "s": 2367, "text": "int *ptr;\nptr = (int * ) calloc (500,2);" }, { "code": null, "e": 2525, "s": 2408, "text": "Here, 500 blocks of memory each of size 2 bytes will be allocated continuously. Total memory allocated = 1000 bytes." }, { "code": null, "e": 2576, "s": 2525, "text": "int *ptr;\nptr = (int * ) calloc (n, sizeof (int));" }, { "code": null, "e": 2721, "s": 2576, "text": "Given below is a C Program to compute sum of even numbers and odd numbers in a set of elements using dynamic memory allocation functions Calloc." }, { "code": null, "e": 2732, "s": 2721, "text": " Live Demo" }, { "code": null, "e": 3631, "s": 2732, "text": "#include<stdio.h>\n#include<stdlib.h>\nvoid main(){\n //Declaring variables, pointers//\n int i,n;\n int *p;\n int even=0,odd=0;\n //Declaring base address p using Calloc//\n p = (int * ) calloc (n, sizeof (int));\n //Reading number of elements//\n printf(\"Enter the number of elements : \");\n scanf(\"%d\",&n);\n /*Printing O/p -\n We have to use if statement because we have to check if memory\n has been successfully allocated/reserved or not*/\n if (p==NULL){\n printf(\"Memory not available\");\n exit(0);\n }\n //Storing elements into location using for loop//\n printf(\"The elements are : \\n\");\n for(i=0;i<n;i++){\n scanf(\"%d\",p+i);\n }\n for(i=0;i<n;i++){\n if(*(p+i)%2==0){\n even=even+*(p+i);\n } else {\n odd=odd+*(p+i);\n }\n }\n printf(\"The sum of even numbers is : %d\\n\",even);\n printf(\"The sum of odd numbers is : %d\\n\",odd);\n}" }, { "code": null, "e": 3702, "s": 3631, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 3829, "s": 3702, "text": "Enter the number of elements : 4\nThe elements are :\n12\n56\n23\n10\nThe sum of even numbers is : 78\nThe sum of odd numbers is : 23" } ]
HTML | default Attribute - GeeksforGeeks
03 Dec, 2021 The HTML default Attribute is a Boolean attribute. This attribute is used to specify that the track will be enabled if the user’s preferences do not indicate that another track would be more appropriate. Note: With a default attribute, there must not be more than one track element per media element.Syntax: <track src="subtitles_en.vtt" default> Applicable: <track> Example: html <html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> HTML default Attribute</h2> <video width="100" height="100" controls> <track src="https://write.geeksforgeeks.org/wp-content/uploads/11.mp4" kind="subtitles" srclang="en" label="English" default> <source id="myTrack" src="https://write.geeksforgeeks.org/wp-content/uploads/11.mp4" type="video/mp4"> </video></body> </html> Output : Supported Browsers: The browsers supported by HTML default Attribute are listed below: Google Chrome 18.0 Internet Explorer 10.0 Firefox 31.0 Apple Safari 6.0 Opera 15.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. hritikbhatnagar2182 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload 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 ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26139, "s": 26111, "text": "\n03 Dec, 2021" }, { "code": null, "e": 26449, "s": 26139, "text": "The HTML default Attribute is a Boolean attribute. This attribute is used to specify that the track will be enabled if the user’s preferences do not indicate that another track would be more appropriate. Note: With a default attribute, there must not be more than one track element per media element.Syntax: " }, { "code": null, "e": 26488, "s": 26449, "text": "<track src=\"subtitles_en.vtt\" default>" }, { "code": null, "e": 26502, "s": 26488, "text": "Applicable: " }, { "code": null, "e": 26510, "s": 26502, "text": "<track>" }, { "code": null, "e": 26521, "s": 26510, "text": "Example: " }, { "code": null, "e": 26526, "s": 26521, "text": "html" }, { "code": "<html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> HTML default Attribute</h2> <video width=\"100\" height=\"100\" controls> <track src=\"https://write.geeksforgeeks.org/wp-content/uploads/11.mp4\" kind=\"subtitles\" srclang=\"en\" label=\"English\" default> <source id=\"myTrack\" src=\"https://write.geeksforgeeks.org/wp-content/uploads/11.mp4\" type=\"video/mp4\"> </video></body> </html>", "e": 27188, "s": 26526, "text": null }, { "code": null, "e": 27199, "s": 27188, "text": "Output : " }, { "code": null, "e": 27288, "s": 27199, "text": "Supported Browsers: The browsers supported by HTML default Attribute are listed below: " }, { "code": null, "e": 27307, "s": 27288, "text": "Google Chrome 18.0" }, { "code": null, "e": 27330, "s": 27307, "text": "Internet Explorer 10.0" }, { "code": null, "e": 27343, "s": 27330, "text": "Firefox 31.0" }, { "code": null, "e": 27360, "s": 27343, "text": "Apple Safari 6.0" }, { "code": null, "e": 27371, "s": 27360, "text": "Opera 15.0" }, { "code": null, "e": 27510, "s": 27373, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 27530, "s": 27510, "text": "hritikbhatnagar2182" }, { "code": null, "e": 27546, "s": 27530, "text": "HTML-Attributes" }, { "code": null, "e": 27551, "s": 27546, "text": "HTML" }, { "code": null, "e": 27568, "s": 27551, "text": "Web Technologies" }, { "code": null, "e": 27573, "s": 27568, "text": "HTML" }, { "code": null, "e": 27671, "s": 27573, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27695, "s": 27671, "text": "REST API (Introduction)" }, { "code": null, "e": 27736, "s": 27695, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 27773, "s": 27736, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27802, "s": 27773, "text": "Form validation using jQuery" }, { "code": null, "e": 27822, "s": 27802, "text": "Angular File Upload" }, { "code": null, "e": 27862, "s": 27822, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27895, "s": 27862, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27940, "s": 27895, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27983, "s": 27940, "text": "How to fetch data from an API in ReactJS ?" } ]
Python - Convert TSV to CSV file - GeeksforGeeks
05 Nov, 2021 In this article, we will see how to Convert TSV Files to CSV using Python. TSV file can be converted into CSV file by reading one line of data at a time from TSV and replacing tab with comma using re library and writing into CSV file. We first open the TSV file from which we read data and then open the CSV file in which we write data. We read data line by line. And in each line we replace tab(“\t”) with comma(“,”) as data in CSV file is comma-separated. Example: Input File: Python3 # Python program to convert .tsv file to .csv file# importing re libraryimport re # reading given tsv filewith open("Olympic.tsv", 'r') as myfile: with open("Olympic.csv", 'w') as csv_file: for line in myfile: # Replace every tab with comma fileContent = re.sub("\t", ",", line) # Writing into csv file csv_file.write(fileContent) # outputprint("Successfully made csv file") Output: Successfully made csv file The Pandas module provides methods that make it very easy to read data stored in a variety of overeats. Here’s a snippet of a code that converts a TSV file to a CSV file. We first read data from TSV file using read_table(). Now we write this data into a CSV file using to_csv(). Here we write index=False because when reading data with read_table() function by default it makes a new column of index starting from 0. But we don’t write it in a CSV file using index=False. Example: Input File: Python3 # Python program to convert .tsv file to .csv file# importing pandas libraryimport pandas as pd tsv_file='GfG.tsv' # readinag given tsv filecsv_table=pd.read_table(tsv_file,sep='\t') # converting tsv file into csvcsv_table.to_csv('GfG.csv',index=False) # outputprint("Successfully made csv file") Output: Successfully made csv file Output File: Picked Python-TSV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25555, "s": 25527, "text": "\n05 Nov, 2021" }, { "code": null, "e": 25631, "s": 25555, "text": "In this article, we will see how to Convert TSV Files to CSV using Python. " }, { "code": null, "e": 26016, "s": 25631, "text": "TSV file can be converted into CSV file by reading one line of data at a time from TSV and replacing tab with comma using re library and writing into CSV file. We first open the TSV file from which we read data and then open the CSV file in which we write data. We read data line by line. And in each line we replace tab(“\\t”) with comma(“,”) as data in CSV file is comma-separated. " }, { "code": null, "e": 26025, "s": 26016, "text": "Example:" }, { "code": null, "e": 26037, "s": 26025, "text": "Input File:" }, { "code": null, "e": 26045, "s": 26037, "text": "Python3" }, { "code": "# Python program to convert .tsv file to .csv file# importing re libraryimport re # reading given tsv filewith open(\"Olympic.tsv\", 'r') as myfile: with open(\"Olympic.csv\", 'w') as csv_file: for line in myfile: # Replace every tab with comma fileContent = re.sub(\"\\t\", \",\", line) # Writing into csv file csv_file.write(fileContent) # outputprint(\"Successfully made csv file\")", "e": 26464, "s": 26045, "text": null }, { "code": null, "e": 26472, "s": 26464, "text": "Output:" }, { "code": null, "e": 26499, "s": 26472, "text": "Successfully made csv file" }, { "code": null, "e": 26971, "s": 26499, "text": "The Pandas module provides methods that make it very easy to read data stored in a variety of overeats. Here’s a snippet of a code that converts a TSV file to a CSV file. We first read data from TSV file using read_table(). Now we write this data into a CSV file using to_csv(). Here we write index=False because when reading data with read_table() function by default it makes a new column of index starting from 0. But we don’t write it in a CSV file using index=False." }, { "code": null, "e": 26980, "s": 26971, "text": "Example:" }, { "code": null, "e": 26992, "s": 26980, "text": "Input File:" }, { "code": null, "e": 27000, "s": 26992, "text": "Python3" }, { "code": "# Python program to convert .tsv file to .csv file# importing pandas libraryimport pandas as pd tsv_file='GfG.tsv' # readinag given tsv filecsv_table=pd.read_table(tsv_file,sep='\\t') # converting tsv file into csvcsv_table.to_csv('GfG.csv',index=False) # outputprint(\"Successfully made csv file\")", "e": 27302, "s": 27000, "text": null }, { "code": null, "e": 27310, "s": 27302, "text": "Output:" }, { "code": null, "e": 27337, "s": 27310, "text": "Successfully made csv file" }, { "code": null, "e": 27350, "s": 27337, "text": "Output File:" }, { "code": null, "e": 27357, "s": 27350, "text": "Picked" }, { "code": null, "e": 27368, "s": 27357, "text": "Python-TSV" }, { "code": null, "e": 27375, "s": 27368, "text": "Python" }, { "code": null, "e": 27473, "s": 27375, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27505, "s": 27473, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27547, "s": 27505, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27589, "s": 27547, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27645, "s": 27589, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27672, "s": 27645, "text": "Python Classes and Objects" }, { "code": null, "e": 27703, "s": 27672, "text": "Python | os.path.join() method" }, { "code": null, "e": 27742, "s": 27703, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27771, "s": 27742, "text": "Create a directory in Python" }, { "code": null, "e": 27793, "s": 27771, "text": "Defaultdict in Python" } ]
How to check for a substring in a PySpark dataframe ? - GeeksforGeeks
18 Jul, 2021 In this article, we are going to see how to check for a substring in PySpark dataframe. Substring is a continuous sequence of characters within a larger string size. For example, “learning pyspark” is a substring of “I am learning pyspark from GeeksForGeeks”. Let us look at different ways in which we can find a substring from one or more columns of a PySpark dataframe. Creating Dataframe for demonstration: Python # 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() # Column names for the dataframecolumns = ["LicenseNo", "ExpiryDate"] # Row data for the dataframedata = [ ("MH201411094334", "2024-11-19"), ("AR202027563890", "2030-03-16"), ("UP202010345567", "2035-12-30"), ("KN201822347800", "2028-10-29"),] # Create the dataframe using the above valuesreg_df = spark.createDataFrame(data=data, schema=columns) # View the dataframereg_df.show() Output: In the above dataframe, LicenseNo is composed of 3 information, 2-letter State Code + Year of registration + 8 digit registration number. The DataFrame.withColumn(colName, col) can be used for extracting substring from the column data by using pyspark’s substring() function along with it. Syntax: DataFrame.withColumn(colName, col) Parameters: colName: str, name of the new column col: str, a column expression for the new column Returns a new DataFrame by adding a column or replacing the existing column that has the same name. We will make use of the pyspark’s substring() function to create a new column “State” by extracting the respective substring from the LicenseNo column. Syntax: pyspark.sql.functions.substring(str, pos, len) Example 1: For single columns as substring. Python from pyspark.sql.functions import substring reg_df.withColumn( 'State', substring('LicenseNo', 1, 2)).show() Output: Here, we have created a new column “State” where the substring is taken from “LicenseNo” column. (1, 2) indicates that we need to start from the first character and extract 2 characters from the “LicenseNo” column. Example 2: For multiple columns as substring Extracting State Code as ‘State’, Registration Year as ‘RegYear’, Registration ID as ‘RegID’, Expiry Year as ‘ExpYr’, Expiry Date as ‘ExpDt’, Expiry Month as ‘ExpMo’. Python from pyspark.sql.functions import substring reg_df \.withColumn('State' , substring('LicenseNo' , 1, 2)) \.withColumn('RegYear', substring('LicenseNo' , 3, 4)) \.withColumn('RegID' , substring('LicenseNo' , 7, 8)) \.withColumn('ExpYr' , substring('ExpiryDate', 1, 4)) \.withColumn('ExpMo' , substring('ExpiryDate', 6, 2)) \.withColumn('ExpDt' , substring('ExpiryDate', 9, 2)) \.show() Output: The above code demonstrates how withColumn() method can be used multiple times to get multiple substring columns. Each withColumn() method adds a new column in the dataframe. It is worth noting that it also retains the original columns as well. Alternatively, we can also use substr from column type instead of using substring. Syntax:pyspark.sql.Column.substr(startPos, length) Returns a Column which is a substring of the column that starts at ‘startPos’ in byte and is of length ‘length’ when ‘str’ is Binary type. Example: Using substr Python from pyspark.sql.functions import col reg_df \.withColumn('State' , col('LicenseNo' ).substr(1, 2)) \.withColumn('RegYear', col('LicenseNo' ).substr(3, 4)) \.withColumn('RegID' , col('LicenseNo' ).substr(7, 8)) \.withColumn('ExpYr' , col('ExpiryDate').substr(1, 4)) \.withColumn('ExpMo' , col('ExpiryDate').substr(6, 2)) \.withColumn('ExpDt' , col('ExpiryDate').substr(9, 2)) \.show() Output: The substr() method works in conjunction with the col function from the spark.sql module. However, more or less it is just a syntactical change and the positioning logic remains the same. Here we will use the select() function to substring the dataframe. Syntax: pyspark.sql.DataFrame.select(*cols) Example: Using DataFrame.select() Python from pyspark.sql.functions import substring reg_df.select( substring('LicenseNo' , 1, 2).alias('State') , substring('LicenseNo' , 3, 4).alias('RegYear'), substring('LicenseNo' , 7, 8).alias('RegID') , substring('ExpiryDate', 1, 4).alias('ExpYr') , substring('ExpiryDate', 6, 2).alias('ExpMo') , substring('ExpiryDate', 9, 2).alias('ExpDt') ,).show() Output: The spark.sql() method helps to run relational SQL queries inside spark itself. It allows the execution of relational queries, including those expressed in SQL using Spark. Syntax: spark.sql(expression) Example: Using ‘spark.sql()’ Python reg_df.createOrReplaceTempView("reg_view") reg_df2 = spark.sql('''SELECT SUBSTR(LicenseNo, 1, 3) AS State, SUBSTR(LicenseNo, 3, 4) AS RegYear, SUBSTR(LicenseNo, 7, 8) AS RegID, SUBSTR(ExpiryDate, 1, 4) AS ExpYr, SUBSTR(ExpiryDate, 6, 2) AS ExpMo, SUBSTR(ExpiryDate, 9, 2) AS ExpDtFROM reg_view;''') reg_df2.show() Output: Here, we can see the expression used inside the spark.sql() is a relational SQL query. We can use the same in an SQL query editor as well to fetch the respective output. Using selectExpr() method is a way of providing SQL queries, but it is different from the relational ones’. We can provide one or more SQL expressions inside the method. It takes one or more SQL expressions in a String and returns a new DataFrame Syntax: selectExpr(exprs) Example: Using spark.DataFrame.selectExpr(). Python from pyspark.sql.functions import substring reg_df.selectExpr( 'LicenseNo', 'ExpiryDate', 'substring(LicenseNo , 1, 2) AS State' , 'substring(LicenseNo , 3, 4) AS RegYear' , 'substring(LicenseNo , 7, 8) AS RegID' , 'substring(ExpiryDate, 1, 4) AS ExpYr' , 'substring(ExpiryDate, 6, 2) AS ExpMo' , 'substring(ExpiryDate, 9, 2) AS ExpDt' ,).show() Output: In the above code snippet, we can observe that we have provided multiple SQL expressions inside the selectExpr() method. Each of these expressions resemble a part of the relational SQL query that we write. We also preserved the original columns by mentioning them explicitly. 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": "\n18 Jul, 2021" }, { "code": null, "e": 25625, "s": 25537, "text": "In this article, we are going to see how to check for a substring in PySpark dataframe." }, { "code": null, "e": 25909, "s": 25625, "text": "Substring is a continuous sequence of characters within a larger string size. For example, “learning pyspark” is a substring of “I am learning pyspark from GeeksForGeeks”. Let us look at different ways in which we can find a substring from one or more columns of a PySpark dataframe." }, { "code": null, "e": 25947, "s": 25909, "text": "Creating Dataframe for demonstration:" }, { "code": null, "e": 25954, "s": 25947, "text": "Python" }, { "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() # Column names for the dataframecolumns = [\"LicenseNo\", \"ExpiryDate\"] # Row data for the dataframedata = [ (\"MH201411094334\", \"2024-11-19\"), (\"AR202027563890\", \"2030-03-16\"), (\"UP202010345567\", \"2035-12-30\"), (\"KN201822347800\", \"2028-10-29\"),] # Create the dataframe using the above valuesreg_df = spark.createDataFrame(data=data, schema=columns) # View the dataframereg_df.show()", "e": 26611, "s": 25954, "text": null }, { "code": null, "e": 26619, "s": 26611, "text": "Output:" }, { "code": null, "e": 26757, "s": 26619, "text": "In the above dataframe, LicenseNo is composed of 3 information, 2-letter State Code + Year of registration + 8 digit registration number." }, { "code": null, "e": 26909, "s": 26757, "text": "The DataFrame.withColumn(colName, col) can be used for extracting substring from the column data by using pyspark’s substring() function along with it." }, { "code": null, "e": 26953, "s": 26909, "text": "Syntax: DataFrame.withColumn(colName, col) " }, { "code": null, "e": 26965, "s": 26953, "text": "Parameters:" }, { "code": null, "e": 27002, "s": 26965, "text": "colName: str, name of the new column" }, { "code": null, "e": 27051, "s": 27002, "text": "col: str, a column expression for the new column" }, { "code": null, "e": 27151, "s": 27051, "text": "Returns a new DataFrame by adding a column or replacing the existing column that has the same name." }, { "code": null, "e": 27303, "s": 27151, "text": "We will make use of the pyspark’s substring() function to create a new column “State” by extracting the respective substring from the LicenseNo column." }, { "code": null, "e": 27358, "s": 27303, "text": "Syntax: pyspark.sql.functions.substring(str, pos, len)" }, { "code": null, "e": 27402, "s": 27358, "text": "Example 1: For single columns as substring." }, { "code": null, "e": 27409, "s": 27402, "text": "Python" }, { "code": "from pyspark.sql.functions import substring reg_df.withColumn( 'State', substring('LicenseNo', 1, 2)).show()", "e": 27520, "s": 27409, "text": null }, { "code": null, "e": 27528, "s": 27520, "text": "Output:" }, { "code": null, "e": 27743, "s": 27528, "text": "Here, we have created a new column “State” where the substring is taken from “LicenseNo” column. (1, 2) indicates that we need to start from the first character and extract 2 characters from the “LicenseNo” column." }, { "code": null, "e": 27788, "s": 27743, "text": "Example 2: For multiple columns as substring" }, { "code": null, "e": 27955, "s": 27788, "text": "Extracting State Code as ‘State’, Registration Year as ‘RegYear’, Registration ID as ‘RegID’, Expiry Year as ‘ExpYr’, Expiry Date as ‘ExpDt’, Expiry Month as ‘ExpMo’." }, { "code": null, "e": 27962, "s": 27955, "text": "Python" }, { "code": "from pyspark.sql.functions import substring reg_df \\.withColumn('State' , substring('LicenseNo' , 1, 2)) \\.withColumn('RegYear', substring('LicenseNo' , 3, 4)) \\.withColumn('RegID' , substring('LicenseNo' , 7, 8)) \\.withColumn('ExpYr' , substring('ExpiryDate', 1, 4)) \\.withColumn('ExpMo' , substring('ExpiryDate', 6, 2)) \\.withColumn('ExpDt' , substring('ExpiryDate', 9, 2)) \\.show()", "e": 28353, "s": 27962, "text": null }, { "code": null, "e": 28361, "s": 28353, "text": "Output:" }, { "code": null, "e": 28606, "s": 28361, "text": "The above code demonstrates how withColumn() method can be used multiple times to get multiple substring columns. Each withColumn() method adds a new column in the dataframe. It is worth noting that it also retains the original columns as well." }, { "code": null, "e": 28689, "s": 28606, "text": "Alternatively, we can also use substr from column type instead of using substring." }, { "code": null, "e": 28740, "s": 28689, "text": "Syntax:pyspark.sql.Column.substr(startPos, length)" }, { "code": null, "e": 28879, "s": 28740, "text": "Returns a Column which is a substring of the column that starts at ‘startPos’ in byte and is of length ‘length’ when ‘str’ is Binary type." }, { "code": null, "e": 28902, "s": 28879, "text": "Example: Using substr " }, { "code": null, "e": 28909, "s": 28902, "text": "Python" }, { "code": "from pyspark.sql.functions import col reg_df \\.withColumn('State' , col('LicenseNo' ).substr(1, 2)) \\.withColumn('RegYear', col('LicenseNo' ).substr(3, 4)) \\.withColumn('RegID' , col('LicenseNo' ).substr(7, 8)) \\.withColumn('ExpYr' , col('ExpiryDate').substr(1, 4)) \\.withColumn('ExpMo' , col('ExpiryDate').substr(6, 2)) \\.withColumn('ExpDt' , col('ExpiryDate').substr(9, 2)) \\.show()", "e": 29300, "s": 28909, "text": null }, { "code": null, "e": 29308, "s": 29300, "text": "Output:" }, { "code": null, "e": 29497, "s": 29308, "text": "The substr() method works in conjunction with the col function from the spark.sql module. However, more or less it is just a syntactical change and the positioning logic remains the same. " }, { "code": null, "e": 29564, "s": 29497, "text": "Here we will use the select() function to substring the dataframe." }, { "code": null, "e": 29608, "s": 29564, "text": "Syntax: pyspark.sql.DataFrame.select(*cols)" }, { "code": null, "e": 29642, "s": 29608, "text": "Example: Using DataFrame.select()" }, { "code": null, "e": 29649, "s": 29642, "text": "Python" }, { "code": "from pyspark.sql.functions import substring reg_df.select( substring('LicenseNo' , 1, 2).alias('State') , substring('LicenseNo' , 3, 4).alias('RegYear'), substring('LicenseNo' , 7, 8).alias('RegID') , substring('ExpiryDate', 1, 4).alias('ExpYr') , substring('ExpiryDate', 6, 2).alias('ExpMo') , substring('ExpiryDate', 9, 2).alias('ExpDt') ,).show()", "e": 30011, "s": 29649, "text": null }, { "code": null, "e": 30019, "s": 30011, "text": "Output:" }, { "code": null, "e": 30194, "s": 30019, "text": "The spark.sql() method helps to run relational SQL queries inside spark itself. It allows the execution of relational queries, including those expressed in SQL using Spark. " }, { "code": null, "e": 30224, "s": 30194, "text": "Syntax: spark.sql(expression)" }, { "code": null, "e": 30253, "s": 30224, "text": "Example: Using ‘spark.sql()’" }, { "code": null, "e": 30260, "s": 30253, "text": "Python" }, { "code": "reg_df.createOrReplaceTempView(\"reg_view\") reg_df2 = spark.sql('''SELECT SUBSTR(LicenseNo, 1, 3) AS State, SUBSTR(LicenseNo, 3, 4) AS RegYear, SUBSTR(LicenseNo, 7, 8) AS RegID, SUBSTR(ExpiryDate, 1, 4) AS ExpYr, SUBSTR(ExpiryDate, 6, 2) AS ExpMo, SUBSTR(ExpiryDate, 9, 2) AS ExpDtFROM reg_view;''') reg_df2.show()", "e": 30586, "s": 30260, "text": null }, { "code": null, "e": 30594, "s": 30586, "text": "Output:" }, { "code": null, "e": 30764, "s": 30594, "text": "Here, we can see the expression used inside the spark.sql() is a relational SQL query. We can use the same in an SQL query editor as well to fetch the respective output." }, { "code": null, "e": 31011, "s": 30764, "text": "Using selectExpr() method is a way of providing SQL queries, but it is different from the relational ones’. We can provide one or more SQL expressions inside the method. It takes one or more SQL expressions in a String and returns a new DataFrame" }, { "code": null, "e": 31037, "s": 31011, "text": "Syntax: selectExpr(exprs)" }, { "code": null, "e": 31082, "s": 31037, "text": "Example: Using spark.DataFrame.selectExpr()." }, { "code": null, "e": 31089, "s": 31082, "text": "Python" }, { "code": "from pyspark.sql.functions import substring reg_df.selectExpr( 'LicenseNo', 'ExpiryDate', 'substring(LicenseNo , 1, 2) AS State' , 'substring(LicenseNo , 3, 4) AS RegYear' , 'substring(LicenseNo , 7, 8) AS RegID' , 'substring(ExpiryDate, 1, 4) AS ExpYr' , 'substring(ExpiryDate, 6, 2) AS ExpMo' , 'substring(ExpiryDate, 9, 2) AS ExpDt' ,).show()", "e": 31454, "s": 31089, "text": null }, { "code": null, "e": 31462, "s": 31454, "text": "Output:" }, { "code": null, "e": 31738, "s": 31462, "text": "In the above code snippet, we can observe that we have provided multiple SQL expressions inside the selectExpr() method. Each of these expressions resemble a part of the relational SQL query that we write. We also preserved the original columns by mentioning them explicitly." }, { "code": null, "e": 31745, "s": 31738, "text": "Picked" }, { "code": null, "e": 31760, "s": 31745, "text": "Python-Pyspark" }, { "code": null, "e": 31767, "s": 31760, "text": "Python" }, { "code": null, "e": 31865, "s": 31767, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31897, "s": 31865, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31939, "s": 31897, "text": "Check if element exists in list in Python" }, { "code": null, "e": 31981, "s": 31939, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 32008, "s": 31981, "text": "Python Classes and Objects" }, { "code": null, "e": 32064, "s": 32008, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 32086, "s": 32064, "text": "Defaultdict in Python" }, { "code": null, "e": 32125, "s": 32086, "text": "Python | Get unique values from a list" }, { "code": null, "e": 32156, "s": 32125, "text": "Python | os.path.join() method" }, { "code": null, "e": 32185, "s": 32156, "text": "Create a directory in Python" } ]
PHP Operators - GeeksforGeeks
19 Dec, 2021 In this article, we will see how to use the operators in PHP, & various available operators along with understanding their implementation through the examples. Operators are used to performing operations on some values. In other words, we can describe operators as something that takes some values, performs some operation on them, and gives a result. From example, “1 + 2 = 3” in this expression ‘+’ is an operator. It takes two values 1 and 2, performs an addition operation on them to give 3. Just like any other programming language, PHP also supports various types of operations like arithmetic operations(addition, subtraction, etc), logical operations(AND, OR etc), Increment/Decrement Operations, etc. Thus, PHP provides us with many operators to perform such operations on various operands or variables, or values. These operators are nothing but symbols needed to perform operations of various types. Given below are the various groups of operators: Arithmetic Operators Logical or Relational Operators Comparison Operators Conditional or Ternary Operators Assignment Operators Spaceship Operators (Introduced in PHP 7) Array Operators Increment/Decrement Operators String Operators Let us now learn about each of these operators in detail. Arithmetic Operators: The arithmetic operators are used to perform simple mathematical operations like addition, subtraction, multiplication, etc. Below is the list of arithmetic operators along with their syntax and operations in PHP. + Addition $x + $y Sum the operands – Subtraction $x – $y Differences the operands * Multiplication $x * $y Product of the operands / Division $x / $y The quotient of the operands ** Exponentiation $x ** $y $x raised to the power $y % Modulus $x % $y The remainder of the operands Note: The exponentiation has been introduced in PHP 5.6. Example: This example explains the arithmetic operator in PHP. PHP <?php $x = 29; // Variable 1 $y = 4; // Variable 2 // Some arithmetic operations on // these two variables echo ($x + $y), "\n"; echo($x - $y), "\n"; echo($x * $y), "\n"; echo($x / $y), "\n"; echo($x % $y), "\n";?> Output: 33 25 116 7.25 1 Logical or Relational Operators: These are basically used to operate with conditional statements and expressions. Conditional statements are based on conditions. Also, a condition can either be met or cannot be met so the result of a conditional statement can either be true or false. Here are the logical operators along with their syntax and operations in PHP. Example: This example describes the logical & relational operator in PHP. PHP <?php$x = 50;$y = 30; if ($x == 50 and $y == 30) echo "and Success \n"; if ($x == 50 or $y == 20) echo "or Success \n"; if ($x == 50 xor $y == 20) echo "xor Success \n"; if ($x == 50 && $y == 30) echo "&& Success \n"; if ($x == 50 || $y == 20) echo "|| Success \n"; if (!$z) echo "! Success \n";?> Output: and Success or Success xor Success && Success || Success ! Success Comparison Operators: These operators are used to compare two elements and outputs the result in boolean form. Here are the comparison operators along with their syntax and operations in PHP. Example: This example describes the comparison operator in PHP. PHP <?php $a = 80; $b = 50; $c = "80"; // Here var_dump function has been used to // display structured information. We will learn // about this function in complete details in further // articles. var_dump($a == $c) + "\n"; var_dump($a != $b) + "\n"; var_dump($a <> $b) + "\n"; var_dump($a === $c) + "\n"; var_dump($a !== $c) + "\n"; var_dump($a < $b) + "\n"; var_dump($a > $b) + "\n"; var_dump($a <= $b) + "\n"; var_dump($a >= $b);?> Output: bool(true) bool(true) bool(true) bool(false) bool(true) bool(false) bool(true) bool(false) bool(true) Conditional or Ternary Operators: These operators are used to compare two values and take either of the results simultaneously, depending on whether the outcome is TRUE or FALSE. These are also used as a shorthand notation for if...else statement that we will read in the article on decision making. Syntax: $var = (condition)? value1 : value2; Here, the condition will either evaluate as true or false. If the condition evaluates to True, then value1 will be assigned to the variable $var otherwise value2 will be assigned to it. ?: Ternary If the condition is true? then $x : or else $y. This means that if the condition is true then the left result of the colon is accepted otherwise the result is on right. Example: This example describes the Conditional or Ternary operators in PHP. PHP <?php $x = -12; echo ($x > 0) ? 'The number is positive' : 'The number is negative';?> Output: The number is negative Assignment Operators: These operators are used to assign values to different variables, with or without mid-operations. Here are the assignment operators along with their syntax and operations, that PHP provides for the operations. = Assign $x = $y Operand on the left obtains the value of the operand on the right += Add then Assign $x += $y Simple Addition same as $x = $x + $y -= Subtract then Assign $x -= $y Simple subtraction same as $x = $x – $y *= Multiply then Assign $x *= $y Simple product same as $x = $x * $y /= Divide then Assign (quotient) $x /= $y Simple division same as $x = $x / $y %= $x %= $y Simple division same as $x = $x % $y Example: This example describes the assignment operator in PHP. PHP <?php // Simple assign operator $y = 75; echo $y, "\n"; // Add then assign operator $y = 100; $y += 200; echo $y, "\n"; // Subtract then assign operator $y = 70; $y -= 10; echo $y, "\n"; // Multiply then assign operator $y = 30; $y *= 20; echo $y, "\n"; // Divide then assign(quotient) operator $y = 100; $y /= 5; echo $y, "\n"; // Divide then assign(remainder) operator $y = 50; $y %= 5; echo $y;?> Output: 75 300 60 600 20 0 Array Operators: These operators are used in the case of arrays. Here are the array operators along with their syntax and operations, that PHP provides for the array operation. + Union $x + $y Union of both i.e., $x and $y == Equality $x == $y Returns true if both has same key-value pair != Inequality $x != $y Returns True if both are unequal === Identity $x === $y Returns True if both have the same key-value pair in the same order and of the same type !== Non-Identity $x !== $y Returns True if both are not identical to each other <> Inequality $x <> $y Returns True if both are unequal Example: This example describes the array operation in PHP. PHP <?php $x = array("k" => "Car", "l" => "Bike"); $y = array("a" => "Train", "b" => "Plane"); var_dump($x + $y); var_dump($x == $y) + "\n"; var_dump($x != $y) + "\n"; var_dump($x <> $y) + "\n"; var_dump($x === $y) + "\n"; var_dump($x !== $y) + "\n";?> Output: array(4) { ["k"]=> string(3) "Car" ["l"]=> string(4) "Bike" ["a"]=> string(5) "Train" ["b"]=> string(5) "Plane" } bool(false) bool(true) bool(true) bool(false) bool(true) Increment/Decrement Operators: These are called the unary operators as they work on single operands. These are used to increment or decrement values. Example: This example describes the Increment/Decrement operators in PHP. PHP <?php $x = 2; echo ++$x, " First increments then prints \n"; echo $x, "\n"; $x = 2; echo $x++, " First prints then increments \n"; echo $x, "\n"; $x = 2; echo --$x, " First decrements then prints \n"; echo $x, "\n"; $x = 2; echo $x--, " First prints then decrements \n"; echo $x;?> Output: 3 First increments then prints 3 2 First prints then increments 3 1 First decrements then prints 1 2 First prints then decrements 1 String Operators: This operator is used for the concatenation of 2 or more strings using the concatenation operator (‘.’). We can also use the concatenating assignment operator (‘.=’) to append the argument on the right side to the argument on the left side. Example: This example describes the string operator in PHP. PHP <?php $x = "Geeks"; $y = "for"; $z = "Geeks!!!"; echo $x . $y . $z, "\n"; $x .= $y . $z; echo $x;?> Output: GeeksforGeeks!!! GeeksforGeeks!!! Spaceship Operators: PHP 7 has introduced a new kind of operator called spaceship operator. The spaceship operator or combined comparison operator is denoted by “<=>“. These operators are used to compare values but instead of returning the boolean results, it returns integer values. If both the operands are equal, it returns 0. If the right operand is greater, it returns -1. If the left operand is greater, it returns 1. The following table shows how it works in detail: Example: This example illustrates the use of the spaceship operator in PHP. PHP <?php $x = 50; $y = 50; $z = 25; echo $x <=> $y; echo "\n"; echo $x <=> $z; echo "\n"; echo $z <=> $y; echo "\n"; // We can do the same for Strings $x = "Ram"; $y = "Krishna"; echo $x <=> $y; echo "\n"; echo $x <=> $y; echo "\n"; echo $y <=> $x;?> Output: 0 1 -1 1 1 -1 This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ManikantaVasupalli bhaskargeeksforgeeks germanshephered48 PHP-Operators PHP Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? PHP | Converting string to Date and DateTime Comparing two dates in PHP How to pass JavaScript variables to PHP ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25211, "s": 25183, "text": "\n19 Dec, 2021" }, { "code": null, "e": 25371, "s": 25211, "text": "In this article, we will see how to use the operators in PHP, & various available operators along with understanding their implementation through the examples." }, { "code": null, "e": 25708, "s": 25371, "text": "Operators are used to performing operations on some values. In other words, we can describe operators as something that takes some values, performs some operation on them, and gives a result. From example, “1 + 2 = 3” in this expression ‘+’ is an operator. It takes two values 1 and 2, performs an addition operation on them to give 3. " }, { "code": null, "e": 26172, "s": 25708, "text": "Just like any other programming language, PHP also supports various types of operations like arithmetic operations(addition, subtraction, etc), logical operations(AND, OR etc), Increment/Decrement Operations, etc. Thus, PHP provides us with many operators to perform such operations on various operands or variables, or values. These operators are nothing but symbols needed to perform operations of various types. Given below are the various groups of operators:" }, { "code": null, "e": 26193, "s": 26172, "text": "Arithmetic Operators" }, { "code": null, "e": 26225, "s": 26193, "text": "Logical or Relational Operators" }, { "code": null, "e": 26246, "s": 26225, "text": "Comparison Operators" }, { "code": null, "e": 26279, "s": 26246, "text": "Conditional or Ternary Operators" }, { "code": null, "e": 26300, "s": 26279, "text": "Assignment Operators" }, { "code": null, "e": 26342, "s": 26300, "text": "Spaceship Operators (Introduced in PHP 7)" }, { "code": null, "e": 26358, "s": 26342, "text": "Array Operators" }, { "code": null, "e": 26388, "s": 26358, "text": "Increment/Decrement Operators" }, { "code": null, "e": 26405, "s": 26388, "text": "String Operators" }, { "code": null, "e": 26463, "s": 26405, "text": "Let us now learn about each of these operators in detail." }, { "code": null, "e": 26486, "s": 26463, "text": "Arithmetic Operators: " }, { "code": null, "e": 26700, "s": 26486, "text": "The arithmetic operators are used to perform simple mathematical operations like addition, subtraction, multiplication, etc. Below is the list of arithmetic operators along with their syntax and operations in PHP." }, { "code": null, "e": 26702, "s": 26700, "text": "+" }, { "code": null, "e": 26711, "s": 26702, "text": "Addition" }, { "code": null, "e": 26719, "s": 26711, "text": "$x + $y" }, { "code": null, "e": 26736, "s": 26719, "text": "Sum the operands" }, { "code": null, "e": 26738, "s": 26736, "text": "–" }, { "code": null, "e": 26750, "s": 26738, "text": "Subtraction" }, { "code": null, "e": 26758, "s": 26750, "text": "$x – $y" }, { "code": null, "e": 26783, "s": 26758, "text": "Differences the operands" }, { "code": null, "e": 26785, "s": 26783, "text": "*" }, { "code": null, "e": 26800, "s": 26785, "text": "Multiplication" }, { "code": null, "e": 26808, "s": 26800, "text": "$x * $y" }, { "code": null, "e": 26832, "s": 26808, "text": "Product of the operands" }, { "code": null, "e": 26834, "s": 26832, "text": "/" }, { "code": null, "e": 26843, "s": 26834, "text": "Division" }, { "code": null, "e": 26851, "s": 26843, "text": "$x / $y" }, { "code": null, "e": 26880, "s": 26851, "text": "The quotient of the operands" }, { "code": null, "e": 26883, "s": 26880, "text": "**" }, { "code": null, "e": 26898, "s": 26883, "text": "Exponentiation" }, { "code": null, "e": 26907, "s": 26898, "text": "$x ** $y" }, { "code": null, "e": 26933, "s": 26907, "text": "$x raised to the power $y" }, { "code": null, "e": 26935, "s": 26933, "text": "%" }, { "code": null, "e": 26943, "s": 26935, "text": "Modulus" }, { "code": null, "e": 26951, "s": 26943, "text": "$x % $y" }, { "code": null, "e": 26981, "s": 26951, "text": "The remainder of the operands" }, { "code": null, "e": 27039, "s": 26981, "text": "Note: The exponentiation has been introduced in PHP 5.6. " }, { "code": null, "e": 27102, "s": 27039, "text": "Example: This example explains the arithmetic operator in PHP." }, { "code": null, "e": 27106, "s": 27102, "text": "PHP" }, { "code": "<?php $x = 29; // Variable 1 $y = 4; // Variable 2 // Some arithmetic operations on // these two variables echo ($x + $y), \"\\n\"; echo($x - $y), \"\\n\"; echo($x * $y), \"\\n\"; echo($x / $y), \"\\n\"; echo($x % $y), \"\\n\";?>", "e": 27331, "s": 27106, "text": null }, { "code": null, "e": 27339, "s": 27331, "text": "Output:" }, { "code": null, "e": 27356, "s": 27339, "text": "33\n25\n116\n7.25\n1" }, { "code": null, "e": 27389, "s": 27356, "text": "Logical or Relational Operators:" }, { "code": null, "e": 27719, "s": 27389, "text": "These are basically used to operate with conditional statements and expressions. Conditional statements are based on conditions. Also, a condition can either be met or cannot be met so the result of a conditional statement can either be true or false. Here are the logical operators along with their syntax and operations in PHP." }, { "code": null, "e": 27793, "s": 27719, "text": "Example: This example describes the logical & relational operator in PHP." }, { "code": null, "e": 27797, "s": 27793, "text": "PHP" }, { "code": "<?php$x = 50;$y = 30; if ($x == 50 and $y == 30) echo \"and Success \\n\"; if ($x == 50 or $y == 20) echo \"or Success \\n\"; if ($x == 50 xor $y == 20) echo \"xor Success \\n\"; if ($x == 50 && $y == 30) echo \"&& Success \\n\"; if ($x == 50 || $y == 20) echo \"|| Success \\n\"; if (!$z) echo \"! Success \\n\";?>", "e": 28136, "s": 27797, "text": null }, { "code": null, "e": 28144, "s": 28136, "text": "Output:" }, { "code": null, "e": 28217, "s": 28144, "text": "and Success \nor Success \nxor Success \n&& Success \n|| Success \n! Success " }, { "code": null, "e": 28409, "s": 28217, "text": "Comparison Operators: These operators are used to compare two elements and outputs the result in boolean form. Here are the comparison operators along with their syntax and operations in PHP." }, { "code": null, "e": 28473, "s": 28409, "text": "Example: This example describes the comparison operator in PHP." }, { "code": null, "e": 28477, "s": 28473, "text": "PHP" }, { "code": "<?php $a = 80; $b = 50; $c = \"80\"; // Here var_dump function has been used to // display structured information. We will learn // about this function in complete details in further // articles. var_dump($a == $c) + \"\\n\"; var_dump($a != $b) + \"\\n\"; var_dump($a <> $b) + \"\\n\"; var_dump($a === $c) + \"\\n\"; var_dump($a !== $c) + \"\\n\"; var_dump($a < $b) + \"\\n\"; var_dump($a > $b) + \"\\n\"; var_dump($a <= $b) + \"\\n\"; var_dump($a >= $b);?>", "e": 28926, "s": 28477, "text": null }, { "code": null, "e": 28934, "s": 28926, "text": "Output:" }, { "code": null, "e": 29036, "s": 28934, "text": "bool(true)\nbool(true)\nbool(true)\nbool(false)\nbool(true)\nbool(false)\nbool(true)\nbool(false)\nbool(true)" }, { "code": null, "e": 29070, "s": 29036, "text": "Conditional or Ternary Operators:" }, { "code": null, "e": 29337, "s": 29070, "text": "These operators are used to compare two values and take either of the results simultaneously, depending on whether the outcome is TRUE or FALSE. These are also used as a shorthand notation for if...else statement that we will read in the article on decision making. " }, { "code": null, "e": 29345, "s": 29337, "text": "Syntax:" }, { "code": null, "e": 29382, "s": 29345, "text": "$var = (condition)? value1 : value2;" }, { "code": null, "e": 29568, "s": 29382, "text": "Here, the condition will either evaluate as true or false. If the condition evaluates to True, then value1 will be assigned to the variable $var otherwise value2 will be assigned to it." }, { "code": null, "e": 29571, "s": 29568, "text": "?:" }, { "code": null, "e": 29579, "s": 29571, "text": "Ternary" }, { "code": null, "e": 29748, "s": 29579, "text": "If the condition is true? then $x : or else $y. This means that if the condition is true then the left result of the colon is accepted otherwise the result is on right." }, { "code": null, "e": 29825, "s": 29748, "text": "Example: This example describes the Conditional or Ternary operators in PHP." }, { "code": null, "e": 29829, "s": 29825, "text": "PHP" }, { "code": "<?php $x = -12; echo ($x > 0) ? 'The number is positive' : 'The number is negative';?>", "e": 29918, "s": 29829, "text": null }, { "code": null, "e": 29926, "s": 29918, "text": "Output:" }, { "code": null, "e": 29949, "s": 29926, "text": "The number is negative" }, { "code": null, "e": 30181, "s": 29949, "text": "Assignment Operators: These operators are used to assign values to different variables, with or without mid-operations. Here are the assignment operators along with their syntax and operations, that PHP provides for the operations." }, { "code": null, "e": 30183, "s": 30181, "text": "=" }, { "code": null, "e": 30190, "s": 30183, "text": "Assign" }, { "code": null, "e": 30198, "s": 30190, "text": "$x = $y" }, { "code": null, "e": 30264, "s": 30198, "text": "Operand on the left obtains the value of the operand on the right" }, { "code": null, "e": 30267, "s": 30264, "text": "+=" }, { "code": null, "e": 30283, "s": 30267, "text": "Add then Assign" }, { "code": null, "e": 30292, "s": 30283, "text": "$x += $y" }, { "code": null, "e": 30329, "s": 30292, "text": "Simple Addition same as $x = $x + $y" }, { "code": null, "e": 30332, "s": 30329, "text": "-=" }, { "code": null, "e": 30353, "s": 30332, "text": "Subtract then Assign" }, { "code": null, "e": 30362, "s": 30353, "text": "$x -= $y" }, { "code": null, "e": 30402, "s": 30362, "text": "Simple subtraction same as $x = $x – $y" }, { "code": null, "e": 30405, "s": 30402, "text": "*=" }, { "code": null, "e": 30426, "s": 30405, "text": "Multiply then Assign" }, { "code": null, "e": 30435, "s": 30426, "text": "$x *= $y" }, { "code": null, "e": 30471, "s": 30435, "text": "Simple product same as $x = $x * $y" }, { "code": null, "e": 30474, "s": 30471, "text": "/=" }, { "code": null, "e": 30504, "s": 30474, "text": "Divide then Assign (quotient)" }, { "code": null, "e": 30513, "s": 30504, "text": "$x /= $y" }, { "code": null, "e": 30550, "s": 30513, "text": "Simple division same as $x = $x / $y" }, { "code": null, "e": 30553, "s": 30550, "text": "%=" }, { "code": null, "e": 30562, "s": 30553, "text": "$x %= $y" }, { "code": null, "e": 30599, "s": 30562, "text": "Simple division same as $x = $x % $y" }, { "code": null, "e": 30663, "s": 30599, "text": "Example: This example describes the assignment operator in PHP." }, { "code": null, "e": 30667, "s": 30663, "text": "PHP" }, { "code": "<?php // Simple assign operator $y = 75; echo $y, \"\\n\"; // Add then assign operator $y = 100; $y += 200; echo $y, \"\\n\"; // Subtract then assign operator $y = 70; $y -= 10; echo $y, \"\\n\"; // Multiply then assign operator $y = 30; $y *= 20; echo $y, \"\\n\"; // Divide then assign(quotient) operator $y = 100; $y /= 5; echo $y, \"\\n\"; // Divide then assign(remainder) operator $y = 50; $y %= 5; echo $y;?>", "e": 31095, "s": 30667, "text": null }, { "code": null, "e": 31103, "s": 31095, "text": "Output:" }, { "code": null, "e": 31122, "s": 31103, "text": "75\n300\n60\n600\n20\n0" }, { "code": null, "e": 31299, "s": 31122, "text": "Array Operators: These operators are used in the case of arrays. Here are the array operators along with their syntax and operations, that PHP provides for the array operation." }, { "code": null, "e": 31301, "s": 31299, "text": "+" }, { "code": null, "e": 31307, "s": 31301, "text": "Union" }, { "code": null, "e": 31315, "s": 31307, "text": "$x + $y" }, { "code": null, "e": 31345, "s": 31315, "text": "Union of both i.e., $x and $y" }, { "code": null, "e": 31348, "s": 31345, "text": "==" }, { "code": null, "e": 31357, "s": 31348, "text": "Equality" }, { "code": null, "e": 31366, "s": 31357, "text": "$x == $y" }, { "code": null, "e": 31411, "s": 31366, "text": "Returns true if both has same key-value pair" }, { "code": null, "e": 31414, "s": 31411, "text": "!=" }, { "code": null, "e": 31425, "s": 31414, "text": "Inequality" }, { "code": null, "e": 31434, "s": 31425, "text": "$x != $y" }, { "code": null, "e": 31467, "s": 31434, "text": "Returns True if both are unequal" }, { "code": null, "e": 31471, "s": 31467, "text": "===" }, { "code": null, "e": 31480, "s": 31471, "text": "Identity" }, { "code": null, "e": 31490, "s": 31480, "text": "$x === $y" }, { "code": null, "e": 31579, "s": 31490, "text": "Returns True if both have the same key-value pair in the same order and of the same type" }, { "code": null, "e": 31583, "s": 31579, "text": "!==" }, { "code": null, "e": 31596, "s": 31583, "text": "Non-Identity" }, { "code": null, "e": 31606, "s": 31596, "text": "$x !== $y" }, { "code": null, "e": 31659, "s": 31606, "text": "Returns True if both are not identical to each other" }, { "code": null, "e": 31662, "s": 31659, "text": "<>" }, { "code": null, "e": 31673, "s": 31662, "text": "Inequality" }, { "code": null, "e": 31682, "s": 31673, "text": "$x <> $y" }, { "code": null, "e": 31715, "s": 31682, "text": "Returns True if both are unequal" }, { "code": null, "e": 31775, "s": 31715, "text": "Example: This example describes the array operation in PHP." }, { "code": null, "e": 31779, "s": 31775, "text": "PHP" }, { "code": "<?php $x = array(\"k\" => \"Car\", \"l\" => \"Bike\"); $y = array(\"a\" => \"Train\", \"b\" => \"Plane\"); var_dump($x + $y); var_dump($x == $y) + \"\\n\"; var_dump($x != $y) + \"\\n\"; var_dump($x <> $y) + \"\\n\"; var_dump($x === $y) + \"\\n\"; var_dump($x !== $y) + \"\\n\";?>", "e": 32037, "s": 31779, "text": null }, { "code": null, "e": 32045, "s": 32037, "text": "Output:" }, { "code": null, "e": 32232, "s": 32045, "text": "array(4) {\n [\"k\"]=>\n string(3) \"Car\"\n [\"l\"]=>\n string(4) \"Bike\"\n [\"a\"]=>\n string(5) \"Train\"\n [\"b\"]=>\n string(5) \"Plane\"\n}\nbool(false)\nbool(true)\nbool(true)\nbool(false)\nbool(true)" }, { "code": null, "e": 32382, "s": 32232, "text": "Increment/Decrement Operators: These are called the unary operators as they work on single operands. These are used to increment or decrement values." }, { "code": null, "e": 32457, "s": 32382, "text": "Example: This example describes the Increment/Decrement operators in PHP. " }, { "code": null, "e": 32461, "s": 32457, "text": "PHP" }, { "code": "<?php $x = 2; echo ++$x, \" First increments then prints \\n\"; echo $x, \"\\n\"; $x = 2; echo $x++, \" First prints then increments \\n\"; echo $x, \"\\n\"; $x = 2; echo --$x, \" First decrements then prints \\n\"; echo $x, \"\\n\"; $x = 2; echo $x--, \" First prints then decrements \\n\"; echo $x;?>", "e": 32758, "s": 32461, "text": null }, { "code": null, "e": 32766, "s": 32758, "text": "Output:" }, { "code": null, "e": 32902, "s": 32766, "text": "3 First increments then prints \n3\n2 First prints then increments \n3\n1 First decrements then prints \n1\n2 First prints then decrements \n1" }, { "code": null, "e": 33161, "s": 32902, "text": "String Operators: This operator is used for the concatenation of 2 or more strings using the concatenation operator (‘.’). We can also use the concatenating assignment operator (‘.=’) to append the argument on the right side to the argument on the left side." }, { "code": null, "e": 33221, "s": 33161, "text": "Example: This example describes the string operator in PHP." }, { "code": null, "e": 33225, "s": 33221, "text": "PHP" }, { "code": "<?php $x = \"Geeks\"; $y = \"for\"; $z = \"Geeks!!!\"; echo $x . $y . $z, \"\\n\"; $x .= $y . $z; echo $x;?>", "e": 33331, "s": 33225, "text": null }, { "code": null, "e": 33339, "s": 33331, "text": "Output:" }, { "code": null, "e": 33373, "s": 33339, "text": "GeeksforGeeks!!!\nGeeksforGeeks!!!" }, { "code": null, "e": 33394, "s": 33373, "text": "Spaceship Operators:" }, { "code": null, "e": 33847, "s": 33394, "text": "PHP 7 has introduced a new kind of operator called spaceship operator. The spaceship operator or combined comparison operator is denoted by “<=>“. These operators are used to compare values but instead of returning the boolean results, it returns integer values. If both the operands are equal, it returns 0. If the right operand is greater, it returns -1. If the left operand is greater, it returns 1. The following table shows how it works in detail:" }, { "code": null, "e": 33923, "s": 33847, "text": "Example: This example illustrates the use of the spaceship operator in PHP." }, { "code": null, "e": 33927, "s": 33923, "text": "PHP" }, { "code": "<?php $x = 50; $y = 50; $z = 25; echo $x <=> $y; echo \"\\n\"; echo $x <=> $z; echo \"\\n\"; echo $z <=> $y; echo \"\\n\"; // We can do the same for Strings $x = \"Ram\"; $y = \"Krishna\"; echo $x <=> $y; echo \"\\n\"; echo $x <=> $y; echo \"\\n\"; echo $y <=> $x;?>", "e": 34199, "s": 33927, "text": null }, { "code": null, "e": 34207, "s": 34199, "text": "Output:" }, { "code": null, "e": 34221, "s": 34207, "text": "0\n1\n-1\n1\n1\n-1" }, { "code": null, "e": 34519, "s": 34221, "text": "This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 34644, "s": 34519, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 34663, "s": 34644, "text": "ManikantaVasupalli" }, { "code": null, "e": 34684, "s": 34663, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 34702, "s": 34684, "text": "germanshephered48" }, { "code": null, "e": 34716, "s": 34702, "text": "PHP-Operators" }, { "code": null, "e": 34720, "s": 34716, "text": "PHP" }, { "code": null, "e": 34737, "s": 34720, "text": "Web Technologies" }, { "code": null, "e": 34764, "s": 34737, "text": "Web technologies Questions" }, { "code": null, "e": 34768, "s": 34764, "text": "PHP" }, { "code": null, "e": 34866, "s": 34768, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34916, "s": 34866, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 34956, "s": 34916, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 35001, "s": 34956, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 35028, "s": 35001, "text": "Comparing two dates in PHP" }, { "code": null, "e": 35070, "s": 35028, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 35110, "s": 35070, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 35143, "s": 35110, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 35188, "s": 35143, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 35231, "s": 35188, "text": "How to fetch data from an API in ReactJS ?" } ]
Binomial Distribution in R Programming - GeeksforGeeks
10 May, 2020 Binomial distribution in R is a probability distribution used in statistics. The binomial distribution is a discrete distribution and has only two outcomes i.e. success or failure. All its trials are independent, the probability of success remains the same and the previous outcome does not affect the next outcome. The outcomes from different trials are independent. Binomial distribution helps us to find the individual probabilities as well as cumulative probabilities over a certain range. It is also used in many real-life scenarios such as in determining whether a particular lottery ticket has won or not, whether a drug is able to cure a person or not, it can be used to determine the number of heads or tails in a finite number of tosses, for analyzing the outcome of a die, etc. Formula: We have four functions for handling binomial distribution in R namely: dbinom()dbinom(k, n, p) dbinom(k, n, p) pbinom()pbinom(k, n, p)where n is total number of trials, p is probability of success, k is the value at which the probability has to be found out. pbinom(k, n, p) where n is total number of trials, p is probability of success, k is the value at which the probability has to be found out. qbinom()qbinom(P, n, p)Where P is the probability, n is the total number of trials and p is the probability of success. qbinom(P, n, p) Where P is the probability, n is the total number of trials and p is the probability of success. rbinom()rbinom(n, N, p)Where n is numbers of observations, N is the total number of trials, p is the probability of success. rbinom(n, N, p) Where n is numbers of observations, N is the total number of trials, p is the probability of success. This function is used to find probability at a particular value for a data that follows binomial distribution i.e. it finds: P(X = k) Syntax: dbinom(k, n, p) Example: dbinom(3, size = 13, prob = 1 / 6)probabilities <- dbinom(x = c(0:10), size = 10, prob = 1 / 6)data.frame(x, probs)plot(0:10, probabilities, type = "l") Output : > dbinom(3, size = 13, prob = 1/6) [1] 0.2138454 > probabilities = dbinom(x = c(0:10), size = 10, prob = 1/6) > data.frame(probabilities) probabilities 1 1.615056e-01 2 3.230112e-01 3 2.907100e-01 4 1.550454e-01 5 5.426588e-02 6 1.302381e-02 7 2.170635e-03 8 2.480726e-04 9 1.860544e-05 10 8.269086e-07 11 1.653817e-08 The above piece of code first finds the probability at k=3, then it displays a data frame containing the probability distribution for k from 0 to 10 which in this case is 0 to n. The function pbinom() is used to find the cumulative probability of a data following binomial distribution till a given value ie it finds P(X <= k) Syntax: pbinom(k, n, p) Example: pbinom(3, size = 13, prob = 1 / 6)plot(0:10, pbinom(0:10, size = 10, prob = 1 / 6), type = "l") Output : > pbinom(3, size = 13, prob = 1/6) [1] 0.8419226 This function is used to find the nth quantile, that is if P(x <= k) is given, it finds k. Syntax: qbinom(P, n, p) Example: qbinom(0.8419226, size = 13, prob = 1 / 6)x <- seq(0, 1, by = 0.1)y <- qbinom(x, size = 13, prob = 1 / 6)plot(x, y, type = 'l') Output : > qbinom(0.8419226, size = 13, prob = 1/6) [1] 3 This function generates n random variables of a particular probability. Syntax: rbinom(n, N, p) Example: rbinom(8, size = 13, prob = 1 / 6)hist(rbinom(8, size = 13, prob = 1 / 6)) Output: > rbinom(8, size = 13, prob = 1/6) [1] 1 1 2 1 4 0 2 3 Picked 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 How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Adding elements in a vector in R programming - append() method How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Convert Factor to Numeric and Numeric to Factor in R Programming Group by function in R using Dplyr How to Change Axis Scales in R Plots?
[ { "code": null, "e": 30289, "s": 30261, "text": "\n10 May, 2020" }, { "code": null, "e": 30783, "s": 30289, "text": "Binomial distribution in R is a probability distribution used in statistics. The binomial distribution is a discrete distribution and has only two outcomes i.e. success or failure. All its trials are independent, the probability of success remains the same and the previous outcome does not affect the next outcome. The outcomes from different trials are independent. Binomial distribution helps us to find the individual probabilities as well as cumulative probabilities over a certain range." }, { "code": null, "e": 31078, "s": 30783, "text": "It is also used in many real-life scenarios such as in determining whether a particular lottery ticket has won or not, whether a drug is able to cure a person or not, it can be used to determine the number of heads or tails in a finite number of tosses, for analyzing the outcome of a die, etc." }, { "code": null, "e": 31087, "s": 31078, "text": "Formula:" }, { "code": null, "e": 31158, "s": 31087, "text": "We have four functions for handling binomial distribution in R namely:" }, { "code": null, "e": 31182, "s": 31158, "text": "dbinom()dbinom(k, n, p)" }, { "code": null, "e": 31198, "s": 31182, "text": "dbinom(k, n, p)" }, { "code": null, "e": 31346, "s": 31198, "text": "pbinom()pbinom(k, n, p)where n is total number of trials, p is probability of success, k is the value at which the probability has to be found out." }, { "code": null, "e": 31362, "s": 31346, "text": "pbinom(k, n, p)" }, { "code": null, "e": 31487, "s": 31362, "text": "where n is total number of trials, p is probability of success, k is the value at which the probability has to be found out." }, { "code": null, "e": 31607, "s": 31487, "text": "qbinom()qbinom(P, n, p)Where P is the probability, n is the total number of trials and p is the probability of success." }, { "code": null, "e": 31623, "s": 31607, "text": "qbinom(P, n, p)" }, { "code": null, "e": 31720, "s": 31623, "text": "Where P is the probability, n is the total number of trials and p is the probability of success." }, { "code": null, "e": 31845, "s": 31720, "text": "rbinom()rbinom(n, N, p)Where n is numbers of observations, N is the total number of trials, p is the probability of success." }, { "code": null, "e": 31861, "s": 31845, "text": "rbinom(n, N, p)" }, { "code": null, "e": 31963, "s": 31861, "text": "Where n is numbers of observations, N is the total number of trials, p is the probability of success." }, { "code": null, "e": 32088, "s": 31963, "text": "This function is used to find probability at a particular value for a data that follows binomial distribution i.e. it finds:" }, { "code": null, "e": 32097, "s": 32088, "text": "P(X = k)" }, { "code": null, "e": 32105, "s": 32097, "text": "Syntax:" }, { "code": null, "e": 32121, "s": 32105, "text": "dbinom(k, n, p)" }, { "code": null, "e": 32130, "s": 32121, "text": "Example:" }, { "code": "dbinom(3, size = 13, prob = 1 / 6)probabilities <- dbinom(x = c(0:10), size = 10, prob = 1 / 6)data.frame(x, probs)plot(0:10, probabilities, type = \"l\")", "e": 32283, "s": 32130, "text": null }, { "code": null, "e": 32292, "s": 32283, "text": "Output :" }, { "code": null, "e": 32635, "s": 32292, "text": "> dbinom(3, size = 13, prob = 1/6)\n[1] 0.2138454\n> probabilities = dbinom(x = c(0:10), size = 10, prob = 1/6)\n> data.frame(probabilities)\n probabilities\n1 1.615056e-01\n2 3.230112e-01\n3 2.907100e-01\n4 1.550454e-01\n5 5.426588e-02\n6 1.302381e-02\n7 2.170635e-03\n8 2.480726e-04\n9 1.860544e-05\n10 8.269086e-07\n11 1.653817e-08\n" }, { "code": null, "e": 32814, "s": 32635, "text": "The above piece of code first finds the probability at k=3, then it displays a data frame containing the probability distribution for k from 0 to 10 which in this case is 0 to n." }, { "code": null, "e": 32952, "s": 32814, "text": "The function pbinom() is used to find the cumulative probability of a data following binomial distribution till a given value ie it finds" }, { "code": null, "e": 32962, "s": 32952, "text": "P(X <= k)" }, { "code": null, "e": 32970, "s": 32962, "text": "Syntax:" }, { "code": null, "e": 32986, "s": 32970, "text": "pbinom(k, n, p)" }, { "code": null, "e": 32995, "s": 32986, "text": "Example:" }, { "code": "pbinom(3, size = 13, prob = 1 / 6)plot(0:10, pbinom(0:10, size = 10, prob = 1 / 6), type = \"l\")", "e": 33091, "s": 32995, "text": null }, { "code": null, "e": 33100, "s": 33091, "text": "Output :" }, { "code": null, "e": 33150, "s": 33100, "text": "> pbinom(3, size = 13, prob = 1/6)\n[1] 0.8419226\n" }, { "code": null, "e": 33241, "s": 33150, "text": "This function is used to find the nth quantile, that is if P(x <= k) is given, it finds k." }, { "code": null, "e": 33249, "s": 33241, "text": "Syntax:" }, { "code": null, "e": 33265, "s": 33249, "text": "qbinom(P, n, p)" }, { "code": null, "e": 33274, "s": 33265, "text": "Example:" }, { "code": "qbinom(0.8419226, size = 13, prob = 1 / 6)x <- seq(0, 1, by = 0.1)y <- qbinom(x, size = 13, prob = 1 / 6)plot(x, y, type = 'l')", "e": 33402, "s": 33274, "text": null }, { "code": null, "e": 33411, "s": 33402, "text": "Output :" }, { "code": null, "e": 33461, "s": 33411, "text": "> qbinom(0.8419226, size = 13, prob = 1/6)\n[1] 3\n" }, { "code": null, "e": 33533, "s": 33461, "text": "This function generates n random variables of a particular probability." }, { "code": null, "e": 33541, "s": 33533, "text": "Syntax:" }, { "code": null, "e": 33557, "s": 33541, "text": "rbinom(n, N, p)" }, { "code": null, "e": 33566, "s": 33557, "text": "Example:" }, { "code": "rbinom(8, size = 13, prob = 1 / 6)hist(rbinom(8, size = 13, prob = 1 / 6))", "e": 33641, "s": 33566, "text": null }, { "code": null, "e": 33649, "s": 33641, "text": "Output:" }, { "code": null, "e": 33705, "s": 33649, "text": "> rbinom(8, size = 13, prob = 1/6)\n[1] 1 1 2 1 4 0 2 3\n" }, { "code": null, "e": 33712, "s": 33705, "text": "Picked" }, { "code": null, "e": 33723, "s": 33712, "text": "R Language" }, { "code": null, "e": 33821, "s": 33723, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33866, "s": 33821, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 33924, "s": 33866, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 33976, "s": 33924, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 34008, "s": 33976, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 34071, "s": 34008, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 34115, "s": 34071, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 34167, "s": 34115, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 34232, "s": 34167, "text": "Convert Factor to Numeric and Numeric to Factor in R Programming" }, { "code": null, "e": 34267, "s": 34232, "text": "Group by function in R using Dplyr" } ]
HTML small Tag - GeeksforGeeks
17 Mar, 2022 The <small> tag in HTML is used to set small font size.Syntax: <small> Contents... </small> Example 1: HTML <html> <body> <h1>GeeksforGeeks</h1> <h2><small> Tag</h2> <!-- html small tag is used here --> <small>Welcome to GeeksforGeeks!</small> </body> </html> Output: Example 2: Use CSS property to set the font size smaller. HTML <!DOCTYPE html><html> <head> <title>small Tag</title> <style> body { text-align:center; } h1 { color:green; } .gfg { font-size:smaller; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>font-size: smaller;</h2> <div class = "gfg">Welcome to GeeksforGeeks!</div> </body></html> Output: Supported Browsers: Google Chrome Internet Explorer Firefox Safari Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. shubhamyadav4 HTML-Tags HTML HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 24292, "s": 24264, "text": "\n17 Mar, 2022" }, { "code": null, "e": 24357, "s": 24292, "text": "The <small> tag in HTML is used to set small font size.Syntax: " }, { "code": null, "e": 24386, "s": 24357, "text": "<small> Contents... </small>" }, { "code": null, "e": 24399, "s": 24386, "text": "Example 1: " }, { "code": null, "e": 24404, "s": 24399, "text": "HTML" }, { "code": "<html> <body> <h1>GeeksforGeeks</h1> <h2><small> Tag</h2> <!-- html small tag is used here --> <small>Welcome to GeeksforGeeks!</small> </body> </html>", "e": 24650, "s": 24404, "text": null }, { "code": null, "e": 24660, "s": 24650, "text": "Output: " }, { "code": null, "e": 24720, "s": 24660, "text": "Example 2: Use CSS property to set the font size smaller. " }, { "code": null, "e": 24725, "s": 24720, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>small Tag</title> <style> body { text-align:center; } h1 { color:green; } .gfg { font-size:smaller; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>font-size: smaller;</h2> <div class = \"gfg\">Welcome to GeeksforGeeks!</div> </body></html> ", "e": 25189, "s": 24725, "text": null }, { "code": null, "e": 25199, "s": 25189, "text": "Output: " }, { "code": null, "e": 25221, "s": 25199, "text": "Supported Browsers: " }, { "code": null, "e": 25235, "s": 25221, "text": "Google Chrome" }, { "code": null, "e": 25253, "s": 25235, "text": "Internet Explorer" }, { "code": null, "e": 25261, "s": 25253, "text": "Firefox" }, { "code": null, "e": 25268, "s": 25261, "text": "Safari" }, { "code": null, "e": 25274, "s": 25268, "text": "Opera" }, { "code": null, "e": 25413, "s": 25276, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 25427, "s": 25413, "text": "shubhamyadav4" }, { "code": null, "e": 25437, "s": 25427, "text": "HTML-Tags" }, { "code": null, "e": 25442, "s": 25437, "text": "HTML" }, { "code": null, "e": 25447, "s": 25442, "text": "HTML" }, { "code": null, "e": 25545, "s": 25447, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25595, "s": 25545, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 25657, "s": 25595, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 25705, "s": 25657, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 25765, "s": 25705, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 25818, "s": 25765, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 25879, "s": 25818, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 25903, "s": 25879, "text": "REST API (Introduction)" }, { "code": null, "e": 25953, "s": 25903, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26003, "s": 25953, "text": "CSS to put icon inside an input element in a form" } ]
Implementation of Artificial Neural Network for NAND Logic Gate with 2-bit Binary Input - GeeksforGeeks
11 Jan, 2022 Artificial Neural Network (ANN) is a computational model based on the biological neural networks of animal brains. ANN is modeled with three types of layers: an input layer, hidden layers (one or more), and an output layer. Each layer comprises nodes (like biological neurons) are called Artificial Neurons. All nodes are connected with weighted edges (like synapses in biological brains) between two layers. Initially, with the forward propagation function, the output is predicted. Then through backpropagation, the weight and bias to the nodes are updated to minimizing the error in prediction to attain the convergence of cost function in determining the final output. NAND logical function truth table for 2-bit binary variables, i.e, the input vector and the corresponding output – Approach: Step1: Import the required Python libraries Step2: Define Activation Function : Sigmoid Function Step3: Initialize neural network parameters (weights, bias) and define model hyperparameters (number of iterations, learning rate) Step4: Forward Propagation Step5: Backward Propagation Step6: Update weight and bias parameters Step7: Train the learning model Step8: Plot Loss value vs Epoch Step9: Test the model performance Python Implementation: Python3 # import Python Librariesimport numpy as npfrom matplotlib import pyplot as plt # Sigmoid Functiondef sigmoid(z): return 1 / (1 + np.exp(-z)) # Initialization of the neural network parameters# Initialized all the weights in the range of between 0 and 1# Bias values are initialized to 0def initializeParameters(inputFeatures, neuronsInHiddenLayers, outputFeatures): W1 = np.random.randn(neuronsInHiddenLayers, inputFeatures) W2 = np.random.randn(outputFeatures, neuronsInHiddenLayers) b1 = np.zeros((neuronsInHiddenLayers, 1)) b2 = np.zeros((outputFeatures, 1)) parameters = {"W1" : W1, "b1": b1, "W2" : W2, "b2": b2} return parameters # Forward Propagationdef forwardPropagation(X, Y, parameters): m = X.shape[1] W1 = parameters["W1"] W2 = parameters["W2"] b1 = parameters["b1"] b2 = parameters["b2"] Z1 = np.dot(W1, X) + b1 A1 = sigmoid(Z1) Z2 = np.dot(W2, A1) + b2 A2 = sigmoid(Z2) cache = (Z1, A1, W1, b1, Z2, A2, W2, b2) logprobs = np.multiply(np.log(A2), Y) + np.multiply(np.log(1 - A2), (1 - Y)) cost = -np.sum(logprobs) / m return cost, cache, A2 # Backward Propagationdef backwardPropagation(X, Y, cache): m = X.shape[1] (Z1, A1, W1, b1, Z2, A2, W2, b2) = cache dZ2 = A2 - Y dW2 = np.dot(dZ2, A1.T) / m db2 = np.sum(dZ2, axis = 1, keepdims = True) dA1 = np.dot(W2.T, dZ2) dZ1 = np.multiply(dA1, A1 * (1- A1)) dW1 = np.dot(dZ1, X.T) / m db1 = np.sum(dZ1, axis = 1, keepdims = True) / m gradients = {"dZ2": dZ2, "dW2": dW2, "db2": db2, "dZ1": dZ1, "dW1": dW1, "db1": db1} return gradients # Updating the weights based on the negative gradientsdef updateParameters(parameters, gradients, learningRate): parameters["W1"] = parameters["W1"] - learningRate * gradients["dW1"] parameters["W2"] = parameters["W2"] - learningRate * gradients["dW2"] parameters["b1"] = parameters["b1"] - learningRate * gradients["db1"] parameters["b2"] = parameters["b2"] - learningRate * gradients["db2"] return parameters # Model to learn the NAND truth tableX = np.array([[0, 0, 1, 1], [0, 1, 0, 1]]) # NAND inputY = np.array([[1, 1, 1, 0]]) # NAND output # Define model parametersneuronsInHiddenLayers = 2 # number of hidden layer neurons (2)inputFeatures = X.shape[0] # number of input features (2)outputFeatures = Y.shape[0] # number of output features (1)parameters = initializeParameters(inputFeatures, neuronsInHiddenLayers, outputFeatures)epoch = 100000learningRate = 0.01losses = np.zeros((epoch, 1)) for i in range(epoch): losses[i, 0], cache, A2 = forwardPropagation(X, Y, parameters) gradients = backwardPropagation(X, Y, cache) parameters = updateParameters(parameters, gradients, learningRate) # Evaluating the performanceplt.figure()plt.plot(losses)plt.xlabel("EPOCHS")plt.ylabel("Loss value")plt.show() # TestingX = np.array([[1, 1, 0, 0], [0, 1, 0, 1]]) # NAND inputcost, _, A2 = forwardPropagation(X, Y, parameters)prediction = (A2 > 0.5) * 1.0# print(A2)print(prediction) [[ 1. 0. 1. 1.]] Here, the model predicted output for each of the test inputs are exactly matched with the NAND logic gate conventional output () according to the truth table and the cost function is also continuously converging. Hence, it signifies that the Artificial Neural Network for the NAND logic gate is correctly implemented. sweetyty Neural Network Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning Decision Tree Decision Tree Introduction with example Support Vector Machine Algorithm Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 26839, "s": 26811, "text": "\n11 Jan, 2022" }, { "code": null, "e": 27628, "s": 26839, "text": "Artificial Neural Network (ANN) is a computational model based on the biological neural networks of animal brains. ANN is modeled with three types of layers: an input layer, hidden layers (one or more), and an output layer. Each layer comprises nodes (like biological neurons) are called Artificial Neurons. All nodes are connected with weighted edges (like synapses in biological brains) between two layers. Initially, with the forward propagation function, the output is predicted. Then through backpropagation, the weight and bias to the nodes are updated to minimizing the error in prediction to attain the convergence of cost function in determining the final output. NAND logical function truth table for 2-bit binary variables, i.e, the input vector and the corresponding output – " }, { "code": null, "e": 28066, "s": 27632, "text": "Approach: Step1: Import the required Python libraries Step2: Define Activation Function : Sigmoid Function Step3: Initialize neural network parameters (weights, bias) and define model hyperparameters (number of iterations, learning rate) Step4: Forward Propagation Step5: Backward Propagation Step6: Update weight and bias parameters Step7: Train the learning model Step8: Plot Loss value vs Epoch Step9: Test the model performance " }, { "code": null, "e": 28091, "s": 28066, "text": "Python Implementation: " }, { "code": null, "e": 28099, "s": 28091, "text": "Python3" }, { "code": "# import Python Librariesimport numpy as npfrom matplotlib import pyplot as plt # Sigmoid Functiondef sigmoid(z): return 1 / (1 + np.exp(-z)) # Initialization of the neural network parameters# Initialized all the weights in the range of between 0 and 1# Bias values are initialized to 0def initializeParameters(inputFeatures, neuronsInHiddenLayers, outputFeatures): W1 = np.random.randn(neuronsInHiddenLayers, inputFeatures) W2 = np.random.randn(outputFeatures, neuronsInHiddenLayers) b1 = np.zeros((neuronsInHiddenLayers, 1)) b2 = np.zeros((outputFeatures, 1)) parameters = {\"W1\" : W1, \"b1\": b1, \"W2\" : W2, \"b2\": b2} return parameters # Forward Propagationdef forwardPropagation(X, Y, parameters): m = X.shape[1] W1 = parameters[\"W1\"] W2 = parameters[\"W2\"] b1 = parameters[\"b1\"] b2 = parameters[\"b2\"] Z1 = np.dot(W1, X) + b1 A1 = sigmoid(Z1) Z2 = np.dot(W2, A1) + b2 A2 = sigmoid(Z2) cache = (Z1, A1, W1, b1, Z2, A2, W2, b2) logprobs = np.multiply(np.log(A2), Y) + np.multiply(np.log(1 - A2), (1 - Y)) cost = -np.sum(logprobs) / m return cost, cache, A2 # Backward Propagationdef backwardPropagation(X, Y, cache): m = X.shape[1] (Z1, A1, W1, b1, Z2, A2, W2, b2) = cache dZ2 = A2 - Y dW2 = np.dot(dZ2, A1.T) / m db2 = np.sum(dZ2, axis = 1, keepdims = True) dA1 = np.dot(W2.T, dZ2) dZ1 = np.multiply(dA1, A1 * (1- A1)) dW1 = np.dot(dZ1, X.T) / m db1 = np.sum(dZ1, axis = 1, keepdims = True) / m gradients = {\"dZ2\": dZ2, \"dW2\": dW2, \"db2\": db2, \"dZ1\": dZ1, \"dW1\": dW1, \"db1\": db1} return gradients # Updating the weights based on the negative gradientsdef updateParameters(parameters, gradients, learningRate): parameters[\"W1\"] = parameters[\"W1\"] - learningRate * gradients[\"dW1\"] parameters[\"W2\"] = parameters[\"W2\"] - learningRate * gradients[\"dW2\"] parameters[\"b1\"] = parameters[\"b1\"] - learningRate * gradients[\"db1\"] parameters[\"b2\"] = parameters[\"b2\"] - learningRate * gradients[\"db2\"] return parameters # Model to learn the NAND truth tableX = np.array([[0, 0, 1, 1], [0, 1, 0, 1]]) # NAND inputY = np.array([[1, 1, 1, 0]]) # NAND output # Define model parametersneuronsInHiddenLayers = 2 # number of hidden layer neurons (2)inputFeatures = X.shape[0] # number of input features (2)outputFeatures = Y.shape[0] # number of output features (1)parameters = initializeParameters(inputFeatures, neuronsInHiddenLayers, outputFeatures)epoch = 100000learningRate = 0.01losses = np.zeros((epoch, 1)) for i in range(epoch): losses[i, 0], cache, A2 = forwardPropagation(X, Y, parameters) gradients = backwardPropagation(X, Y, cache) parameters = updateParameters(parameters, gradients, learningRate) # Evaluating the performanceplt.figure()plt.plot(losses)plt.xlabel(\"EPOCHS\")plt.ylabel(\"Loss value\")plt.show() # TestingX = np.array([[1, 1, 0, 0], [0, 1, 0, 1]]) # NAND inputcost, _, A2 = forwardPropagation(X, Y, parameters)prediction = (A2 > 0.5) * 1.0# print(A2)print(prediction)", "e": 31147, "s": 28099, "text": null }, { "code": null, "e": 31169, "s": 31149, "text": "[[ 1. 0. 1. 1.]]" }, { "code": null, "e": 31490, "s": 31171, "text": "Here, the model predicted output for each of the test inputs are exactly matched with the NAND logic gate conventional output () according to the truth table and the cost function is also continuously converging. Hence, it signifies that the Artificial Neural Network for the NAND logic gate is correctly implemented. " }, { "code": null, "e": 31499, "s": 31490, "text": "sweetyty" }, { "code": null, "e": 31514, "s": 31499, "text": "Neural Network" }, { "code": null, "e": 31531, "s": 31514, "text": "Machine Learning" }, { "code": null, "e": 31538, "s": 31531, "text": "Python" }, { "code": null, "e": 31555, "s": 31538, "text": "Machine Learning" }, { "code": null, "e": 31653, "s": 31555, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31676, "s": 31653, "text": "ML | Linear Regression" }, { "code": null, "e": 31699, "s": 31676, "text": "Reinforcement learning" }, { "code": null, "e": 31713, "s": 31699, "text": "Decision Tree" }, { "code": null, "e": 31753, "s": 31713, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 31786, "s": 31753, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 31814, "s": 31786, "text": "Read JSON file using Python" }, { "code": null, "e": 31864, "s": 31814, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 31886, "s": 31864, "text": "Python map() function" } ]