title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Python String isalnum() Method
12 Aug, 2021 Python String isalnum() method checks whether all the characters in a given string are alphanumeric or not. Alphanumeric means a character that is either a letter or a number. Syntax: string_name.isalnum() Parameter: isalnum() method takes no parameters Return: True: If all the characters are alphanumeric False: If one or more characters are not alphanumeric Python # Python program to demonstrate the use of# isalnum() method # here a,b and c are characters and 1,2 and 3# are numbersstring = "abc123"print(string.isalnum()) # here a,b and c are characters and 1,2 and 3 # are numbers but space is not a alphanumeric # characterstring = "abc 123" print(string.isalnum()) Output: True False AmiyaRanjanRout python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n12 Aug, 2021" }, { "code": null, "e": 229, "s": 53, "text": "Python String isalnum() method checks whether all the characters in a given string are alphanumeric or not. Alphanumeric means a character that is either a letter or a number." }, { "code": null, "e": 238, "s": 229, "text": "Syntax: " }, { "code": null, "e": 261, "s": 238, "text": "string_name.isalnum() " }, { "code": null, "e": 273, "s": 261, "text": "Parameter: " }, { "code": null, "e": 311, "s": 273, "text": "isalnum() method takes no parameters " }, { "code": null, "e": 320, "s": 311, "text": "Return: " }, { "code": null, "e": 366, "s": 320, "text": "True: If all the characters are alphanumeric " }, { "code": null, "e": 421, "s": 366, "text": "False: If one or more characters are not alphanumeric " }, { "code": null, "e": 428, "s": 421, "text": "Python" }, { "code": "# Python program to demonstrate the use of# isalnum() method # here a,b and c are characters and 1,2 and 3# are numbersstring = \"abc123\"print(string.isalnum()) # here a,b and c are characters and 1,2 and 3 # are numbers but space is not a alphanumeric # characterstring = \"abc 123\" print(string.isalnum())", "e": 738, "s": 428, "text": null }, { "code": null, "e": 747, "s": 738, "text": "Output: " }, { "code": null, "e": 758, "s": 747, "text": "True\nFalse" }, { "code": null, "e": 774, "s": 758, "text": "AmiyaRanjanRout" }, { "code": null, "e": 788, "s": 774, "text": "python-string" }, { "code": null, "e": 795, "s": 788, "text": "Python" } ]
C# Program to Print the Names that Contain ‘MAN’ Substring Using LINQ
06 Mar, 2022 LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives the ability to .NET languages to generate queries to retrieve data from the data source. It removes the mismatch between programming languages and databases and the syntax used to create a query is the same no matter which type of data source is used. In this article, we will learn how to print those names contains ‘MAN’ substring from the given array using LINQ. So to do our task we use Contains() method in the Where() method. Syntax: Where(employee => employee.Contains("MAN")) Here, the Contains() method is used to check whether the given string contains the “MAN” word in it or not, and then the Where() method filters the array accordingly. Example: Input : [("MANVITHA"),("SRIMANTH"),("RAVI"),("MANASA"),("MOUNIKA")("MANAS");] Output : [("MANVITHA"),("SRIMANTH"),("MANASA"),("MANAS")] Input : [("bobby"),("ramya"),("sairam");] Output : No Output Approach To print the list of names contains “MAN” as a substring follow the following steps: Create a list(i.e., XEmployee) that will holds the name of the employees.Add the names to the list.Now find the names whose contains “MAN” as a substring by using XEmployee.Where(employee => employee.Contains(“MAN”))Display the employee names. Create a list(i.e., XEmployee) that will holds the name of the employees. Add the names to the list. Now find the names whose contains “MAN” as a substring by using XEmployee.Where(employee => employee.Contains(“MAN”)) Display the employee names. Example: C# // C# program to display those names that// contain 'MAN' substringusing System;using System.Collections.Generic;using System.Linq; class GFG{ static void Main(string[] args){ // Define a list List<string> XEmployee = new List<string>(); // Add names into the list XEmployee.Add("MANVITHA"); XEmployee.Add("SRIMANTH"); XEmployee.Add("RAVI"); XEmployee.Add("MANASA"); XEmployee.Add("MOUNIKA"); XEmployee.Add("MANAS"); // Choose the employee's name that // contains MAN as a sub string IEnumerable<string> final = XEmployee.Where( employee => employee.Contains("MAN")); Console.WriteLine("Names that contain MAN substring:"); // Display employee names foreach (string stname in final) { Console.WriteLine(stname); }}} Names that contain MAN substring: MANVITHA SRIMANTH MANASA MANAS kalrap615 sumitgumber28 CSharp LINQ CSharp-programs Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Mar, 2022" }, { "code": null, "e": 547, "s": 28, "text": "LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives the ability to .NET languages to generate queries to retrieve data from the data source. It removes the mismatch between programming languages and databases and the syntax used to create a query is the same no matter which type of data source is used. In this article, we will learn how to print those names contains ‘MAN’ substring from the given array using LINQ. So to do our task we use Contains() method in the Where() method. " }, { "code": null, "e": 555, "s": 547, "text": "Syntax:" }, { "code": null, "e": 599, "s": 555, "text": "Where(employee => employee.Contains(\"MAN\"))" }, { "code": null, "e": 767, "s": 599, "text": "Here, the Contains() method is used to check whether the given string contains the “MAN” word in it or not, and then the Where() method filters the array accordingly. " }, { "code": null, "e": 776, "s": 767, "text": "Example:" }, { "code": null, "e": 976, "s": 776, "text": "Input : [(\"MANVITHA\"),(\"SRIMANTH\"),(\"RAVI\"),(\"MANASA\"),(\"MOUNIKA\")(\"MANAS\");]\nOutput : [(\"MANVITHA\"),(\"SRIMANTH\"),(\"MANASA\"),(\"MANAS\")]\n\nInput : [(\"bobby\"),(\"ramya\"),(\"sairam\");]\nOutput : No Output" }, { "code": null, "e": 985, "s": 976, "text": "Approach" }, { "code": null, "e": 1071, "s": 985, "text": "To print the list of names contains “MAN” as a substring follow the following steps:" }, { "code": null, "e": 1315, "s": 1071, "text": "Create a list(i.e., XEmployee) that will holds the name of the employees.Add the names to the list.Now find the names whose contains “MAN” as a substring by using XEmployee.Where(employee => employee.Contains(“MAN”))Display the employee names." }, { "code": null, "e": 1389, "s": 1315, "text": "Create a list(i.e., XEmployee) that will holds the name of the employees." }, { "code": null, "e": 1416, "s": 1389, "text": "Add the names to the list." }, { "code": null, "e": 1534, "s": 1416, "text": "Now find the names whose contains “MAN” as a substring by using XEmployee.Where(employee => employee.Contains(“MAN”))" }, { "code": null, "e": 1562, "s": 1534, "text": "Display the employee names." }, { "code": null, "e": 1571, "s": 1562, "text": "Example:" }, { "code": null, "e": 1574, "s": 1571, "text": "C#" }, { "code": "// C# program to display those names that// contain 'MAN' substringusing System;using System.Collections.Generic;using System.Linq; class GFG{ static void Main(string[] args){ // Define a list List<string> XEmployee = new List<string>(); // Add names into the list XEmployee.Add(\"MANVITHA\"); XEmployee.Add(\"SRIMANTH\"); XEmployee.Add(\"RAVI\"); XEmployee.Add(\"MANASA\"); XEmployee.Add(\"MOUNIKA\"); XEmployee.Add(\"MANAS\"); // Choose the employee's name that // contains MAN as a sub string IEnumerable<string> final = XEmployee.Where( employee => employee.Contains(\"MAN\")); Console.WriteLine(\"Names that contain MAN substring:\"); // Display employee names foreach (string stname in final) { Console.WriteLine(stname); }}}", "e": 2396, "s": 1574, "text": null }, { "code": null, "e": 2462, "s": 2396, "text": "Names that contain MAN substring:\nMANVITHA\nSRIMANTH\nMANASA\nMANAS\n" }, { "code": null, "e": 2472, "s": 2462, "text": "kalrap615" }, { "code": null, "e": 2486, "s": 2472, "text": "sumitgumber28" }, { "code": null, "e": 2498, "s": 2486, "text": "CSharp LINQ" }, { "code": null, "e": 2514, "s": 2498, "text": "CSharp-programs" }, { "code": null, "e": 2521, "s": 2514, "text": "Picked" }, { "code": null, "e": 2524, "s": 2521, "text": "C#" } ]
How to create two dimensional array in JavaScript?
26 Jul, 2021 The two-dimensional array is a collection of items which share a common name and they are organized as a matrix in the form of rows and columns. The two-dimensional array is an array of arrays, so we create an array of one-dimensional array objects.The following program shows how to create an 2D array : Example-1: Javascript <script> // Create one dimensional array var gfg = new Array(2); document.write("Creating 2D array <br>"); // Loop to create 2D array using 1D arrayfor (var i = 0; i < gfg.length; i++) { gfg[i] = new Array(2);} var h = 0; // Loop to initialize 2D array elements.for (var i = 0; i < 2; i++) { for (var j = 0; j < 2; j++) { gfg[i][j] = h++; }} // Loop to display the elements of 2D array. for (var i = 0; i < 2; i++) { for (var j = 0; j < 2; j++) { document.write(gfg[i][j] + " "); } document.write("<br>");} </script> Output: Creating 2D array 0 1 2 3 Example-2: javascript <script> // Create one dimensional arrayvar gfg = new Array(3); // Loop to create 2D array using 1D arraydocument.write("Creating 2D array <br>");for (var i = 0; i < gfg.length; i++) { gfg[i] = [];}var h = 0;var s = "GeeksforGeeks"; // Loop to initialize 2D array elements.for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { gfg[i][j] = s[h++]; }} // Loop to display the elements of 2D array.for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { document.write(gfg[i][j] + " "); } document.write("<br>");} </script> Output: Creating 2D array G e e k s f o r G JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. arorakashish0911 javascript-array Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Differences between Functional Components and Class Components in React Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Jul, 2021" }, { "code": null, "e": 372, "s": 54, "text": "The two-dimensional array is a collection of items which share a common name and they are organized as a matrix in the form of rows and columns. The two-dimensional array is an array of arrays, so we create an array of one-dimensional array objects.The following program shows how to create an 2D array : Example-1: " }, { "code": null, "e": 383, "s": 372, "text": "Javascript" }, { "code": "<script> // Create one dimensional array var gfg = new Array(2); document.write(\"Creating 2D array <br>\"); // Loop to create 2D array using 1D arrayfor (var i = 0; i < gfg.length; i++) { gfg[i] = new Array(2);} var h = 0; // Loop to initialize 2D array elements.for (var i = 0; i < 2; i++) { for (var j = 0; j < 2; j++) { gfg[i][j] = h++; }} // Loop to display the elements of 2D array. for (var i = 0; i < 2; i++) { for (var j = 0; j < 2; j++) { document.write(gfg[i][j] + \" \"); } document.write(\"<br>\");} </script> ", "e": 964, "s": 383, "text": null }, { "code": null, "e": 974, "s": 964, "text": "Output: " }, { "code": null, "e": 1002, "s": 974, "text": "Creating 2D array\n0 1 \n2 3 " }, { "code": null, "e": 1017, "s": 1004, "text": "Example-2: " }, { "code": null, "e": 1028, "s": 1017, "text": "javascript" }, { "code": "<script> // Create one dimensional arrayvar gfg = new Array(3); // Loop to create 2D array using 1D arraydocument.write(\"Creating 2D array <br>\");for (var i = 0; i < gfg.length; i++) { gfg[i] = [];}var h = 0;var s = \"GeeksforGeeks\"; // Loop to initialize 2D array elements.for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { gfg[i][j] = s[h++]; }} // Loop to display the elements of 2D array.for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { document.write(gfg[i][j] + \" \"); } document.write(\"<br>\");} </script> ", "e": 1622, "s": 1028, "text": null }, { "code": null, "e": 1632, "s": 1622, "text": "Output: " }, { "code": null, "e": 1671, "s": 1632, "text": "Creating 2D array\nG e e \nk s f \no r G " }, { "code": null, "e": 1894, "s": 1675, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 1911, "s": 1894, "text": "arorakashish0911" }, { "code": null, "e": 1928, "s": 1911, "text": "javascript-array" }, { "code": null, "e": 1935, "s": 1928, "text": "Picked" }, { "code": null, "e": 1946, "s": 1935, "text": "JavaScript" }, { "code": null, "e": 1963, "s": 1946, "text": "Web Technologies" }, { "code": null, "e": 2061, "s": 1963, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2122, "s": 2061, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2162, "s": 2122, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2204, "s": 2162, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2276, "s": 2204, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2317, "s": 2276, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2350, "s": 2317, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2412, "s": 2350, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2473, "s": 2412, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2516, "s": 2473, "text": "How to fetch data from an API in ReactJS ?" } ]
jQuery UI | Tooltip
06 Dec, 2019 The tooltip widget in jQuery UI is different from the traditional tooltip primarily by making it more themeable and making it much more customizable. Some of the customizations available are: Extra content like footnotes etc can also be displayed by retrieving it through Ajax. Customizing the fields for Warning and error fields. Customize the position, i.e. to center the tooltip above elements. By default, a fading animation is used to display the tooltip. Syntax: $( "#div_tooltip" ).tooltip({ }); Attribute Values: content: This attribute represents the content of a tooltip. By default, its value is a function returning the title attribute. disabled: This attribute when set to true disables the tooltip. By default its value is false. hide: This attribute represents the animation effect when hiding the tooltip. By default its value is true. items: This option indicates which items can show tooltips. By default its value is [title]. position: This attribute decides the position of the tooltip with respect to the associated target element. By default its value is function returning the title attribute. Possible values are: my, at, of, collision, using, within. show: This attribute represents how to animate the showing of tooltip. By default its value is true. tooltipClass: This attribute is a class which can be added to the tooltip widget for tooltips such as warning or errors. By default its value is null. track: This attribute when set to true, the tooltip follows/tracks the mouse. By default its value is false. The tooltip is addable which will override the parent string written with the title attribute. This gives us an advantage as we can change the tooltip by using a script, it is like the same element can show different strings of tooltips under different requirements. Let’s try that. Here we have defined the title as “Welcome to geeksforgeeks” which is overwritten inside the javascript code.Example 1: <html> <head> <link href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css' rel='stylesheet'></head> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <div id=div_tooltip title='Welcome to geeksforgeeks'> Bring your Mouse here </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"> </script> <script> $(document).ready(function() { $("#div_tooltip").tooltip({}); }) </script> </center></body> </html> Output: Overwriting the title in Tooltip: Another major advantage of the Tooltip widget in jQuery UI is that the title can be overwritten as specified while defining the element. This can be done by specifying the message inside the content option inside our JavaScript code. Example 2: <html> <head> <link href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css' rel='stylesheet'></head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <div id=div_tooltip title='Welcome to geeksforgeeks'> Bring your Mouse here </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"> </script> <script> $(document).ready(function() { $("#div_tooltip").tooltip({ content: "This is my content" }); }) </script> </center></body> </html> Output: Disabling Tooltip: This attribute when set to true disables the tooltip. By default its value is false. Example 3: <html> <head> <link href= 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css' rel='stylesheet'></head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <div id=div_tooltip title='Welcome to geeksforgeeks'> Bring your Mouse here </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"> </script> <script> $(document).ready(function() { $("#div_tooltip").tooltip({ disabled: true }); }) </script> </center></body> </html> Output: Items: The items attribute is used to set a different element message to be displayed as a tooltip. In the below example, one textbox is kept inside the div tag. By default, the message written inside the textbox is to be displayed as a tooltip, but by setting the items to the div tag, and display the message written inside the title attribute of div tag as tooltip. Example 4: <html> <head> <link href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css' rel='stylesheet'></head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <div id=div_tooltip title='I am inside a Div tag'> <input type=textbox name=my_text id=my_text title='I am the input box'> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"> </script> <script> $(document).ready(function() { $("#my_text").tooltip({ items: 'div' }); }) </script> </center></body> </html> Output: Position: This attribute is used to display the tooltip at any position relative to the main element.Possible values are. my: This is the tooltip box. at: The element for which the tooltip is displayed. Also note that: All horizontal alignment can take three positions: left or right or center. All vertical alignment can take three positions: top or bottom or center. Check this line position: { my: "left center", at: "right top" } Here the tooltip’s left side center position (my: “left center”) will be aligned to main elements right side top position (at: “right top”) Example 5: <html> <head> <link href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css' rel='stylesheet'></head> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <div align=center> <input type=textbox name=my_text id=my_text title=''> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"> </script> <script> $(document).ready(function() { $("#my_text").tooltip({ content: "I am the textbox", position: { my: "left center", at: "right top" } }); }) </script> </center></body> </html> Output: Show-Hide Tooltip: Show & hide are two independent options but we can learn them together. The show attribute is used to add effects to manage the appearance of the tooltip. This is the animation that is created while showing the tooltip. The hide attribute is used to add effects to manage the disappearance of the tooltip. This is the animation that is created while hiding the tooltip.For both show and hide options, use several effects in the below example.Example 6: <html> <head> <link href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css' rel='stylesheet'></head> <body> <center> <h1 style="color:green">Geeksforgeeks</h1> <input type=textbox name=my_text id=my_text title='I am the input box'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"> </script> <script> $(document).ready(function() { $("#my_text").tooltip({ show: { effect: "slide", duration: 400 }, hide: { effect: "pulsate", duration: 400 } }); }) </script> </center></body> </html> Output: jQuery-Misc JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Dec, 2019" }, { "code": null, "e": 220, "s": 28, "text": "The tooltip widget in jQuery UI is different from the traditional tooltip primarily by making it more themeable and making it much more customizable. Some of the customizations available are:" }, { "code": null, "e": 306, "s": 220, "text": "Extra content like footnotes etc can also be displayed by retrieving it through Ajax." }, { "code": null, "e": 359, "s": 306, "text": "Customizing the fields for Warning and error fields." }, { "code": null, "e": 426, "s": 359, "text": "Customize the position, i.e. to center the tooltip above elements." }, { "code": null, "e": 489, "s": 426, "text": "By default, a fading animation is used to display the tooltip." }, { "code": null, "e": 497, "s": 489, "text": "Syntax:" }, { "code": null, "e": 531, "s": 497, "text": "$( \"#div_tooltip\" ).tooltip({\n});" }, { "code": null, "e": 549, "s": 531, "text": "Attribute Values:" }, { "code": null, "e": 677, "s": 549, "text": "content: This attribute represents the content of a tooltip. By default, its value is a function returning the title attribute." }, { "code": null, "e": 772, "s": 677, "text": "disabled: This attribute when set to true disables the tooltip. By default its value is false." }, { "code": null, "e": 880, "s": 772, "text": "hide: This attribute represents the animation effect when hiding the tooltip. By default its value is true." }, { "code": null, "e": 973, "s": 880, "text": "items: This option indicates which items can show tooltips. By default its value is [title]." }, { "code": null, "e": 1204, "s": 973, "text": "position: This attribute decides the position of the tooltip with respect to the associated target element. By default its value is function returning the title attribute. Possible values are: my, at, of, collision, using, within." }, { "code": null, "e": 1305, "s": 1204, "text": "show: This attribute represents how to animate the showing of tooltip. By default its value is true." }, { "code": null, "e": 1456, "s": 1305, "text": "tooltipClass: This attribute is a class which can be added to the tooltip widget for tooltips such as warning or errors. By default its value is null." }, { "code": null, "e": 1565, "s": 1456, "text": "track: This attribute when set to true, the tooltip follows/tracks the mouse. By default its value is false." }, { "code": null, "e": 1968, "s": 1565, "text": "The tooltip is addable which will override the parent string written with the title attribute. This gives us an advantage as we can change the tooltip by using a script, it is like the same element can show different strings of tooltips under different requirements. Let’s try that. Here we have defined the title as “Welcome to geeksforgeeks” which is overwritten inside the javascript code.Example 1:" }, { "code": "<html> <head> <link href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css' rel='stylesheet'></head> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <div id=div_tooltip title='Welcome to geeksforgeeks'> Bring your Mouse here </div> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js\"> </script> <script src=\"https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js\"> </script> <script> $(document).ready(function() { $(\"#div_tooltip\").tooltip({}); }) </script> </center></body> </html>", "e": 2712, "s": 1968, "text": null }, { "code": null, "e": 2720, "s": 2712, "text": "Output:" }, { "code": null, "e": 2988, "s": 2720, "text": "Overwriting the title in Tooltip: Another major advantage of the Tooltip widget in jQuery UI is that the title can be overwritten as specified while defining the element. This can be done by specifying the message inside the content option inside our JavaScript code." }, { "code": null, "e": 2999, "s": 2988, "text": "Example 2:" }, { "code": "<html> <head> <link href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css' rel='stylesheet'></head> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <div id=div_tooltip title='Welcome to geeksforgeeks'> Bring your Mouse here </div> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js\"> </script> <script src=\"https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js\"> </script> <script> $(document).ready(function() { $(\"#div_tooltip\").tooltip({ content: \"This is my content\" }); }) </script> </center></body> </html>", "e": 3782, "s": 2999, "text": null }, { "code": null, "e": 3790, "s": 3782, "text": "Output:" }, { "code": null, "e": 3894, "s": 3790, "text": "Disabling Tooltip: This attribute when set to true disables the tooltip. By default its value is false." }, { "code": null, "e": 3905, "s": 3894, "text": "Example 3:" }, { "code": "<html> <head> <link href= 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css' rel='stylesheet'></head> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <div id=div_tooltip title='Welcome to geeksforgeeks'> Bring your Mouse here </div> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js\"> </script> <script src=\"https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js\"> </script> <script> $(document).ready(function() { $(\"#div_tooltip\").tooltip({ disabled: true }); }) </script> </center></body> </html>", "e": 4686, "s": 3905, "text": null }, { "code": null, "e": 4694, "s": 4686, "text": "Output:" }, { "code": null, "e": 5063, "s": 4694, "text": "Items: The items attribute is used to set a different element message to be displayed as a tooltip. In the below example, one textbox is kept inside the div tag. By default, the message written inside the textbox is to be displayed as a tooltip, but by setting the items to the div tag, and display the message written inside the title attribute of div tag as tooltip." }, { "code": null, "e": 5074, "s": 5063, "text": "Example 4:" }, { "code": "<html> <head> <link href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css' rel='stylesheet'></head> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <div id=div_tooltip title='I am inside a Div tag'> <input type=textbox name=my_text id=my_text title='I am the input box'> </div> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js\"> </script> <script src=\"https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js\"> </script> <script> $(document).ready(function() { $(\"#my_text\").tooltip({ items: 'div' }); }) </script> </center></body> </html>", "e": 5935, "s": 5074, "text": null }, { "code": null, "e": 5943, "s": 5935, "text": "Output:" }, { "code": null, "e": 6065, "s": 5943, "text": "Position: This attribute is used to display the tooltip at any position relative to the main element.Possible values are." }, { "code": null, "e": 6094, "s": 6065, "text": "my: This is the tooltip box." }, { "code": null, "e": 6146, "s": 6094, "text": "at: The element for which the tooltip is displayed." }, { "code": null, "e": 6162, "s": 6146, "text": "Also note that:" }, { "code": null, "e": 6238, "s": 6162, "text": "All horizontal alignment can take three positions: left or right or center." }, { "code": null, "e": 6312, "s": 6238, "text": "All vertical alignment can take three positions: top or bottom or center." }, { "code": null, "e": 6328, "s": 6312, "text": "Check this line" }, { "code": null, "e": 6378, "s": 6328, "text": "position: { my: \"left center\", at: \"right top\" } " }, { "code": null, "e": 6518, "s": 6378, "text": "Here the tooltip’s left side center position (my: “left center”) will be aligned to main elements right side top position (at: “right top”)" }, { "code": null, "e": 6529, "s": 6518, "text": "Example 5:" }, { "code": "<html> <head> <link href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css' rel='stylesheet'></head> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <div align=center> <input type=textbox name=my_text id=my_text title=''> </div> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js\"> </script> <script src=\"https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js\"> </script> <script> $(document).ready(function() { $(\"#my_text\").tooltip({ content: \"I am the textbox\", position: { my: \"left center\", at: \"right top\" } }); }) </script> </center></body> </html>", "e": 7491, "s": 6529, "text": null }, { "code": null, "e": 7499, "s": 7491, "text": "Output:" }, { "code": null, "e": 7971, "s": 7499, "text": "Show-Hide Tooltip: Show & hide are two independent options but we can learn them together. The show attribute is used to add effects to manage the appearance of the tooltip. This is the animation that is created while showing the tooltip. The hide attribute is used to add effects to manage the disappearance of the tooltip. This is the animation that is created while hiding the tooltip.For both show and hide options, use several effects in the below example.Example 6:" }, { "code": "<html> <head> <link href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css' rel='stylesheet'></head> <body> <center> <h1 style=\"color:green\">Geeksforgeeks</h1> <input type=textbox name=my_text id=my_text title='I am the input box'> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js\"> </script> <script src=\"https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js\"> </script> <script> $(document).ready(function() { $(\"#my_text\").tooltip({ show: { effect: \"slide\", duration: 400 }, hide: { effect: \"pulsate\", duration: 400 } }); }) </script> </center></body> </html>", "e": 8965, "s": 7971, "text": null }, { "code": null, "e": 8973, "s": 8965, "text": "Output:" }, { "code": null, "e": 8985, "s": 8973, "text": "jQuery-Misc" }, { "code": null, "e": 8992, "s": 8985, "text": "JQuery" }, { "code": null, "e": 9009, "s": 8992, "text": "Web Technologies" } ]
Types of Parsers in Compiler Design
07 Jun, 2022 The parser is that phase of the compiler which takes a token string as input and with the help of existing grammar, converts it into the corresponding Intermediate Representation(IR). The parser is also known as Syntax Analyzer. Classification of Parser The parser is mainly classified into two categories, i.e. Top-down Parser, and Bottom-up Parser. These are explained below: The top-down parser is the parser that generates parse for the given input string with the help of grammar productions by expanding the non-terminals i.e. it starts from the start symbol and ends on the terminals. It uses left most derivation. Further Top-down parser is classified into 2 types: A recursive descent parser, and Non-recursive descent parser. Recursive descent parser is also known as the Brute force parser or the backtracking parser. It basically generates the parse tree by using brute force and backtracking. Non-recursive descent parser is also known as LL(1) parser or predictive parser or without backtracking parser or dynamic parser. It uses a parsing table to generate the parse tree instead of backtracking. Recursive descent parser is also known as the Brute force parser or the backtracking parser. It basically generates the parse tree by using brute force and backtracking. Non-recursive descent parser is also known as LL(1) parser or predictive parser or without backtracking parser or dynamic parser. It uses a parsing table to generate the parse tree instead of backtracking. Bottom-up Parser is the parser that generates the parse tree for the given input string with the help of grammar productions by compressing the non-terminals i.e. it starts from non-terminals and ends on the start symbol. It uses the reverse of the rightmost derivation. Further Bottom-up parser is classified into two types: LR parser, and Operator precedence parser. LR parser is the bottom-up parser that generates the parse tree for the given string by using unambiguous grammar. It follows the reverse of the rightmost derivation. LR parser is of four types: (a)LR(0) (b)SLR(1) (c)LALR(1) (d)CLR(1) Operator precedence parser generates the parse tree from given grammar and string but the only condition is two consecutive non-terminals and epsilon never appears on the right-hand side of any production. The operator precedence parsing techniques can be applied to Operator grammars. Operator grammar: A grammar is said to be operator grammar if there does not exist any production rule on the right-hand side. 1. as ε(Epsilon) 2. Two non-terminals appear consecutively, that is, without any terminal between them operator precedence parsing is not a simple technique to apply to most the language constructs, but it evolves into an easy technique to implement where a suitable grammar may be produced. jacobbridges3283 amandeepkaur93031 nwekechiemezie65 akash1908232 Compiler Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Issues in the design of a code generator Peephole Optimization in Compiler Design Directed Acyclic graph in Compiler Design (with examples) Type Checking in Compiler Design S - attributed and L - attributed SDTs in Syntax directed translation Layers of OSI Model ACID Properties in DBMS Types of Operating Systems TCP/IP Model Page Replacement Algorithms in Operating Systems
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jun, 2022" }, { "code": null, "e": 284, "s": 54, "text": "The parser is that phase of the compiler which takes a token string as input and with the help of existing grammar, converts it into the corresponding Intermediate Representation(IR). The parser is also known as Syntax Analyzer. " }, { "code": null, "e": 309, "s": 284, "text": "Classification of Parser" }, { "code": null, "e": 434, "s": 309, "text": "The parser is mainly classified into two categories, i.e. Top-down Parser, and Bottom-up Parser. These are explained below: " }, { "code": null, "e": 793, "s": 434, "text": "The top-down parser is the parser that generates parse for the given input string with the help of grammar productions by expanding the non-terminals i.e. it starts from the start symbol and ends on the terminals. It uses left most derivation. Further Top-down parser is classified into 2 types: A recursive descent parser, and Non-recursive descent parser. " }, { "code": null, "e": 1169, "s": 793, "text": "Recursive descent parser is also known as the Brute force parser or the backtracking parser. It basically generates the parse tree by using brute force and backtracking. Non-recursive descent parser is also known as LL(1) parser or predictive parser or without backtracking parser or dynamic parser. It uses a parsing table to generate the parse tree instead of backtracking." }, { "code": null, "e": 1340, "s": 1169, "text": "Recursive descent parser is also known as the Brute force parser or the backtracking parser. It basically generates the parse tree by using brute force and backtracking. " }, { "code": null, "e": 1546, "s": 1340, "text": "Non-recursive descent parser is also known as LL(1) parser or predictive parser or without backtracking parser or dynamic parser. It uses a parsing table to generate the parse tree instead of backtracking." }, { "code": null, "e": 1916, "s": 1546, "text": "Bottom-up Parser is the parser that generates the parse tree for the given input string with the help of grammar productions by compressing the non-terminals i.e. it starts from non-terminals and ends on the start symbol. It uses the reverse of the rightmost derivation. Further Bottom-up parser is classified into two types: LR parser, and Operator precedence parser. " }, { "code": null, "e": 2112, "s": 1916, "text": "LR parser is the bottom-up parser that generates the parse tree for the given string by using unambiguous grammar. It follows the reverse of the rightmost derivation. LR parser is of four types: " }, { "code": null, "e": 2153, "s": 2112, "text": "(a)LR(0)\n(b)SLR(1)\n(c)LALR(1)\n(d)CLR(1) " }, { "code": null, "e": 2360, "s": 2153, "text": "Operator precedence parser generates the parse tree from given grammar and string but the only condition is two consecutive non-terminals and epsilon never appears on the right-hand side of any production. " }, { "code": null, "e": 2440, "s": 2360, "text": "The operator precedence parsing techniques can be applied to Operator grammars." }, { "code": null, "e": 2895, "s": 2440, "text": "Operator grammar: A grammar is said to be operator grammar if there does not exist any production rule on the right-hand side. 1. as ε(Epsilon) 2. Two non-terminals appear consecutively, that is, without any terminal between them operator precedence parsing is not a simple technique to apply to most the language constructs, but it evolves into an easy technique to implement where a suitable grammar may be produced." }, { "code": null, "e": 2912, "s": 2895, "text": "jacobbridges3283" }, { "code": null, "e": 2930, "s": 2912, "text": "amandeepkaur93031" }, { "code": null, "e": 2947, "s": 2930, "text": "nwekechiemezie65" }, { "code": null, "e": 2960, "s": 2947, "text": "akash1908232" }, { "code": null, "e": 2976, "s": 2960, "text": "Compiler Design" }, { "code": null, "e": 2984, "s": 2976, "text": "GATE CS" }, { "code": null, "e": 3082, "s": 2984, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3123, "s": 3082, "text": "Issues in the design of a code generator" }, { "code": null, "e": 3164, "s": 3123, "text": "Peephole Optimization in Compiler Design" }, { "code": null, "e": 3222, "s": 3164, "text": "Directed Acyclic graph in Compiler Design (with examples)" }, { "code": null, "e": 3255, "s": 3222, "text": "Type Checking in Compiler Design" }, { "code": null, "e": 3325, "s": 3255, "text": "S - attributed and L - attributed SDTs in Syntax directed translation" }, { "code": null, "e": 3345, "s": 3325, "text": "Layers of OSI Model" }, { "code": null, "e": 3369, "s": 3345, "text": "ACID Properties in DBMS" }, { "code": null, "e": 3396, "s": 3369, "text": "Types of Operating Systems" }, { "code": null, "e": 3409, "s": 3396, "text": "TCP/IP Model" } ]
How to Install and Use Hydra in Linux?
06 Oct, 2021 Weak passwords are still a big problem in security, nowadays guessing passwords and cracking algorithms is becoming easy and brute-forcing is a major kind of attack in the boom. A general rule for making a strong password is using a combination that is long(more than 8 letters) with capitals, symbols, and numeric’s. To crack passwords a great tool to brute force is a hydra. It is a parallelized login cracker or password cracker. It was faster and flexible where adding modules is easy. Hydra usually comes preinstalled in the Kali Linux system but if in any case it is not installed or you are using any other distribution you can follow the steps in this article. sudo apt-get install hydra-gtk This command will directly install hydra from repositories, this will install the command-line version of hydra with front end GUI on your Linux system. The major drawback of using this command is that you will not be able to get the latest version, so in case you used this command or hydra was preinstalled on your system you can remove it using: sudo apt-get purge hydra-gtk && sudo apt-get autoremove && sudo apt-get autoclean Before doing anything first we need to get our system up to date by using command: sudo apt-get update && sudo apt-get upgrade && sudo apt-get dist-upgrade Once our system is up to date we need to install some essential things required for hydra. sudo apt-get -y install build-essential sudo apt-get install git When we are using ubuntu/debian based distribution there are some supplementary libraries needed for some optional modules, these can be installed using this command (note than some may not be available for your distribution sudo apt-get install libssl-dev libssh-dev libidn11-dev libpcre3-dev \ libgtk2.0-dev libmysqlclient-dev libpq-dev libsvn-dev \ firebird-dev libncp-dev It will enable all the optional modules and features with the exception of Oracle, SAP R/3, NCP, and the apple filling protocol. Once it is done now we need to clone the repository from git hub, use the command: git clone https://github.com/vanhauser-thc/thc-hydra.git Locate to the cloned folder directory in your terminal. cd thc-hydra After locating to the directory we need to configure it ./configure Now if you see this kind of screen with a message “make”, follow the instructions. Use root privileges for “make install”. Go to your home directory and use “hydra -help” ensure hydra is installed properly and working well. how-to-install How To Installation Guide Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Oct, 2021" }, { "code": null, "e": 370, "s": 52, "text": "Weak passwords are still a big problem in security, nowadays guessing passwords and cracking algorithms is becoming easy and brute-forcing is a major kind of attack in the boom. A general rule for making a strong password is using a combination that is long(more than 8 letters) with capitals, symbols, and numeric’s." }, { "code": null, "e": 721, "s": 370, "text": "To crack passwords a great tool to brute force is a hydra. It is a parallelized login cracker or password cracker. It was faster and flexible where adding modules is easy. Hydra usually comes preinstalled in the Kali Linux system but if in any case it is not installed or you are using any other distribution you can follow the steps in this article." }, { "code": null, "e": 752, "s": 721, "text": "sudo apt-get install hydra-gtk" }, { "code": null, "e": 1101, "s": 752, "text": "This command will directly install hydra from repositories, this will install the command-line version of hydra with front end GUI on your Linux system. The major drawback of using this command is that you will not be able to get the latest version, so in case you used this command or hydra was preinstalled on your system you can remove it using:" }, { "code": null, "e": 1183, "s": 1101, "text": "sudo apt-get purge hydra-gtk && sudo apt-get autoremove && sudo apt-get autoclean" }, { "code": null, "e": 1266, "s": 1183, "text": "Before doing anything first we need to get our system up to date by using command:" }, { "code": null, "e": 1339, "s": 1266, "text": "sudo apt-get update && sudo apt-get upgrade && sudo apt-get dist-upgrade" }, { "code": null, "e": 1430, "s": 1339, "text": "Once our system is up to date we need to install some essential things required for hydra." }, { "code": null, "e": 1496, "s": 1430, "text": "sudo apt-get -y install build-essential\nsudo apt-get install git\n" }, { "code": null, "e": 1721, "s": 1496, "text": "When we are using ubuntu/debian based distribution there are some supplementary libraries needed for some optional modules, these can be installed using this command (note than some may not be available for your distribution" }, { "code": null, "e": 1872, "s": 1721, "text": "sudo apt-get install libssl-dev libssh-dev libidn11-dev libpcre3-dev \\ libgtk2.0-dev libmysqlclient-dev libpq-dev libsvn-dev \\ firebird-dev libncp-dev" }, { "code": null, "e": 2084, "s": 1872, "text": "It will enable all the optional modules and features with the exception of Oracle, SAP R/3, NCP, and the apple filling protocol. Once it is done now we need to clone the repository from git hub, use the command:" }, { "code": null, "e": 2141, "s": 2084, "text": "git clone https://github.com/vanhauser-thc/thc-hydra.git" }, { "code": null, "e": 2197, "s": 2141, "text": "Locate to the cloned folder directory in your terminal." }, { "code": null, "e": 2210, "s": 2197, "text": "cd thc-hydra" }, { "code": null, "e": 2266, "s": 2210, "text": "After locating to the directory we need to configure it" }, { "code": null, "e": 2278, "s": 2266, "text": "./configure" }, { "code": null, "e": 2401, "s": 2278, "text": "Now if you see this kind of screen with a message “make”, follow the instructions. Use root privileges for “make install”." }, { "code": null, "e": 2502, "s": 2401, "text": "Go to your home directory and use “hydra -help” ensure hydra is installed properly and working well." }, { "code": null, "e": 2517, "s": 2502, "text": "how-to-install" }, { "code": null, "e": 2524, "s": 2517, "text": "How To" }, { "code": null, "e": 2543, "s": 2524, "text": "Installation Guide" }, { "code": null, "e": 2554, "s": 2543, "text": "Linux-Unix" } ]
Robotic Process Automation(RPA) – Google Form Automation using UIPath
14 Oct, 2020 In this article, we are going to learn how we can automate filling the Google Forms using Uipath Studio. This project is a basic application of Robotic Process Automation (RPA). The user just needs to provide the Excel file that holds the data to be entered in the form and that’s it, rest of the work will be done by the bot that we are going to create using the steps mentioned below: Note: The Excel file should store data as per the requirement of the Google Form. Step 1: Create a new process in Uipath Studio by clicking on the Process Tab. Step 2: Set the name of the process, give a brief description and click on Create. The Uipath studio will automatically load and add all the dependencies of the project. The following screen will be opened. Step 3: Now in the activities panel search for Sequence activity. Drag and drop it in the designer window. Step 4: Now in the activities panel search for Select File activity. Add it to the sequence. This activity will open a select file dialog box for the user to select the file. Step 5: Now click on the Variables tab to create a variable of string type that will store the path of the Excel file selected by the user. In the properties panel of Select File activity add the variable in the Output area to the Selected File field. Step 6: In the activities panel search for Excel Application Scope activity. Add it to the sequence. This activity helps you access and manipulate Excel files. Now pass the variable that stores the file path to this activity. Step 7: Now in the activities panel search for Read Range activity. You will notice that there are two Read Range activities. Select the one under App Integration. Add it to the Do area of Excel application scope. Specify the SheetName and Range for reading the data. Now in the Properties Panel of the Read Range activity, in the Output area, select the DataTable tab and press Ctrl+K. This will create a variable of the required type, in this case, DataTable type. Specify the name and press Enter. Step 8: Now in the activities panel search for Open Browser activity and drag and drop it below Excel Application Scope. Now in the URL field pass the URL of the Google Form that you want to automate. Step 9: Now search for For Each Row activity in the activities panel and add it to the Do of Open Browser activity. Now in the Properties Panel of the For Each Row activity specify the DataTable variable created earlier in Read Range activity. Step 10: Open the Google form in the Internet Explorer in the background. Now search for Type Into activity in the activity panel and add it to the Body of For Each Row activity. Now click on Indicate Screen and select the text field of the form where you want to enter the text. Provide the text in the given format. row("columnname").tostring Replace the column name with the column name in your Excel sheet. Step 11: Repeat Step-10 for all the column headers in your Excel sheet. Step 12: Now in the activities panel search Click activity and drop it below the last Type Into activity. Click on Indicate Screen and indicate the Submit button of the form. Step 13: Fill the Google Form with random values once so that you are redirected to submit another response page. Now add another Click activity and indicate the submit another response button. Step 14: Save the process using the Save button in the design panel and then click on Run. Your bot is ready for automating the Google Forms. The below video displays the working of Bot. Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Oct, 2020" }, { "code": null, "e": 415, "s": 28, "text": "In this article, we are going to learn how we can automate filling the Google Forms using Uipath Studio. This project is a basic application of Robotic Process Automation (RPA). The user just needs to provide the Excel file that holds the data to be entered in the form and that’s it, rest of the work will be done by the bot that we are going to create using the steps mentioned below:" }, { "code": null, "e": 497, "s": 415, "text": "Note: The Excel file should store data as per the requirement of the Google Form." }, { "code": null, "e": 575, "s": 497, "text": "Step 1: Create a new process in Uipath Studio by clicking on the Process Tab." }, { "code": null, "e": 745, "s": 575, "text": "Step 2: Set the name of the process, give a brief description and click on Create. The Uipath studio will automatically load and add all the dependencies of the project." }, { "code": null, "e": 782, "s": 745, "text": "The following screen will be opened." }, { "code": null, "e": 889, "s": 782, "text": "Step 3: Now in the activities panel search for Sequence activity. Drag and drop it in the designer window." }, { "code": null, "e": 1064, "s": 889, "text": "Step 4: Now in the activities panel search for Select File activity. Add it to the sequence. This activity will open a select file dialog box for the user to select the file." }, { "code": null, "e": 1316, "s": 1064, "text": "Step 5: Now click on the Variables tab to create a variable of string type that will store the path of the Excel file selected by the user. In the properties panel of Select File activity add the variable in the Output area to the Selected File field." }, { "code": null, "e": 1476, "s": 1316, "text": "Step 6: In the activities panel search for Excel Application Scope activity. Add it to the sequence. This activity helps you access and manipulate Excel files." }, { "code": null, "e": 1542, "s": 1476, "text": "Now pass the variable that stores the file path to this activity." }, { "code": null, "e": 1810, "s": 1542, "text": "Step 7: Now in the activities panel search for Read Range activity. You will notice that there are two Read Range activities. Select the one under App Integration. Add it to the Do area of Excel application scope. Specify the SheetName and Range for reading the data." }, { "code": null, "e": 2045, "s": 1810, "text": "Now in the Properties Panel of the Read Range activity, in the Output area, select the DataTable tab and press Ctrl+K. This will create a variable of the required type, in this case, DataTable type. Specify the name and press Enter. " }, { "code": null, "e": 2246, "s": 2045, "text": "Step 8: Now in the activities panel search for Open Browser activity and drag and drop it below Excel Application Scope. Now in the URL field pass the URL of the Google Form that you want to automate." }, { "code": null, "e": 2363, "s": 2246, "text": "Step 9: Now search for For Each Row activity in the activities panel and add it to the Do of Open Browser activity. " }, { "code": null, "e": 2491, "s": 2363, "text": "Now in the Properties Panel of the For Each Row activity specify the DataTable variable created earlier in Read Range activity." }, { "code": null, "e": 2810, "s": 2491, "text": "Step 10: Open the Google form in the Internet Explorer in the background. Now search for Type Into activity in the activity panel and add it to the Body of For Each Row activity. Now click on Indicate Screen and select the text field of the form where you want to enter the text. Provide the text in the given format. " }, { "code": null, "e": 2838, "s": 2810, "text": "row(\"columnname\").tostring\n" }, { "code": null, "e": 2904, "s": 2838, "text": "Replace the column name with the column name in your Excel sheet." }, { "code": null, "e": 2976, "s": 2904, "text": "Step 11: Repeat Step-10 for all the column headers in your Excel sheet." }, { "code": null, "e": 3152, "s": 2976, "text": "Step 12: Now in the activities panel search Click activity and drop it below the last Type Into activity. Click on Indicate Screen and indicate the Submit button of the form. " }, { "code": null, "e": 3348, "s": 3152, "text": "Step 13: Fill the Google Form with random values once so that you are redirected to submit another response page. Now add another Click activity and indicate the submit another response button. " }, { "code": null, "e": 3536, "s": 3348, "text": " Step 14: Save the process using the Save button in the design panel and then click on Run. Your bot is ready for automating the Google Forms. The below video displays the working of Bot." }, { "code": null, "e": 3562, "s": 3536, "text": "Advanced Computer Subject" } ]
Connecting to MySQL database from the command line?
To connect MySQL from the command line, firstly open command prompt. You can do this with the help of shortcut key “Windows + R”. On clicking, a panel will open and you need to type CMD and need to press OK button as shown below − After pressing the OK button, you will get command line window. Reach the MySQL Server “bin” directory as shown in the following screenshot − Now you have reached the bin directory. Type the following statement in order to connect with MySQL. mysql -u yourUserName -p Apply the above statement to connect with MySQL. The snapshot is as follows with username “Manish” and password −
[ { "code": null, "e": 1293, "s": 1062, "text": "To connect MySQL from the command line, firstly open command prompt. You can do this with the help of shortcut key “Windows + R”. On clicking, a panel will open and you need to type CMD and need to press OK button as shown below −" }, { "code": null, "e": 1357, "s": 1293, "text": "After pressing the OK button, you will get command line window." }, { "code": null, "e": 1435, "s": 1357, "text": "Reach the MySQL Server “bin” directory as shown in the following screenshot −" }, { "code": null, "e": 1536, "s": 1435, "text": "Now you have reached the bin directory. Type the following statement in order to connect with MySQL." }, { "code": null, "e": 1561, "s": 1536, "text": "mysql -u yourUserName -p" }, { "code": null, "e": 1675, "s": 1561, "text": "Apply the above statement to connect with MySQL. The snapshot is as follows with username “Manish” and password −" } ]
SQL Tryit Editor v1.6
SELECT * FROM Customers WHERE City LIKE '[!bsp]%'; ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, Opera, and Edge(79). If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 24, "s": 0, "text": "SELECT * FROM Customers" }, { "code": null, "e": 51, "s": 24, "text": "WHERE City LIKE '[!bsp]%';" }, { "code": null, "e": 53, "s": 51, "text": "​" }, { "code": null, "e": 116, "s": 53, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 176, "s": 116, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 244, "s": 176, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 282, "s": 244, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 367, "s": 282, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 541, "s": 367, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 592, "s": 541, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 660, "s": 592, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 831, "s": 660, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 931, "s": 831, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 991, "s": 931, "text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)." } ]
Finetune a Facial Recognition Classifier to Recognize your Face using PyTorch | by Mike Chaykowsky | Towards Data Science
This is part of a series I am writing on tricking facial recognition systems using adversarial attacks with GANs. However, before we trick a facial recognition classifier we need to build one to trick. I personally want to build one that can recognize my own face. Instead of training a neural network from scratch I can start with a pre-trained network and then finetune it to recognize my face. Finetuning is greatly beneficial as we can start with the model weights already trained on a large-scale face database and then update some of them to reflect the new tasks we want it to perform. These weights already understand how to recognize faces, but the only difference is it does not know my face. So to have this pretrained model learn my own face is much easier to train as the model weights already contain much of the needed information to perform the task. project│ README.md│ AGN.ipynb │└───data│ │ files_sample.csv│ └───eyeglasses│ ││ └───test_me│ └───train| └───Adrien_Brody| ...| └───Michael_Chaykowsky| ...| └───Venus_Williams│ └───val| └───Adrien_Brody| ...| └───Michael_Chaykowsky| ...| └───Venus_Williams│ └───models│ │ inception_resnet_v1.py│ │ mtcnn.py│ └───utils models directory is from the PyTorch facenet implementation based on the Tensorflow implementation linked above. └───models│ │ inception_resnet_v1.py│ │ mtcnn.py│ └───utils This inception_resnet_v1.py file is where we will pull in the pretrained model. The Inception Resnet V1 model is pretrained on VGGFace2 where VGGFace2 is a large-scale face recognition dataset developed from Google image searches and “have large variations in pose, age, illumination, ethnicity and profession.” Each layer’s weights in the model have an attribute called requires_grad that can be set to True or False . When you run loss.backward() in the training loop these weights are updated and this is what contains all of the information needed to perform the predictions. When finetuning the network we freeze all of the layers up through the last convolutional block by setting the requires_grad attributes to False and then only update the weights on the remaining layers — which intuitively you can imagine the earlier layers as containing the base-level information needed to recognize face attributes and base level characteristics so we keep all of that performance while updating the final layers to include another face (mine). All train directories have 11 or 12 images of each individual and all val directories have 4 or 5 images of each individual. Michael_Chaykowsky is a directory of my face where I used various poses, lighting, and angles. To collect these images I took videos with a standard iPhone in various spaces and then transformed these videos to image and used MTCNN on each to perform face-alignment and cropping to appropriate size (160 x 160 pixels). from torch import nn, optim, as_tensorfrom torch.utils.data import Dataset, DataLoaderimport torch.nn.functional as Ffrom torch.optim import lr_schedulerfrom torch.nn.init import *from torchvision import transforms, utils, datasets, modelsfrom models.inception_resnet_v1 import InceptionResnetV1import cv2from PIL import Imagefrom pdb import set_traceimport timeimport copyfrom pathlib import Pathimport osimport sysimport matplotlib.pyplot as pltimport matplotlib.animation as animationfrom skimage import io, transformfrom tqdm import trange, tqdmimport csvimport globimport dlibimport pandas as pdimport numpy as np from IPython.display import VideoVideo("data/IMG_2411.MOV", width=200, height=350) Capture the frames of the video as .png files and rotate/crop/align. vidcap = cv2.VideoCapture('IMG_2411.MOV')success,image = vidcap.read()count = 0success = Truewhile success: cv2.imwrite(f"./Michael_Chaykowsky/Michael_Chaykowsky_{ format(count, '04d') }.png", image) success,image = vidcap.read() print('Read a new frame: ', success) count += 1 The images come in rotated so I use imagemagick to make them right-side up. Make sure to brew install imagemagick first. I think there’s another way to install the library but if I recall it was a nightmare — so definitely suggest brew install . %%!for szFile in ./Michael_Chaykowsky/*.pngdo magick mogrify -rotate 90 ./Michael_Chaykowsky/"$(basename "$szFile")" ; done ! pip install autocrop Autocrop has a nice feature where they do some resizing of face images and you can specify the face percentage. You can forgo this if you are doing the full MTCNN method (prefferred), but if not you can do this which is quite a bit easier. ! autocrop -i ./me_orig/Michael_Chaykowsky -o ./me/Michael_Chaykowsky160 -w 720 -H 720 --facePercent 80 ! pip install tensorflow==1.13.0rc1 ! pip install scipy==1.1.0 Now using the align_dataset_mtcnn.py script from David Sandberg’s Tensorflow implementation of facenet we can apply this to the directory of face images. %%!for N in {1..4}; do \python ~/Adversarial/data/align/align_dataset_mtcnn.py \ # tensorflow script~/Adversarial/data/me/ \ # current directory~/Adversarial/data/me160/ \ # new directory--image_size 160 \--margin 32 \--random_order \--gpu_memory_fraction 0.25 \& done Now you have a directory with all of your faces aligned and cropped appropriately for modeling. When we load in the data we will perform some random transforms to the images to improve training. Different transforms can be attempted and you may try various ones, like Here I use random horizontal flip. All of these transforms make the model more generalizable and prevent overfitting. data_transforms = { 'train': transforms.Compose([ transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]), 'val': transforms.Compose([ transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]),}data_dir = 'data/test_me'image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x]) for x in ['train', 'val']}dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=8, shuffle=True) for x in ['train', 'val']}dataset_sizes = {x: len(image_datasets[x]) for x in ['train','val']}class_names = image_datasets['train'].classesclass_names Out[1]: ['Adrien_Brody','Alejandro_Toledo','Angelina_Jolie','Arnold_Schwarzenegger','Carlos_Moya','Charles_Moose','James_Blake','Jennifer_Lopez','Michael_Chaykowsky','Roh_Moo-hyun','Venus_Williams'] def imshow(inp, title=None): """Imshow for Tensor.""" inp = inp.numpy().transpose((1, 2, 0)) mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) inp = std * inp + mean inp = np.clip(inp, 0, 1) plt.imshow(inp) if title is not None: plt.title(title) plt.pause(0.001) # pause a bit so that plots are updated# Get a batch of training datainputs, classes = next(iter(dataloaders['train']))# Make a grid from batchout = utils.make_grid(inputs)imshow(out, title=[class_names[x] for x in classes]) from models.inception_resnet_v1 import InceptionResnetV1print('Running on device: {}'.format(device))model_ft = InceptionResnetV1(pretrained='vggface2', classify=False, num_classes = len(class_names)) Recall earlier I mentioned that we will freeze up through the last conv block. To find where that is we can iterate through this list using -n, -n-1, ... until we find the block. list(model_ft.children())[-6:] Out[2]: [Block8( (branch0): BasicConv2d( (conv): Conv2d(1792, 192, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn): BatchNorm2d(192, eps=0.001, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU() ) (branch1): Sequential( (0): BasicConv2d( (conv): Conv2d(1792, 192, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn): BatchNorm2d(192, eps=0.001, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU() ) (1): BasicConv2d( (conv): Conv2d(192, 192, kernel_size=(1, 3), stride=(1, 1), padding=(0, 1), bias=False) (bn): BatchNorm2d(192, eps=0.001, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU() ) (2): BasicConv2d( (conv): Conv2d(192, 192, kernel_size=(3, 1), stride=(1, 1), padding=(1, 0), bias=False) (bn): BatchNorm2d(192, eps=0.001, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU() ) ) (conv2d): Conv2d(384, 1792, kernel_size=(1, 1), stride=(1, 1)) ), AdaptiveAvgPool2d(output_size=1), Linear(in_features=1792, out_features=512, bias=False), BatchNorm1d(512, eps=0.001, momentum=0.1, affine=True, track_running_stats=True), Linear(in_features=512, out_features=8631, bias=True), Softmax(dim=1)] Remove the last layers after conv block and place in layer_list . layer_list = list(model_ft.children())[-5:] # all final layerslayer_list Out[3]: [AdaptiveAvgPool2d(output_size=1), Linear(in_features=1792, out_features=512, bias=False), BatchNorm1d(512, eps=0.001, momentum=0.1, affine=True, track_running_stats=True), Linear(in_features=512, out_features=8631, bias=True), Softmax(dim=1)] Put all beginning layers in an nn.Sequential . model_ft is now a torch model but without the final linear, pooling, batchnorm, and sigmoid layers. model_ft = nn.Sequential(*list(model_ft.children())[:-5]) If training just final layers: for param in model_ft.parameters(): param.requires_grad = False Re-attach the last 5 layers which automatically sets requires_grad = True . This linear layer Linear(in_features=1792, out_features=512, bias=False) actually requires writing two custom classes which is not entirely obvious by looking at it, but if you look at the data input/output you can see that there is a Flatten and normalize class within the layer. Check resnet implementation for reason of reshaping in last_linear layer. class Flatten(nn.Module): def __init__(self): super(Flatten, self).__init__() def forward(self, x): x = x.view(x.size(0), -1) return xclass normalize(nn.Module): def __init__(self): super(normalize, self).__init__() def forward(self, x): x = F.normalize(x, p=2, dim=1) return x Then you can apply the final layers back to the new Sequential model. model_ft.avgpool_1a = nn.AdaptiveAvgPool2d(output_size=1)model_ft.last_linear = nn.Sequential( Flatten(), nn.Linear(in_features=1792, out_features=512, bias=False), normalize())model_ft.logits = nn.Linear(layer_list[3].in_features, len(class_names))model_ft.softmax = nn.Softmax(dim=1)model_ft = model_ft.to(device)criterion = nn.CrossEntropyLoss()# Observe that all parameters are being optimizedoptimizer_ft = optim.SGD(model_ft.parameters(), lr=1e-2, momentum=0.9)# Decay LR by a factor of *gamma* every *step_size* epochsexp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1) def train_model(model, criterion, optimizer, scheduler, num_epochs=25): since = time.time() FT_losses = [] best_model_wts = copy.deepcopy(model.state_dict()) best_acc = 0.0 for epoch in range(num_epochs): print('Epoch {}/{}'.format(epoch, num_epochs - 1)) print('-' * 10) # Each epoch has a training and validation phase for phase in ['train', 'val']: if phase == 'train': model.train() # Set model to training mode else: model.eval() # Set model to evaluate mode running_loss = 0.0 running_corrects = 0 # Iterate over data. for inputs, labels in dataloaders[phase]: inputs = inputs.to(device) labels = labels.to(device) # zero the parameter gradients optimizer.zero_grad() # forward # track history if only in train with torch.set_grad_enabled(phase == 'train'): outputs = model(inputs) _, preds = torch.max(outputs, 1) loss = criterion(outputs, labels) # backward + optimize only if in training phase if phase == 'train': loss.backward() optimizer.step() scheduler.step() FT_losses.append(loss.item()) # statistics running_loss += loss.item() * inputs.size(0) running_corrects += torch.sum(preds == labels.data) epoch_loss = running_loss / dataset_sizes[phase] epoch_acc = running_corrects.double() / dataset_sizes[phase] print('{} Loss: {:.4f} Acc: {:.4f}'.format( phase, epoch_loss, epoch_acc)) # deep copy the model if phase == 'val' and epoch_acc > best_acc: best_acc = epoch_acc best_model_wts = copy.deepcopy(model.state_dict()) time_elapsed = time.time() - since print('Training complete in {:.0f}m {:.0f}s'.format( time_elapsed // 60, time_elapsed % 60)) print('Best val Acc: {:4f}'.format(best_acc)) # load best model weights model.load_state_dict(best_model_wts) return model, FT_losses model_ft, FT_losses = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler, num_epochs=500)plt.figure(figsize=(10,5))plt.title("FRT Loss During Training")plt.plot(FT_losses, label="FT loss")plt.xlabel("iterations")plt.ylabel("Loss")plt.legend()plt.show() Keep an eye out for more from this series where I will describe how to trick this classifier using adversarial attacks with GANs.
[ { "code": null, "e": 286, "s": 172, "text": "This is part of a series I am writing on tricking facial recognition systems using adversarial attacks with GANs." }, { "code": null, "e": 1039, "s": 286, "text": "However, before we trick a facial recognition classifier we need to build one to trick. I personally want to build one that can recognize my own face. Instead of training a neural network from scratch I can start with a pre-trained network and then finetune it to recognize my face. Finetuning is greatly beneficial as we can start with the model weights already trained on a large-scale face database and then update some of them to reflect the new tasks we want it to perform. These weights already understand how to recognize faces, but the only difference is it does not know my face. So to have this pretrained model learn my own face is much easier to train as the model weights already contain much of the needed information to perform the task." }, { "code": null, "e": 1495, "s": 1039, "text": "project│ README.md│ AGN.ipynb │└───data│ │ files_sample.csv│ └───eyeglasses│ ││ └───test_me│ └───train| └───Adrien_Brody| ...| └───Michael_Chaykowsky| ...| └───Venus_Williams│ └───val| └───Adrien_Brody| ...| └───Michael_Chaykowsky| ...| └───Venus_Williams│ └───models│ │ inception_resnet_v1.py│ │ mtcnn.py│ └───utils" }, { "code": null, "e": 1608, "s": 1495, "text": "models directory is from the PyTorch facenet implementation based on the Tensorflow implementation linked above." }, { "code": null, "e": 1678, "s": 1608, "text": "└───models│ │ inception_resnet_v1.py│ │ mtcnn.py│ └───utils" }, { "code": null, "e": 1990, "s": 1678, "text": "This inception_resnet_v1.py file is where we will pull in the pretrained model. The Inception Resnet V1 model is pretrained on VGGFace2 where VGGFace2 is a large-scale face recognition dataset developed from Google image searches and “have large variations in pose, age, illumination, ethnicity and profession.”" }, { "code": null, "e": 2722, "s": 1990, "text": "Each layer’s weights in the model have an attribute called requires_grad that can be set to True or False . When you run loss.backward() in the training loop these weights are updated and this is what contains all of the information needed to perform the predictions. When finetuning the network we freeze all of the layers up through the last convolutional block by setting the requires_grad attributes to False and then only update the weights on the remaining layers — which intuitively you can imagine the earlier layers as containing the base-level information needed to recognize face attributes and base level characteristics so we keep all of that performance while updating the final layers to include another face (mine)." }, { "code": null, "e": 3166, "s": 2722, "text": "All train directories have 11 or 12 images of each individual and all val directories have 4 or 5 images of each individual. Michael_Chaykowsky is a directory of my face where I used various poses, lighting, and angles. To collect these images I took videos with a standard iPhone in various spaces and then transformed these videos to image and used MTCNN on each to perform face-alignment and cropping to appropriate size (160 x 160 pixels)." }, { "code": null, "e": 3785, "s": 3166, "text": "from torch import nn, optim, as_tensorfrom torch.utils.data import Dataset, DataLoaderimport torch.nn.functional as Ffrom torch.optim import lr_schedulerfrom torch.nn.init import *from torchvision import transforms, utils, datasets, modelsfrom models.inception_resnet_v1 import InceptionResnetV1import cv2from PIL import Imagefrom pdb import set_traceimport timeimport copyfrom pathlib import Pathimport osimport sysimport matplotlib.pyplot as pltimport matplotlib.animation as animationfrom skimage import io, transformfrom tqdm import trange, tqdmimport csvimport globimport dlibimport pandas as pdimport numpy as np" }, { "code": null, "e": 3868, "s": 3785, "text": "from IPython.display import VideoVideo(\"data/IMG_2411.MOV\", width=200, height=350)" }, { "code": null, "e": 3937, "s": 3868, "text": "Capture the frames of the video as .png files and rotate/crop/align." }, { "code": null, "e": 4244, "s": 3937, "text": "vidcap = cv2.VideoCapture('IMG_2411.MOV')success,image = vidcap.read()count = 0success = Truewhile success: cv2.imwrite(f\"./Michael_Chaykowsky/Michael_Chaykowsky_{ format(count, '04d') }.png\", image) success,image = vidcap.read() print('Read a new frame: ', success) count += 1" }, { "code": null, "e": 4490, "s": 4244, "text": "The images come in rotated so I use imagemagick to make them right-side up. Make sure to brew install imagemagick first. I think there’s another way to install the library but if I recall it was a nightmare — so definitely suggest brew install ." }, { "code": null, "e": 4618, "s": 4490, "text": "%%!for szFile in ./Michael_Chaykowsky/*.pngdo magick mogrify -rotate 90 ./Michael_Chaykowsky/\"$(basename \"$szFile\")\" ; done" }, { "code": null, "e": 4641, "s": 4618, "text": "! pip install autocrop" }, { "code": null, "e": 4881, "s": 4641, "text": "Autocrop has a nice feature where they do some resizing of face images and you can specify the face percentage. You can forgo this if you are doing the full MTCNN method (prefferred), but if not you can do this which is quite a bit easier." }, { "code": null, "e": 4985, "s": 4881, "text": "! autocrop -i ./me_orig/Michael_Chaykowsky -o ./me/Michael_Chaykowsky160 -w 720 -H 720 --facePercent 80" }, { "code": null, "e": 5021, "s": 4985, "text": "! pip install tensorflow==1.13.0rc1" }, { "code": null, "e": 5048, "s": 5021, "text": "! pip install scipy==1.1.0" }, { "code": null, "e": 5202, "s": 5048, "text": "Now using the align_dataset_mtcnn.py script from David Sandberg’s Tensorflow implementation of facenet we can apply this to the directory of face images." }, { "code": null, "e": 5471, "s": 5202, "text": "%%!for N in {1..4}; do \\python ~/Adversarial/data/align/align_dataset_mtcnn.py \\ # tensorflow script~/Adversarial/data/me/ \\ # current directory~/Adversarial/data/me160/ \\ # new directory--image_size 160 \\--margin 32 \\--random_order \\--gpu_memory_fraction 0.25 \\& done" }, { "code": null, "e": 5567, "s": 5471, "text": "Now you have a directory with all of your faces aligned and cropped appropriately for modeling." }, { "code": null, "e": 5739, "s": 5567, "text": "When we load in the data we will perform some random transforms to the images to improve training. Different transforms can be attempted and you may try various ones, like" }, { "code": null, "e": 5857, "s": 5739, "text": "Here I use random horizontal flip. All of these transforms make the model more generalizable and prevent overfitting." }, { "code": null, "e": 6750, "s": 5857, "text": "data_transforms = { 'train': transforms.Compose([ transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]), 'val': transforms.Compose([ transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]),}data_dir = 'data/test_me'image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x]) for x in ['train', 'val']}dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=8, shuffle=True) for x in ['train', 'val']}dataset_sizes = {x: len(image_datasets[x]) for x in ['train','val']}class_names = image_datasets['train'].classesclass_names" }, { "code": null, "e": 6758, "s": 6750, "text": "Out[1]:" }, { "code": null, "e": 6949, "s": 6758, "text": "['Adrien_Brody','Alejandro_Toledo','Angelina_Jolie','Arnold_Schwarzenegger','Carlos_Moya','Charles_Moose','James_Blake','Jennifer_Lopez','Michael_Chaykowsky','Roh_Moo-hyun','Venus_Williams']" }, { "code": null, "e": 7499, "s": 6949, "text": "def imshow(inp, title=None): \"\"\"Imshow for Tensor.\"\"\" inp = inp.numpy().transpose((1, 2, 0)) mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) inp = std * inp + mean inp = np.clip(inp, 0, 1) plt.imshow(inp) if title is not None: plt.title(title) plt.pause(0.001) # pause a bit so that plots are updated# Get a batch of training datainputs, classes = next(iter(dataloaders['train']))# Make a grid from batchout = utils.make_grid(inputs)imshow(out, title=[class_names[x] for x in classes])" }, { "code": null, "e": 7700, "s": 7499, "text": "from models.inception_resnet_v1 import InceptionResnetV1print('Running on device: {}'.format(device))model_ft = InceptionResnetV1(pretrained='vggface2', classify=False, num_classes = len(class_names))" }, { "code": null, "e": 7879, "s": 7700, "text": "Recall earlier I mentioned that we will freeze up through the last conv block. To find where that is we can iterate through this list using -n, -n-1, ... until we find the block." }, { "code": null, "e": 7910, "s": 7879, "text": "list(model_ft.children())[-6:]" }, { "code": null, "e": 7918, "s": 7910, "text": "Out[2]:" }, { "code": null, "e": 9177, "s": 7918, "text": "[Block8( (branch0): BasicConv2d( (conv): Conv2d(1792, 192, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn): BatchNorm2d(192, eps=0.001, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU() ) (branch1): Sequential( (0): BasicConv2d( (conv): Conv2d(1792, 192, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn): BatchNorm2d(192, eps=0.001, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU() ) (1): BasicConv2d( (conv): Conv2d(192, 192, kernel_size=(1, 3), stride=(1, 1), padding=(0, 1), bias=False) (bn): BatchNorm2d(192, eps=0.001, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU() ) (2): BasicConv2d( (conv): Conv2d(192, 192, kernel_size=(3, 1), stride=(1, 1), padding=(1, 0), bias=False) (bn): BatchNorm2d(192, eps=0.001, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU() ) ) (conv2d): Conv2d(384, 1792, kernel_size=(1, 1), stride=(1, 1)) ), AdaptiveAvgPool2d(output_size=1), Linear(in_features=1792, out_features=512, bias=False), BatchNorm1d(512, eps=0.001, momentum=0.1, affine=True, track_running_stats=True), Linear(in_features=512, out_features=8631, bias=True), Softmax(dim=1)]" }, { "code": null, "e": 9243, "s": 9177, "text": "Remove the last layers after conv block and place in layer_list ." }, { "code": null, "e": 9316, "s": 9243, "text": "layer_list = list(model_ft.children())[-5:] # all final layerslayer_list" }, { "code": null, "e": 9324, "s": 9316, "text": "Out[3]:" }, { "code": null, "e": 9568, "s": 9324, "text": "[AdaptiveAvgPool2d(output_size=1), Linear(in_features=1792, out_features=512, bias=False), BatchNorm1d(512, eps=0.001, momentum=0.1, affine=True, track_running_stats=True), Linear(in_features=512, out_features=8631, bias=True), Softmax(dim=1)]" }, { "code": null, "e": 9715, "s": 9568, "text": "Put all beginning layers in an nn.Sequential . model_ft is now a torch model but without the final linear, pooling, batchnorm, and sigmoid layers." }, { "code": null, "e": 9773, "s": 9715, "text": "model_ft = nn.Sequential(*list(model_ft.children())[:-5])" }, { "code": null, "e": 9804, "s": 9773, "text": "If training just final layers:" }, { "code": null, "e": 9871, "s": 9804, "text": "for param in model_ft.parameters(): param.requires_grad = False" }, { "code": null, "e": 9947, "s": 9871, "text": "Re-attach the last 5 layers which automatically sets requires_grad = True ." }, { "code": null, "e": 10302, "s": 9947, "text": "This linear layer Linear(in_features=1792, out_features=512, bias=False) actually requires writing two custom classes which is not entirely obvious by looking at it, but if you look at the data input/output you can see that there is a Flatten and normalize class within the layer. Check resnet implementation for reason of reshaping in last_linear layer." }, { "code": null, "e": 10650, "s": 10302, "text": "class Flatten(nn.Module): def __init__(self): super(Flatten, self).__init__() def forward(self, x): x = x.view(x.size(0), -1) return xclass normalize(nn.Module): def __init__(self): super(normalize, self).__init__() def forward(self, x): x = F.normalize(x, p=2, dim=1) return x" }, { "code": null, "e": 10720, "s": 10650, "text": "Then you can apply the final layers back to the new Sequential model." }, { "code": null, "e": 11331, "s": 10720, "text": "model_ft.avgpool_1a = nn.AdaptiveAvgPool2d(output_size=1)model_ft.last_linear = nn.Sequential( Flatten(), nn.Linear(in_features=1792, out_features=512, bias=False), normalize())model_ft.logits = nn.Linear(layer_list[3].in_features, len(class_names))model_ft.softmax = nn.Softmax(dim=1)model_ft = model_ft.to(device)criterion = nn.CrossEntropyLoss()# Observe that all parameters are being optimizedoptimizer_ft = optim.SGD(model_ft.parameters(), lr=1e-2, momentum=0.9)# Decay LR by a factor of *gamma* every *step_size* epochsexp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)" }, { "code": null, "e": 13677, "s": 11331, "text": "def train_model(model, criterion, optimizer, scheduler, num_epochs=25): since = time.time() FT_losses = [] best_model_wts = copy.deepcopy(model.state_dict()) best_acc = 0.0 for epoch in range(num_epochs): print('Epoch {}/{}'.format(epoch, num_epochs - 1)) print('-' * 10) # Each epoch has a training and validation phase for phase in ['train', 'val']: if phase == 'train': model.train() # Set model to training mode else: model.eval() # Set model to evaluate mode running_loss = 0.0 running_corrects = 0 # Iterate over data. for inputs, labels in dataloaders[phase]: inputs = inputs.to(device) labels = labels.to(device) # zero the parameter gradients optimizer.zero_grad() # forward # track history if only in train with torch.set_grad_enabled(phase == 'train'): outputs = model(inputs) _, preds = torch.max(outputs, 1) loss = criterion(outputs, labels) # backward + optimize only if in training phase if phase == 'train': loss.backward() optimizer.step() scheduler.step() FT_losses.append(loss.item()) # statistics running_loss += loss.item() * inputs.size(0) running_corrects += torch.sum(preds == labels.data) epoch_loss = running_loss / dataset_sizes[phase] epoch_acc = running_corrects.double() / dataset_sizes[phase] print('{} Loss: {:.4f} Acc: {:.4f}'.format( phase, epoch_loss, epoch_acc)) # deep copy the model if phase == 'val' and epoch_acc > best_acc: best_acc = epoch_acc best_model_wts = copy.deepcopy(model.state_dict()) time_elapsed = time.time() - since print('Training complete in {:.0f}m {:.0f}s'.format( time_elapsed // 60, time_elapsed % 60)) print('Best val Acc: {:4f}'.format(best_acc)) # load best model weights model.load_state_dict(best_model_wts) return model, FT_losses" }, { "code": null, "e": 13943, "s": 13677, "text": "model_ft, FT_losses = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler, num_epochs=500)plt.figure(figsize=(10,5))plt.title(\"FRT Loss During Training\")plt.plot(FT_losses, label=\"FT loss\")plt.xlabel(\"iterations\")plt.ylabel(\"Loss\")plt.legend()plt.show()" } ]
java.time.Instant Class
The java.time.Instant class models a single instantaneous point on the time-line. Following is the declaration for java.time.Instant class − public final class Instant extends Object implements Temporal, TemporalAdjuster, Comparable, Serializable Following are the fields for Java.time.Instant class − Following are the fields for Java.time.Instant class − static Instant EPOCH − Constant for the 1970-01-01T00:00:00Z epoch instant. static Instant EPOCH − Constant for the 1970-01-01T00:00:00Z epoch instant. static Instant MAX − The maximum supported Instant, '1000000000-12-31T23:59:59.999999999Z'. static Instant MAX − The maximum supported Instant, '1000000000-12-31T23:59:59.999999999Z'. static Instant MIN − The minimum supported Instant, '-1000000000-01-01T00:00Z'. static Instant MIN − The minimum supported Instant, '-1000000000-01-01T00:00Z'. Adjusts the specified temporal object to have this instant. Combines this instant with an offset to create an OffsetDateTime. Combines this instant with a time-zone to create a ZonedDateTime. Compares this instant to the specified instant. Checks if this instant is equal to the specified instant. Obtains an instance of Instant from a temporal object. Gets the value of the specified field from this instant as an int. Gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z. Gets the value of the specified field from this instant as a long. Gets the number of nanoseconds, later along the time-line, from the start of the second. Returns a hash code for this instant. Checks if this instant is after the specified instant. Checks if this instant is before the specified instant. Checks if the specified field is supported. Checks if the specified unit is supported. Returns a copy of this instant with the specified amount subtracted. Returns a copy of this instant with the specified amount subtracted. Returns a copy of this instant with the specified duration in milliseconds subtracted. Returns a copy of this instant with the specified duration in nanoseconds subtracted. Returns a copy of this instant with the specified duration in seconds subtracted. Obtains the current instant from the system clock. Obtains the current instant from the specified clock. Obtains an instance of Instant using milliseconds from the epoch of 1970-01-01T00:00:00Z. Obtains an instance of Instant using seconds from the epoch of 1970-01-01T00:00:00Z. Obtains an instance of Instant using seconds from the epoch of 1970-01-01T00:00:00Z and nanosecond fraction of second. Obtains an instance of Instant from a text string such as 2007-12-03T10:15:30.00Z. Returns a copy of this instant with the specified amount added. Returns a copy of this instant with the specified amount added. Returns a copy of this instant with the specified duration in milliseconds added. Returns a copy of this instant with the specified duration in nanoseconds added. Returns a copy of this instant with the specified duration in seconds added. Queries this instant using the specified query. Gets the range of valid values for the specified field. Converts this instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z. A string representation of this instant using ISO-8601 representation. Returns a copy of this Instant truncated to the specified unit. Calculates the amount of time until another instant in terms of the specified unit. Returns an adjusted copy of this instant. Returns a copy of this instant with the specified field set to a new value. This class inherits methods from the following classes − Java.lang.Object Print Add Notes Bookmark this page
[ { "code": null, "e": 1997, "s": 1915, "text": "The java.time.Instant class models a single instantaneous point on the time-line." }, { "code": null, "e": 2056, "s": 1997, "text": "Following is the declaration for java.time.Instant class −" }, { "code": null, "e": 2172, "s": 2056, "text": "public final class Instant\n extends Object\n implements Temporal, TemporalAdjuster, Comparable, Serializable\n" }, { "code": null, "e": 2227, "s": 2172, "text": "Following are the fields for Java.time.Instant class −" }, { "code": null, "e": 2282, "s": 2227, "text": "Following are the fields for Java.time.Instant class −" }, { "code": null, "e": 2358, "s": 2282, "text": "static Instant EPOCH − Constant for the 1970-01-01T00:00:00Z epoch instant." }, { "code": null, "e": 2434, "s": 2358, "text": "static Instant EPOCH − Constant for the 1970-01-01T00:00:00Z epoch instant." }, { "code": null, "e": 2526, "s": 2434, "text": "static Instant MAX − The maximum supported Instant, '1000000000-12-31T23:59:59.999999999Z'." }, { "code": null, "e": 2618, "s": 2526, "text": "static Instant MAX − The maximum supported Instant, '1000000000-12-31T23:59:59.999999999Z'." }, { "code": null, "e": 2698, "s": 2618, "text": "static Instant MIN − The minimum supported Instant, '-1000000000-01-01T00:00Z'." }, { "code": null, "e": 2778, "s": 2698, "text": "static Instant MIN − The minimum supported Instant, '-1000000000-01-01T00:00Z'." }, { "code": null, "e": 2838, "s": 2778, "text": "Adjusts the specified temporal object to have this instant." }, { "code": null, "e": 2904, "s": 2838, "text": "Combines this instant with an offset to create an OffsetDateTime." }, { "code": null, "e": 2970, "s": 2904, "text": "Combines this instant with a time-zone to create a ZonedDateTime." }, { "code": null, "e": 3018, "s": 2970, "text": "Compares this instant to the specified instant." }, { "code": null, "e": 3076, "s": 3018, "text": "Checks if this instant is equal to the specified instant." }, { "code": null, "e": 3131, "s": 3076, "text": "Obtains an instance of Instant from a temporal object." }, { "code": null, "e": 3198, "s": 3131, "text": "Gets the value of the specified field from this instant as an int." }, { "code": null, "e": 3270, "s": 3198, "text": "Gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z." }, { "code": null, "e": 3337, "s": 3270, "text": "Gets the value of the specified field from this instant as a long." }, { "code": null, "e": 3426, "s": 3337, "text": "Gets the number of nanoseconds, later along the time-line, from the start of the second." }, { "code": null, "e": 3464, "s": 3426, "text": "Returns a hash code for this instant." }, { "code": null, "e": 3519, "s": 3464, "text": "Checks if this instant is after the specified instant." }, { "code": null, "e": 3575, "s": 3519, "text": "Checks if this instant is before the specified instant." }, { "code": null, "e": 3619, "s": 3575, "text": "Checks if the specified field is supported." }, { "code": null, "e": 3662, "s": 3619, "text": "Checks if the specified unit is supported." }, { "code": null, "e": 3731, "s": 3662, "text": "Returns a copy of this instant with the specified amount subtracted." }, { "code": null, "e": 3800, "s": 3731, "text": "Returns a copy of this instant with the specified amount subtracted." }, { "code": null, "e": 3887, "s": 3800, "text": "Returns a copy of this instant with the specified duration in milliseconds subtracted." }, { "code": null, "e": 3973, "s": 3887, "text": "Returns a copy of this instant with the specified duration in nanoseconds subtracted." }, { "code": null, "e": 4055, "s": 3973, "text": "Returns a copy of this instant with the specified duration in seconds subtracted." }, { "code": null, "e": 4106, "s": 4055, "text": "Obtains the current instant from the system clock." }, { "code": null, "e": 4160, "s": 4106, "text": "Obtains the current instant from the specified clock." }, { "code": null, "e": 4250, "s": 4160, "text": "Obtains an instance of Instant using milliseconds from the epoch of 1970-01-01T00:00:00Z." }, { "code": null, "e": 4335, "s": 4250, "text": "Obtains an instance of Instant using seconds from the epoch of 1970-01-01T00:00:00Z." }, { "code": null, "e": 4454, "s": 4335, "text": "Obtains an instance of Instant using seconds from the epoch of 1970-01-01T00:00:00Z and nanosecond fraction of second." }, { "code": null, "e": 4537, "s": 4454, "text": "Obtains an instance of Instant from a text string such as 2007-12-03T10:15:30.00Z." }, { "code": null, "e": 4601, "s": 4537, "text": "Returns a copy of this instant with the specified amount added." }, { "code": null, "e": 4665, "s": 4601, "text": "Returns a copy of this instant with the specified amount added." }, { "code": null, "e": 4747, "s": 4665, "text": "Returns a copy of this instant with the specified duration in milliseconds added." }, { "code": null, "e": 4828, "s": 4747, "text": "Returns a copy of this instant with the specified duration in nanoseconds added." }, { "code": null, "e": 4905, "s": 4828, "text": "Returns a copy of this instant with the specified duration in seconds added." }, { "code": null, "e": 4953, "s": 4905, "text": "Queries this instant using the specified query." }, { "code": null, "e": 5009, "s": 4953, "text": "Gets the range of valid values for the specified field." }, { "code": null, "e": 5101, "s": 5009, "text": "Converts this instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z." }, { "code": null, "e": 5172, "s": 5101, "text": "A string representation of this instant using ISO-8601 representation." }, { "code": null, "e": 5236, "s": 5172, "text": "Returns a copy of this Instant truncated to the specified unit." }, { "code": null, "e": 5320, "s": 5236, "text": "Calculates the amount of time until another instant in terms of the specified unit." }, { "code": null, "e": 5362, "s": 5320, "text": "Returns an adjusted copy of this instant." }, { "code": null, "e": 5438, "s": 5362, "text": "Returns a copy of this instant with the specified field set to a new value." }, { "code": null, "e": 5495, "s": 5438, "text": "This class inherits methods from the following classes −" }, { "code": null, "e": 5512, "s": 5495, "text": "Java.lang.Object" }, { "code": null, "e": 5519, "s": 5512, "text": " Print" }, { "code": null, "e": 5530, "s": 5519, "text": " Add Notes" } ]
How to insert Date value into table in JDBC?
You can insert date values in SQL using the date datatype, The java.sql.Date class maps to the SQL DATE type. The PreparedStatement interface provides a method named setDate(). Using this you can insert date into a table. This method accepts two parameters − An integer representing the parameter index of the place holder (?) to which we need to set date value. An integer representing the parameter index of the place holder (?) to which we need to set date value. a Date object representing the date value to be passed. The constructor of java.sql.Date class accepts a variable of long type representing the number of milliseconds from the epoch (standard base time I.e. January 1, 1970, 00:00:00 GMT). a Date object representing the date value to be passed. The constructor of java.sql.Date class accepts a variable of long type representing the number of milliseconds from the epoch (standard base time I.e. January 1, 1970, 00:00:00 GMT). Assume we have created a table named Emp in MySQL database with the following description − +----------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+--------------+------+-----+---------+-------+ | Name | varchar(255) | YES | | NULL | | | DOB | date | YES | | NULL | | | Location | varchar(255) | YES | | NULL | | +----------+--------------+------+-----+---------+-------+ Following JDBC program inserts records in to this table − import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.sql.Date; public class InsertingDate { public static void main(String args[])throws Exception { //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/sampleDB"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Inserting values to a table String query = "INSERT INTO Emp(Name, DOB, Location) VALUES (?, ?, ?)"; PreparedStatement pstmt = con.prepareStatement(query); pstmt.setString(1, "Amit"); pstmt.setDate(2, new Date(622790105000L)); pstmt.setString(3, "Hyderabad"); pstmt.execute(); pstmt.setString(1, "Sumith"); pstmt.setDate(2, new Date(620611200000L)); pstmt.setString(3, "Vishakhapatnam"); pstmt.execute(); pstmt.setString(1, "Sudha"); pstmt.setDate(2, new Date(336614400000L)); pstmt.setString(3, "Vijayawada"); pstmt.execute(); System.out.println("Records inserted......"); } } Connection established...... Records inserted...... If you verify the table in MySQL database, you can observe the contents of the table as − mysql> select * from Emp; +--------+------------+----------------+ | Name | DOB | Location | +--------+------------+----------------+ | Amit | 1989-09-26 | Hyderabad | | Sumith | 2019-03-19 | Vishakhapatnam | | Sudha | 2019-03-19 | Vijayawada | +--------+------------+----------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1172, "s": 1062, "text": "You can insert date values in SQL using the date datatype, The java.sql.Date class maps to the SQL DATE type." }, { "code": null, "e": 1321, "s": 1172, "text": "The PreparedStatement interface provides a method named setDate(). Using this you can insert date into a table. This method accepts two parameters −" }, { "code": null, "e": 1425, "s": 1321, "text": "An integer representing the parameter index of the place holder (?) to which we need to set date value." }, { "code": null, "e": 1529, "s": 1425, "text": "An integer representing the parameter index of the place holder (?) to which we need to set date value." }, { "code": null, "e": 1768, "s": 1529, "text": "a Date object representing the date value to be passed. The constructor of java.sql.Date class accepts a variable of long type representing the number of milliseconds from the epoch (standard base time I.e. January 1, 1970, 00:00:00 GMT)." }, { "code": null, "e": 2007, "s": 1768, "text": "a Date object representing the date value to be passed. The constructor of java.sql.Date class accepts a variable of long type representing the number of milliseconds from the epoch (standard base time I.e. January 1, 1970, 00:00:00 GMT)." }, { "code": null, "e": 2099, "s": 2007, "text": "Assume we have created a table named Emp in MySQL database with the following description −" }, { "code": null, "e": 2512, "s": 2099, "text": "+----------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+----------+--------------+------+-----+---------+-------+\n| Name | varchar(255) | YES | | NULL | |\n| DOB | date | YES | | NULL | |\n| Location | varchar(255) | YES | | NULL | |\n+----------+--------------+------+-----+---------+-------+" }, { "code": null, "e": 2570, "s": 2512, "text": "Following JDBC program inserts records in to this table −" }, { "code": null, "e": 3725, "s": 2570, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\nimport java.sql.Date;\npublic class InsertingDate {\n public static void main(String args[])throws Exception {\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/sampleDB\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Inserting values to a table\n String query = \"INSERT INTO Emp(Name, DOB, Location) VALUES (?, ?, ?)\";\n PreparedStatement pstmt = con.prepareStatement(query);\n pstmt.setString(1, \"Amit\"); pstmt.setDate(2, new Date(622790105000L));\n pstmt.setString(3, \"Hyderabad\");\n pstmt.execute();\n pstmt.setString(1, \"Sumith\"); pstmt.setDate(2, new Date(620611200000L));\n pstmt.setString(3, \"Vishakhapatnam\");\n pstmt.execute();\n pstmt.setString(1, \"Sudha\");\n pstmt.setDate(2, new Date(336614400000L));\n pstmt.setString(3, \"Vijayawada\");\n pstmt.execute();\n System.out.println(\"Records inserted......\");\n }\n}" }, { "code": null, "e": 3777, "s": 3725, "text": "Connection established......\nRecords inserted......" }, { "code": null, "e": 3867, "s": 3777, "text": "If you verify the table in MySQL database, you can observe the contents of the table as −" }, { "code": null, "e": 4205, "s": 3867, "text": "mysql> select * from Emp;\n+--------+------------+----------------+\n| Name | DOB | Location |\n+--------+------------+----------------+\n| Amit | 1989-09-26 | Hyderabad |\n| Sumith | 2019-03-19 | Vishakhapatnam |\n| Sudha | 2019-03-19 | Vijayawada |\n+--------+------------+----------------+\n3 rows in set (0.00 sec)" } ]
SQL BETWEEN Operator
The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates. The BETWEEN operator is inclusive: begin and end values are included. Below is a selection from the "Products" table in the Northwind sample database: The following SQL statement selects all products with a price between 10 and 20: To display the products outside the range of the previous example, use NOT BETWEEN: The following SQL statement selects all products with a price between 10 and 20. In addition; do not show products with a CategoryID of 1,2, or 3: The following SQL statement selects all products with a ProductName between Carnarvon Tigers and Mozzarella di Giovanni: The following SQL statement selects all products with a ProductName between Carnarvon Tigers and Chef Anton's Cajun Seasoning: The following SQL statement selects all products with a ProductName not between Carnarvon Tigers and Mozzarella di Giovanni: Below is a selection from the "Orders" table in the Northwind sample database: The following SQL statement selects all orders with an OrderDate between '01-July-1996' and '31-July-1996': OR: Use the BETWEEN operator to select all the records where the value of the Price column is between 10 and 20. SELECT * FROM Products WHERE Price ; 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": 101, "s": 0, "text": "The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates." }, { "code": null, "e": 172, "s": 101, "text": "The BETWEEN operator is inclusive: begin and end values are included. " }, { "code": null, "e": 254, "s": 172, "text": "Below is a selection from the \"Products\" table in the Northwind \nsample database:" }, { "code": null, "e": 335, "s": 254, "text": "The following SQL statement selects all products with a price between 10 and 20:" }, { "code": null, "e": 420, "s": 335, "text": "To display the products outside the range of the previous example, use \nNOT BETWEEN:" }, { "code": null, "e": 568, "s": 420, "text": "The following SQL statement selects all products with a price between 10 and \n20. In addition; do not show products with a CategoryID of 1,2, or 3:" }, { "code": null, "e": 690, "s": 568, "text": "The following SQL statement selects all products with a ProductName between Carnarvon \nTigers and Mozzarella di Giovanni:" }, { "code": null, "e": 818, "s": 690, "text": "The following SQL statement selects all products with a ProductName between Carnarvon \nTigers and Chef Anton's Cajun Seasoning:" }, { "code": null, "e": 945, "s": 818, "text": "The following SQL statement selects all products with a ProductName not \nbetween Carnarvon \nTigers and Mozzarella di Giovanni:" }, { "code": null, "e": 1025, "s": 945, "text": "Below is a selection from the \"Orders\" table in the Northwind \nsample database:" }, { "code": null, "e": 1134, "s": 1025, "text": "The following SQL statement selects all orders with an OrderDate between '01-July-1996' and \n'31-July-1996':" }, { "code": null, "e": 1138, "s": 1134, "text": "OR:" }, { "code": null, "e": 1247, "s": 1138, "text": "Use the BETWEEN operator to select all the records where the value of the Price column is between 10 and 20." }, { "code": null, "e": 1285, "s": 1247, "text": "SELECT * FROM Products\nWHERE Price ;\n" }, { "code": null, "e": 1304, "s": 1285, "text": "Start the Exercise" }, { "code": null, "e": 1337, "s": 1304, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1379, "s": 1337, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1486, "s": 1379, "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": 1505, "s": 1486, "text": "help@w3schools.com" } ]
VGG-16 Transfer Learning in Classifying Log-Mel Spectrogram Images | by Muriel Kosaka | Towards Data Science
As a follow-up to my previous post, I will be applying transfer learning to the RAVDESS Audio Dataset in hopes to improve the model’s accuracy. To review, transfer learning is a deep learning approach in which a model that has been trained on one task is used as a starting point to train a model for a similar task. In this post by DJ Sarkar, he provides a great guide in understanding transfer learning with examples. We will first try to use the VGG-16 pretrained model as a feature extractor on our dataset, which is where we freeze the convolution blocks of a pretrained model and modify the dense layers. Then we will try the pretrained model with Image Augmentation. So let’s get started! After importing the necessary libraries, we must import the training and test images with labels. # For training set onlyimport globangry = glob.glob('/content/drive/My_Drive/train_logmel/angry/*.*')calm = glob.glob('/content/drive/My_Drive/train_logmel/calm/*.*')disgust = glob.glob('/content/drive/My_Drive/train_logmel/disgust/*.*')fearful = glob.glob('/content/drive/My_Drive/train_logmel/fearful/*.*')happy = glob.glob('/content/drive/My_Drive/train_logmel/happy/*.*')neutral = glob.glob('/content/drive/My_Drive/train_logmel/neutral/*.*')sad = glob.glob('/content/drive/My_Drive/train_logmel/sad/*.*')surprised = glob.glob('/content/drive/My_Drive/train_logmel/surprised/*.*')data = []labels = []for i in angry: image=tf.keras.preprocessing.image.load_img(i, color_mode='rgb', target_size= (224,224)) image=np.array(image) data.append(image) labels.append('Angry')for i in calm: image=tf.keras.preprocessing.image.load_img(i, color_mode='rgb', target_size= (224,224)) image=np.array(image) data.append(image) labels.append('Calm')for i in disgust: image=tf.keras.preprocessing.image.load_img(i, color_mode='rgb', target_size= (224,224)) image=np.array(image) data.append(image) labels.append('Disgust')for i in fearful: image=tf.keras.preprocessing.image.load_img(i, color_mode='rgb', target_size= (224,224)) image=np.array(image) data.append(image) labels.append('Fearful')for i in happy: image=tf.keras.preprocessing.image.load_img(i, color_mode='rgb', target_size= (224,224)) image=np.array(image) data.append(image) labels.append('Happy')for i in neutral: image=tf.keras.preprocessing.image.load_img(i, color_mode='rgb', target_size= (224,224)) image=np.array(image) data.append(image) labels.append('Neutral')for i in sad: image=tf.keras.preprocessing.image.load_img(i, color_mode='rgb', target_size= (224,224)) image=np.array(image) data.append(image) labels.append('Sad')for i in surprised: image=tf.keras.preprocessing.image.load_img(i, color_mode='rgb', target_size= (224,224)) image=np.array(image) data.append(image) labels.append('Surprised')train_data = np.array(data)train_labels = np.array(labels) Let’s see a sample of images from the training set: Normalize data Normalize data X_train = X_train.astype('float32')X_test = X_test.astype('float32')X_train /= 255X_test /= 255 2. One-hot encode target classes lb = LabelEncoder()y_train = np_utils.to_categorical(lb.fit_transform(y_train))y_test = np_utils.to_categorical(lb.fit_transform(y_test)) First we import VGG16 and set the necessary arguments: from keras.applications import VGG16vgg_model = VGG16(weights='imagenet',include_top=False, input_shape=(224, 224, 3)) weights = ‘imagenet’ : use the pretrained weights instead of training the model from scratch include_top=False : we want to load the model without the classifier layers and add our own input_shape=(224,224,3) : specify the preferred shape of the images in our dataset Next we freeze the convolution blocks: for layer in vgg_model.layers:layer.trainable = False# Make sure you have frozen the correct layersfor i, layer in enumerate(vgg_model.layers): print(i, layer.name, layer.trainable) Then create our Dense layers: x = vgg_model.outputx = Flatten()(x) # Flatten dimensions to for use in FC layersx = Dense(512, activation='relu')(x)x = Dropout(0.5)(x) # Dropout layer to reduce overfittingx = Dense(256, activation='relu')(x)x = Dense(8, activation='softmax')(x) # Softmax for multiclasstransfer_model = Model(inputs=vgg_model.input, outputs=x) And lastly, we compile and fit the model: learning_rate= 5e-5transfer_model.compile(loss="categorical_crossentropy", optimizer=optimizers.Adam(lr=learning_rate), metrics=["accuracy"])history = transfer_model.fit(X_train, y_train, batch_size = 1, epochs=50, validation_data=(X_test,y_test)) After 50 epochs, we achieved an accuracy score of 69%. This performed slightly better than previous models, but there has to be a way to improve model accuracy! Let’s try using the VGG-16 as a feature extractor with Image Augmentation. Image Augmentation is a great way to add more training data when dealing with a small dataset. Using ImageDataGenerator we can augment the images: train_datagen = ImageDataGenerator(rescale=1./255, zoom_range=0.3, rotation_range=40, width_shift_range=0.3, height_shift_range=0.3, shear_range=0.3, horizontal_flip=True, fill_mode="nearest")train_generator = train_datagen.flow(train_data, train_lb, batch_size=1)val_datagen = ImageDataGenerator(rescale=1./255)val_generator = val_datagen.flow(test_data,val_lb,batch_size=1) Next, we will build our deep learning model, compile the model, then fit it: x = vgg_model.outputx = Flatten()(x) # Flatten dimensions to for use in FC layersx = Dense(512, activation='relu')(x)x = Dropout(0.5)(x) # Dropout layer to reduce overfittingx = Dense(256, activation='relu')(x)x = Dense(8, activation='softmax')(x) # Softmax for multiclasstransfer_model = Model(inputs=vgg_model.input, outputs=x)learning_rate= 5e-5transfer_model.compile(loss="sparse_categorical_crossentropy", optimizer=keras.optimizers.Adam(lr=learning_rate), metrics=["accuracy"])history = transfer_model.fit_generator(train_generator, validation_data=val_generator, epochs=100, shuffle=True, verbose=1) After 100 epochs, we achieved an accuracy score of 78% As you can see this did not perform much better than our previous model and the current model is overfitting the training data. I will look into other pretrained models (such as Inception_V3 and Resnet50) and explore fine-tuning rather than using pretrained models as feature extractors. Thank you for reading! :)
[ { "code": null, "e": 466, "s": 46, "text": "As a follow-up to my previous post, I will be applying transfer learning to the RAVDESS Audio Dataset in hopes to improve the model’s accuracy. To review, transfer learning is a deep learning approach in which a model that has been trained on one task is used as a starting point to train a model for a similar task. In this post by DJ Sarkar, he provides a great guide in understanding transfer learning with examples." }, { "code": null, "e": 720, "s": 466, "text": "We will first try to use the VGG-16 pretrained model as a feature extractor on our dataset, which is where we freeze the convolution blocks of a pretrained model and modify the dense layers. Then we will try the pretrained model with Image Augmentation." }, { "code": null, "e": 742, "s": 720, "text": "So let’s get started!" }, { "code": null, "e": 840, "s": 742, "text": "After importing the necessary libraries, we must import the training and test images with labels." }, { "code": null, "e": 3013, "s": 840, "text": "# For training set onlyimport globangry = glob.glob('/content/drive/My_Drive/train_logmel/angry/*.*')calm = glob.glob('/content/drive/My_Drive/train_logmel/calm/*.*')disgust = glob.glob('/content/drive/My_Drive/train_logmel/disgust/*.*')fearful = glob.glob('/content/drive/My_Drive/train_logmel/fearful/*.*')happy = glob.glob('/content/drive/My_Drive/train_logmel/happy/*.*')neutral = glob.glob('/content/drive/My_Drive/train_logmel/neutral/*.*')sad = glob.glob('/content/drive/My_Drive/train_logmel/sad/*.*')surprised = glob.glob('/content/drive/My_Drive/train_logmel/surprised/*.*')data = []labels = []for i in angry: image=tf.keras.preprocessing.image.load_img(i, color_mode='rgb', target_size= (224,224)) image=np.array(image) data.append(image) labels.append('Angry')for i in calm: image=tf.keras.preprocessing.image.load_img(i, color_mode='rgb', target_size= (224,224)) image=np.array(image) data.append(image) labels.append('Calm')for i in disgust: image=tf.keras.preprocessing.image.load_img(i, color_mode='rgb', target_size= (224,224)) image=np.array(image) data.append(image) labels.append('Disgust')for i in fearful: image=tf.keras.preprocessing.image.load_img(i, color_mode='rgb', target_size= (224,224)) image=np.array(image) data.append(image) labels.append('Fearful')for i in happy: image=tf.keras.preprocessing.image.load_img(i, color_mode='rgb', target_size= (224,224)) image=np.array(image) data.append(image) labels.append('Happy')for i in neutral: image=tf.keras.preprocessing.image.load_img(i, color_mode='rgb', target_size= (224,224)) image=np.array(image) data.append(image) labels.append('Neutral')for i in sad: image=tf.keras.preprocessing.image.load_img(i, color_mode='rgb', target_size= (224,224)) image=np.array(image) data.append(image) labels.append('Sad')for i in surprised: image=tf.keras.preprocessing.image.load_img(i, color_mode='rgb', target_size= (224,224)) image=np.array(image) data.append(image) labels.append('Surprised')train_data = np.array(data)train_labels = np.array(labels)" }, { "code": null, "e": 3065, "s": 3013, "text": "Let’s see a sample of images from the training set:" }, { "code": null, "e": 3080, "s": 3065, "text": "Normalize data" }, { "code": null, "e": 3095, "s": 3080, "text": "Normalize data" }, { "code": null, "e": 3191, "s": 3095, "text": "X_train = X_train.astype('float32')X_test = X_test.astype('float32')X_train /= 255X_test /= 255" }, { "code": null, "e": 3224, "s": 3191, "text": "2. One-hot encode target classes" }, { "code": null, "e": 3362, "s": 3224, "text": "lb = LabelEncoder()y_train = np_utils.to_categorical(lb.fit_transform(y_train))y_test = np_utils.to_categorical(lb.fit_transform(y_test))" }, { "code": null, "e": 3417, "s": 3362, "text": "First we import VGG16 and set the necessary arguments:" }, { "code": null, "e": 3536, "s": 3417, "text": "from keras.applications import VGG16vgg_model = VGG16(weights='imagenet',include_top=False, input_shape=(224, 224, 3))" }, { "code": null, "e": 3629, "s": 3536, "text": "weights = ‘imagenet’ : use the pretrained weights instead of training the model from scratch" }, { "code": null, "e": 3721, "s": 3629, "text": "include_top=False : we want to load the model without the classifier layers and add our own" }, { "code": null, "e": 3804, "s": 3721, "text": "input_shape=(224,224,3) : specify the preferred shape of the images in our dataset" }, { "code": null, "e": 3843, "s": 3804, "text": "Next we freeze the convolution blocks:" }, { "code": null, "e": 4028, "s": 3843, "text": "for layer in vgg_model.layers:layer.trainable = False# Make sure you have frozen the correct layersfor i, layer in enumerate(vgg_model.layers): print(i, layer.name, layer.trainable)" }, { "code": null, "e": 4058, "s": 4028, "text": "Then create our Dense layers:" }, { "code": null, "e": 4388, "s": 4058, "text": "x = vgg_model.outputx = Flatten()(x) # Flatten dimensions to for use in FC layersx = Dense(512, activation='relu')(x)x = Dropout(0.5)(x) # Dropout layer to reduce overfittingx = Dense(256, activation='relu')(x)x = Dense(8, activation='softmax')(x) # Softmax for multiclasstransfer_model = Model(inputs=vgg_model.input, outputs=x)" }, { "code": null, "e": 4430, "s": 4388, "text": "And lastly, we compile and fit the model:" }, { "code": null, "e": 4678, "s": 4430, "text": "learning_rate= 5e-5transfer_model.compile(loss=\"categorical_crossentropy\", optimizer=optimizers.Adam(lr=learning_rate), metrics=[\"accuracy\"])history = transfer_model.fit(X_train, y_train, batch_size = 1, epochs=50, validation_data=(X_test,y_test))" }, { "code": null, "e": 4733, "s": 4678, "text": "After 50 epochs, we achieved an accuracy score of 69%." }, { "code": null, "e": 5009, "s": 4733, "text": "This performed slightly better than previous models, but there has to be a way to improve model accuracy! Let’s try using the VGG-16 as a feature extractor with Image Augmentation. Image Augmentation is a great way to add more training data when dealing with a small dataset." }, { "code": null, "e": 5061, "s": 5009, "text": "Using ImageDataGenerator we can augment the images:" }, { "code": null, "e": 5437, "s": 5061, "text": "train_datagen = ImageDataGenerator(rescale=1./255, zoom_range=0.3, rotation_range=40, width_shift_range=0.3, height_shift_range=0.3, shear_range=0.3, horizontal_flip=True, fill_mode=\"nearest\")train_generator = train_datagen.flow(train_data, train_lb, batch_size=1)val_datagen = ImageDataGenerator(rescale=1./255)val_generator = val_datagen.flow(test_data,val_lb,batch_size=1)" }, { "code": null, "e": 5514, "s": 5437, "text": "Next, we will build our deep learning model, compile the model, then fit it:" }, { "code": null, "e": 6121, "s": 5514, "text": "x = vgg_model.outputx = Flatten()(x) # Flatten dimensions to for use in FC layersx = Dense(512, activation='relu')(x)x = Dropout(0.5)(x) # Dropout layer to reduce overfittingx = Dense(256, activation='relu')(x)x = Dense(8, activation='softmax')(x) # Softmax for multiclasstransfer_model = Model(inputs=vgg_model.input, outputs=x)learning_rate= 5e-5transfer_model.compile(loss=\"sparse_categorical_crossentropy\", optimizer=keras.optimizers.Adam(lr=learning_rate), metrics=[\"accuracy\"])history = transfer_model.fit_generator(train_generator, validation_data=val_generator, epochs=100, shuffle=True, verbose=1)" }, { "code": null, "e": 6176, "s": 6121, "text": "After 100 epochs, we achieved an accuracy score of 78%" }, { "code": null, "e": 6304, "s": 6176, "text": "As you can see this did not perform much better than our previous model and the current model is overfitting the training data." } ]
Volume Calculation - Online Quiz
Following quiz provides Multiple Choice Questions (MCQs) related to Volume Calculation. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz. Q 1 - A rectangular marble stone 28 cm wide and 5 cm thick weighs 112 kg. In the event that 1 cubic cm of marble measures 25 gm, then the length of given stone is: A - 36 cm B - 37.5 cm C - 32 cm D - 26.5 cm Let the required length be x cm. Then, its volume = (x*28*5*25/1000) kg = 7x/2 kg ∴ 7x/2= 112 ⇒x= 112*2/7= 32 cm Required length = 32 cm Q 2 - A rectangular water tank is open at the top. Its ability is 24m3. Its length and broadness are 4m and 3m separately. Overlooking the thickness of the material utilized for building the tank, the aggregate expense of painting the internal and external surfaces of the tank at Rs 10 for every m2, is: A - Rs 400 B - Rs. 500 C - Rs. 600 D - Rs. 800 Let the depth of the tank be x meters. Then, 4*3*x = 24 ⇒x =2m Area of the surface to be painted = 2* [{2*(L+b)*h} + (L*b)}] = 2*[2*(4+3)*2+ (4*3)] m2= 80m2 Cost of painting = (80*10) = 800 Rs. Q 3 - A swimming shower is 24 m long and 15 m wide. At the point when various men jump into the shower, the tallness of water ascends by 1 cm. On the off chance that the normal volume of water uprooted by every men be 0.1 m3, what number of men arrive in the shower? A - 32 B - 36 C - 42 D - 46 Let there be x man in the bath .Then, x *0.1= (24*15*1/100) ⇒x*1/10= 24*15*1/100⇒x= 36. Q 4 - The surface territory of a (10cm *4cm*3cm) block is: A - 84 cm2 B - 124 cm2 C - 164 cm2 D - 180 cm2 Here L =10 cm, b= 4 cm, h = 3cm Surface area = 2(Lb+bh+Lh) = 2(10*4+4*3+10*3) cm2 = 2*82 = 164cm2 Q 5 - The region of three contiguous appearances of a cuboid are in the proportion 2:3:4 and its volume is 9000 cm3. The littlest side has a length of: A - 10 cm B - 15 cm C - 20 cm D - 30 cm Let the area of the three adjacent faces be 2x, 3x and 4x then, Lb= 2x, bh= 3x and Lh= 4x ∴ (Lb*bh*Lh) = 24x3 ⇒ (Lbh) 2 =(9000) 2= 81000000 ⇒x3= 81000000/24= 27000000/8 ⇒x = 300/2= 150 ∴ Lb= 300, bh =450 and Lh= 600 and Lbh= 9000 ∴ h = 9000/300= 30cm, L= 9000/450 = 20cm, b= 9000/600= 15cm Smallest side = 15 cm Q 6 - A metal 3D square of edge 12cm is liquefied and framed into three littler 3D shape. In the event that the edge of two littler 3D shapes is 6cm and 8 cm. the edge of the third littler solid shape is: A - 10 cm B - 14 cm C - 12 cm D - 16 cm Let the edge of third smaller cube be a cm. Then, (6) 3+ (8) 3+a3= (12) 3 ⇒ (216+512) +a3=1728 ⇒a3= (1728-728) = 1000= (10) 3⇒a= 10cm ∴ Edge of third smaller cube = 10 cm Q 7 - If the span of a barrel is diminished by half and the stature is expanded by half to frame another chamber, then the volume will be diminished by: A - 1:4 B - 4:1 C - 2:5 D - none of these Initial volume = πr2h New radius = r/2, new volume = [π*(r/2)2*4] = 1/4 πr2h Required ratio = 1/4 πr2h: πr2h = 1/4:1 = 1:4 Q 8 - The bended surface of a tube shaped column is 264 m2 and its volume is 924 m3. The proportion of its width to its stature is: A - 7:3 B - 3:7 C - 7:6 D - 6:7 2πrh =264 and πr2h =924 ∴πr2h/2πrh= 924/264= 7/2 ⇒r =7 ⇒d= 2r =14m 2*22/7*7*h =264 ⇒h = 264/44= 6 ∴ d/h= 14/6= 7/3 = 7:3 Q 9 - The total of the range of base and the tallness of a barrel is 37 m. On the off chance that the aggregate surface region of the chamber is 1628m2, then its volume is: A - 5240 m3 B - 4620 m3 C - 3180 m3 D - none of these Given: (r+h) = 37m Total surface area = 2πr (h+r) ∴2πr* 37= 1628 ⇒22/7* r= 22 ⇒ r = 7m h =(37-7)= 30 m Volume = πr2h= (22/7* 7* 7* 30) m3= 4620 m3 Q 10 - The volume of the circle is 2145(11/21) cm3. Its sweep is: A - 7 cm B - 8 cm C - 9 cm D - none of these 4/3πr3=45056/21 ⇒4/3*22/7* r3 = 45056/21 ⇒r3= (45056/21 *21/88) = 512 = (8) 3 ⇒r =8 ∴Radius of the sphere =8cm 87 Lectures 22.5 hours Programming Line Print Add Notes Bookmark this page
[ { "code": null, "e": 4224, "s": 3892, "text": "Following quiz provides Multiple Choice Questions (MCQs) related to Volume Calculation. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz." }, { "code": null, "e": 4388, "s": 4224, "text": "Q 1 - A rectangular marble stone 28 cm wide and 5 cm thick weighs 112 kg. In the event that 1 cubic cm of marble measures 25 gm, then the length of given stone is:" }, { "code": null, "e": 4398, "s": 4388, "text": "A - 36 cm" }, { "code": null, "e": 4410, "s": 4398, "text": "B - 37.5 cm" }, { "code": null, "e": 4420, "s": 4410, "text": "C - 32 cm" }, { "code": null, "e": 4432, "s": 4420, "text": "D - 26.5 cm" }, { "code": null, "e": 4569, "s": 4432, "text": "Let the required length be x cm.\nThen, its volume = (x*28*5*25/1000) kg = 7x/2 kg\n∴ 7x/2= 112 ⇒x= 112*2/7= 32 cm\nRequired length = 32 cm" }, { "code": null, "e": 4874, "s": 4569, "text": "Q 2 - A rectangular water tank is open at the top. Its ability is 24m3. Its length and broadness are 4m and 3m separately. Overlooking the thickness of the material utilized for building the tank, the aggregate expense of painting the internal and external surfaces of the tank at Rs 10 for every m2, is:" }, { "code": null, "e": 4885, "s": 4874, "text": "A - Rs 400" }, { "code": null, "e": 4897, "s": 4885, "text": "B - Rs. 500" }, { "code": null, "e": 4909, "s": 4897, "text": "C - Rs. 600" }, { "code": null, "e": 4921, "s": 4909, "text": "D - Rs. 800" }, { "code": null, "e": 5115, "s": 4921, "text": "Let the depth of the tank be x meters. Then, 4*3*x = 24 ⇒x =2m\nArea of the surface to be painted = 2* [{2*(L+b)*h} + (L*b)}]\n= 2*[2*(4+3)*2+ (4*3)] m2= 80m2\nCost of painting = (80*10) = 800 Rs." }, { "code": null, "e": 5382, "s": 5115, "text": "Q 3 - A swimming shower is 24 m long and 15 m wide. At the point when various men jump into the shower, the tallness of water ascends by 1 cm. On the off chance that the normal volume of water uprooted by every men be 0.1 m3, what number of men arrive in the shower?" }, { "code": null, "e": 5389, "s": 5382, "text": "A - 32" }, { "code": null, "e": 5396, "s": 5389, "text": "B - 36" }, { "code": null, "e": 5403, "s": 5396, "text": "C - 42" }, { "code": null, "e": 5410, "s": 5403, "text": "D - 46" }, { "code": null, "e": 5500, "s": 5410, "text": "Let there be x man in the bath .Then,\nx *0.1= (24*15*1/100) ⇒x*1/10= 24*15*1/100⇒x= 36." }, { "code": null, "e": 5559, "s": 5500, "text": "Q 4 - The surface territory of a (10cm *4cm*3cm) block is:" }, { "code": null, "e": 5570, "s": 5559, "text": "A - 84 cm2" }, { "code": null, "e": 5582, "s": 5570, "text": "B - 124 cm2" }, { "code": null, "e": 5594, "s": 5582, "text": "C - 164 cm2" }, { "code": null, "e": 5606, "s": 5594, "text": "D - 180 cm2" }, { "code": null, "e": 5704, "s": 5606, "text": "Here L =10 cm, b= 4 cm, h = 3cm\nSurface area = 2(Lb+bh+Lh)\n= 2(10*4+4*3+10*3) cm2 = 2*82 = 164cm2" }, { "code": null, "e": 5856, "s": 5704, "text": "Q 5 - The region of three contiguous appearances of a cuboid are in the proportion 2:3:4 and its volume is 9000 cm3. The littlest side has a length of:" }, { "code": null, "e": 5866, "s": 5856, "text": "A - 10 cm" }, { "code": null, "e": 5876, "s": 5866, "text": "B - 15 cm" }, { "code": null, "e": 5886, "s": 5876, "text": "C - 20 cm" }, { "code": null, "e": 5896, "s": 5886, "text": "D - 30 cm" }, { "code": null, "e": 6208, "s": 5896, "text": "Let the area of the three adjacent faces be 2x, 3x and 4x then,\nLb= 2x, bh= 3x and Lh= 4x\n∴ (Lb*bh*Lh) = 24x3 ⇒ (Lbh) 2 =(9000) 2= 81000000\n⇒x3= 81000000/24= 27000000/8 ⇒x = 300/2= 150\n∴ Lb= 300, bh =450 and Lh= 600 and Lbh= 9000\n∴ h = 9000/300= 30cm, L= 9000/450 = 20cm, b= 9000/600= 15cm\nSmallest side = 15 cm" }, { "code": null, "e": 6413, "s": 6208, "text": "Q 6 - A metal 3D square of edge 12cm is liquefied and framed into three littler 3D shape. In the event that the edge of two littler 3D shapes is 6cm and 8 cm. the edge of the third littler solid shape is:" }, { "code": null, "e": 6423, "s": 6413, "text": "A - 10 cm" }, { "code": null, "e": 6433, "s": 6423, "text": "B - 14 cm" }, { "code": null, "e": 6443, "s": 6433, "text": "C - 12 cm" }, { "code": null, "e": 6453, "s": 6443, "text": "D - 16 cm" }, { "code": null, "e": 6624, "s": 6453, "text": "Let the edge of third smaller cube be a cm. Then,\n(6) 3+ (8) 3+a3= (12) 3 ⇒ (216+512) +a3=1728\n⇒a3= (1728-728) = 1000= (10) 3⇒a= 10cm\n∴ Edge of third smaller cube = 10 cm" }, { "code": null, "e": 6777, "s": 6624, "text": "Q 7 - If the span of a barrel is diminished by half and the stature is expanded by half to frame another chamber, then the volume will be diminished by:" }, { "code": null, "e": 6785, "s": 6777, "text": "A - 1:4" }, { "code": null, "e": 6793, "s": 6785, "text": "B - 4:1" }, { "code": null, "e": 6801, "s": 6793, "text": "C - 2:5" }, { "code": null, "e": 6819, "s": 6801, "text": "D - none of these" }, { "code": null, "e": 6942, "s": 6819, "text": "Initial volume = πr2h\nNew radius = r/2, new volume = [π*(r/2)2*4] = 1/4 πr2h\nRequired ratio = 1/4 πr2h: πr2h = 1/4:1 = 1:4" }, { "code": null, "e": 7074, "s": 6942, "text": "Q 8 - The bended surface of a tube shaped column is 264 m2 and its volume is 924 m3. The proportion of its width to its stature is:" }, { "code": null, "e": 7082, "s": 7074, "text": "A - 7:3" }, { "code": null, "e": 7090, "s": 7082, "text": "B - 3:7" }, { "code": null, "e": 7098, "s": 7090, "text": "C - 7:6" }, { "code": null, "e": 7106, "s": 7098, "text": "D - 6:7" }, { "code": null, "e": 7232, "s": 7106, "text": "2πrh =264 and πr2h =924\n∴πr2h/2πrh= 924/264= 7/2 ⇒r =7 ⇒d= 2r =14m\n2*22/7*7*h =264 ⇒h = 264/44= 6\n∴ d/h= 14/6= 7/3 = 7:3" }, { "code": null, "e": 7405, "s": 7232, "text": "Q 9 - The total of the range of base and the tallness of a barrel is 37 m. On the off chance that the aggregate surface region of the chamber is 1628m2, then its volume is:" }, { "code": null, "e": 7417, "s": 7405, "text": "A - 5240 m3" }, { "code": null, "e": 7429, "s": 7417, "text": "B - 4620 m3" }, { "code": null, "e": 7441, "s": 7429, "text": "C - 3180 m3" }, { "code": null, "e": 7459, "s": 7441, "text": "D - none of these" }, { "code": null, "e": 7606, "s": 7459, "text": "Given: (r+h) = 37m\nTotal surface area = 2πr (h+r)\n∴2πr* 37= 1628 ⇒22/7* r= 22 ⇒ r = 7m\nh =(37-7)= 30 m\nVolume = πr2h= (22/7* 7* 7* 30) m3= 4620 m3" }, { "code": null, "e": 7672, "s": 7606, "text": "Q 10 - The volume of the circle is 2145(11/21) cm3. Its sweep is:" }, { "code": null, "e": 7681, "s": 7672, "text": "A - 7 cm" }, { "code": null, "e": 7690, "s": 7681, "text": "B - 8 cm" }, { "code": null, "e": 7699, "s": 7690, "text": "C - 9 cm" }, { "code": null, "e": 7717, "s": 7699, "text": "D - none of these" }, { "code": null, "e": 7828, "s": 7717, "text": "4/3πr3=45056/21 ⇒4/3*22/7* r3 = 45056/21\n⇒r3= (45056/21 *21/88) = 512 = (8) 3 ⇒r =8\n∴Radius of the sphere =8cm" }, { "code": null, "e": 7864, "s": 7828, "text": "\n 87 Lectures \n 22.5 hours \n" }, { "code": null, "e": 7882, "s": 7864, "text": " Programming Line" }, { "code": null, "e": 7889, "s": 7882, "text": " Print" }, { "code": null, "e": 7900, "s": 7889, "text": " Add Notes" } ]
Python String isnumeric() Method
Python string method isnumeric() checks whether the string consists of only numeric characters. This method is present only on unicode objects. Note − To define a string as Unicode, one simply prefixes a 'u' to the opening quotation mark of the assignment. Below is the example. Following is the syntax for isnumeric() method − str.isnumeric() NA NA This method returns true if all characters in the string are numeric, false otherwise. The following example shows the usage of isnumeric() method. #!/usr/bin/python str = u"this2009"; print str.isnumeric() str = u"23443434"; print str.isnumeric() When we run above program, it produces following result − False True 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": 2388, "s": 2244, "text": "Python string method isnumeric() checks whether the string consists of only numeric characters. This method is present only on unicode objects." }, { "code": null, "e": 2523, "s": 2388, "text": "Note − To define a string as Unicode, one simply prefixes a 'u' to the opening quotation mark of the assignment. Below is the example." }, { "code": null, "e": 2572, "s": 2523, "text": "Following is the syntax for isnumeric() method −" }, { "code": null, "e": 2589, "s": 2572, "text": "str.isnumeric()\n" }, { "code": null, "e": 2592, "s": 2589, "text": "NA" }, { "code": null, "e": 2595, "s": 2592, "text": "NA" }, { "code": null, "e": 2682, "s": 2595, "text": "This method returns true if all characters in the string are numeric, false otherwise." }, { "code": null, "e": 2743, "s": 2682, "text": "The following example shows the usage of isnumeric() method." }, { "code": null, "e": 2847, "s": 2743, "text": "#!/usr/bin/python\n\nstr = u\"this2009\"; \nprint str.isnumeric()\n\nstr = u\"23443434\";\nprint str.isnumeric()" }, { "code": null, "e": 2905, "s": 2847, "text": "When we run above program, it produces following result −" }, { "code": null, "e": 2917, "s": 2905, "text": "False\nTrue\n" }, { "code": null, "e": 2954, "s": 2917, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 2970, "s": 2954, "text": " Malhar Lathkar" }, { "code": null, "e": 3003, "s": 2970, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3022, "s": 3003, "text": " Arnab Chakraborty" }, { "code": null, "e": 3057, "s": 3022, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3079, "s": 3057, "text": " In28Minutes Official" }, { "code": null, "e": 3113, "s": 3079, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3141, "s": 3113, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3176, "s": 3141, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3190, "s": 3176, "text": " Lets Kode It" }, { "code": null, "e": 3223, "s": 3190, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3240, "s": 3223, "text": " Abhilash Nelson" }, { "code": null, "e": 3247, "s": 3240, "text": " Print" }, { "code": null, "e": 3258, "s": 3247, "text": " Add Notes" } ]
How to store and retrieve a date into MySQL database using Python?
To insert a date in a MySQL database, you need to have a column of Type date or datetime in your table. Once you have that, you'll need to convert your date in a string format before inserting it to your database. To do this, you can use the datetime module's strftime formatting function. from datetime import datetime now = datetime.now() id = 1 formatted_date = now.strftime('%Y-%m-%d %H:%M:%S') # Assuming you have a cursor named cursor you want to execute this query on: cursor.execute('insert into table(id, date_created) values(%s, %s)', (id, formatted_date)) Running this will try to insert the tuple (id, date) in your table. When you fetch a date from a database using a select query, you'll need to parse it back to a datetime object using functions like strptime. from datetime import datetime # Assuming you have a cursor named cursor you want to execute this query on: cursor.execute('select id, date_created from table where id=1') # if you inserted the row above, you can get it back like this id, date_str = cursor.fetchone() # date is returned as a string in format we sent it as. So parse it using strptime created_date = datetime.strptime(date_created, '%Y-%m-%d %H:%M:%S') This will get the created date and parse it to a datetime object.
[ { "code": null, "e": 1352, "s": 1062, "text": "To insert a date in a MySQL database, you need to have a column of Type date or datetime in your table. Once you have that, you'll need to convert your date in a string format before inserting it to your database. To do this, you can use the datetime module's strftime formatting function." }, { "code": null, "e": 1629, "s": 1352, "text": "from datetime import datetime\nnow = datetime.now()\nid = 1\nformatted_date = now.strftime('%Y-%m-%d %H:%M:%S')\n# Assuming you have a cursor named cursor you want to execute this query on:\ncursor.execute('insert into table(id, date_created) values(%s, %s)', (id, formatted_date))" }, { "code": null, "e": 1697, "s": 1629, "text": "Running this will try to insert the tuple (id, date) in your table." }, { "code": null, "e": 1838, "s": 1697, "text": "When you fetch a date from a database using a select query, you'll need to parse it back to a datetime object using functions like strptime." }, { "code": null, "e": 2256, "s": 1838, "text": "from datetime import datetime\n# Assuming you have a cursor named cursor you want to execute this query on:\ncursor.execute('select id, date_created from table where id=1')\n# if you inserted the row above, you can get it back like this\nid, date_str = cursor.fetchone()\n# date is returned as a string in format we sent it as. So parse it using strptime\ncreated_date = datetime.strptime(date_created, '%Y-%m-%d %H:%M:%S')" }, { "code": null, "e": 2322, "s": 2256, "text": "This will get the created date and parse it to a datetime object." } ]
User-defined variables vs Local Variables in MySQL?
The user defined variable is also known as session-specific variable. It is a type of loosely typed variable which can be initialized somewhere in session and contains the value of user defined variable until session ends. The user defined variable is prefixed with symbol @. For Example: @anyVariableName; There are two approaches by which you can initialize the user-defined variable. You can use SET command or using SELECT query. The first approach is as follows: SET @anyVariableName=anyValue; The second approach is as follows: SELECT @anyVariableName :=anyValue; If you do not use colon (:) in SELECT query then it evaluates it as expression. The result will either be true or false: mysql> select @m=10; The following is the output: +-------+ | @m=10 | +-------+ | 1 | +-------+ 1 row in set (0.00 sec) Local variable can be used in stored procedure, function etc. It is used with the DECLARE keyword. No @ prefix like user-defined variable is needed. The syntax is as follows to local variables. DECLARE yourVariableName dataType; NOTE: The main difference between local variables and user-defined variable is that local variable is reinitialized with NULL value each time whenever stored procedure is called while session-specific variable or user-defined variable does not reinitialized with NULL. A user-defined variable set by one user can not be seen by other user.Whatever session variable for a given user is automatically destroyed when user exits. Here is the demo of session-specific variable and local variable with stored procedure. The query to create a stored procedure with local variable and user-defined variable is as follows: mysql> DELIMITER // mysql> CREATE PROCEDURE sp_LocalAndUserDefinedVariableDemo() -> BEGIN -> DECLARE localVariable int default 10; -> SET localVariable=localVariable+10; -> SET @userVariable=@userVariable+10; -> SELECT localVariable; -> SELECT @userVariable; -> END; -> // Query OK, 0 rows affected (0.39 sec) mysql> DELIMITER ; Now set the value for user-defined variable. The query is as follows: mysql> SET @userVariable=10; Query OK, 0 rows affected (0.00 sec) Now call the stored procedure. In first call, the user-defined variable will be 10+10=20 while local variable will 10+10=20. Call the stored procedure using call command: mysql> CALL sp_LocalAndUserDefinedVariableDemo(); The following is the output: +---------------+ | localVariable | +---------------+ | 20 | +---------------+ 1 row in set (0.32 sec) +---------------+ | @userVariable | +---------------+ | 20 | +---------------+ 1 row in set (0.34 sec) Query OK, 0 rows affected (0.36 sec) In second call, the user-defined variable will hold value 20 and add 10 like 20+10=30 while local variable again reinitialized with 10 and add 10 like 10+10=20. Call the stored procedure and check the sample output: mysql> CALL sp_LocalAndUserDefinedVariableDemo(); The following is the output: +---------------+ | localVariable | +---------------+ | 20 | +---------------+ 1 row in set (0.00 sec) +---------------+ | @userVariable | +---------------+ | 30 | +---------------+ 1 row in set (0.01 sec) Query OK, 0 rows affected (0.02 sec) In the third call, the user-defined variable will hold value 30 and add 10 like 30+10=40 while local variable again reinitialized with 10 and add 10 like 10+10=20. Now you can say that in every procedure call local variable is re-initialized with some value which may be NULL or some other value like in my case I have provided default value which is 10. This means it sets the local variable with value 10 in every procedure call while user defined variable does not.
[ { "code": null, "e": 1285, "s": 1062, "text": "The user defined variable is also known as session-specific variable. It is a type of loosely typed variable which can be initialized somewhere in session and contains the value of user defined variable until session ends." }, { "code": null, "e": 1351, "s": 1285, "text": "The user defined variable is prefixed with symbol @. For Example:" }, { "code": null, "e": 1369, "s": 1351, "text": "@anyVariableName;" }, { "code": null, "e": 1530, "s": 1369, "text": "There are two approaches by which you can initialize the user-defined variable. You can use SET command or using SELECT query. The first approach is as follows:" }, { "code": null, "e": 1561, "s": 1530, "text": "SET @anyVariableName=anyValue;" }, { "code": null, "e": 1596, "s": 1561, "text": "The second approach is as follows:" }, { "code": null, "e": 1632, "s": 1596, "text": "SELECT @anyVariableName :=anyValue;" }, { "code": null, "e": 1753, "s": 1632, "text": "If you do not use colon (:) in SELECT query then it evaluates it as expression. The result will either be true or false:" }, { "code": null, "e": 1774, "s": 1753, "text": "mysql> select @m=10;" }, { "code": null, "e": 1803, "s": 1774, "text": "The following is the output:" }, { "code": null, "e": 1877, "s": 1803, "text": "+-------+\n| @m=10 |\n+-------+\n| 1 |\n+-------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 2026, "s": 1877, "text": "Local variable can be used in stored procedure, function etc. It is used with the DECLARE keyword. No @ prefix like user-defined variable is needed." }, { "code": null, "e": 2071, "s": 2026, "text": "The syntax is as follows to local variables." }, { "code": null, "e": 2106, "s": 2071, "text": "DECLARE yourVariableName dataType;" }, { "code": null, "e": 2532, "s": 2106, "text": "NOTE: The main difference between local variables and user-defined variable is that local variable is reinitialized with NULL value each time whenever stored procedure is called while session-specific variable or user-defined variable does not reinitialized with NULL. A user-defined variable set by one user can not be seen by other user.Whatever session variable for a given user is automatically destroyed when user exits." }, { "code": null, "e": 2720, "s": 2532, "text": "Here is the demo of session-specific variable and local variable with stored procedure. The query to create a stored procedure with local variable and user-defined variable is as follows:" }, { "code": null, "e": 3075, "s": 2720, "text": "mysql> DELIMITER //\nmysql> CREATE PROCEDURE sp_LocalAndUserDefinedVariableDemo()\n -> BEGIN\n -> DECLARE localVariable int default 10;\n -> SET localVariable=localVariable+10; \n -> SET @userVariable=@userVariable+10;\n -> SELECT localVariable;\n -> SELECT @userVariable;\n -> END;\n -> //\nQuery OK, 0 rows affected (0.39 sec)\nmysql> DELIMITER ;" }, { "code": null, "e": 3145, "s": 3075, "text": "Now set the value for user-defined variable. The query is as follows:" }, { "code": null, "e": 3211, "s": 3145, "text": "mysql> SET @userVariable=10;\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 3336, "s": 3211, "text": "Now call the stored procedure. In first call, the user-defined variable will be 10+10=20 while local variable will 10+10=20." }, { "code": null, "e": 3382, "s": 3336, "text": "Call the stored procedure using call command:" }, { "code": null, "e": 3432, "s": 3382, "text": "mysql> CALL sp_LocalAndUserDefinedVariableDemo();" }, { "code": null, "e": 3461, "s": 3432, "text": "The following is the output:" }, { "code": null, "e": 3726, "s": 3461, "text": "+---------------+\n| localVariable |\n+---------------+\n| 20 |\n+---------------+\n1 row in set (0.32 sec)\n+---------------+\n| @userVariable |\n+---------------+\n| 20 |\n+---------------+\n1 row in set (0.34 sec)\nQuery OK, 0 rows affected (0.36 sec)" }, { "code": null, "e": 3887, "s": 3726, "text": "In second call, the user-defined variable will hold value 20 and add 10 like 20+10=30 while local variable again reinitialized with 10 and add 10 like 10+10=20." }, { "code": null, "e": 3942, "s": 3887, "text": "Call the stored procedure and check the sample output:" }, { "code": null, "e": 3992, "s": 3942, "text": "mysql> CALL sp_LocalAndUserDefinedVariableDemo();" }, { "code": null, "e": 4021, "s": 3992, "text": "The following is the output:" }, { "code": null, "e": 4286, "s": 4021, "text": "+---------------+\n| localVariable |\n+---------------+\n| 20 |\n+---------------+\n1 row in set (0.00 sec)\n+---------------+\n| @userVariable |\n+---------------+\n| 30 |\n+---------------+\n1 row in set (0.01 sec)\nQuery OK, 0 rows affected (0.02 sec)" }, { "code": null, "e": 4450, "s": 4286, "text": "In the third call, the user-defined variable will hold value 30 and add 10 like 30+10=40 while local variable again reinitialized with 10 and add 10 like 10+10=20." }, { "code": null, "e": 4755, "s": 4450, "text": "Now you can say that in every procedure call local variable is re-initialized with some value which may be NULL or some other value like in my case I have provided default value which is 10. This means it sets the local variable with value 10 in every procedure call while user defined variable does not." } ]
What would be a query to remove \n\r from the text in MySQL?
To remove \n\r from the text, you need to use REPLACE command. The syntax is as follows − UPDATE yourTableName SET yourColumnName=REPLACE(yourColumnName,’\r\n’,’ ‘); To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table removeDemo -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Name text, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.79 sec) Now insert some records in the table using insert command. The query is as follows − mysql> insert into removeDemo(Name) values('John\r\nSmithCarol'); Query OK, 1 row affected (0.13 sec) mysql> insert into removeDemo(Name) values('LarryMike\r\nSam'); Query OK, 1 row affected (0.34 sec) mysql> insert into removeDemo(Name) values('David\r\nBobJames'); Query OK, 1 row affected (0.10 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from removeDemo; The following is the output in a format that includes \r\n, therefore the output isn’t looking properly formatted − +----+------------------+ | Id | Name | +----+------------------+ | 1 | John SmithCarol | | 2 | LarryMike Sam | | 3 | David BobJames | +----+------------------+ 3 rows in set (0.00 sec) Here is the query to remove \r\n from text − mysql> update removeDemo set Name=replace(Name,'\r\n',''); Query OK, 3 rows affected (0.12 sec) Rows matched: 3 Changed: 3 Warnings: 0 Now check the table records once again. The query is as follows − mysql> select *from removeDemo; The following is the output − +----+----------------+ | Id | Name | +----+----------------+ | 1 | JohnSmithCarol | | 2 | LarryMikeSam | | 3 | DavidBobJames | +----+----------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1152, "s": 1062, "text": "To remove \\n\\r from the text, you need to use REPLACE command. The syntax is as follows −" }, { "code": null, "e": 1228, "s": 1152, "text": "UPDATE yourTableName SET yourColumnName=REPLACE(yourColumnName,’\\r\\n’,’ ‘);" }, { "code": null, "e": 1327, "s": 1228, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1474, "s": 1327, "text": "mysql> create table removeDemo\n-> (\n-> Id int NOT NULL AUTO_INCREMENT,\n-> Name text,\n-> PRIMARY KEY(Id)\n-> );\nQuery OK, 0 rows affected (0.79 sec)" }, { "code": null, "e": 1559, "s": 1474, "text": "Now insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 1862, "s": 1559, "text": "mysql> insert into removeDemo(Name) values('John\\r\\nSmithCarol');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into removeDemo(Name) values('LarryMike\\r\\nSam');\nQuery OK, 1 row affected (0.34 sec)\nmysql> insert into removeDemo(Name) values('David\\r\\nBobJames');\nQuery OK, 1 row affected (0.10 sec)" }, { "code": null, "e": 1947, "s": 1862, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 1979, "s": 1947, "text": "mysql> select *from removeDemo;" }, { "code": null, "e": 2095, "s": 1979, "text": "The following is the output in a format that includes \\r\\n, therefore the output isn’t looking properly formatted −" }, { "code": null, "e": 2302, "s": 2095, "text": "+----+------------------+\n| Id | Name |\n+----+------------------+\n| 1 | John SmithCarol |\n| 2 | LarryMike Sam |\n| 3 | David BobJames |\n+----+------------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2347, "s": 2302, "text": "Here is the query to remove \\r\\n from text −" }, { "code": null, "e": 2482, "s": 2347, "text": "mysql> update removeDemo set Name=replace(Name,'\\r\\n','');\nQuery OK, 3 rows affected (0.12 sec)\nRows matched: 3 Changed: 3 Warnings: 0" }, { "code": null, "e": 2548, "s": 2482, "text": "Now check the table records once again. The query is as follows −" }, { "code": null, "e": 2580, "s": 2548, "text": "mysql> select *from removeDemo;" }, { "code": null, "e": 2610, "s": 2580, "text": "The following is the output −" }, { "code": null, "e": 2803, "s": 2610, "text": "+----+----------------+\n| Id | Name |\n+----+----------------+\n| 1 | JohnSmithCarol |\n| 2 | LarryMikeSam |\n| 3 | DavidBobJames |\n+----+----------------+\n3 rows in set (0.00 sec)" } ]
C Program For Flattening A Multilevel Linked List - GeeksforGeeks
22 Dec, 2021 Given a linked list where in addition to the next pointer, each node has a child pointer, which may or may not point to a separate list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in below figure.You are given the head of the first level of the list. Flatten the list so that all the nodes appear in a single-level linked list. You need to flatten the list in way that all nodes at first level should come first, then nodes of second level, and so on.Each node is a C struct with the following definition. C struct List{ int data; struct List *next; struct List *child;}; The above list should be converted to 10->5->12->7->11->4->20->13->17->6->2->16->9->8->3->19->15 The problem clearly says that we need to flatten level by level. The idea of a solution is, we start from the first level, process all nodes one by one, if a node has a child, then we append the child at the end of the list, otherwise, we don’t do anything. After the first level is processed, all next-level nodes will be appended after the first level. The same process is followed for the appended nodes. 1) Take "cur" pointer, which will point to head of the first level of the list 2) Take "tail" pointer, which will point to end of the first level of the list 3) Repeat the below procedure while "curr" is not NULL. I) if current node has a child then a) append this new child list to the "tail" tail->next = cur->child b) find the last node of new child list and update "tail" tmp = cur->child; while (tmp->next != NULL) tmp = tmp->next; tail = tmp; II) move to the next node. i.e. cur = cur->next Following is the implementation of the above algorithm. C // Program to flatten list with next // and child pointers#include <stdio.h>#include <stdlib.h> // Macro to find number of elements // in array#define SIZE(arr) (sizeof(arr)/ sizeof(arr[0])) // A linked list node has data, // next pointer and child pointerstruct Node{ int data; struct Node *next; struct Node *child;}; // A utility function to create a linked list // with n nodes. The data of nodes is taken // from arr[]. All child pointers are set as NULLstruct Node *createList(int *arr, int n){ struct Node *head = NULL; struct Node *p; int i; for (i = 0; i < n; ++i) { if (head == NULL) head = p = (struct Node *)malloc(sizeof(*p)); else { p->next = (struct Node *)malloc(sizeof(*p)); p = p->next; } p->data = arr[i]; p->next = p->child = NULL; } return head;} // A utility function to print all nodes // of a linked listvoid printList(struct Node *head){ while (head != NULL) { printf("%d ", head->data); head = head->next; } printf("");} // This function creates the input list. // The created list is same as shown in // the above figurestruct Node *createList(void){ int arr1[] = {10, 5, 12, 7, 11}; int arr2[] = {4, 20, 13}; int arr3[] = {17, 6}; int arr4[] = {9, 8}; int arr5[] = {19, 15}; int arr6[] = {2}; int arr7[] = {16}; int arr8[] = {3}; // Create 8 linked lists struct Node *head1 = createList(arr1, SIZE(arr1)); struct Node *head2 = createList(arr2, SIZE(arr2)); struct Node *head3 = createList(arr3, SIZE(arr3)); struct Node *head4 = createList(arr4, SIZE(arr4)); struct Node *head5 = createList(arr5, SIZE(arr5)); struct Node *head6 = createList(arr6, SIZE(arr6)); struct Node *head7 = createList(arr7, SIZE(arr7)); struct Node *head8 = createList(arr8, SIZE(arr8)); // Modify child pointers to create the // list shown above head1->child = head2; head1->next->next->next->child = head3; head3->child = head4; head4->child = head5; head2->next->child = head6; head2->next->next->child = head7; head7->child = head8; /* Return head pointer of first linked list. Note that all nodes are reachable from head1 */ return head1;} /* The main function that flattens a multilevel linked list */void flattenList(struct Node *head){ // Base case if (head == NULL) return; struct Node *tmp; /* Find tail node of first level linked list */ struct Node *tail = head; while (tail->next != NULL) tail = tail->next; // One by one traverse through all nodes // of first level linked list till we // reach the tail node struct Node *cur = head; while (cur != tail) { // If current node has a child if (cur->child) { // then append the child at the // end of current list tail->next = cur->child; // and update the tail to new // last node tmp = cur->child; while (tmp->next) tmp = tmp->next; tail = tmp; } // Change current node cur = cur->next; }} // Driver codeint main(void){ struct Node *head = NULL; head = createList(); flattenList(head); printList(head); return 0;} Output: 10 5 12 7 11 4 20 13 17 6 2 16 9 8 3 19 15 Time Complexity: Since every node is visited at most twice, the time complexity is O(n) where n is the number of nodes in given linked list. Please refer complete article on Flatten a multilevel linked list for more details! Linked Lists C Language C Programs Linked List Linked List 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 'this' pointer in C++ UDP Server-Client implementation in C Strings in C UDP Server-Client implementation in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File Header files in C/C++ and its uses
[ { "code": null, "e": 24286, "s": 24258, "text": "\n22 Dec, 2021" }, { "code": null, "e": 24871, "s": 24286, "text": "Given a linked list where in addition to the next pointer, each node has a child pointer, which may or may not point to a separate list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in below figure.You are given the head of the first level of the list. Flatten the list so that all the nodes appear in a single-level linked list. You need to flatten the list in way that all nodes at first level should come first, then nodes of second level, and so on.Each node is a C struct with the following definition." }, { "code": null, "e": 24873, "s": 24871, "text": "C" }, { "code": "struct List{ int data; struct List *next; struct List *child;};", "e": 24946, "s": 24873, "text": null }, { "code": null, "e": 25043, "s": 24946, "text": "The above list should be converted to 10->5->12->7->11->4->20->13->17->6->2->16->9->8->3->19->15" }, { "code": null, "e": 25452, "s": 25043, "text": "The problem clearly says that we need to flatten level by level. The idea of a solution is, we start from the first level, process all nodes one by one, if a node has a child, then we append the child at the end of the list, otherwise, we don’t do anything. After the first level is processed, all next-level nodes will be appended after the first level. The same process is followed for the appended nodes. " }, { "code": null, "e": 26009, "s": 25452, "text": "1) Take \"cur\" pointer, which will point to head of the first level of the list\n2) Take \"tail\" pointer, which will point to end of the first level of the list\n3) Repeat the below procedure while \"curr\" is not NULL.\n I) if current node has a child then\n a) append this new child list to the \"tail\"\n tail->next = cur->child\n b) find the last node of new child list and update \"tail\"\n tmp = cur->child;\n while (tmp->next != NULL)\n tmp = tmp->next;\n tail = tmp;\n II) move to the next node. i.e. cur = cur->next" }, { "code": null, "e": 26066, "s": 26009, "text": "Following is the implementation of the above algorithm. " }, { "code": null, "e": 26068, "s": 26066, "text": "C" }, { "code": "// Program to flatten list with next // and child pointers#include <stdio.h>#include <stdlib.h> // Macro to find number of elements // in array#define SIZE(arr) (sizeof(arr)/ sizeof(arr[0])) // A linked list node has data, // next pointer and child pointerstruct Node{ int data; struct Node *next; struct Node *child;}; // A utility function to create a linked list // with n nodes. The data of nodes is taken // from arr[]. All child pointers are set as NULLstruct Node *createList(int *arr, int n){ struct Node *head = NULL; struct Node *p; int i; for (i = 0; i < n; ++i) { if (head == NULL) head = p = (struct Node *)malloc(sizeof(*p)); else { p->next = (struct Node *)malloc(sizeof(*p)); p = p->next; } p->data = arr[i]; p->next = p->child = NULL; } return head;} // A utility function to print all nodes // of a linked listvoid printList(struct Node *head){ while (head != NULL) { printf(\"%d \", head->data); head = head->next; } printf(\"\");} // This function creates the input list. // The created list is same as shown in // the above figurestruct Node *createList(void){ int arr1[] = {10, 5, 12, 7, 11}; int arr2[] = {4, 20, 13}; int arr3[] = {17, 6}; int arr4[] = {9, 8}; int arr5[] = {19, 15}; int arr6[] = {2}; int arr7[] = {16}; int arr8[] = {3}; // Create 8 linked lists struct Node *head1 = createList(arr1, SIZE(arr1)); struct Node *head2 = createList(arr2, SIZE(arr2)); struct Node *head3 = createList(arr3, SIZE(arr3)); struct Node *head4 = createList(arr4, SIZE(arr4)); struct Node *head5 = createList(arr5, SIZE(arr5)); struct Node *head6 = createList(arr6, SIZE(arr6)); struct Node *head7 = createList(arr7, SIZE(arr7)); struct Node *head8 = createList(arr8, SIZE(arr8)); // Modify child pointers to create the // list shown above head1->child = head2; head1->next->next->next->child = head3; head3->child = head4; head4->child = head5; head2->next->child = head6; head2->next->next->child = head7; head7->child = head8; /* Return head pointer of first linked list. Note that all nodes are reachable from head1 */ return head1;} /* The main function that flattens a multilevel linked list */void flattenList(struct Node *head){ // Base case if (head == NULL) return; struct Node *tmp; /* Find tail node of first level linked list */ struct Node *tail = head; while (tail->next != NULL) tail = tail->next; // One by one traverse through all nodes // of first level linked list till we // reach the tail node struct Node *cur = head; while (cur != tail) { // If current node has a child if (cur->child) { // then append the child at the // end of current list tail->next = cur->child; // and update the tail to new // last node tmp = cur->child; while (tmp->next) tmp = tmp->next; tail = tmp; } // Change current node cur = cur->next; }} // Driver codeint main(void){ struct Node *head = NULL; head = createList(); flattenList(head); printList(head); return 0;}", "e": 29747, "s": 26068, "text": null }, { "code": null, "e": 29755, "s": 29747, "text": "Output:" }, { "code": null, "e": 29798, "s": 29755, "text": "10 5 12 7 11 4 20 13 17 6 2 16 9 8 3 19 15" }, { "code": null, "e": 29939, "s": 29798, "text": "Time Complexity: Since every node is visited at most twice, the time complexity is O(n) where n is the number of nodes in given linked list." }, { "code": null, "e": 30023, "s": 29939, "text": "Please refer complete article on Flatten a multilevel linked list for more details!" }, { "code": null, "e": 30036, "s": 30023, "text": "Linked Lists" }, { "code": null, "e": 30047, "s": 30036, "text": "C Language" }, { "code": null, "e": 30058, "s": 30047, "text": "C Programs" }, { "code": null, "e": 30070, "s": 30058, "text": "Linked List" }, { "code": null, "e": 30082, "s": 30070, "text": "Linked List" }, { "code": null, "e": 30180, "s": 30082, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30189, "s": 30180, "text": "Comments" }, { "code": null, "e": 30202, "s": 30189, "text": "Old Comments" }, { "code": null, "e": 30240, "s": 30202, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 30266, "s": 30240, "text": "Exception Handling in C++" }, { "code": null, "e": 30286, "s": 30266, "text": "Multithreading in C" }, { "code": null, "e": 30308, "s": 30286, "text": "'this' pointer in C++" }, { "code": null, "e": 30346, "s": 30308, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 30359, "s": 30346, "text": "Strings in C" }, { "code": null, "e": 30397, "s": 30359, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 30438, "s": 30397, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 30479, "s": 30438, "text": "C Program to read contents of Whole File" } ]
How to set axis ticks in multiples of pi in Python Matplotlib?
To set axis ticks in multiples of pi in Python, we take following steps − Initialize a pi variable, create theta and y data points using numpy. Initialize a pi variable, create theta and y data points using numpy. Plot theta and y using plot() method. Plot theta and y using plot() method. Get or set the current tick locations and labels of the X-axis using xticks() method. Get or set the current tick locations and labels of the X-axis using xticks() method. Convenience method to set or retrieve autoscaling margins using margins() method. Convenience method to set or retrieve autoscaling margins using margins() method. To display the figure, use show() method. To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True pi = np.pi theta = np.arange(-2 * pi, 2 * pi+pi/2, step=(pi / 2)) y = np.sin(theta) plt.plot(theta, y) plt.xticks(theta, ['-2π', '-3π/2', 'π', '-π/2', '0', 'π/2', 'π', '3π/2', '2π']) plt.margins(x=0) plt.show()
[ { "code": null, "e": 1136, "s": 1062, "text": "To set axis ticks in multiples of pi in Python, we take following steps −" }, { "code": null, "e": 1206, "s": 1136, "text": "Initialize a pi variable, create theta and y data points using numpy." }, { "code": null, "e": 1276, "s": 1206, "text": "Initialize a pi variable, create theta and y data points using numpy." }, { "code": null, "e": 1314, "s": 1276, "text": "Plot theta and y using plot() method." }, { "code": null, "e": 1352, "s": 1314, "text": "Plot theta and y using plot() method." }, { "code": null, "e": 1438, "s": 1352, "text": "Get or set the current tick locations and labels of the X-axis using xticks() method." }, { "code": null, "e": 1524, "s": 1438, "text": "Get or set the current tick locations and labels of the X-axis using xticks() method." }, { "code": null, "e": 1606, "s": 1524, "text": "Convenience method to set or retrieve autoscaling margins using margins() method." }, { "code": null, "e": 1688, "s": 1606, "text": "Convenience method to set or retrieve autoscaling margins using margins() method." }, { "code": null, "e": 1730, "s": 1688, "text": "To display the figure, use show() method." }, { "code": null, "e": 1772, "s": 1730, "text": "To display the figure, use show() method." }, { "code": null, "e": 2127, "s": 1772, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\npi = np.pi\ntheta = np.arange(-2 * pi, 2 * pi+pi/2, step=(pi / 2))\ny = np.sin(theta)\n\nplt.plot(theta, y)\nplt.xticks(theta, ['-2π', '-3π/2', 'π', '-π/2', '0', 'π/2', 'π', '3π/2', '2π'])\nplt.margins(x=0)\nplt.show()" } ]
C# Program to Demonstrate the Example of LINQ Union() Method with StringComparer - GeeksforGeeks
08 Dec, 2021 LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives a feature to .NET languages to create queries to retrieve data from the data source. Here in this article, we will demonstrate the example of the LINQ Union() method with the StringComparer. 1. Union() Method: This method is used to get the unique elements from the given lists. Or we can say that this method returns the union of two lists. The function takes two lists as input and then it will get the elements only once in repeating elements. Syntax: data1.Union(data2) Where data1 is the first list and data2 is the second list. 2. StringComparer: It is a class that is used to compare the strings that use some specific case or ordinal comparison rules. We can use this StringComparer in the Union() function to get the elements with string(case sensitive). It will compare the strings from the two lists and return the strings. Syntax: StringComparer.OrdinalIgnoreCase If we are using union() function with StringComparer, then we have to first use Union() function then apply stringcomparer function with the given syntax. Syntax: data1.Union(data2, StringComparer.OrdinalIgnoreCase); Where data1 is the second list and data2 is the second list. Example: Input: { "Hello", "Geeks", "For", "Geeks" }; { "Hello", "geeks" , "python" } Output: Hello Geeks For python Input: { "Hello", "Geeks" } { "Hello", "geeks" , "python" }; Output: Hello Geeks python Approach: 1. Create two lists of string types named data1 and data2. 2. Perform the Union Operation with StringComparer data1.Union(data2, StringComparer.OrdinalIgnoreCase); 3. Display the results using foreach loop foreach(var j in final) { Console.WriteLine(j + " "); } Example: C# // C# program to illustrate how to use// Union() Method with StringComparer in LINQusing System;using System.Linq;using System.Collections.Generic; class GFG{ static void Main(string[] args){ // Create first list with 4 elements List<string> data1 = new List<string>(){ "Hello", "Geeks", "For", "Geeks" }; // Create first list with 3 elements List<string> data2 = new List<string>(){ "Hello", "geeks", "python" }; // Perform union operation var final = data1.Union(data2, StringComparer.OrdinalIgnoreCase); // Display the result foreach(var j in final) { Console.WriteLine(j + " "); }}} Output: Hello Geeks For python sweetyty CSharp LINQ Picked C# C# Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Extension Method in C# Top 50 C# Interview Questions & Answers HashSet in C# with Examples C# | How to insert an element in an Array? Partial Classes in C# Convert String to Character Array in C# Socket Programming in C# Getting a Month Name Using Month Number in C# Program to Print a New Line in C# Program to find absolute value of a given number
[ { "code": null, "e": 24302, "s": 24274, "text": "\n08 Dec, 2021" }, { "code": null, "e": 24579, "s": 24302, "text": "LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives a feature to .NET languages to create queries to retrieve data from the data source. Here in this article, we will demonstrate the example of the LINQ Union() method with the StringComparer." }, { "code": null, "e": 24835, "s": 24579, "text": "1. Union() Method: This method is used to get the unique elements from the given lists. Or we can say that this method returns the union of two lists. The function takes two lists as input and then it will get the elements only once in repeating elements." }, { "code": null, "e": 24843, "s": 24835, "text": "Syntax:" }, { "code": null, "e": 24862, "s": 24843, "text": "data1.Union(data2)" }, { "code": null, "e": 24922, "s": 24862, "text": "Where data1 is the first list and data2 is the second list." }, { "code": null, "e": 25223, "s": 24922, "text": "2. StringComparer: It is a class that is used to compare the strings that use some specific case or ordinal comparison rules. We can use this StringComparer in the Union() function to get the elements with string(case sensitive). It will compare the strings from the two lists and return the strings." }, { "code": null, "e": 25231, "s": 25223, "text": "Syntax:" }, { "code": null, "e": 25264, "s": 25231, "text": "StringComparer.OrdinalIgnoreCase" }, { "code": null, "e": 25419, "s": 25264, "text": "If we are using union() function with StringComparer, then we have to first use Union() function then apply stringcomparer function with the given syntax." }, { "code": null, "e": 25427, "s": 25419, "text": "Syntax:" }, { "code": null, "e": 25481, "s": 25427, "text": "data1.Union(data2, StringComparer.OrdinalIgnoreCase);" }, { "code": null, "e": 25542, "s": 25481, "text": "Where data1 is the second list and data2 is the second list." }, { "code": null, "e": 25551, "s": 25542, "text": "Example:" }, { "code": null, "e": 25768, "s": 25551, "text": "Input: { \"Hello\", \"Geeks\", \"For\", \"Geeks\" };\n { \"Hello\", \"geeks\" , \"python\" }\nOutput:\nHello \nGeeks \nFor \npython \n\nInput: { \"Hello\", \"Geeks\" }\n { \"Hello\", \"geeks\" , \"python\" };\nOutput:\nHello \nGeeks \npython" }, { "code": null, "e": 25778, "s": 25768, "text": "Approach:" }, { "code": null, "e": 25837, "s": 25778, "text": "1. Create two lists of string types named data1 and data2." }, { "code": null, "e": 25888, "s": 25837, "text": "2. Perform the Union Operation with StringComparer" }, { "code": null, "e": 25942, "s": 25888, "text": "data1.Union(data2, StringComparer.OrdinalIgnoreCase);" }, { "code": null, "e": 25984, "s": 25942, "text": "3. Display the results using foreach loop" }, { "code": null, "e": 26045, "s": 25984, "text": "foreach(var j in final)\n{\n Console.WriteLine(j + \" \");\n} " }, { "code": null, "e": 26054, "s": 26045, "text": "Example:" }, { "code": null, "e": 26057, "s": 26054, "text": "C#" }, { "code": "// C# program to illustrate how to use// Union() Method with StringComparer in LINQusing System;using System.Linq;using System.Collections.Generic; class GFG{ static void Main(string[] args){ // Create first list with 4 elements List<string> data1 = new List<string>(){ \"Hello\", \"Geeks\", \"For\", \"Geeks\" }; // Create first list with 3 elements List<string> data2 = new List<string>(){ \"Hello\", \"geeks\", \"python\" }; // Perform union operation var final = data1.Union(data2, StringComparer.OrdinalIgnoreCase); // Display the result foreach(var j in final) { Console.WriteLine(j + \" \"); }}}", "e": 26738, "s": 26057, "text": null }, { "code": null, "e": 26746, "s": 26738, "text": "Output:" }, { "code": null, "e": 26773, "s": 26746, "text": "Hello \nGeeks \nFor \npython " }, { "code": null, "e": 26782, "s": 26773, "text": "sweetyty" }, { "code": null, "e": 26794, "s": 26782, "text": "CSharp LINQ" }, { "code": null, "e": 26801, "s": 26794, "text": "Picked" }, { "code": null, "e": 26804, "s": 26801, "text": "C#" }, { "code": null, "e": 26816, "s": 26804, "text": "C# Programs" }, { "code": null, "e": 26914, "s": 26816, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26923, "s": 26914, "text": "Comments" }, { "code": null, "e": 26936, "s": 26923, "text": "Old Comments" }, { "code": null, "e": 26959, "s": 26936, "text": "Extension Method in C#" }, { "code": null, "e": 26999, "s": 26959, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27027, "s": 26999, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27070, "s": 27027, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27092, "s": 27070, "text": "Partial Classes in C#" }, { "code": null, "e": 27132, "s": 27092, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 27157, "s": 27132, "text": "Socket Programming in C#" }, { "code": null, "e": 27203, "s": 27157, "text": "Getting a Month Name Using Month Number in C#" }, { "code": null, "e": 27237, "s": 27203, "text": "Program to Print a New Line in C#" } ]
HTML | input value Attribute - GeeksforGeeks
16 Apr, 2019 The value attribute for <input> element in HTML is used to specify the initial value of the input element. It has different meaning for different input type: The “button”, “reset” and “submit” property specifies the text on the button. The “text”, “password” and “hidden” property specifies the initial value of the input field. The “checkbox”, “radio” and “image” property specifies the value associated with the input. Syntax: <input value = "text"> Attribute Value: It contains single value text which specifies the value of input element. Example 1: This example describes the <input> value attribute. <!DOCTYPE html><html> <head> <title>HTML input value Attribute</title></head> <body style = "text-align:center"> <h1 style = "color:green;"> GeeksforGeeks </h1> <h2> HTML input value Attribute </h2> Input: <input type = "text" value = "GeeksforGeeks"></body> </html> Output: Example 2: This example describes the <input> value attribute. <!DOCTYPE html><html> <head> <title>HTML input value Attribute</title></head> <body style = "text-align:center"> <h1 style = "color:green;"> GeeksforGeeks </h1> <h2> HTML input value Attribute </h2> <input type = "button" value = "Submit"></body> </html> Output: Supported Browsers: The browser supported by <input> value attribute are listed below: Apple Safari 1.0 Google Chrome 1.0 Firefox 1.0 Opera 1.0 Internet Explorer 2.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? How to Insert Form Data into Database using PHP ? REST API (Introduction) Types of CSS (Cascading Style Sheet) Form validation using HTML and JavaScript Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24716, "s": 24688, "text": "\n16 Apr, 2019" }, { "code": null, "e": 24874, "s": 24716, "text": "The value attribute for <input> element in HTML is used to specify the initial value of the input element. It has different meaning for different input type:" }, { "code": null, "e": 24952, "s": 24874, "text": "The “button”, “reset” and “submit” property specifies the text on the button." }, { "code": null, "e": 25045, "s": 24952, "text": "The “text”, “password” and “hidden” property specifies the initial value of the input field." }, { "code": null, "e": 25137, "s": 25045, "text": "The “checkbox”, “radio” and “image” property specifies the value associated with the input." }, { "code": null, "e": 25145, "s": 25137, "text": "Syntax:" }, { "code": null, "e": 25168, "s": 25145, "text": "<input value = \"text\">" }, { "code": null, "e": 25259, "s": 25168, "text": "Attribute Value: It contains single value text which specifies the value of input element." }, { "code": null, "e": 25322, "s": 25259, "text": "Example 1: This example describes the <input> value attribute." }, { "code": "<!DOCTYPE html><html> <head> <title>HTML input value Attribute</title></head> <body style = \"text-align:center\"> <h1 style = \"color:green;\"> GeeksforGeeks </h1> <h2> HTML input value Attribute </h2> Input: <input type = \"text\" value = \"GeeksforGeeks\"></body> </html> ", "e": 25682, "s": 25322, "text": null }, { "code": null, "e": 25690, "s": 25682, "text": "Output:" }, { "code": null, "e": 25753, "s": 25690, "text": "Example 2: This example describes the <input> value attribute." }, { "code": "<!DOCTYPE html><html> <head> <title>HTML input value Attribute</title></head> <body style = \"text-align:center\"> <h1 style = \"color:green;\"> GeeksforGeeks </h1> <h2> HTML input value Attribute </h2> <input type = \"button\" value = \"Submit\"></body> </html>", "e": 26071, "s": 25753, "text": null }, { "code": null, "e": 26079, "s": 26071, "text": "Output:" }, { "code": null, "e": 26166, "s": 26079, "text": "Supported Browsers: The browser supported by <input> value attribute are listed below:" }, { "code": null, "e": 26183, "s": 26166, "text": "Apple Safari 1.0" }, { "code": null, "e": 26201, "s": 26183, "text": "Google Chrome 1.0" }, { "code": null, "e": 26213, "s": 26201, "text": "Firefox 1.0" }, { "code": null, "e": 26223, "s": 26213, "text": "Opera 1.0" }, { "code": null, "e": 26245, "s": 26223, "text": "Internet Explorer 2.0" }, { "code": null, "e": 26382, "s": 26245, "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": 26398, "s": 26382, "text": "HTML-Attributes" }, { "code": null, "e": 26403, "s": 26398, "text": "HTML" }, { "code": null, "e": 26420, "s": 26403, "text": "Web Technologies" }, { "code": null, "e": 26425, "s": 26420, "text": "HTML" }, { "code": null, "e": 26523, "s": 26425, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26571, "s": 26523, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26621, "s": 26571, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26645, "s": 26621, "text": "REST API (Introduction)" }, { "code": null, "e": 26682, "s": 26645, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 26724, "s": 26682, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 26766, "s": 26724, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26799, "s": 26766, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26842, "s": 26799, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26887, "s": 26842, "text": "Convert a string to an integer in JavaScript" } ]
File.WriteAllLines(String, String[], Encoding) Method in C# with Examples - GeeksforGeeks
09 Mar, 2021 File.WriteAllLines(String, String[], Encoding) is an inbuilt File class method that is used to create a new file, writes the specified string array to the file by using the specified encoding, and then closes the file.Syntax: public static void WriteAllLines (string path, string[] contents, System.Text.Encoding encoding); Parameter: This function accepts three parameters which are illustrated below: path: This is the specified file where specified string array are going to be written. contents: This is the specified string array to write to the file. encoding: This represents the character encoding applied to the string array. Exceptions: ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars. ArgumentNullException: Either path or contents are null. PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length. DirectoryNotFoundException: The specified path is invalid. IOException: An I/O error occurred while opening the file. UnauthorizedAccessException: The path specified a file that is read-only. OR the path specified a file that is hidden. OR this operation is not supported on the current platform. OR the path specified a directory. OR the caller does not have the required permission. NotSupportedException: The path is in an invalid format. SecurityException: The caller does not have the required permission. Below are the programs to illustrate the File.WriteAllLines(String, String[]) method.Program 1: Initially, no file was created. Below code itself create a file file.txt and write the specified string array into the file. C# // C# program to illustrate the usage// of File.WriteAllLines(String, String[], // Encoding) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file string path = @"file.txt"; // Creating some string array to // write into the file string[] createText = { "GFG", "is a", "CS portal." }; // Calling WriteAllLines() function to write // the specified string array into the file File.WriteAllLines(path, createText, Encoding.UTF8); // Reading the file contents string[] readText = File.ReadAllLines(path, Encoding.UTF8); foreach(string s in readText) { Console.WriteLine(s); } }} Output: GFG is a CS portal. After running the above code, the above output is shown, and a new file file.txt is created shown below- Program 2: Initially, a file file.txt is created with some contents shown below- Below code overwrites the file contents with the specified string array. C# // C# program to illustrate the usage// of File.WriteAllLines(String, // String[], Encoding) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file string path = @"file.txt"; // Creating some string array to // write into the file string[] createText = { "GFG", "Geeks", "GeeksforGeeks" }; // Calling WriteAllLines() function to overwrite // the specified string array into the file File.WriteAllLines(path, createText, Encoding.UTF8); // Reading the file contents string[] readText = File.ReadAllLines(path, Encoding.UTF8); foreach(string s in readText) { Console.WriteLine(s); } }} Output: GFG Geeks GeeksforGeeks After running the above code, the above output is shown, and the file file.txt contents became like shown below- arorakashish0911 CSharp-File-Handling C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? C# | Inheritance C# | List Class Partial Classes in C# Convert String to Character Array in C# Lambda Expressions in C# Linked List Implementation in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n09 Mar, 2021" }, { "code": null, "e": 24529, "s": 24302, "text": "File.WriteAllLines(String, String[], Encoding) is an inbuilt File class method that is used to create a new file, writes the specified string array to the file by using the specified encoding, and then closes the file.Syntax: " }, { "code": null, "e": 24629, "s": 24529, "text": "public static void WriteAllLines (string path, string[] contents, System.Text.Encoding encoding); " }, { "code": null, "e": 24709, "s": 24629, "text": "Parameter: This function accepts three parameters which are illustrated below: " }, { "code": null, "e": 24796, "s": 24709, "text": "path: This is the specified file where specified string array are going to be written." }, { "code": null, "e": 24863, "s": 24796, "text": "contents: This is the specified string array to write to the file." }, { "code": null, "e": 24941, "s": 24863, "text": "encoding: This represents the character encoding applied to the string array." }, { "code": null, "e": 24954, "s": 24941, "text": "Exceptions: " }, { "code": null, "e": 25100, "s": 24954, "text": "ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars." }, { "code": null, "e": 25157, "s": 25100, "text": "ArgumentNullException: Either path or contents are null." }, { "code": null, "e": 25260, "s": 25157, "text": "PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length." }, { "code": null, "e": 25319, "s": 25260, "text": "DirectoryNotFoundException: The specified path is invalid." }, { "code": null, "e": 25378, "s": 25319, "text": "IOException: An I/O error occurred while opening the file." }, { "code": null, "e": 25645, "s": 25378, "text": "UnauthorizedAccessException: The path specified a file that is read-only. OR the path specified a file that is hidden. OR this operation is not supported on the current platform. OR the path specified a directory. OR the caller does not have the required permission." }, { "code": null, "e": 25702, "s": 25645, "text": "NotSupportedException: The path is in an invalid format." }, { "code": null, "e": 25771, "s": 25702, "text": "SecurityException: The caller does not have the required permission." }, { "code": null, "e": 25993, "s": 25771, "text": "Below are the programs to illustrate the File.WriteAllLines(String, String[]) method.Program 1: Initially, no file was created. Below code itself create a file file.txt and write the specified string array into the file. " }, { "code": null, "e": 25996, "s": 25993, "text": "C#" }, { "code": "// C# program to illustrate the usage// of File.WriteAllLines(String, String[], // Encoding) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file string path = @\"file.txt\"; // Creating some string array to // write into the file string[] createText = { \"GFG\", \"is a\", \"CS portal.\" }; // Calling WriteAllLines() function to write // the specified string array into the file File.WriteAllLines(path, createText, Encoding.UTF8); // Reading the file contents string[] readText = File.ReadAllLines(path, Encoding.UTF8); foreach(string s in readText) { Console.WriteLine(s); } }}", "e": 26807, "s": 25996, "text": null }, { "code": null, "e": 26817, "s": 26807, "text": "Output: " }, { "code": null, "e": 26837, "s": 26817, "text": "GFG\nis a\nCS portal." }, { "code": null, "e": 26943, "s": 26837, "text": "After running the above code, the above output is shown, and a new file file.txt is created shown below- " }, { "code": null, "e": 27025, "s": 26943, "text": "Program 2: Initially, a file file.txt is created with some contents shown below- " }, { "code": null, "e": 27099, "s": 27025, "text": "Below code overwrites the file contents with the specified string array. " }, { "code": null, "e": 27102, "s": 27099, "text": "C#" }, { "code": "// C# program to illustrate the usage// of File.WriteAllLines(String, // String[], Encoding) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file string path = @\"file.txt\"; // Creating some string array to // write into the file string[] createText = { \"GFG\", \"Geeks\", \"GeeksforGeeks\" }; // Calling WriteAllLines() function to overwrite // the specified string array into the file File.WriteAllLines(path, createText, Encoding.UTF8); // Reading the file contents string[] readText = File.ReadAllLines(path, Encoding.UTF8); foreach(string s in readText) { Console.WriteLine(s); } }}", "e": 27921, "s": 27102, "text": null }, { "code": null, "e": 27931, "s": 27921, "text": "Output: " }, { "code": null, "e": 27955, "s": 27931, "text": "GFG\nGeeks\nGeeksforGeeks" }, { "code": null, "e": 28069, "s": 27955, "text": "After running the above code, the above output is shown, and the file file.txt contents became like shown below- " }, { "code": null, "e": 28086, "s": 28069, "text": "arorakashish0911" }, { "code": null, "e": 28107, "s": 28086, "text": "CSharp-File-Handling" }, { "code": null, "e": 28110, "s": 28107, "text": "C#" }, { "code": null, "e": 28208, "s": 28110, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28217, "s": 28208, "text": "Comments" }, { "code": null, "e": 28230, "s": 28217, "text": "Old Comments" }, { "code": null, "e": 28253, "s": 28230, "text": "Extension Method in C#" }, { "code": null, "e": 28281, "s": 28253, "text": "HashSet in C# with Examples" }, { "code": null, "e": 28321, "s": 28281, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28364, "s": 28321, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 28381, "s": 28364, "text": "C# | Inheritance" }, { "code": null, "e": 28397, "s": 28381, "text": "C# | List Class" }, { "code": null, "e": 28419, "s": 28397, "text": "Partial Classes in C#" }, { "code": null, "e": 28459, "s": 28419, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 28484, "s": 28459, "text": "Lambda Expressions in C#" } ]
gcd() function Python
Greatest common divisor or gcd is a mathematical expression to find the highest number which can divide both the numbers whose gcd has to be found with the resulting remainder as zero. It has many mathematical applications. Python has a inbuilt gcd function in the math module which can be used for this purpose. It accepts two integers as parameter and returns the integer which is the gcd value. Syntax: gcd(x,y) Where x and y are positive integers. In the below example we print the result of gcd of a pair of integers. import math print ("GCD of 75 and 30 is ",math.gcd(75, 30)) print ("GCD of 0 and 12 is ",math.gcd(0, 12)) print ("GCD of 0 and 0 is ",math.gcd(0, 0)) print ("GCD of -24 and -18 is ",math.gcd(-24, -18)) Running the above code gives us the following result − GCD of 75 and 30 is 15 GCD of 0 and 12 is 12 GCD of 0 and 0 is 0 GCD of -24 and -18 is 6
[ { "code": null, "e": 1375, "s": 1062, "text": "Greatest common divisor or gcd is a mathematical expression to find the highest number which can divide both the numbers whose gcd has to be found with the resulting remainder as zero. It has many mathematical applications. Python has a inbuilt gcd function in the math module which can be used for this purpose." }, { "code": null, "e": 1460, "s": 1375, "text": "It accepts two integers as parameter and returns the integer which is the gcd value." }, { "code": null, "e": 1514, "s": 1460, "text": "Syntax: gcd(x,y)\nWhere x and y are positive integers." }, { "code": null, "e": 1585, "s": 1514, "text": "In the below example we print the result of gcd of a pair of integers." }, { "code": null, "e": 1787, "s": 1585, "text": "import math\nprint (\"GCD of 75 and 30 is \",math.gcd(75, 30))\nprint (\"GCD of 0 and 12 is \",math.gcd(0, 12))\nprint (\"GCD of 0 and 0 is \",math.gcd(0, 0))\nprint (\"GCD of -24 and -18 is \",math.gcd(-24, -18))" }, { "code": null, "e": 1842, "s": 1787, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1931, "s": 1842, "text": "GCD of 75 and 30 is 15\nGCD of 0 and 12 is 12\nGCD of 0 and 0 is 0\nGCD of -24 and -18 is 6" } ]
Find a time for which angle between hour and minute hands is given theta - GeeksforGeeks
31 Aug, 2021 Given angle theta, find a possible time (in hh:mm format) when angle between hour hand and clock hand is theta. If no such time exists then print -1. Examples : Input : theta = 90.0 Output : 3:0 Input : theta = 60.0 Output : 2:0 We have discussed how to find angle for given time in below post.Calculate the angle between hour hand and minute hand In this problem, we are asked to do reverse. Since there are 12 possibilities for hour and 60 possibilities for minute, we loop through all possible time which is 12*60 = 720, if angle for any time is equal to given theta then we print that time. C++ Java Python3 C# PHP Javascript // C++ program to find time for a given angle.#include <bits/stdc++.h>using namespace std; // function to find angle between// hour hand and minute handfloat calcAngle(int hh, int mm){ // Calculate the angles moved by hour and // minute hands with reference to 12:00 float hour_angle = 0.5 * (hh*60 + mm); float minute_angle = 6*mm; // Find the difference between two angles float angle = abs(hour_angle - minute_angle); // Return the smaller angle of two possible // angles angle = min(360-angle, angle); return angle;} // function to print all time when angle between// hour hand and minute hand is thetavoid printTime(float theta){ for (int hh=0; hh<12; hh++) { for (int mm=0; mm<60; mm++) { if (calcAngle(hh, mm)==theta) { printf("%d:%d\n", hh, mm); return; } } } printf("Input angle not valid.\n"); return;} // driver code to test above functionint main(){ float theta = 90.0; printTime(theta); return 0;} // Java program to find time// for a given angle.class GFG{// function to find angle between// hour hand and minute handstatic float calcAngle(int hh, int mm){ // Calculate the angles moved by hour and // minute hands with reference to 12:00 float hour_angle = 0.5f * (hh * 60 + mm); float minute_angle = 6 * mm; // Find the difference between two angles float angle = Math.abs(hour_angle - minute_angle); // Return the smaller angle of // two possible angles angle = Math.min(360-angle, angle); return angle;} // function to print all time when// angle between hour hand and minute// hand is thetastatic void printTime(float theta){ for (int hh = 0; hh < 12; hh++) { for (int mm = 0; mm < 60; mm++) { if (calcAngle(hh, mm) == theta) { System.out.println(hh + ":" + mm); return; } } } System.out.println("Input angle not valid."); return;} // Driver codepublic static void main (String[] args){ float theta = 90.0f; printTime(theta);}} // This code is contributed by Anant Agarwal. # Python 3 program to find time for a# given angle. # function to find angle between# hour hand and minute handdef calcAngle(hh, mm): # Calculate the angles moved by # hour and minute hands with # reference to 12:00 hour_angle = 0.5 * (hh * 60 + mm) minute_angle = 6 * mm # Find the difference between # two angles angle = abs(hour_angle - minute_angle) # Return the smaller angle of two # possible angles angle = min(360 - angle, angle) return angle # function to print all time when# angle between hour hand and minute# hand is thetadef printTime(theta): for hh in range(0, 12): for mm in range(0, 60): if (calcAngle(hh, mm)==theta): print(hh, ":", mm, sep = "") return print("Input angle not valid.") return # driver code to test above functiontheta = 90.0printTime(theta) # This code is contributed by Smitha // C# program to find time for a given// angle.using System; class GFG { // function to find angle between // hour hand and minute hand static float calcAngle(int hh, int mm) { // Calculate the angles moved by hour // and minute hands with reference // to 12:00 float hour_angle = 0.5f * (hh * 60 + mm); float minute_angle = 6 * mm; // Find the difference between two angles float angle = Math.Abs(hour_angle - minute_angle); // Return the smaller angle of // two possible angles angle = Math.Min(360 - angle, angle); return angle; } // function to print all time when // angle between hour hand and minute // hand is theta static void printTime(float theta) { for (int hh = 0; hh < 12; hh++) { for (int mm = 0; mm < 60; mm++) { if (calcAngle(hh, mm) == theta) { Console.WriteLine(hh + ":" + mm); return; } } } Console.WriteLine("Input angle not valid."); return; } // Driver code public static void Main () { float theta = 90.0f; printTime(theta); }} // This code is contributed by vt_m. <?php// PHP program to find// time for a given angle. // Function to find angle between// hour hand and minute handfunction calcAngle($hh, $mm){ // Calculate the angles // moved by hour and minute // hands with reference to 12:00 $hour_angle = 0.5 * ($hh * 60 + $mm); $minute_angle = 6 * $mm; // Find the difference // between two angles $angle = abs($hour_angle - $minute_angle); // Return the smaller angle // of two possible angles $angle = min(360 - $angle, $angle); return $angle;} // function to print all// time when angle between// hour hand and minute// hand is thetafunction printTime( $theta){ for ($hh = 0; $hh < 12; $hh++) { for ($mm = 0; $mm < 60; $mm++) { if (calcAngle($hh, $mm) == $theta) { echo $hh, ":", $mm; return; } } } echo "Input angle not valid.\n"; return;} // Driver Code$theta = 90.0;printTime($theta); // This code is contributed by anuj_67.?> <script> // JavaScript program to find // time for a given angle. // function to find angle between // hour hand and minute hand function calcAngle(hh, mm) { // Calculate the angles moved by hour and // minute hands with reference to 12:00 var hour_angle = 0.5 * (hh * 60 + mm); var minute_angle = 6 * mm; // Find the difference between two angles var angle = Math.abs(hour_angle - minute_angle); // Return the smaller angle of two possible // angles angle = Math.min(360 - angle, angle); return angle; } // function to print all time // when angle between // hour hand and minute hand is theta function printTime(theta) { for (var hh = 0; hh < 12; hh++) { for (var mm = 0; mm < 60; mm++) { if (calcAngle(hh, mm) === theta) { document.write(hh + ":" + mm + "<br>"); return; } } } document.write("Input angle not valid.<br>"); return; } // driver code to test above function var theta = 90.0; printTime(theta); </script> Output : 3:0 Time Complexity : O(1) Auxiliary Space : O(1) This article is contributed by Pratik Chhajer. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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. Smitha Dinesh Semwal vt_m rdtank adnanirshad158 simranarora5sos date-time-program School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Constructors in Java Exceptions in Java Ternary Operator in Python Inline Functions in C++ Difference between Abstract Class and Interface in Java Destructors in C++ Pure Virtual Functions and Abstract Classes in C++ Python Exception Handling Exception Handling in C++ Taking input from console in Python
[ { "code": null, "e": 24232, "s": 24204, "text": "\n31 Aug, 2021" }, { "code": null, "e": 24382, "s": 24232, "text": "Given angle theta, find a possible time (in hh:mm format) when angle between hour hand and clock hand is theta. If no such time exists then print -1." }, { "code": null, "e": 24394, "s": 24382, "text": "Examples : " }, { "code": null, "e": 24429, "s": 24394, "text": "Input : theta = 90.0\nOutput : 3:0 " }, { "code": null, "e": 24463, "s": 24429, "text": "Input : theta = 60.0\nOutput : 2:0" }, { "code": null, "e": 24582, "s": 24463, "text": "We have discussed how to find angle for given time in below post.Calculate the angle between hour hand and minute hand" }, { "code": null, "e": 24830, "s": 24582, "text": "In this problem, we are asked to do reverse. Since there are 12 possibilities for hour and 60 possibilities for minute, we loop through all possible time which is 12*60 = 720, if angle for any time is equal to given theta then we print that time. " }, { "code": null, "e": 24834, "s": 24830, "text": "C++" }, { "code": null, "e": 24839, "s": 24834, "text": "Java" }, { "code": null, "e": 24847, "s": 24839, "text": "Python3" }, { "code": null, "e": 24850, "s": 24847, "text": "C#" }, { "code": null, "e": 24854, "s": 24850, "text": "PHP" }, { "code": null, "e": 24865, "s": 24854, "text": "Javascript" }, { "code": "// C++ program to find time for a given angle.#include <bits/stdc++.h>using namespace std; // function to find angle between// hour hand and minute handfloat calcAngle(int hh, int mm){ // Calculate the angles moved by hour and // minute hands with reference to 12:00 float hour_angle = 0.5 * (hh*60 + mm); float minute_angle = 6*mm; // Find the difference between two angles float angle = abs(hour_angle - minute_angle); // Return the smaller angle of two possible // angles angle = min(360-angle, angle); return angle;} // function to print all time when angle between// hour hand and minute hand is thetavoid printTime(float theta){ for (int hh=0; hh<12; hh++) { for (int mm=0; mm<60; mm++) { if (calcAngle(hh, mm)==theta) { printf(\"%d:%d\\n\", hh, mm); return; } } } printf(\"Input angle not valid.\\n\"); return;} // driver code to test above functionint main(){ float theta = 90.0; printTime(theta); return 0;}", "e": 25917, "s": 24865, "text": null }, { "code": "// Java program to find time// for a given angle.class GFG{// function to find angle between// hour hand and minute handstatic float calcAngle(int hh, int mm){ // Calculate the angles moved by hour and // minute hands with reference to 12:00 float hour_angle = 0.5f * (hh * 60 + mm); float minute_angle = 6 * mm; // Find the difference between two angles float angle = Math.abs(hour_angle - minute_angle); // Return the smaller angle of // two possible angles angle = Math.min(360-angle, angle); return angle;} // function to print all time when// angle between hour hand and minute// hand is thetastatic void printTime(float theta){ for (int hh = 0; hh < 12; hh++) { for (int mm = 0; mm < 60; mm++) { if (calcAngle(hh, mm) == theta) { System.out.println(hh + \":\" + mm); return; } } } System.out.println(\"Input angle not valid.\"); return;} // Driver codepublic static void main (String[] args){ float theta = 90.0f; printTime(theta);}} // This code is contributed by Anant Agarwal.", "e": 27042, "s": 25917, "text": null }, { "code": "# Python 3 program to find time for a# given angle. # function to find angle between# hour hand and minute handdef calcAngle(hh, mm): # Calculate the angles moved by # hour and minute hands with # reference to 12:00 hour_angle = 0.5 * (hh * 60 + mm) minute_angle = 6 * mm # Find the difference between # two angles angle = abs(hour_angle - minute_angle) # Return the smaller angle of two # possible angles angle = min(360 - angle, angle) return angle # function to print all time when# angle between hour hand and minute# hand is thetadef printTime(theta): for hh in range(0, 12): for mm in range(0, 60): if (calcAngle(hh, mm)==theta): print(hh, \":\", mm, sep = \"\") return print(\"Input angle not valid.\") return # driver code to test above functiontheta = 90.0printTime(theta) # This code is contributed by Smitha", "e": 27966, "s": 27042, "text": null }, { "code": "// C# program to find time for a given// angle.using System; class GFG { // function to find angle between // hour hand and minute hand static float calcAngle(int hh, int mm) { // Calculate the angles moved by hour // and minute hands with reference // to 12:00 float hour_angle = 0.5f * (hh * 60 + mm); float minute_angle = 6 * mm; // Find the difference between two angles float angle = Math.Abs(hour_angle - minute_angle); // Return the smaller angle of // two possible angles angle = Math.Min(360 - angle, angle); return angle; } // function to print all time when // angle between hour hand and minute // hand is theta static void printTime(float theta) { for (int hh = 0; hh < 12; hh++) { for (int mm = 0; mm < 60; mm++) { if (calcAngle(hh, mm) == theta) { Console.WriteLine(hh + \":\" + mm); return; } } } Console.WriteLine(\"Input angle not valid.\"); return; } // Driver code public static void Main () { float theta = 90.0f; printTime(theta); }} // This code is contributed by vt_m.", "e": 29327, "s": 27966, "text": null }, { "code": "<?php// PHP program to find// time for a given angle. // Function to find angle between// hour hand and minute handfunction calcAngle($hh, $mm){ // Calculate the angles // moved by hour and minute // hands with reference to 12:00 $hour_angle = 0.5 * ($hh * 60 + $mm); $minute_angle = 6 * $mm; // Find the difference // between two angles $angle = abs($hour_angle - $minute_angle); // Return the smaller angle // of two possible angles $angle = min(360 - $angle, $angle); return $angle;} // function to print all// time when angle between// hour hand and minute// hand is thetafunction printTime( $theta){ for ($hh = 0; $hh < 12; $hh++) { for ($mm = 0; $mm < 60; $mm++) { if (calcAngle($hh, $mm) == $theta) { echo $hh, \":\", $mm; return; } } } echo \"Input angle not valid.\\n\"; return;} // Driver Code$theta = 90.0;printTime($theta); // This code is contributed by anuj_67.?>", "e": 30354, "s": 29327, "text": null }, { "code": "<script> // JavaScript program to find // time for a given angle. // function to find angle between // hour hand and minute hand function calcAngle(hh, mm) { // Calculate the angles moved by hour and // minute hands with reference to 12:00 var hour_angle = 0.5 * (hh * 60 + mm); var minute_angle = 6 * mm; // Find the difference between two angles var angle = Math.abs(hour_angle - minute_angle); // Return the smaller angle of two possible // angles angle = Math.min(360 - angle, angle); return angle; } // function to print all time // when angle between // hour hand and minute hand is theta function printTime(theta) { for (var hh = 0; hh < 12; hh++) { for (var mm = 0; mm < 60; mm++) { if (calcAngle(hh, mm) === theta) { document.write(hh + \":\" + mm + \"<br>\"); return; } } } document.write(\"Input angle not valid.<br>\"); return; } // driver code to test above function var theta = 90.0; printTime(theta); </script>", "e": 31552, "s": 30354, "text": null }, { "code": null, "e": 31563, "s": 31552, "text": "Output : " }, { "code": null, "e": 31567, "s": 31563, "text": "3:0" }, { "code": null, "e": 31613, "s": 31567, "text": "Time Complexity : O(1) Auxiliary Space : O(1)" }, { "code": null, "e": 32036, "s": 31613, "text": "This article is contributed by Pratik Chhajer. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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": 32057, "s": 32036, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 32062, "s": 32057, "text": "vt_m" }, { "code": null, "e": 32069, "s": 32062, "text": "rdtank" }, { "code": null, "e": 32084, "s": 32069, "text": "adnanirshad158" }, { "code": null, "e": 32100, "s": 32084, "text": "simranarora5sos" }, { "code": null, "e": 32118, "s": 32100, "text": "date-time-program" }, { "code": null, "e": 32137, "s": 32118, "text": "School Programming" }, { "code": null, "e": 32235, "s": 32137, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32256, "s": 32235, "text": "Constructors in Java" }, { "code": null, "e": 32275, "s": 32256, "text": "Exceptions in Java" }, { "code": null, "e": 32302, "s": 32275, "text": "Ternary Operator in Python" }, { "code": null, "e": 32326, "s": 32302, "text": "Inline Functions in C++" }, { "code": null, "e": 32382, "s": 32326, "text": "Difference between Abstract Class and Interface in Java" }, { "code": null, "e": 32401, "s": 32382, "text": "Destructors in C++" }, { "code": null, "e": 32452, "s": 32401, "text": "Pure Virtual Functions and Abstract Classes in C++" }, { "code": null, "e": 32478, "s": 32452, "text": "Python Exception Handling" }, { "code": null, "e": 32504, "s": 32478, "text": "Exception Handling in C++" } ]
Five Best Practices for Writing Clean and Professional SQL Code | by Terence Shin | Towards Data Science
SQL is the universal language in the data world. If you’re a data analyst, data scientist, data engineer, data architect, etc., you need to write good SQL code. Learning how to write basic SQL queries isn’t hard, but learning how to write good SQL code is another story. Writing good SQL code isn’t necessarily hard, but it does require learning some rules. If you’re fluent in Python or another coding language, some of these rules might seem familiar with you, and that’s because they’re very much transferable! And so, I’m going to share with you five tips to write cleaner and better SQL queries. Let’s dive into it: If you think that your programming style is trivial for SQL, think again. The style in which you code is essential for interpretability and minimizing errors. Let me give you a quick example — which of the following two blocks of code are more legible? SELECT name,height,weight,age,gender,CASE WHEN age<18 THEN "child" ELSE "adult" END AS childOrAdult,salaryFROM People LEFT JOIN Income USING (name)WHERE height<=200 and age<=65 or SELECT name , height , weight , age , gender , CASE WHEN age < 18 THEN "child" ELSE "adult" END AS childOrAdult , salaryFROM PeopleLEFT JOIN Income USING (name)WHERE height <= 200 AND age <= 65 It’s quite obvious that the second one is much easier to read and that’s completely attributed to its programming style! There are several components of programming style, but we’re going to focus on indentation and spaces. The main reason why the second block of code is more legible is because of its indentation and vertical alignment. Notice how all of the column names in the SELECT clause are aligned, the conditions in the WHERE clause are aligned, and the conditions in the CASE statement are aligned. You don’t necessarily have to follow this exact way, but you should apply indentation and align your statements where ever you can. Spaces refers to the white space that you use in your code. For example, instead of... WHERE height<=200 AND age<=65 consider using white spaces to make it more legible: WHERE height <= 200 AND age <= 65 Most importantly, you want to make sure that your programming style is consistent throughout your code. There are other things to consider like naming conventions and commenting, which we’ll cover later in this article. Using common table expressions (CTEs) is a great way to modularize and break down your code, the same way that you would break down an essay into several paragraphs. You can check out this article if you want to learn more about CTEs in greater depth but if you ever wanted query a query, that’s when CTEs come into play — CTEs essentially create a temporary table. Consider the following query with a sub query in the where clause. SELECT name , salaryFROM PeopleWHERE name in (SELECT DISTINCT name FROM population WHERE country = "Canada" AND city = "Toronto") AND salary >= (SELECT AVG(salary) FROM salaries WHERE gender = "Female") This may not seem to difficult to understand, but what if there were many sub queries or sub queries in sub queries? This is where CTEs come into play. with toronto_ppl as ( SELECT DISTINCT name FROM population WHERE country = "Canada" AND city = "Toronto"), avg_female_salary as ( SELECT AVG(salary) as avgSalary FROM salaries WHERE gender = "Female")SELECT name , salaryFROM PeopleWHERE name in (SELECT DISTINCT FROM toronto_ppl) AND salary >= (SELECT avgSalary FROM avg_female_salary) Now it’s clear that the WHERE clause is filtering for names in Toronto. If you noticed, CTEs are useful because you can break down your code into smaller chunks, but they’re also useful because it allows you to assign a variable name to each CTE (i.e. toronto_ppl and avg_female_salary) Note: programming style also applies for CTEs! Speaking of naming conventions, that leads to my next point: There’s two parts to naming conventions that you should consider: the type of letter-casing that you use and how descriptive your variables are. Personally, I like to use snake_case for naming CTEs and camelCase for column names. You can choose to style your variables however you like but make sure that you’re consistent. Here’s an example: with short_people as ( SELECT firstName FROM people WHERE height < 165)SELECT * FROM short_people Notice how i used snake_case for the CTE (short_people) and used camelCase for firstName. Ideally, you want your variable names to describe what they represent. Consider my previous example: with toronto_ppl as ( SELECT DISTINCT name FROM population WHERE country = "Canada" AND city = "Toronto"), avg_female_salary as ( SELECT AVG(salary) as avgSalary FROM salaries WHERE gender = "Female")SELECT name , salaryFROM PeopleWHERE name in (SELECT DISTINCT FROM toronto_ppl) AND salary >= (SELECT avgSalary FROM avg_female_salary) It’s very clear that the first CTE is querying people from toronto and the second CTE is getting the average female salary. This would be an example of poor naming conventions: with table1 as ( SELECT DISTINCT name FROM population WHERE country = "Canada" AND city = "Toronto"), table2 as ( SELECT AVG(salary) as var1 FROM salaries WHERE gender = "Female")SELECT name , salaryFROM PeopleWHERE name in (SELECT DISTINCT FROM table1) AND salary >= (SELECT var1 FROM table2) If you only read the last query, it’s very difficult to understand what it’s doing. So make sure that your casing is consistent and that your variable names are descriptive! If you want to read more about temporary functions, check this out, but temporary functions are also a good way of breaking down code, writing cleaner code, and being able to reuse code. Consider the following example: SELECT name , CASE WHEN tenure < 1 THEN "analyst" WHEN tenure BETWEEN 1 and 3 THEN "associate" WHEN tenure BETWEEN 3 and 5 THEN "senior" WHEN tenure > 5 THEN "vp" ELSE "n/a" END AS seniority FROM employees Instead, you can leverage a temporary function to capture the CASE clause. CREATE TEMPORARY FUNCTION seniority(tenure INT64) AS ( CASE WHEN tenure < 1 THEN "analyst" WHEN tenure BETWEEN 1 and 3 THEN "associate" WHEN tenure BETWEEN 3 and 5 THEN "senior" WHEN tenure > 5 THEN "vp" ELSE "n/a" END);SELECT name , seniority(tenure) as seniorityFROM employees With a temporary function, the query itself is much simpler, more readable, and you can reuse the seniority function! It’s important to write comments only when you need to. By using descriptive names, writing modular code, and having a clean programming style, you shouldn’t need to write many comments. That being said, comments are useful when the code itself can’t explain what you’re trying to achieve. Comments typically answer “why” you’re doing something rather than “what” you’re doing. Here’s an example of bad commenting: # Getting names of people in Toronto, Canadawith table1 as ( SELECT DISTINCT name FROM population WHERE country = "Canada" AND city = "Toronto")# Getting the average salary of females, table2 as ( SELECT AVG(salary) as var1 FROM salaries WHERE gender = "Female") These are poor comments because it’s telling us what we’d already know by reading the code itself. Remember, comments typically answer “why” you’re doing something rather than “what” you’re doing. If you made it to the end, I hope that you learned a thing or two. As I said before, learning how to write good SQL code is essential for all kinds of data professions, so make sure that you take the time to learn how to write good code! If you enjoyed this, be sure to follow me on Medium for future content, and as always, I wish you the best in your learning endeavors! Not sure what to read next? I’ve picked another article for you: towardsdatascience.com and another one! towardsdatascience.com If you enjoyed this, follow me on Medium for more Interested in collaborating? Let’s connect on LinkedIn Sign up for my email list here!
[ { "code": null, "e": 332, "s": 171, "text": "SQL is the universal language in the data world. If you’re a data analyst, data scientist, data engineer, data architect, etc., you need to write good SQL code." }, { "code": null, "e": 529, "s": 332, "text": "Learning how to write basic SQL queries isn’t hard, but learning how to write good SQL code is another story. Writing good SQL code isn’t necessarily hard, but it does require learning some rules." }, { "code": null, "e": 685, "s": 529, "text": "If you’re fluent in Python or another coding language, some of these rules might seem familiar with you, and that’s because they’re very much transferable!" }, { "code": null, "e": 792, "s": 685, "text": "And so, I’m going to share with you five tips to write cleaner and better SQL queries. Let’s dive into it:" }, { "code": null, "e": 951, "s": 792, "text": "If you think that your programming style is trivial for SQL, think again. The style in which you code is essential for interpretability and minimizing errors." }, { "code": null, "e": 1045, "s": 951, "text": "Let me give you a quick example — which of the following two blocks of code are more legible?" }, { "code": null, "e": 1222, "s": 1045, "text": "SELECT name,height,weight,age,gender,CASE WHEN age<18 THEN \"child\" ELSE \"adult\" END AS childOrAdult,salaryFROM People LEFT JOIN Income USING (name)WHERE height<=200 and age<=65" }, { "code": null, "e": 1225, "s": 1222, "text": "or" }, { "code": null, "e": 1481, "s": 1225, "text": "SELECT name , height , weight , age , gender , CASE WHEN age < 18 THEN \"child\" ELSE \"adult\" END AS childOrAdult , salaryFROM PeopleLEFT JOIN Income USING (name)WHERE height <= 200 AND age <= 65" }, { "code": null, "e": 1705, "s": 1481, "text": "It’s quite obvious that the second one is much easier to read and that’s completely attributed to its programming style! There are several components of programming style, but we’re going to focus on indentation and spaces." }, { "code": null, "e": 1991, "s": 1705, "text": "The main reason why the second block of code is more legible is because of its indentation and vertical alignment. Notice how all of the column names in the SELECT clause are aligned, the conditions in the WHERE clause are aligned, and the conditions in the CASE statement are aligned." }, { "code": null, "e": 2123, "s": 1991, "text": "You don’t necessarily have to follow this exact way, but you should apply indentation and align your statements where ever you can." }, { "code": null, "e": 2210, "s": 2123, "text": "Spaces refers to the white space that you use in your code. For example, instead of..." }, { "code": null, "e": 2240, "s": 2210, "text": "WHERE height<=200 AND age<=65" }, { "code": null, "e": 2293, "s": 2240, "text": "consider using white spaces to make it more legible:" }, { "code": null, "e": 2327, "s": 2293, "text": "WHERE height <= 200 AND age <= 65" }, { "code": null, "e": 2547, "s": 2327, "text": "Most importantly, you want to make sure that your programming style is consistent throughout your code. There are other things to consider like naming conventions and commenting, which we’ll cover later in this article." }, { "code": null, "e": 2713, "s": 2547, "text": "Using common table expressions (CTEs) is a great way to modularize and break down your code, the same way that you would break down an essay into several paragraphs." }, { "code": null, "e": 2913, "s": 2713, "text": "You can check out this article if you want to learn more about CTEs in greater depth but if you ever wanted query a query, that’s when CTEs come into play — CTEs essentially create a temporary table." }, { "code": null, "e": 2980, "s": 2913, "text": "Consider the following query with a sub query in the where clause." }, { "code": null, "e": 3296, "s": 2980, "text": "SELECT name , salaryFROM PeopleWHERE name in (SELECT DISTINCT name FROM population WHERE country = \"Canada\" AND city = \"Toronto\") AND salary >= (SELECT AVG(salary) FROM salaries WHERE gender = \"Female\")" }, { "code": null, "e": 3448, "s": 3296, "text": "This may not seem to difficult to understand, but what if there were many sub queries or sub queries in sub queries? This is where CTEs come into play." }, { "code": null, "e": 3815, "s": 3448, "text": "with toronto_ppl as ( SELECT DISTINCT name FROM population WHERE country = \"Canada\" AND city = \"Toronto\"), avg_female_salary as ( SELECT AVG(salary) as avgSalary FROM salaries WHERE gender = \"Female\")SELECT name , salaryFROM PeopleWHERE name in (SELECT DISTINCT FROM toronto_ppl) AND salary >= (SELECT avgSalary FROM avg_female_salary)" }, { "code": null, "e": 4102, "s": 3815, "text": "Now it’s clear that the WHERE clause is filtering for names in Toronto. If you noticed, CTEs are useful because you can break down your code into smaller chunks, but they’re also useful because it allows you to assign a variable name to each CTE (i.e. toronto_ppl and avg_female_salary)" }, { "code": null, "e": 4149, "s": 4102, "text": "Note: programming style also applies for CTEs!" }, { "code": null, "e": 4210, "s": 4149, "text": "Speaking of naming conventions, that leads to my next point:" }, { "code": null, "e": 4355, "s": 4210, "text": "There’s two parts to naming conventions that you should consider: the type of letter-casing that you use and how descriptive your variables are." }, { "code": null, "e": 4534, "s": 4355, "text": "Personally, I like to use snake_case for naming CTEs and camelCase for column names. You can choose to style your variables however you like but make sure that you’re consistent." }, { "code": null, "e": 4553, "s": 4534, "text": "Here’s an example:" }, { "code": null, "e": 4657, "s": 4553, "text": "with short_people as ( SELECT firstName FROM people WHERE height < 165)SELECT * FROM short_people" }, { "code": null, "e": 4747, "s": 4657, "text": "Notice how i used snake_case for the CTE (short_people) and used camelCase for firstName." }, { "code": null, "e": 4848, "s": 4747, "text": "Ideally, you want your variable names to describe what they represent. Consider my previous example:" }, { "code": null, "e": 5215, "s": 4848, "text": "with toronto_ppl as ( SELECT DISTINCT name FROM population WHERE country = \"Canada\" AND city = \"Toronto\"), avg_female_salary as ( SELECT AVG(salary) as avgSalary FROM salaries WHERE gender = \"Female\")SELECT name , salaryFROM PeopleWHERE name in (SELECT DISTINCT FROM toronto_ppl) AND salary >= (SELECT avgSalary FROM avg_female_salary)" }, { "code": null, "e": 5392, "s": 5215, "text": "It’s very clear that the first CTE is querying people from toronto and the second CTE is getting the average female salary. This would be an example of poor naming conventions:" }, { "code": null, "e": 5717, "s": 5392, "text": "with table1 as ( SELECT DISTINCT name FROM population WHERE country = \"Canada\" AND city = \"Toronto\"), table2 as ( SELECT AVG(salary) as var1 FROM salaries WHERE gender = \"Female\")SELECT name , salaryFROM PeopleWHERE name in (SELECT DISTINCT FROM table1) AND salary >= (SELECT var1 FROM table2)" }, { "code": null, "e": 5891, "s": 5717, "text": "If you only read the last query, it’s very difficult to understand what it’s doing. So make sure that your casing is consistent and that your variable names are descriptive!" }, { "code": null, "e": 6078, "s": 5891, "text": "If you want to read more about temporary functions, check this out, but temporary functions are also a good way of breaking down code, writing cleaner code, and being able to reuse code." }, { "code": null, "e": 6110, "s": 6078, "text": "Consider the following example:" }, { "code": null, "e": 6383, "s": 6110, "text": "SELECT name , CASE WHEN tenure < 1 THEN \"analyst\" WHEN tenure BETWEEN 1 and 3 THEN \"associate\" WHEN tenure BETWEEN 3 and 5 THEN \"senior\" WHEN tenure > 5 THEN \"vp\" ELSE \"n/a\" END AS seniority FROM employees " }, { "code": null, "e": 6458, "s": 6383, "text": "Instead, you can leverage a temporary function to capture the CASE clause." }, { "code": null, "e": 6775, "s": 6458, "text": "CREATE TEMPORARY FUNCTION seniority(tenure INT64) AS ( CASE WHEN tenure < 1 THEN \"analyst\" WHEN tenure BETWEEN 1 and 3 THEN \"associate\" WHEN tenure BETWEEN 3 and 5 THEN \"senior\" WHEN tenure > 5 THEN \"vp\" ELSE \"n/a\" END);SELECT name , seniority(tenure) as seniorityFROM employees" }, { "code": null, "e": 6893, "s": 6775, "text": "With a temporary function, the query itself is much simpler, more readable, and you can reuse the seniority function!" }, { "code": null, "e": 7080, "s": 6893, "text": "It’s important to write comments only when you need to. By using descriptive names, writing modular code, and having a clean programming style, you shouldn’t need to write many comments." }, { "code": null, "e": 7271, "s": 7080, "text": "That being said, comments are useful when the code itself can’t explain what you’re trying to achieve. Comments typically answer “why” you’re doing something rather than “what” you’re doing." }, { "code": null, "e": 7308, "s": 7271, "text": "Here’s an example of bad commenting:" }, { "code": null, "e": 7591, "s": 7308, "text": "# Getting names of people in Toronto, Canadawith table1 as ( SELECT DISTINCT name FROM population WHERE country = \"Canada\" AND city = \"Toronto\")# Getting the average salary of females, table2 as ( SELECT AVG(salary) as var1 FROM salaries WHERE gender = \"Female\")" }, { "code": null, "e": 7788, "s": 7591, "text": "These are poor comments because it’s telling us what we’d already know by reading the code itself. Remember, comments typically answer “why” you’re doing something rather than “what” you’re doing." }, { "code": null, "e": 8026, "s": 7788, "text": "If you made it to the end, I hope that you learned a thing or two. As I said before, learning how to write good SQL code is essential for all kinds of data professions, so make sure that you take the time to learn how to write good code!" }, { "code": null, "e": 8161, "s": 8026, "text": "If you enjoyed this, be sure to follow me on Medium for future content, and as always, I wish you the best in your learning endeavors!" }, { "code": null, "e": 8226, "s": 8161, "text": "Not sure what to read next? I’ve picked another article for you:" }, { "code": null, "e": 8249, "s": 8226, "text": "towardsdatascience.com" }, { "code": null, "e": 8266, "s": 8249, "text": "and another one!" }, { "code": null, "e": 8289, "s": 8266, "text": "towardsdatascience.com" }, { "code": null, "e": 8339, "s": 8289, "text": "If you enjoyed this, follow me on Medium for more" }, { "code": null, "e": 8394, "s": 8339, "text": "Interested in collaborating? Let’s connect on LinkedIn" } ]
How to Use Microsoft’s Graph API to Query, Create and Analyze Data from OneDrive, Outlook and more | by Dominik Polzer | Towards Data Science
From my emails, calendar entries, files in my cloud storage to the workgroups in Teams, a large part of my daily activities on my computer and phone are done with Microsoft applications. All these data are stored in the Microsoft Cloud, whether I like it or not. The good thing is that Microsoft provides an API that allows it to access and control most of this data, so why don`t use it to generate your own insights. The following screenshot should give you an idea of what I want to convey with this article. I want to show you: what my experiences are with the API itself and how you can build the queries you need to access the data how the authentication process works, which gives your app the necessary permissions how you can process and visualize the data in Django Graph Quick Start — a fast way to start with Microsoft’s Graph API OAuth 2.0 — How the login process works Query Data using the Graph API Analyze and visualize the data with Plotly Summary A few years ago, Microsoft switched from Live SDK to Microsoft Graph. Microsoft Graph is now the API to access all the data and insights in Microsoft 365. [1][2] There are several ways you can start with Microsoft Graph API. The fastest way is to use the Graph Quick Start, which creates a new App ID and App Secret for the authentication process and already provides you with a first sample project. (1) In the first step you need to define the language you want to use to build your App. Since I prefer Python, the example app will be a simple Django app. If you are not familiar with Django, you can take a look at one of my previous articles, which explains the principle of Django as simply as possible and includes the most important points. In case you prefer to build your own app from scratch, you can also find a tutorial how to do that in the Microsoft docs. towardsdatascience.com (2) After selecting the language, the Quick Start gives you the option to directly create a new App ID with App Secret, which you will need later on for the authorization process. To get an overview of your registered apps, you can do so in your Azure Portal under Azure Active Directory. (3) The Quick Start provides you with a first sample app that already contains the basic structure and the authentication process. Download the code sample and save it in your project dictionary. The structure of the code sample will look like any ordinary Django app. Furthermore, the YAML file oauth_settings.yml includes the settings for the authentication, such as required endpoints, App ID and App Secret. (4) To be able to start the app for the first time, you have to install the necessary Python packages. The requirements.txt provides an easy way to install a whole environment. [3] Since applications sometimes need specific versions of a library it makes sense to set up a Virtual Environment. [4] To do so, navigate into your project directory and execute the following command, which creates the Virtual Environment virtualenv_graph. python -m venv virtualenv_graph You will find a new directory virtualenv_graph in your project folder, which contains a copy of the Python interpreter. To actually work with the just created Environment graph-tutorial, you have to activate it by executing the batch file activate as follows: graph-tutorial\Scripts\activate.bat After activation, you will see the name of your virtual environment in brackets at the beginning of the input line of the CMD. This shows you that your environment is currently activated. With the following command, you can now install all necessary Python packages to your environment: (5) The following command maps the model structure used in the app to the database: python manage.py migrate This will create some default tables for the used Django apps django.contrib.auth and django.contrib.session . (6) The command python manage.py runserver starts a lightweight web server on our localhost. Unless otherwise specified, the local web server runs on port 8000 and the address 127.0.0.1. You have now the possibility to just sign in with the login data of your Office365 account. In the following I will briefly outline the functionality of OAuth 2.0 to explain what the given sample code does. OAuth 2.0 is a industry-standard protocol for authentication and allows users to grant a third-party application access to the users resources, without giving the app your long-term credentials. [5][6] This is possible, since the OAuth authorization layer separates the role of the client from the resource owner. To understand that a bit better, I will try to explain briefly which roles are part of the OAuth workflow and how they relate to each other. [5] Resource Owner: The entity that grants access to the resource. In this case it’s you, the end-user which grants the app access to the data in the Microsoft Cloud related to your Microsoft 365 account. Resource Server: Where the protected resources are located. Client: The Client is the application that is requesting access to the resource, in this case the Django App we just downloaded. Authorization Server: This server gives the end-user (the Resource Owner) the possibility to authenticate him/herself. After the proper authorization, the Authorization Server issues an access token to the App. In the following I would like to show you how the Authorization Workflow is initiated with Python using the Template App. As described before, the application first needs to send a request to the Authentication Server. Therefore we are using the Microsoft identity platform implementation of OAuth 2.0. [7] Clicking the Sign-in button calls the sign_in function in tutorial.views.py , which in turn uses the get_sign_in_url function to form the request URL. In the first step of the authorization flow, the client app directs the users to the /authorize endpoint. The request contains the [7]: Application ID, which were assigned to your app during the registration Scope, which defines the permissions the app requests from the user. Redirect URI, where authentication responses can be sent and received by your app. All the parameters you need during the authorization process are stored in the YAML file oauth_settings.yml . (3) After the user has authenticated him/herself and thus granted the app access, the Authentification Server response with the Authorization Code and redirects the user to the Redirect URI you specified. (4) Together with your App ID and App Secret you can ask the Authorization Server for an Access Token and Refresh Token . (5) The access token then gives you the ability to access the API, at least as far as the required permissions were defined in scope . That gives us access to the requested resources. In the following I will show you how to retrieve the data you are looking for. To find the right data endpoints we can use Graph Explorer . It already gives you some requests about your account and various Microsoft applications. If you are looking for information that the given queries do not provide, it is worth taking a look at the docs. (e.g. for OneDrive) I am specifically interested in data to my One Drive storage. However, the concept is the same for SharePoint, OneNote, Outlook, Teams and more. You may need to add the proper permissions to the scope variable in oauth_settings.yml . You will find an overview of the permissions in the docs. For reading and writing files in One Drive add Files.ReadWrite.All to the scope . As an example, I would like to retrieve the information to all files in the folder /Bilder/Eigene Aufnahmen. Together with the just generated Access Token, I send a GET request to /drive/root:/<path>:/children to get the data to all files in the specified path. The last line of the view function one_drive is rendering the HTML one_drive.html , which I now create to print the data I just got from the API. The HTML one_drive.html is similar to the calendar.html , which is already part of the sample app. Now we just need to add the view function one_drive to the Router, the urls.py . # <tutorial.urls.py>from django.urls import pathfrom . import viewsurlpatterns = [ ... path('calendar', views.calendar, name='calendar'), path('one_drive', views.one_drive, name='one_drive'),] Now http://localhost:8000/one_drive shows me a HTML table with all files in the folder /Bilder/Eigene Aufnahme . For the visualization of the data I use Plotly. If not already done so, install Plotly with pip as follows: pip install plotly In the following I am interested in the time when the pictures were taken. For the sake of clarity, I summarize the images by the calendar week in which they were taken. Therefor I add a new key-values pair to the dictionary files['values'], which is defined as the calendar week of the creation date. Afterwards I transfer the values of the dictionary into a Pandas data frame. Pandas offers me a number of methods to manipulate the data frame, one of them I will use in the following. The operation groupby groups all entries based on the attribute CreationWeek, the method .count() counts the occurrences of the entries. Visualized as a barplot, the whole thing looks like this. A simple example of how you can gradually build your own dashboard app, which shows you the most important key figures for your Microsoft services. With this article I tried to share my experiences with the Microsoft Graph API: the authentication process using the Microsoft identity platformquerying the data via the Graph APIvisualizing the data using Plotly the authentication process using the Microsoft identity platform querying the data via the Graph API visualizing the data using Plotly Beside retrieving data, the Graph interface offers a wide range of POST options. Add calendar entries, upload files or create a new Microsoft Team channel can be done via HTTP requests. This can help you to automate your processes. [1] Overview of Microsoft Graph, https://docs.microsoft.com/en-us/graph/overview [2] Migrating from Live SDK to Microsoft Graph, https://docs.microsoft.com/en-us/onedrive/developer/rest-api/concepts/migrating-from-live-sdk?view=odsp-graph-online [3] Pip install, https://pip.pypa.io/en/stable/reference/pip_install/ [4] Virtual Environment and Packages, https://docs.python.org/3/tutorial/venv.html [5] OAuth 2.0 Authorization Framework, https://auth0.com/docs/protocols/protocol-oauth2 [6] OAuth 2.0 Workflow, https://www.ibm.com/support/knowledgecenter/en/SS4J57_6.2.2.6/com.ibm.tivoli.fim.doc_6226/config/concept/OAuth20Workflow.html [7] Microsoft identity platform and OAuth 2.0 authorization code flow, https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow [8] Calling a secured API from a web server application, https://oauth.vlaanderen.be/authorization/Help/Api/AuthorizationCodeGrant
[ { "code": null, "e": 591, "s": 172, "text": "From my emails, calendar entries, files in my cloud storage to the workgroups in Teams, a large part of my daily activities on my computer and phone are done with Microsoft applications. All these data are stored in the Microsoft Cloud, whether I like it or not. The good thing is that Microsoft provides an API that allows it to access and control most of this data, so why don`t use it to generate your own insights." }, { "code": null, "e": 704, "s": 591, "text": "The following screenshot should give you an idea of what I want to convey with this article. I want to show you:" }, { "code": null, "e": 810, "s": 704, "text": "what my experiences are with the API itself and how you can build the queries you need to access the data" }, { "code": null, "e": 895, "s": 810, "text": "how the authentication process works, which gives your app the necessary permissions" }, { "code": null, "e": 948, "s": 895, "text": "how you can process and visualize the data in Django" }, { "code": null, "e": 1015, "s": 948, "text": "Graph Quick Start — a fast way to start with Microsoft’s Graph API" }, { "code": null, "e": 1055, "s": 1015, "text": "OAuth 2.0 — How the login process works" }, { "code": null, "e": 1086, "s": 1055, "text": "Query Data using the Graph API" }, { "code": null, "e": 1129, "s": 1086, "text": "Analyze and visualize the data with Plotly" }, { "code": null, "e": 1137, "s": 1129, "text": "Summary" }, { "code": null, "e": 1299, "s": 1137, "text": "A few years ago, Microsoft switched from Live SDK to Microsoft Graph. Microsoft Graph is now the API to access all the data and insights in Microsoft 365. [1][2]" }, { "code": null, "e": 1538, "s": 1299, "text": "There are several ways you can start with Microsoft Graph API. The fastest way is to use the Graph Quick Start, which creates a new App ID and App Secret for the authentication process and already provides you with a first sample project." }, { "code": null, "e": 1695, "s": 1538, "text": "(1) In the first step you need to define the language you want to use to build your App. Since I prefer Python, the example app will be a simple Django app." }, { "code": null, "e": 2007, "s": 1695, "text": "If you are not familiar with Django, you can take a look at one of my previous articles, which explains the principle of Django as simply as possible and includes the most important points. In case you prefer to build your own app from scratch, you can also find a tutorial how to do that in the Microsoft docs." }, { "code": null, "e": 2030, "s": 2007, "text": "towardsdatascience.com" }, { "code": null, "e": 2210, "s": 2030, "text": "(2) After selecting the language, the Quick Start gives you the option to directly create a new App ID with App Secret, which you will need later on for the authorization process." }, { "code": null, "e": 2319, "s": 2210, "text": "To get an overview of your registered apps, you can do so in your Azure Portal under Azure Active Directory." }, { "code": null, "e": 2515, "s": 2319, "text": "(3) The Quick Start provides you with a first sample app that already contains the basic structure and the authentication process. Download the code sample and save it in your project dictionary." }, { "code": null, "e": 2731, "s": 2515, "text": "The structure of the code sample will look like any ordinary Django app. Furthermore, the YAML file oauth_settings.yml includes the settings for the authentication, such as required endpoints, App ID and App Secret." }, { "code": null, "e": 2834, "s": 2731, "text": "(4) To be able to start the app for the first time, you have to install the necessary Python packages." }, { "code": null, "e": 3167, "s": 2834, "text": "The requirements.txt provides an easy way to install a whole environment. [3] Since applications sometimes need specific versions of a library it makes sense to set up a Virtual Environment. [4] To do so, navigate into your project directory and execute the following command, which creates the Virtual Environment virtualenv_graph." }, { "code": null, "e": 3199, "s": 3167, "text": "python -m venv virtualenv_graph" }, { "code": null, "e": 3459, "s": 3199, "text": "You will find a new directory virtualenv_graph in your project folder, which contains a copy of the Python interpreter. To actually work with the just created Environment graph-tutorial, you have to activate it by executing the batch file activate as follows:" }, { "code": null, "e": 3495, "s": 3459, "text": "graph-tutorial\\Scripts\\activate.bat" }, { "code": null, "e": 3782, "s": 3495, "text": "After activation, you will see the name of your virtual environment in brackets at the beginning of the input line of the CMD. This shows you that your environment is currently activated. With the following command, you can now install all necessary Python packages to your environment:" }, { "code": null, "e": 3866, "s": 3782, "text": "(5) The following command maps the model structure used in the app to the database:" }, { "code": null, "e": 3891, "s": 3866, "text": "python manage.py migrate" }, { "code": null, "e": 4002, "s": 3891, "text": "This will create some default tables for the used Django apps django.contrib.auth and django.contrib.session ." }, { "code": null, "e": 4189, "s": 4002, "text": "(6) The command python manage.py runserver starts a lightweight web server on our localhost. Unless otherwise specified, the local web server runs on port 8000 and the address 127.0.0.1." }, { "code": null, "e": 4281, "s": 4189, "text": "You have now the possibility to just sign in with the login data of your Office365 account." }, { "code": null, "e": 4396, "s": 4281, "text": "In the following I will briefly outline the functionality of OAuth 2.0 to explain what the given sample code does." }, { "code": null, "e": 4598, "s": 4396, "text": "OAuth 2.0 is a industry-standard protocol for authentication and allows users to grant a third-party application access to the users resources, without giving the app your long-term credentials. [5][6]" }, { "code": null, "e": 4855, "s": 4598, "text": "This is possible, since the OAuth authorization layer separates the role of the client from the resource owner. To understand that a bit better, I will try to explain briefly which roles are part of the OAuth workflow and how they relate to each other. [5]" }, { "code": null, "e": 5056, "s": 4855, "text": "Resource Owner: The entity that grants access to the resource. In this case it’s you, the end-user which grants the app access to the data in the Microsoft Cloud related to your Microsoft 365 account." }, { "code": null, "e": 5116, "s": 5056, "text": "Resource Server: Where the protected resources are located." }, { "code": null, "e": 5245, "s": 5116, "text": "Client: The Client is the application that is requesting access to the resource, in this case the Django App we just downloaded." }, { "code": null, "e": 5456, "s": 5245, "text": "Authorization Server: This server gives the end-user (the Resource Owner) the possibility to authenticate him/herself. After the proper authorization, the Authorization Server issues an access token to the App." }, { "code": null, "e": 5578, "s": 5456, "text": "In the following I would like to show you how the Authorization Workflow is initiated with Python using the Template App." }, { "code": null, "e": 5763, "s": 5578, "text": "As described before, the application first needs to send a request to the Authentication Server. Therefore we are using the Microsoft identity platform implementation of OAuth 2.0. [7]" }, { "code": null, "e": 5914, "s": 5763, "text": "Clicking the Sign-in button calls the sign_in function in tutorial.views.py , which in turn uses the get_sign_in_url function to form the request URL." }, { "code": null, "e": 6050, "s": 5914, "text": "In the first step of the authorization flow, the client app directs the users to the /authorize endpoint. The request contains the [7]:" }, { "code": null, "e": 6122, "s": 6050, "text": "Application ID, which were assigned to your app during the registration" }, { "code": null, "e": 6191, "s": 6122, "text": "Scope, which defines the permissions the app requests from the user." }, { "code": null, "e": 6274, "s": 6191, "text": "Redirect URI, where authentication responses can be sent and received by your app." }, { "code": null, "e": 6384, "s": 6274, "text": "All the parameters you need during the authorization process are stored in the YAML file oauth_settings.yml ." }, { "code": null, "e": 6846, "s": 6384, "text": "(3) After the user has authenticated him/herself and thus granted the app access, the Authentification Server response with the Authorization Code and redirects the user to the Redirect URI you specified. (4) Together with your App ID and App Secret you can ask the Authorization Server for an Access Token and Refresh Token . (5) The access token then gives you the ability to access the API, at least as far as the required permissions were defined in scope ." }, { "code": null, "e": 6974, "s": 6846, "text": "That gives us access to the requested resources. In the following I will show you how to retrieve the data you are looking for." }, { "code": null, "e": 7258, "s": 6974, "text": "To find the right data endpoints we can use Graph Explorer . It already gives you some requests about your account and various Microsoft applications. If you are looking for information that the given queries do not provide, it is worth taking a look at the docs. (e.g. for OneDrive)" }, { "code": null, "e": 7403, "s": 7258, "text": "I am specifically interested in data to my One Drive storage. However, the concept is the same for SharePoint, OneNote, Outlook, Teams and more." }, { "code": null, "e": 7894, "s": 7403, "text": "You may need to add the proper permissions to the scope variable in oauth_settings.yml . You will find an overview of the permissions in the docs. For reading and writing files in One Drive add Files.ReadWrite.All to the scope . As an example, I would like to retrieve the information to all files in the folder /Bilder/Eigene Aufnahmen. Together with the just generated Access Token, I send a GET request to /drive/root:/<path>:/children to get the data to all files in the specified path." }, { "code": null, "e": 8139, "s": 7894, "text": "The last line of the view function one_drive is rendering the HTML one_drive.html , which I now create to print the data I just got from the API. The HTML one_drive.html is similar to the calendar.html , which is already part of the sample app." }, { "code": null, "e": 8220, "s": 8139, "text": "Now we just need to add the view function one_drive to the Router, the urls.py ." }, { "code": null, "e": 8416, "s": 8220, "text": "# <tutorial.urls.py>from django.urls import pathfrom . import viewsurlpatterns = [ ... path('calendar', views.calendar, name='calendar'), path('one_drive', views.one_drive, name='one_drive'),]" }, { "code": null, "e": 8529, "s": 8416, "text": "Now http://localhost:8000/one_drive shows me a HTML table with all files in the folder /Bilder/Eigene Aufnahme ." }, { "code": null, "e": 8637, "s": 8529, "text": "For the visualization of the data I use Plotly. If not already done so, install Plotly with pip as follows:" }, { "code": null, "e": 8656, "s": 8637, "text": "pip install plotly" }, { "code": null, "e": 8826, "s": 8656, "text": "In the following I am interested in the time when the pictures were taken. For the sake of clarity, I summarize the images by the calendar week in which they were taken." }, { "code": null, "e": 9280, "s": 8826, "text": "Therefor I add a new key-values pair to the dictionary files['values'], which is defined as the calendar week of the creation date. Afterwards I transfer the values of the dictionary into a Pandas data frame. Pandas offers me a number of methods to manipulate the data frame, one of them I will use in the following. The operation groupby groups all entries based on the attribute CreationWeek, the method .count() counts the occurrences of the entries." }, { "code": null, "e": 9486, "s": 9280, "text": "Visualized as a barplot, the whole thing looks like this. A simple example of how you can gradually build your own dashboard app, which shows you the most important key figures for your Microsoft services." }, { "code": null, "e": 9566, "s": 9486, "text": "With this article I tried to share my experiences with the Microsoft Graph API:" }, { "code": null, "e": 9699, "s": 9566, "text": "the authentication process using the Microsoft identity platformquerying the data via the Graph APIvisualizing the data using Plotly" }, { "code": null, "e": 9764, "s": 9699, "text": "the authentication process using the Microsoft identity platform" }, { "code": null, "e": 9800, "s": 9764, "text": "querying the data via the Graph API" }, { "code": null, "e": 9834, "s": 9800, "text": "visualizing the data using Plotly" }, { "code": null, "e": 10066, "s": 9834, "text": "Beside retrieving data, the Graph interface offers a wide range of POST options. Add calendar entries, upload files or create a new Microsoft Team channel can be done via HTTP requests. This can help you to automate your processes." }, { "code": null, "e": 10147, "s": 10066, "text": "[1] Overview of Microsoft Graph, https://docs.microsoft.com/en-us/graph/overview" }, { "code": null, "e": 10312, "s": 10147, "text": "[2] Migrating from Live SDK to Microsoft Graph, https://docs.microsoft.com/en-us/onedrive/developer/rest-api/concepts/migrating-from-live-sdk?view=odsp-graph-online" }, { "code": null, "e": 10382, "s": 10312, "text": "[3] Pip install, https://pip.pypa.io/en/stable/reference/pip_install/" }, { "code": null, "e": 10465, "s": 10382, "text": "[4] Virtual Environment and Packages, https://docs.python.org/3/tutorial/venv.html" }, { "code": null, "e": 10553, "s": 10465, "text": "[5] OAuth 2.0 Authorization Framework, https://auth0.com/docs/protocols/protocol-oauth2" }, { "code": null, "e": 10703, "s": 10553, "text": "[6] OAuth 2.0 Workflow, https://www.ibm.com/support/knowledgecenter/en/SS4J57_6.2.2.6/com.ibm.tivoli.fim.doc_6226/config/concept/OAuth20Workflow.html" }, { "code": null, "e": 10863, "s": 10703, "text": "[7] Microsoft identity platform and OAuth 2.0 authorization code flow, https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow" } ]
How to change the title size of a graph using ggplot2 in R?
The size of a graph title mattes a lot for the visibility because it is the first thing people look at after plot area. Its size must not be very large nor very small but is should be different from the axis titles and axes labels so that there exists a clarity in the graph. This can be done by using theme function. Consider the below data frame − set.seed(1) x <-rnorm(100) df <-data.frame(x) library(ggplot2) Creating histogram of x and writing title of the graph − ggplot(df,aes(x))+geom_histogram(binwidth=0.5)+ggtitle("Histogram") Changing the size of the title ggplot(df,aes(x))+geom_histogram(binwidth=0.5)+ggtitle("Histogram")+theme(plot.title = element_text(size=20))
[ { "code": null, "e": 1380, "s": 1062, "text": "The size of a graph title mattes a lot for the visibility because it is the first thing people look at after plot area. Its size must not be very large nor very small but is should be different from the axis titles and axes labels so that there exists a clarity in the graph. This can be done by using theme function." }, { "code": null, "e": 1412, "s": 1380, "text": "Consider the below data frame −" }, { "code": null, "e": 1475, "s": 1412, "text": "set.seed(1)\nx <-rnorm(100)\ndf <-data.frame(x)\nlibrary(ggplot2)" }, { "code": null, "e": 1532, "s": 1475, "text": "Creating histogram of x and writing title of the graph −" }, { "code": null, "e": 1600, "s": 1532, "text": "ggplot(df,aes(x))+geom_histogram(binwidth=0.5)+ggtitle(\"Histogram\")" }, { "code": null, "e": 1631, "s": 1600, "text": "Changing the size of the title" }, { "code": null, "e": 1741, "s": 1631, "text": "ggplot(df,aes(x))+geom_histogram(binwidth=0.5)+ggtitle(\"Histogram\")+theme(plot.title = element_text(size=20))" } ]
Using Kafka for Collecting Web Application Metrics in Your Cloud Data Lake | by Lucio Daza | Towards Data Science
Metrics are the indicators (values) that reflect the state of a process or a system. When we have a sequence of values, we can also make a conclusion about trends or seasonality. In summary, metrics are indicators of how the process or the system evolves. Metrics can be generated by applications, hardware components (CPU, memory, etc.), web servers, search engines, IoT devices, databases and so on. Metrics can reflect the internal state of the system and even some real-world processes. Examples of real-world metrics include an e-commerce website that can generate information about the number of new orders over any given period, air quality devices that can collect data about the concentration of different chemical substances in the air, and CPU load, which is an example of the metrics pertaining to the internal state of the computer system. The collected metrics can be analyzed in real time or stored for batch analysis later. Collected metrics can also be used to train machine learning models. Collecting metrics can be a complex process because it depends on many parameters and conditions. The source of the metric produces the values, then those values are either delivered to a cloud data lake storage or used in real time. The method in which metrics are delivered from source to storage, as well as the approach for storing, can vary significantly from one case to another. One of the tools that can help with the collection of metrics is Apache Kafka. Apache Kafka is a tool used for building real-time data processing pipelines and streaming applications. Kafka is a distributed system, which means it can operate as a cluster from several sources. The Kafka cluster is the central hub used by different data generators (called producers) and data consumers (called consumers). Applications (desktop, web, mobile), APIs, databases, web services and IoT devices are all typical examples of producers. The producer is the entity that sends data to the Kafka cluster. The consumer is the entity that receives data from the Kafka cluster. The Kafka cluster can consist of one or more Kafka brokers. Kafka uses topics to organize data. The topic is the category for streams of data. Each data point in the topic has its own unique timestamp, key and value. Producers can write data into specific topics, while consumers can subscribe to the desired topics to receive specific sets of data. Kafka supports data replication, which is the creation of copies of the same data on different brokers. This prevents data loss when one of the brokers is damaged or out for some reason. Kafka is one of the most popular event streaming platforms and messaging queues. It is used by many large companies to manage their data pipelines. Here are several of the most important advantages that Kafka provides: Scalability (due to the support for distributed operation) Fault tolerance Durability Fast operation High throughput Real-time mode as well as the ability to work in batch mode Let’s take a look at how Kafka can be used for collecting metrics. Usually, collecting metrics is done in real time. This means that the source of the metrics constantly generates data and can send it as a data stream. As we know, Kafka is a good tool for handling data streams, which is why it can be used for collecting metrics. In this example, we will use a simple Flask web application as a producer. It will send metrics about its activity to the Kafka cluster. The consumer will be a python script which will receive metrics from Kafka and write data into a CSV file. This script will receive metrics from Kafka and write data into the CSV file. On its own, the Python app can enrich data, and send metrics to cloud storage. At this stage, the data is available for a range of best-of-breed data lake engines like Dremio to query and process. Here’s a tip: If you want to perform metrics monitoring, you can use tools like Prometheus, Grafana, Kibana, etc. The pipeline is the same: the web application sends data into the Kafka cluster after which the metrics should be delivered to the aforementioned platforms where they are visualized and analyzed. It is also possible to set up alerts and notifications if some events occur. Let’s look at the example of metrics collection with the help of Kafka. We will use a Flask web application as a source of metrics. Using the app, people can create orders and buy essential goods. Here is the main page of the website: It is very simple: when the user clicks on the New order button, they will go to the next page where they can place the order. When the user checks the checkbox field, this means they want to pay for the order immediately. If not, the goods will be supplied under credit conditions. After the user clicks on the Make an order button, the next page is loaded: On this page, the user can review the details of the created order. The new element here is the total price, which is calculated by multiplying the price for the 1 unit times the ordered amount. Let’s now look at the code of the application. It has several files including forms, templates, configs, database (SQLite), etc. But we will demonstrate only the files that play a role in generating and sending metrics to the Kafka cluster. It is important to note that for this article, we will use the kafka-python package. It allows us to work with Kafka directly from Python code. We installed it using the following command: pip install kafka-python Below, you can see the code from the models.py file. This file describes the structure of the database. We have just one table there called Order. It is represented by a Python class, where each attribute is the column in the database. But the most interesting part of this file is the send_order_info_to_kafka() function. import jsonfrom app import dbfrom sqlalchemy import eventfrom kafka import KafkaProducerclass Order(db.Model):id = db.Column(db.Integer, primary_key=True)customer_email = db.Column(db.String(120),nullable=False, default=””)amount = db.Column(db.Integer)total_price = db.Column(db.Integer)is_prepaid = db.Column(db.Boolean, default=False)@event.listens_for(Order, ‘after_insert’)def send_order_info_to_kafka(mapper, connection, target):assert target.id is not Noneproducer = KafkaProducer(bootstrap_servers=[‘localhost:9092’])topic_name = ‘new_orders’order_dict = {“order_id”: target.id,“order_amount”: target.amount,“order_total_price”: target.total_price,“is_paid”: target.is_prepaid}producer.send(topic_name, value=json.dumps(order_dict).encode())producer.flush() This function is enhanced by the event.listens_for() decorator (imported from the sqlalchemy library). This decorator monitors the event when the record about the new order is inserted into the database. When this occurs, the function creates a KafkaProducer instance (which points to the URL where the running Kafka cluster is located) and specifies the name of the Kafka topic — new_orders. Then the function creates the body of the message. We want to send statistics about the orders to Kafka. That’s why for each order, we create the dictionary with information about the order amount, its total price, and whether it is prepaid or not. Then we transform this dictionary into JSON format, encode it, and send it to Kafka using the producer’s methods send() and flush(). So, this function is triggered every time that users create a new order. The purpose of the function is to send information about the created order to the Kafka cluster. We want to collect one more set of metrics — the number of requests for a certain period of time. It is a common metric to monitor for any web application. So each time someone visits a page on our website, we need to send the notification about this to our Kafka cluster. Here is how we can implement this behavior. In the file utils.py we define the function called ping_kafka_when_request(). The body of this function is very similar to the function that we saw before. It creates the instance of the producer, defines the name of the topic where the producer should commit messages (web_requests), and then uses the send() and flush() methods to send messages. This function is a little bit simpler because we don’t need to create a complex body for the message. We just send value=1 each time a new request occurs. from kafka import KafkaProducerdef ping_kafka_when_request():producer = KafkaProducer(bootstrap_servers=[‘localhost:9092’])topic_name = ‘web_requests’producer.send(topic_name, value=”1".encode())producer.flush() To make this function work, we need to call it in the view functions for each of our pages. This can be done in the routes.py file (see the code below). There are three functions: (index(), create_order(), and order_complete()). Each of these functions are responsible for executing some logic while rendering pages on the website. The most complex function is the create_order() function because it should process form posting and the insertion of new records into the database. But if we talk about interaction with Kafka, you should pay attention to the fact that we import the ping_kafka_when_request() function from the utils file and call it inside each of the view functions (before executing all remaining code in that function). from app import app, dbfrom app.models import Orderfrom flask import render_template, redirect, sessionfrom app.forms import OrderFormfrom .utils import ping_kafka_when_request@app.route(‘/’)def index():ping_kafka_when_request()return render_template(‘index.html’)@app.route(‘/order-new’, methods=[‘GET’, ‘POST’])def create_order():ping_kafka_when_request()form = OrderForm()if form.validate_on_submit():price = 15customer_email = form.email.dataamount = form.amount.datais_prepaid = form.is_paid_now.datatotal_price = amount * priceorder = Order(customer_email=customer_email,amount=amount,total_price=total_price,is_prepaid=is_prepaid)db.session.add(order)db.session.commit()session[‘order’] = {“email”: customer_email,“amount”: amount,“total_price”: total_price,“is_paid”: is_prepaid}return redirect(‘/order-new-complete’)return render_template(‘new_order.html’,title=’Make a new order’, form=form)@app.route(‘/order-new-complete’)def order_complete():ping_kafka_when_request()return render_template(‘new_order_complete.html’,order=session[‘order’]) Those were the producer sides of our architecture. We explained that the code needed to be located inside the web application in order to send metrics to the Kafka cluster. Now let’s look at another side — consumers. The first file is consumer_requests.py. Let’s examine it by chunks. At the beginning of the file, we import all the packages we’ll need and create the instance of Kafka consumer. We will apply several parameters so it can work the way it was intended. You can read about them in the documentation. The most important parameters are the names of the topics to which we want to subscribe the consumer (web_requests) and the bootstrap_servers parameter that points to the server where the Kafka cluster is located. import timeimport threadingimport datetimefrom kafka import KafkaConsumerconsumer = KafkaConsumer(‘web_requests’,bootstrap_servers=[‘localhost:9092’],auto_offset_reset=’earliest’,enable_auto_commit=True,auto_commit_interval_ms=1000,consumer_timeout_ms=-1) Next, we need to create a function which will poll the Kafka cluster once a minute and process the messages which Kafka will return. The name of the function is fetch_last_min_requests() and you can see it in the code sample below. It needs two parameters as inputs. The next_call_in parameter shows when the next call of this function should occur (remember that we need to fetch new data from Kafka every 60 seconds). The is_first_execution parameter is not required. By default, it is equal to False. At the beginning of the function, we fix the time when the next call of this function should occur (60 seconds from now). Also, we initialize the counter for requests. Then, if it is the first execution, we create the file requests.csv and write a row with headers to it. The structure of this dataset will be simple. It should have two columns — datetime and requests_num. Each row will have the timestamp in the datetime column as well as the number of requests that were processed by the website during the given minute in the requests_num column. def fetch_last_min_requests(next_call_in, is_first_execution=False):next_call_in += 60counter_requests = 0if is_first_execution:with open(‘requests.csv’,’a’) as file:headers = [“datetime”, “requests_num”]file.write(“,”.join(headers))file.write(‘\n’)else:batch = consumer.poll(timeout_ms=100)if len(batch) > 0:for message in list(batch.values())[0]:counter_requests += 1with open(‘requests.csv’,’a’) as file:data = [datetime.datetime.now().strftime(“%Y-%m-%d %H:%M:%S”), str(counter_requests)]file.write(“,”.join(data))file.write(‘\n’)threading.Timer(next_call_in — time.time(),fetch_last_minute_requests,[next_call_in]).start() If this is not the first execution of the function, we will force the consumer to poll the Kafka cluster. You should set the timeout_ms parameter of the poll() method to a number greater than zero, because otherwise, you can miss some messages. If the poll() method returns the non-void object (batch) we want to loop over all fetched messages and on each iteration increment the count_requests variable by 1. Then we open the request.csv file, generate the row (string from the current datetime and counter_requests values joined by comma), and append this row to the file. The last line in the given function is the timer setup. We insert three parameters into the Timer object. First is the period of time after which the function (the second parameter) should be triggered. The period of time is calculated dynamically by subtracting the current timestamp from the time stored in the next_call_in variable, which we computed at the beginning of the function. The third parameter of the Timer object is the list with arguments which should be passed into the function which we want to execute. We immediately start the timer using its start() method. Why do we need such a tricky way of defining the time where the next function call will occur? Can’t we just use the more popular time.sleep() method? The answer is no. We used this approach because the execution of the logic that is located inside the function takes some time. For example, the Kafka cluster polling will take at least 100 milliseconds. Moreover, we then need to count requests and write the result into the file. All these things could be time consuming, and if we simply pause the execution using time.sleep(), the minute period will drift every next iteration. This can corrupt the results. Using the threading.Timer object is a slightly different and more suitable approach. Instead of pausing for 60 seconds, we compute the time when the function should be triggered by subtracting the time that was spent on the execution of the code inside the function’s body. Now we can use the defined function. Just initialize the next_call_in variable by the current time and use the fetch_last_minute_requests() function with this variable as the first parameter and the True flag as the second (to mark that this is the first execution). next_call_in = time.time()fetch_last_minute_requests(next_call_in, True) That is all for the consumer_requests.py file. But before you can execute it, you should run the Kafka cluster. Here is how you can do it locally from the Terminal (assuming that you already have it installed): sudo kafka-server-start.sh /etc/kafka.properties Now you can run the file. Then go to the web application (you can run the Flask application using the command flask run) in your browser and try to browse it — visit its pages. After a while, you should have the file requests.csv in the folder where your consumer file is located. The file could look like this (actual data will be different and depends on the number of times you visited the pages of your app): What we did was to build the pipeline, allowing us to collect a web application metric (number of requests) using Kafka and Python. Now let’s look at another consumer. We called this file as consumer_orders.py. The first part of the file is very similar to the previous file. The one difference is that we import the json library because we will need to work with JSON-encoded messages. Another difference is that the Kafka consumer is subscribed to the new_orders topic. import jsonimport timeimport datetimeimport threadingfrom kafka import KafkaConsumerconsumer = KafkaConsumer(‘new_orders’,bootstrap_servers=[‘localhost:9092’],auto_offset_reset=’earliest’,enable_auto_commit=True,auto_commit_interval_ms=1000,consumer_timeout_ms==-1) The main function is the fetch_last_minute_orders(). The difference from the function with the previous consumer is that this function has six counters instead of just one. We want to count the total number of orders created over one minute, the total amount of items ordered, the total cost for all orders, as well as how many orders are prepaid, how many items were in prepaid orders, and the total price for all prepaid orders. These metrics could be useful for further analysis. Another difference is that before starting the calculation of the aforementioned values, we need to decode the message fetched from Kafka using the json library. All other logic is the same as for the consumer that works with requests. This file to which the data should be written is called orders.csv. def fetch_last_minute_orders(next_call_in, is_first_execution=False):next_call_in += 60count_orders = 0count_tot_amount = 0count_tot_price = 0count_orders_paid = 0count_tot_paid_amount = 0count_tot_paid_price = 0if is_first_execution:with open(‘orders.csv’,’a’) as file:headers = [“datetime”, “total_orders_num”,“total_orders_amount”, “total_orders_price”,“total_paid_orders_num”,“total_paid_orders_amount”,“Total_paid_orders_price”]file.write(“,”.join(headers))file.write(‘\n’)else:batch = consumer.poll(timeout_ms=100)if len(batch) > 0:for message in list(batch.values())[0]:value = message.value.decode()order_dict = json.loads(value)# all orderscount_orders += 1count_tot_amount += order_dict[“order_amount”]count_tot_price += order_dict[“order_total_price”]if order_dict[“is_paid”]:# only paid orderscount_orders_paid += 1count_tot_paid_amount += order_dict[“order_amount”]count_tot_paid_price += order_dict[“order_total_price”]with open(‘orders.csv’,’a’) as file:data = [datetime.datetime.now().strftime(“%Y-%m-%d %H:%M:%S”),str(count_orders), str(count_tot_amount),str(count_tot_price), str(count_orders_paid),str(count_tot_paid_amount),str(count_tot_paid_price)]file.write(“,”.join(data))file.write(‘\n’)threading.Timer(next_call_in — time.time(),fetch_last_minute_orders,[next_call_in]).start() The last part of the file is the same: getting the current time and triggering the function defined above: next_call_in = time.time()fetch_last_minute_orders(next_call_in, True) Given that you already have the Kafka cluster running, you can execute the consumer_orders.py file. Next, go to your Flask app and create some orders for several minutes. The generated orders.csv file will have the following structure: You can see that our Python scripts (especially those that work with order data) perform some data enrichment. Data engineers can customize this process. For example, if the app is very large and high-loaded, the Kafka cluster should be scaled horizontally. You can have many topics for different metrics, and each topic could be processed in its own way. It is possible to track new user registrations, user churns, the number of feedbacks, survey results, etc. Also, you can set up a collection of some low-level metrics like CPU load or memory consumption. The basic pipeline will be similar. It is also worth mentioning that writing data into CSV files is not the only option you can also make use of open data formats such as Parquet and land all this data directly on your data lake. Once you have the metrics collected, you can use Dremio to directly query the data, as well as to create and share virtual data sets that combine the metrics with other sources in the data lake, all without any copies. In this article, we built a data pipeline for the collection of metrics from the Flask web application. The Kafka cluster is used as the layer between data producers (deployed in the web application) and data consumers (Python scripts). Python scripts act as apps that fetch metrics from the Kafka and then process and transform data. The examples given are basic, but you can use it to build more complex and diverse pipelines for metrics collection according to your needs. You can then use Dremio’s data lake engine to query and process the resulting datasets.
[ { "code": null, "e": 1024, "s": 171, "text": "Metrics are the indicators (values) that reflect the state of a process or a system. When we have a sequence of values, we can also make a conclusion about trends or seasonality. In summary, metrics are indicators of how the process or the system evolves. Metrics can be generated by applications, hardware components (CPU, memory, etc.), web servers, search engines, IoT devices, databases and so on. Metrics can reflect the internal state of the system and even some real-world processes. Examples of real-world metrics include an e-commerce website that can generate information about the number of new orders over any given period, air quality devices that can collect data about the concentration of different chemical substances in the air, and CPU load, which is an example of the metrics pertaining to the internal state of the computer system." }, { "code": null, "e": 1180, "s": 1024, "text": "The collected metrics can be analyzed in real time or stored for batch analysis later. Collected metrics can also be used to train machine learning models." }, { "code": null, "e": 1566, "s": 1180, "text": "Collecting metrics can be a complex process because it depends on many parameters and conditions. The source of the metric produces the values, then those values are either delivered to a cloud data lake storage or used in real time. The method in which metrics are delivered from source to storage, as well as the approach for storing, can vary significantly from one case to another." }, { "code": null, "e": 1645, "s": 1566, "text": "One of the tools that can help with the collection of metrics is Apache Kafka." }, { "code": null, "e": 2289, "s": 1645, "text": "Apache Kafka is a tool used for building real-time data processing pipelines and streaming applications. Kafka is a distributed system, which means it can operate as a cluster from several sources. The Kafka cluster is the central hub used by different data generators (called producers) and data consumers (called consumers). Applications (desktop, web, mobile), APIs, databases, web services and IoT devices are all typical examples of producers. The producer is the entity that sends data to the Kafka cluster. The consumer is the entity that receives data from the Kafka cluster. The Kafka cluster can consist of one or more Kafka brokers." }, { "code": null, "e": 2766, "s": 2289, "text": "Kafka uses topics to organize data. The topic is the category for streams of data. Each data point in the topic has its own unique timestamp, key and value. Producers can write data into specific topics, while consumers can subscribe to the desired topics to receive specific sets of data. Kafka supports data replication, which is the creation of copies of the same data on different brokers. This prevents data loss when one of the brokers is damaged or out for some reason." }, { "code": null, "e": 2985, "s": 2766, "text": "Kafka is one of the most popular event streaming platforms and messaging queues. It is used by many large companies to manage their data pipelines. Here are several of the most important advantages that Kafka provides:" }, { "code": null, "e": 3044, "s": 2985, "text": "Scalability (due to the support for distributed operation)" }, { "code": null, "e": 3060, "s": 3044, "text": "Fault tolerance" }, { "code": null, "e": 3071, "s": 3060, "text": "Durability" }, { "code": null, "e": 3086, "s": 3071, "text": "Fast operation" }, { "code": null, "e": 3102, "s": 3086, "text": "High throughput" }, { "code": null, "e": 3162, "s": 3102, "text": "Real-time mode as well as the ability to work in batch mode" }, { "code": null, "e": 3229, "s": 3162, "text": "Let’s take a look at how Kafka can be used for collecting metrics." }, { "code": null, "e": 3493, "s": 3229, "text": "Usually, collecting metrics is done in real time. This means that the source of the metrics constantly generates data and can send it as a data stream. As we know, Kafka is a good tool for handling data streams, which is why it can be used for collecting metrics." }, { "code": null, "e": 4012, "s": 3493, "text": "In this example, we will use a simple Flask web application as a producer. It will send metrics about its activity to the Kafka cluster. The consumer will be a python script which will receive metrics from Kafka and write data into a CSV file. This script will receive metrics from Kafka and write data into the CSV file. On its own, the Python app can enrich data, and send metrics to cloud storage. At this stage, the data is available for a range of best-of-breed data lake engines like Dremio to query and process." }, { "code": null, "e": 4399, "s": 4012, "text": "Here’s a tip: If you want to perform metrics monitoring, you can use tools like Prometheus, Grafana, Kibana, etc. The pipeline is the same: the web application sends data into the Kafka cluster after which the metrics should be delivered to the aforementioned platforms where they are visualized and analyzed. It is also possible to set up alerts and notifications if some events occur." }, { "code": null, "e": 4634, "s": 4399, "text": "Let’s look at the example of metrics collection with the help of Kafka. We will use a Flask web application as a source of metrics. Using the app, people can create orders and buy essential goods. Here is the main page of the website:" }, { "code": null, "e": 4761, "s": 4634, "text": "It is very simple: when the user clicks on the New order button, they will go to the next page where they can place the order." }, { "code": null, "e": 4993, "s": 4761, "text": "When the user checks the checkbox field, this means they want to pay for the order immediately. If not, the goods will be supplied under credit conditions. After the user clicks on the Make an order button, the next page is loaded:" }, { "code": null, "e": 5188, "s": 4993, "text": "On this page, the user can review the details of the created order. The new element here is the total price, which is calculated by multiplying the price for the 1 unit times the ordered amount." }, { "code": null, "e": 5429, "s": 5188, "text": "Let’s now look at the code of the application. It has several files including forms, templates, configs, database (SQLite), etc. But we will demonstrate only the files that play a role in generating and sending metrics to the Kafka cluster." }, { "code": null, "e": 5618, "s": 5429, "text": "It is important to note that for this article, we will use the kafka-python package. It allows us to work with Kafka directly from Python code. We installed it using the following command:" }, { "code": null, "e": 5643, "s": 5618, "text": "pip install kafka-python" }, { "code": null, "e": 5966, "s": 5643, "text": "Below, you can see the code from the models.py file. This file describes the structure of the database. We have just one table there called Order. It is represented by a Python class, where each attribute is the column in the database. But the most interesting part of this file is the send_order_info_to_kafka() function." }, { "code": null, "e": 6732, "s": 5966, "text": "import jsonfrom app import dbfrom sqlalchemy import eventfrom kafka import KafkaProducerclass Order(db.Model):id = db.Column(db.Integer, primary_key=True)customer_email = db.Column(db.String(120),nullable=False, default=””)amount = db.Column(db.Integer)total_price = db.Column(db.Integer)is_prepaid = db.Column(db.Boolean, default=False)@event.listens_for(Order, ‘after_insert’)def send_order_info_to_kafka(mapper, connection, target):assert target.id is not Noneproducer = KafkaProducer(bootstrap_servers=[‘localhost:9092’])topic_name = ‘new_orders’order_dict = {“order_id”: target.id,“order_amount”: target.amount,“order_total_price”: target.total_price,“is_paid”: target.is_prepaid}producer.send(topic_name, value=json.dumps(order_dict).encode())producer.flush()" }, { "code": null, "e": 7677, "s": 6732, "text": "This function is enhanced by the event.listens_for() decorator (imported from the sqlalchemy library). This decorator monitors the event when the record about the new order is inserted into the database. When this occurs, the function creates a KafkaProducer instance (which points to the URL where the running Kafka cluster is located) and specifies the name of the Kafka topic — new_orders. Then the function creates the body of the message. We want to send statistics about the orders to Kafka. That’s why for each order, we create the dictionary with information about the order amount, its total price, and whether it is prepaid or not. Then we transform this dictionary into JSON format, encode it, and send it to Kafka using the producer’s methods send() and flush(). So, this function is triggered every time that users create a new order. The purpose of the function is to send information about the created order to the Kafka cluster." }, { "code": null, "e": 8497, "s": 7677, "text": "We want to collect one more set of metrics — the number of requests for a certain period of time. It is a common metric to monitor for any web application. So each time someone visits a page on our website, we need to send the notification about this to our Kafka cluster. Here is how we can implement this behavior. In the file utils.py we define the function called ping_kafka_when_request(). The body of this function is very similar to the function that we saw before. It creates the instance of the producer, defines the name of the topic where the producer should commit messages (web_requests), and then uses the send() and flush() methods to send messages. This function is a little bit simpler because we don’t need to create a complex body for the message. We just send value=1 each time a new request occurs." }, { "code": null, "e": 8709, "s": 8497, "text": "from kafka import KafkaProducerdef ping_kafka_when_request():producer = KafkaProducer(bootstrap_servers=[‘localhost:9092’])topic_name = ‘web_requests’producer.send(topic_name, value=”1\".encode())producer.flush()" }, { "code": null, "e": 9447, "s": 8709, "text": "To make this function work, we need to call it in the view functions for each of our pages. This can be done in the routes.py file (see the code below). There are three functions: (index(), create_order(), and order_complete()). Each of these functions are responsible for executing some logic while rendering pages on the website. The most complex function is the create_order() function because it should process form posting and the insertion of new records into the database. But if we talk about interaction with Kafka, you should pay attention to the fact that we import the ping_kafka_when_request() function from the utils file and call it inside each of the view functions (before executing all remaining code in that function)." }, { "code": null, "e": 10500, "s": 9447, "text": "from app import app, dbfrom app.models import Orderfrom flask import render_template, redirect, sessionfrom app.forms import OrderFormfrom .utils import ping_kafka_when_request@app.route(‘/’)def index():ping_kafka_when_request()return render_template(‘index.html’)@app.route(‘/order-new’, methods=[‘GET’, ‘POST’])def create_order():ping_kafka_when_request()form = OrderForm()if form.validate_on_submit():price = 15customer_email = form.email.dataamount = form.amount.datais_prepaid = form.is_paid_now.datatotal_price = amount * priceorder = Order(customer_email=customer_email,amount=amount,total_price=total_price,is_prepaid=is_prepaid)db.session.add(order)db.session.commit()session[‘order’] = {“email”: customer_email,“amount”: amount,“total_price”: total_price,“is_paid”: is_prepaid}return redirect(‘/order-new-complete’)return render_template(‘new_order.html’,title=’Make a new order’, form=form)@app.route(‘/order-new-complete’)def order_complete():ping_kafka_when_request()return render_template(‘new_order_complete.html’,order=session[‘order’])" }, { "code": null, "e": 10717, "s": 10500, "text": "Those were the producer sides of our architecture. We explained that the code needed to be located inside the web application in order to send metrics to the Kafka cluster. Now let’s look at another side — consumers." }, { "code": null, "e": 11229, "s": 10717, "text": "The first file is consumer_requests.py. Let’s examine it by chunks. At the beginning of the file, we import all the packages we’ll need and create the instance of Kafka consumer. We will apply several parameters so it can work the way it was intended. You can read about them in the documentation. The most important parameters are the names of the topics to which we want to subscribe the consumer (web_requests) and the bootstrap_servers parameter that points to the server where the Kafka cluster is located." }, { "code": null, "e": 11485, "s": 11229, "text": "import timeimport threadingimport datetimefrom kafka import KafkaConsumerconsumer = KafkaConsumer(‘web_requests’,bootstrap_servers=[‘localhost:9092’],auto_offset_reset=’earliest’,enable_auto_commit=True,auto_commit_interval_ms=1000,consumer_timeout_ms=-1)" }, { "code": null, "e": 11989, "s": 11485, "text": "Next, we need to create a function which will poll the Kafka cluster once a minute and process the messages which Kafka will return. The name of the function is fetch_last_min_requests() and you can see it in the code sample below. It needs two parameters as inputs. The next_call_in parameter shows when the next call of this function should occur (remember that we need to fetch new data from Kafka every 60 seconds). The is_first_execution parameter is not required. By default, it is equal to False." }, { "code": null, "e": 12540, "s": 11989, "text": "At the beginning of the function, we fix the time when the next call of this function should occur (60 seconds from now). Also, we initialize the counter for requests. Then, if it is the first execution, we create the file requests.csv and write a row with headers to it. The structure of this dataset will be simple. It should have two columns — datetime and requests_num. Each row will have the timestamp in the datetime column as well as the number of requests that were processed by the website during the given minute in the requests_num column." }, { "code": null, "e": 13168, "s": 12540, "text": "def fetch_last_min_requests(next_call_in, is_first_execution=False):next_call_in += 60counter_requests = 0if is_first_execution:with open(‘requests.csv’,’a’) as file:headers = [“datetime”, “requests_num”]file.write(“,”.join(headers))file.write(‘\\n’)else:batch = consumer.poll(timeout_ms=100)if len(batch) > 0:for message in list(batch.values())[0]:counter_requests += 1with open(‘requests.csv’,’a’) as file:data = [datetime.datetime.now().strftime(“%Y-%m-%d %H:%M:%S”), str(counter_requests)]file.write(“,”.join(data))file.write(‘\\n’)threading.Timer(next_call_in — time.time(),fetch_last_minute_requests,[next_call_in]).start()" }, { "code": null, "e": 13743, "s": 13168, "text": "If this is not the first execution of the function, we will force the consumer to poll the Kafka cluster. You should set the timeout_ms parameter of the poll() method to a number greater than zero, because otherwise, you can miss some messages. If the poll() method returns the non-void object (batch) we want to loop over all fetched messages and on each iteration increment the count_requests variable by 1. Then we open the request.csv file, generate the row (string from the current datetime and counter_requests values joined by comma), and append this row to the file." }, { "code": null, "e": 14322, "s": 13743, "text": "The last line in the given function is the timer setup. We insert three parameters into the Timer object. First is the period of time after which the function (the second parameter) should be triggered. The period of time is calculated dynamically by subtracting the current timestamp from the time stored in the next_call_in variable, which we computed at the beginning of the function. The third parameter of the Timer object is the list with arguments which should be passed into the function which we want to execute. We immediately start the timer using its start() method." }, { "code": null, "e": 15208, "s": 14322, "text": "Why do we need such a tricky way of defining the time where the next function call will occur? Can’t we just use the more popular time.sleep() method? The answer is no. We used this approach because the execution of the logic that is located inside the function takes some time. For example, the Kafka cluster polling will take at least 100 milliseconds. Moreover, we then need to count requests and write the result into the file. All these things could be time consuming, and if we simply pause the execution using time.sleep(), the minute period will drift every next iteration. This can corrupt the results. Using the threading.Timer object is a slightly different and more suitable approach. Instead of pausing for 60 seconds, we compute the time when the function should be triggered by subtracting the time that was spent on the execution of the code inside the function’s body." }, { "code": null, "e": 15475, "s": 15208, "text": "Now we can use the defined function. Just initialize the next_call_in variable by the current time and use the fetch_last_minute_requests() function with this variable as the first parameter and the True flag as the second (to mark that this is the first execution)." }, { "code": null, "e": 15548, "s": 15475, "text": "next_call_in = time.time()fetch_last_minute_requests(next_call_in, True)" }, { "code": null, "e": 15759, "s": 15548, "text": "That is all for the consumer_requests.py file. But before you can execute it, you should run the Kafka cluster. Here is how you can do it locally from the Terminal (assuming that you already have it installed):" }, { "code": null, "e": 15808, "s": 15759, "text": "sudo kafka-server-start.sh /etc/kafka.properties" }, { "code": null, "e": 16221, "s": 15808, "text": "Now you can run the file. Then go to the web application (you can run the Flask application using the command flask run) in your browser and try to browse it — visit its pages. After a while, you should have the file requests.csv in the folder where your consumer file is located. The file could look like this (actual data will be different and depends on the number of times you visited the pages of your app):" }, { "code": null, "e": 16353, "s": 16221, "text": "What we did was to build the pipeline, allowing us to collect a web application metric (number of requests) using Kafka and Python." }, { "code": null, "e": 16693, "s": 16353, "text": "Now let’s look at another consumer. We called this file as consumer_orders.py. The first part of the file is very similar to the previous file. The one difference is that we import the json library because we will need to work with JSON-encoded messages. Another difference is that the Kafka consumer is subscribed to the new_orders topic." }, { "code": null, "e": 16959, "s": 16693, "text": "import jsonimport timeimport datetimeimport threadingfrom kafka import KafkaConsumerconsumer = KafkaConsumer(‘new_orders’,bootstrap_servers=[‘localhost:9092’],auto_offset_reset=’earliest’,enable_auto_commit=True,auto_commit_interval_ms=1000,consumer_timeout_ms==-1)" }, { "code": null, "e": 17442, "s": 16959, "text": "The main function is the fetch_last_minute_orders(). The difference from the function with the previous consumer is that this function has six counters instead of just one. We want to count the total number of orders created over one minute, the total amount of items ordered, the total cost for all orders, as well as how many orders are prepaid, how many items were in prepaid orders, and the total price for all prepaid orders. These metrics could be useful for further analysis." }, { "code": null, "e": 17746, "s": 17442, "text": "Another difference is that before starting the calculation of the aforementioned values, we need to decode the message fetched from Kafka using the json library. All other logic is the same as for the consumer that works with requests. This file to which the data should be written is called orders.csv." }, { "code": null, "e": 19050, "s": 17746, "text": "def fetch_last_minute_orders(next_call_in, is_first_execution=False):next_call_in += 60count_orders = 0count_tot_amount = 0count_tot_price = 0count_orders_paid = 0count_tot_paid_amount = 0count_tot_paid_price = 0if is_first_execution:with open(‘orders.csv’,’a’) as file:headers = [“datetime”, “total_orders_num”,“total_orders_amount”, “total_orders_price”,“total_paid_orders_num”,“total_paid_orders_amount”,“Total_paid_orders_price”]file.write(“,”.join(headers))file.write(‘\\n’)else:batch = consumer.poll(timeout_ms=100)if len(batch) > 0:for message in list(batch.values())[0]:value = message.value.decode()order_dict = json.loads(value)# all orderscount_orders += 1count_tot_amount += order_dict[“order_amount”]count_tot_price += order_dict[“order_total_price”]if order_dict[“is_paid”]:# only paid orderscount_orders_paid += 1count_tot_paid_amount += order_dict[“order_amount”]count_tot_paid_price += order_dict[“order_total_price”]with open(‘orders.csv’,’a’) as file:data = [datetime.datetime.now().strftime(“%Y-%m-%d %H:%M:%S”),str(count_orders), str(count_tot_amount),str(count_tot_price), str(count_orders_paid),str(count_tot_paid_amount),str(count_tot_paid_price)]file.write(“,”.join(data))file.write(‘\\n’)threading.Timer(next_call_in — time.time(),fetch_last_minute_orders,[next_call_in]).start()" }, { "code": null, "e": 19157, "s": 19050, "text": "The last part of the file is the same: getting the current time and triggering the function defined above:" }, { "code": null, "e": 19228, "s": 19157, "text": "next_call_in = time.time()fetch_last_minute_orders(next_call_in, True)" }, { "code": null, "e": 19464, "s": 19228, "text": "Given that you already have the Kafka cluster running, you can execute the consumer_orders.py file. Next, go to your Flask app and create some orders for several minutes. The generated orders.csv file will have the following structure:" }, { "code": null, "e": 19575, "s": 19464, "text": "You can see that our Python scripts (especially those that work with order data) perform some data enrichment." }, { "code": null, "e": 19927, "s": 19575, "text": "Data engineers can customize this process. For example, if the app is very large and high-loaded, the Kafka cluster should be scaled horizontally. You can have many topics for different metrics, and each topic could be processed in its own way. It is possible to track new user registrations, user churns, the number of feedbacks, survey results, etc." }, { "code": null, "e": 20254, "s": 19927, "text": "Also, you can set up a collection of some low-level metrics like CPU load or memory consumption. The basic pipeline will be similar. It is also worth mentioning that writing data into CSV files is not the only option you can also make use of open data formats such as Parquet and land all this data directly on your data lake." }, { "code": null, "e": 20473, "s": 20254, "text": "Once you have the metrics collected, you can use Dremio to directly query the data, as well as to create and share virtual data sets that combine the metrics with other sources in the data lake, all without any copies." } ]
Initialization of static variables in C - GeeksforGeeks
31 Jul, 2018 In C, static variables can only be initialized using constant literals. For example, following program fails in compilation. #include<stdio.h>int initializer(void){ return 50;} int main(){ static int i = initializer(); printf(" value of i = %d", i); getchar(); return 0;} If we change the program to following, then it works without any error. #include<stdio.h>int main(){ static int i = 50; printf(" value of i = %d", i); getchar(); return 0;} The reason for this is simple: All objects with static storage duration must be initialized (set to their initial values) before execution of main() starts. So a value which is not known at translation time cannot be used for initialization of static variables. Thanks to Venki and Prateek for their contribution. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. C-Storage Classes and Type Qualifiers C Language 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++ Different methods to reverse a string in C/C++ Structures in C TCP Server-Client implementation in C Enumeration (or enum) in C Data Types in C std::string class in C++
[ { "code": null, "e": 24436, "s": 24408, "text": "\n31 Jul, 2018" }, { "code": null, "e": 24561, "s": 24436, "text": "In C, static variables can only be initialized using constant literals. For example, following program fails in compilation." }, { "code": "#include<stdio.h>int initializer(void){ return 50;} int main(){ static int i = initializer(); printf(\" value of i = %d\", i); getchar(); return 0;}", "e": 24724, "s": 24561, "text": null }, { "code": null, "e": 24796, "s": 24724, "text": "If we change the program to following, then it works without any error." }, { "code": "#include<stdio.h>int main(){ static int i = 50; printf(\" value of i = %d\", i); getchar(); return 0;}", "e": 24909, "s": 24796, "text": null }, { "code": null, "e": 25171, "s": 24909, "text": "The reason for this is simple: All objects with static storage duration must be initialized (set to their initial values) before execution of main() starts. So a value which is not known at translation time cannot be used for initialization of static variables." }, { "code": null, "e": 25223, "s": 25171, "text": "Thanks to Venki and Prateek for their contribution." }, { "code": null, "e": 25348, "s": 25223, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 25386, "s": 25348, "text": "C-Storage Classes and Type Qualifiers" }, { "code": null, "e": 25397, "s": 25386, "text": "C Language" }, { "code": null, "e": 25495, "s": 25397, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25507, "s": 25495, "text": "fork() in C" }, { "code": null, "e": 25539, "s": 25507, "text": "Command line arguments in C/C++" }, { "code": null, "e": 25561, "s": 25539, "text": "Function Pointer in C" }, { "code": null, "e": 25578, "s": 25561, "text": "Substring in C++" }, { "code": null, "e": 25625, "s": 25578, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 25641, "s": 25625, "text": "Structures in C" }, { "code": null, "e": 25679, "s": 25641, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 25706, "s": 25679, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 25722, "s": 25706, "text": "Data Types in C" } ]
Calculate age based on date of birth in MySQL?
Calculate Age based on date of birth with the help of DATE_FORMAT() method in MySQL. Firstly, get the current date time with the help of now() method and you can place your date of birth in DATE_FORMAT(). The syntax is as follows − SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(now(),'yourDateofbirth')), '%Y')+0 AS anyVariableName; Apply the above syntax to calculate age from yourDateofbirth. In the above syntax, replace yourDateofbirth with your date of birth. The query is as follows − SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(now(),'2010-11-25')), '%Y')+0 AS Age; The following is the output − +------+ | Age | +------+ | 8 | +------+ 1 row in set (0.00 sec) Let us now see this in an example. Firstly, create a table − mysql> create table AgeCalculationFromDatetime -> ( -> YourDateofBirth datetime -> ); Query OK, 0 rows affected (0.52 sec) Inserting date of birth into table. The query is as follows − mysql> insert into AgeCalculationFromDatetime values('1995-11-25'); Query OK, 1 row affected (0.13 sec) Displaying all records with the help of select statement. The query is as follows − mysql> select *from AgeCalculationFromDatetime; The following is the output − +---------------------+ | YourDateofBirth | +---------------------+ | 1995-11-25 00:00:00 | +---------------------+ 1 row in set (0.00 sec) The query to calculate age is as follows − mysql> SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(now(),YourDateofBirth)), '%Y')+0 AS Age from AgeCalculationFromDatetime; Here is the output − +------+ | Age | +------+ | 23 | +------+ 1 row in set (0.00 sec)`
[ { "code": null, "e": 1267, "s": 1062, "text": "Calculate Age based on date of birth with the help of DATE_FORMAT() method in MySQL. Firstly, get the current date time with the help of now() method and you can place your date of birth in DATE_FORMAT()." }, { "code": null, "e": 1294, "s": 1267, "text": "The syntax is as follows −" }, { "code": null, "e": 1387, "s": 1294, "text": "SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(now(),'yourDateofbirth')), '%Y')+0 AS anyVariableName;" }, { "code": null, "e": 1545, "s": 1387, "text": "Apply the above syntax to calculate age from yourDateofbirth. In the above syntax, replace yourDateofbirth with your date of birth. The query is as follows −" }, { "code": null, "e": 1621, "s": 1545, "text": "SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(now(),'2010-11-25')), '%Y')+0 AS Age;" }, { "code": null, "e": 1651, "s": 1621, "text": "The following is the output −" }, { "code": null, "e": 1720, "s": 1651, "text": "+------+\n| Age |\n+------+\n| 8 |\n+------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 1781, "s": 1720, "text": "Let us now see this in an example. Firstly, create a table −" }, { "code": null, "e": 1913, "s": 1781, "text": "mysql> create table AgeCalculationFromDatetime\n -> (\n -> YourDateofBirth datetime\n -> );\nQuery OK, 0 rows affected (0.52 sec)" }, { "code": null, "e": 1975, "s": 1913, "text": "Inserting date of birth into table. The query is as follows −" }, { "code": null, "e": 2079, "s": 1975, "text": "mysql> insert into AgeCalculationFromDatetime values('1995-11-25');\nQuery OK, 1 row affected (0.13 sec)" }, { "code": null, "e": 2163, "s": 2079, "text": "Displaying all records with the help of select statement. The query is as follows −" }, { "code": null, "e": 2211, "s": 2163, "text": "mysql> select *from AgeCalculationFromDatetime;" }, { "code": null, "e": 2241, "s": 2211, "text": "The following is the output −" }, { "code": null, "e": 2385, "s": 2241, "text": "+---------------------+\n| YourDateofBirth |\n+---------------------+\n| 1995-11-25 00:00:00 |\n+---------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 2428, "s": 2385, "text": "The query to calculate age is as follows −" }, { "code": null, "e": 2546, "s": 2428, "text": "mysql> SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(now(),YourDateofBirth)), '%Y')+0 AS Age from AgeCalculationFromDatetime;" }, { "code": null, "e": 2567, "s": 2546, "text": "Here is the output −" }, { "code": null, "e": 2637, "s": 2567, "text": "+------+\n| Age |\n+------+\n| 23 |\n+------+\n1 row in set (0.00 sec)`" } ]
Recurrent Neural Nets for Audio Classification | by Papia Nandi | Towards Data Science
RNNs or Recurrent Neural nets are a type of deep learning algorithm that can remember sequences. What kind of sequences? Handwriting/speech recognition Time series Text for natural language processing Things that depend on a previous item Yes. Unless the audio is a random stream of garbage (not the band), audio information tends to follow a pattern. Behold the first two measures of Beethoven’s Moonlight Sonata: Pretty repetitive! How do you think he kept writing music after he lost his hearing? Pattern recognition and memory. Also genius. The data for this example are bird and frog recordings from the Kaggle competition Rainforest Connection Species Audio Detection. They’re adorable. To get started, load the necessary imports: import pandas as pdimport osimport librosaimport librosa.displayimport matplotlib.pyplot as pltfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import normalizeimport warningswarnings.filterwarnings('ignore')from sklearn.model_selection import train_test_splitimport tensorflowfrom tensorflow.keras.layers import LSTM, Dense Then the dataframe: os.chdir('/kaggle/input/rfcx-species-audio-detection')df = pd.read_csv('train_tp.csv') This dataset comes as a csv file with the names of audio files listed under recording_id, labels under species_id, and the start/end of the audio sample under t_min and t_max: df.head() Use the librosa package to load and display an audio file like this: sample_num=3 #pick a file to displayfilename=df.recording_id[sample_num]+str('.flac') #get the filename#define the beginning time of the signaltstart = df.t_min[sample_num] tend = df.t_max[sample_num] #define the end time of the signaly,sr=librosa.load('train/'+str(filename))librosa.display.waveplot(y,sr=sr, x_axis='time', color='purple',offset=0.0) Librosa has great tutorials on how to extract features here. For RNNs, I found that the best feature were the Mel-frequency cepstral coefficients (MFCCs), a spectral feature of sound. You can calculate it like this: hop_length = 512 #the default spacing between framesn_fft = 255 #number of samples #cut the sample to the relevant timesy_cut=y[int(round(tstart*sr)):int(round(tend*sr))]MFCCs = librosa.feature.mfcc(y_cut, n_fft=n_fft,hop_length=hop_length,n_mfcc=128)fig, ax = plt.subplots(figsize=(20,7))librosa.display.specshow(MFCCs,sr=sr, cmap='cool',hop_length=hop_length)ax.set_xlabel('Time', fontsize=15)ax.set_title('MFCC', size=20)plt.colorbar()plt.show() def get_features(df_in): features=[] #list to save features labels=[] #list to save labels for index in range(0,len(df_in)): #get the filename filename = df_in.iloc[index]['recording_id']+str('.flac') #cut to start of signal tstart = df_in.iloc[index]['t_min'] #cut to end of signal tend = df_in.iloc[index]['t_max'] #save labels species_id = df_in.iloc[index]['species_id'] #load the file y, sr = librosa.load('train/'+filename,sr=28000) #cut the file from tstart to tend y_cut = y[round(tstart*sr,ndigits=None) :round(tend*sr, ndigits= None)] data = np.array([padding(librosa.feature.mfcc(y_cut, n_fft=n_fft,hop_length=hop_length,n_mfcc=128),1,400)]) features.append(data) labels.append(species_id) output=np.concatenate(features,axis=0) return(np.array(output), labels)X,y=get_features(df) X = np.array((X-np.min(X))/(np.max(X)-np.min(X)))X = X/np.std(X)y = np.array(y) #Split twice to get the validation setX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=123, stratify=y)X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.25, random_state=123)#Print the shapesX_train.shape, X_test.shape, X_val.shape, len(y_train), len(y_test), len(y_val) In this example model, a Long Short-Term Memory (LSTM) unit is the portion that does the remembering, the Dropout randomly sets the weights of a portion of the data to zero to guard against overfitting, and the Dense units contain hidden layers tied to the degrees of freedom the model has to try and fit the data. The more complex the data, the more degrees of freedom the model needs all the while taking care to avoid overfitting (more on this later). The last Dense layer outputs the 24 species that the model is supposed to classify the audio recordings into. input_shape=(128,1000)model = keras.Sequential()model.add(LSTM(128,input_shape=input_shape))model.add(Dropout(0.2))model.add(Dense(128, activation='relu'))model.add(Dense(64, activation='relu'))model.add(Dropout(0.4))model.add(Dense(48, activation='relu'))model.add(Dropout(0.4))model.add(Dense(24, activation='softmax'))model.summary() The activation functions add nonlinearity to the model. Here, the relu function is used, which zeros out negative weights. The last Dense layer’s activation function is softmax, which outputs a probability for each class. Tensorflow has other activation functions that you can read about here. The input shape can be confusing because even though it appears to be 2D, it’s actually 3D. Because of the parameters chosen when they were created, the shape of these MFCCs happen to be 128 in height and 1000 in length, and there are as many of them as there are audio files. If we only extracted features for the 5 audio files pictured in the dataframe.head() figure, the shape of the input would be 5x128x1000. This parameter is called the batch size and it’s not included in the input shape. model.compile(optimizer='adam',loss='SparseCategoricalCrossentropy',metrics=['acc']) The Adam optimizer manages the learning rate for stochastic gradient descent, and is a good one to start with. The loss function is SparseCategoricalCrossentropy, which is used when each sample belongs to one label, as opposed to more than one, and it’s not binary classification. That’s the case for this classification problem where each audio sample belongs to one species. history = model.fit(X_train, y_train, epochs=50, batch_size=72, validation_data=(X_val, y_val), shuffle=False) BUT you have to overfit temporarily in order to know where the boundary between overfitting and underfitting is (F. Chollet, 2018). Try this: input_shape=(128,1000)model = tensorflow.keras.Sequential()model.add(LSTM(NUM,input_shape=input_shape))model.add(Dense(24, activation='softmax'))model.summary() where NUM is some number larger than your output layer, and add layers until your model starts to overfit the data. How do you know when this happens? If the performance between the training and test set is different (training accuracy is 99% and test is 89% for example), you have overfit the data.When the validation measure of choice (accuracy in this case) begins to decrease, stop iterating. In the graphs below, this happens around 50 epochs. If the performance between the training and test set is different (training accuracy is 99% and test is 89% for example), you have overfit the data. When the validation measure of choice (accuracy in this case) begins to decrease, stop iterating. In the graphs below, this happens around 50 epochs. #Adapted from Deep Learning with Python by Francois Chollet, 2018history_dict=history.historyloss_values=history_dict['loss']acc_values=history_dict['acc']val_loss_values = history_dict['val_loss']val_acc_values=history_dict['val_acc']epochs=range(1,51)fig,(ax1,ax2)=plt.subplots(1,2,figsize=(15,5))ax1.plot(epochs,loss_values,'co',label='Training Loss')ax1.plot(epochs,val_loss_values,'m', label='Validation Loss')ax1.set_title('Training and validation loss')ax1.set_xlabel('Epochs')ax1.set_ylabel('Loss')ax1.legend()ax2.plot(epochs,acc_values,'co', label='Training accuracy')ax2.plot(epochs,val_acc_values,'m',label='Validation accuracy')ax2.set_title('Training and validation accuracy')ax2.set_xlabel('Epochs')ax2.set_ylabel('Accuracy')ax2.legend()plt.show() If all of the entries line up on the diagonal of the matrix, the model has made perfect predictions on the test set. Anything else has been misclassified. TrainLoss, Trainacc = model.evaluate(X_train,y_train)TestLoss, Testacc = model.evaluate(X_test, y_test)y_pred=model.predict(X_test)print('Confusion_matrix: ',tf.math.confusion_matrix(y_test, np.argmax(y_pred,axis=1))) You now know how to create an RNN using audio data by starting with a simple model, and adding layers until it is able to predict the data to the best of its ability. Modify the architecture until your model begins to overfit the data to understand where this boundary is, then go back and remove layers. Look for discrepancies in performance between the training and test data and add Dropout layers to prevent overfitting to the training data. Look for a decrease in performance in the validation data to know when to stop iterating. Sarkar, Dipanjan (2021) Personal communication. Chollet, F. Deep Learning with Python (2018), v. 361, New York: Manning. Gervias, Nicolas, (2021) Code adopted from https://stackoverflow.com/questions/59241216/padding-numpy-arrays-to-a-specific-size, retrieved on 1/10/2021. frenzykryger (2021) https://datascience.stackexchange.com/questions/41921/sparse-categorical-crossentropy-vs-categorical-crossentropy-keras-accuracy#:~:text=Use%20sparse%20categorical%20crossentropy%20when,0.5%2C%200.3%2C%200.2%5D, retrieved on 2/21/2021.
[ { "code": null, "e": 143, "s": 46, "text": "RNNs or Recurrent Neural nets are a type of deep learning algorithm that can remember sequences." }, { "code": null, "e": 167, "s": 143, "text": "What kind of sequences?" }, { "code": null, "e": 198, "s": 167, "text": "Handwriting/speech recognition" }, { "code": null, "e": 210, "s": 198, "text": "Time series" }, { "code": null, "e": 247, "s": 210, "text": "Text for natural language processing" }, { "code": null, "e": 285, "s": 247, "text": "Things that depend on a previous item" }, { "code": null, "e": 398, "s": 285, "text": "Yes. Unless the audio is a random stream of garbage (not the band), audio information tends to follow a pattern." }, { "code": null, "e": 461, "s": 398, "text": "Behold the first two measures of Beethoven’s Moonlight Sonata:" }, { "code": null, "e": 578, "s": 461, "text": "Pretty repetitive! How do you think he kept writing music after he lost his hearing? Pattern recognition and memory." }, { "code": null, "e": 591, "s": 578, "text": "Also genius." }, { "code": null, "e": 739, "s": 591, "text": "The data for this example are bird and frog recordings from the Kaggle competition Rainforest Connection Species Audio Detection. They’re adorable." }, { "code": null, "e": 783, "s": 739, "text": "To get started, load the necessary imports:" }, { "code": null, "e": 1138, "s": 783, "text": "import pandas as pdimport osimport librosaimport librosa.displayimport matplotlib.pyplot as pltfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import normalizeimport warningswarnings.filterwarnings('ignore')from sklearn.model_selection import train_test_splitimport tensorflowfrom tensorflow.keras.layers import LSTM, Dense" }, { "code": null, "e": 1158, "s": 1138, "text": "Then the dataframe:" }, { "code": null, "e": 1245, "s": 1158, "text": "os.chdir('/kaggle/input/rfcx-species-audio-detection')df = pd.read_csv('train_tp.csv')" }, { "code": null, "e": 1421, "s": 1245, "text": "This dataset comes as a csv file with the names of audio files listed under recording_id, labels under species_id, and the start/end of the audio sample under t_min and t_max:" }, { "code": null, "e": 1431, "s": 1421, "text": "df.head()" }, { "code": null, "e": 1500, "s": 1431, "text": "Use the librosa package to load and display an audio file like this:" }, { "code": null, "e": 1852, "s": 1500, "text": "sample_num=3 #pick a file to displayfilename=df.recording_id[sample_num]+str('.flac') #get the filename#define the beginning time of the signaltstart = df.t_min[sample_num] tend = df.t_max[sample_num] #define the end time of the signaly,sr=librosa.load('train/'+str(filename))librosa.display.waveplot(y,sr=sr, x_axis='time', color='purple',offset=0.0)" }, { "code": null, "e": 2068, "s": 1852, "text": "Librosa has great tutorials on how to extract features here. For RNNs, I found that the best feature were the Mel-frequency cepstral coefficients (MFCCs), a spectral feature of sound. You can calculate it like this:" }, { "code": null, "e": 2517, "s": 2068, "text": "hop_length = 512 #the default spacing between framesn_fft = 255 #number of samples #cut the sample to the relevant timesy_cut=y[int(round(tstart*sr)):int(round(tend*sr))]MFCCs = librosa.feature.mfcc(y_cut, n_fft=n_fft,hop_length=hop_length,n_mfcc=128)fig, ax = plt.subplots(figsize=(20,7))librosa.display.specshow(MFCCs,sr=sr, cmap='cool',hop_length=hop_length)ax.set_xlabel('Time', fontsize=15)ax.set_title('MFCC', size=20)plt.colorbar()plt.show()" }, { "code": null, "e": 3443, "s": 2517, "text": "def get_features(df_in): features=[] #list to save features labels=[] #list to save labels for index in range(0,len(df_in)): #get the filename filename = df_in.iloc[index]['recording_id']+str('.flac') #cut to start of signal tstart = df_in.iloc[index]['t_min'] #cut to end of signal tend = df_in.iloc[index]['t_max'] #save labels species_id = df_in.iloc[index]['species_id'] #load the file y, sr = librosa.load('train/'+filename,sr=28000) #cut the file from tstart to tend y_cut = y[round(tstart*sr,ndigits=None) :round(tend*sr, ndigits= None)] data = np.array([padding(librosa.feature.mfcc(y_cut, n_fft=n_fft,hop_length=hop_length,n_mfcc=128),1,400)]) features.append(data) labels.append(species_id) output=np.concatenate(features,axis=0) return(np.array(output), labels)X,y=get_features(df)" }, { "code": null, "e": 3523, "s": 3443, "text": "X = np.array((X-np.min(X))/(np.max(X)-np.min(X)))X = X/np.std(X)y = np.array(y)" }, { "code": null, "e": 3862, "s": 3523, "text": "#Split twice to get the validation setX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=123, stratify=y)X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.25, random_state=123)#Print the shapesX_train.shape, X_test.shape, X_val.shape, len(y_train), len(y_test), len(y_val)" }, { "code": null, "e": 4427, "s": 3862, "text": "In this example model, a Long Short-Term Memory (LSTM) unit is the portion that does the remembering, the Dropout randomly sets the weights of a portion of the data to zero to guard against overfitting, and the Dense units contain hidden layers tied to the degrees of freedom the model has to try and fit the data. The more complex the data, the more degrees of freedom the model needs all the while taking care to avoid overfitting (more on this later). The last Dense layer outputs the 24 species that the model is supposed to classify the audio recordings into." }, { "code": null, "e": 4764, "s": 4427, "text": "input_shape=(128,1000)model = keras.Sequential()model.add(LSTM(128,input_shape=input_shape))model.add(Dropout(0.2))model.add(Dense(128, activation='relu'))model.add(Dense(64, activation='relu'))model.add(Dropout(0.4))model.add(Dense(48, activation='relu'))model.add(Dropout(0.4))model.add(Dense(24, activation='softmax'))model.summary()" }, { "code": null, "e": 5058, "s": 4764, "text": "The activation functions add nonlinearity to the model. Here, the relu function is used, which zeros out negative weights. The last Dense layer’s activation function is softmax, which outputs a probability for each class. Tensorflow has other activation functions that you can read about here." }, { "code": null, "e": 5554, "s": 5058, "text": "The input shape can be confusing because even though it appears to be 2D, it’s actually 3D. Because of the parameters chosen when they were created, the shape of these MFCCs happen to be 128 in height and 1000 in length, and there are as many of them as there are audio files. If we only extracted features for the 5 audio files pictured in the dataframe.head() figure, the shape of the input would be 5x128x1000. This parameter is called the batch size and it’s not included in the input shape." }, { "code": null, "e": 5639, "s": 5554, "text": "model.compile(optimizer='adam',loss='SparseCategoricalCrossentropy',metrics=['acc'])" }, { "code": null, "e": 6016, "s": 5639, "text": "The Adam optimizer manages the learning rate for stochastic gradient descent, and is a good one to start with. The loss function is SparseCategoricalCrossentropy, which is used when each sample belongs to one label, as opposed to more than one, and it’s not binary classification. That’s the case for this classification problem where each audio sample belongs to one species." }, { "code": null, "e": 6147, "s": 6016, "text": "history = model.fit(X_train, y_train, epochs=50, batch_size=72, validation_data=(X_val, y_val), shuffle=False)" }, { "code": null, "e": 6279, "s": 6147, "text": "BUT you have to overfit temporarily in order to know where the boundary between overfitting and underfitting is (F. Chollet, 2018)." }, { "code": null, "e": 6289, "s": 6279, "text": "Try this:" }, { "code": null, "e": 6450, "s": 6289, "text": "input_shape=(128,1000)model = tensorflow.keras.Sequential()model.add(LSTM(NUM,input_shape=input_shape))model.add(Dense(24, activation='softmax'))model.summary()" }, { "code": null, "e": 6566, "s": 6450, "text": "where NUM is some number larger than your output layer, and add layers until your model starts to overfit the data." }, { "code": null, "e": 6601, "s": 6566, "text": "How do you know when this happens?" }, { "code": null, "e": 6899, "s": 6601, "text": "If the performance between the training and test set is different (training accuracy is 99% and test is 89% for example), you have overfit the data.When the validation measure of choice (accuracy in this case) begins to decrease, stop iterating. In the graphs below, this happens around 50 epochs." }, { "code": null, "e": 7048, "s": 6899, "text": "If the performance between the training and test set is different (training accuracy is 99% and test is 89% for example), you have overfit the data." }, { "code": null, "e": 7198, "s": 7048, "text": "When the validation measure of choice (accuracy in this case) begins to decrease, stop iterating. In the graphs below, this happens around 50 epochs." }, { "code": null, "e": 7960, "s": 7198, "text": "#Adapted from Deep Learning with Python by Francois Chollet, 2018history_dict=history.historyloss_values=history_dict['loss']acc_values=history_dict['acc']val_loss_values = history_dict['val_loss']val_acc_values=history_dict['val_acc']epochs=range(1,51)fig,(ax1,ax2)=plt.subplots(1,2,figsize=(15,5))ax1.plot(epochs,loss_values,'co',label='Training Loss')ax1.plot(epochs,val_loss_values,'m', label='Validation Loss')ax1.set_title('Training and validation loss')ax1.set_xlabel('Epochs')ax1.set_ylabel('Loss')ax1.legend()ax2.plot(epochs,acc_values,'co', label='Training accuracy')ax2.plot(epochs,val_acc_values,'m',label='Validation accuracy')ax2.set_title('Training and validation accuracy')ax2.set_xlabel('Epochs')ax2.set_ylabel('Accuracy')ax2.legend()plt.show()" }, { "code": null, "e": 8115, "s": 7960, "text": "If all of the entries line up on the diagonal of the matrix, the model has made perfect predictions on the test set. Anything else has been misclassified." }, { "code": null, "e": 8333, "s": 8115, "text": "TrainLoss, Trainacc = model.evaluate(X_train,y_train)TestLoss, Testacc = model.evaluate(X_test, y_test)y_pred=model.predict(X_test)print('Confusion_matrix: ',tf.math.confusion_matrix(y_test, np.argmax(y_pred,axis=1)))" }, { "code": null, "e": 8869, "s": 8333, "text": "You now know how to create an RNN using audio data by starting with a simple model, and adding layers until it is able to predict the data to the best of its ability. Modify the architecture until your model begins to overfit the data to understand where this boundary is, then go back and remove layers. Look for discrepancies in performance between the training and test data and add Dropout layers to prevent overfitting to the training data. Look for a decrease in performance in the validation data to know when to stop iterating." }, { "code": null, "e": 8917, "s": 8869, "text": "Sarkar, Dipanjan (2021) Personal communication." }, { "code": null, "e": 8990, "s": 8917, "text": "Chollet, F. Deep Learning with Python (2018), v. 361, New York: Manning." }, { "code": null, "e": 9143, "s": 8990, "text": "Gervias, Nicolas, (2021) Code adopted from https://stackoverflow.com/questions/59241216/padding-numpy-arrays-to-a-specific-size, retrieved on 1/10/2021." } ]
How to Pull Data from an API using Python Requests | by Cameron Warren | Towards Data Science
The thing that I’m asked to do over and over again is automate pulling data from an API. Despite holding the title “Data Scientist” I’m on a small team, so I’m not only responsible for building models, but also pulling data, cleaning it, and pushing and pulling it wherever it needs to go. Many of you are probably in the same boat. When I first began my journey for learning how to make HTTP requests, pull back a JSON string, parse it, and then push it into a database I had a very hard time finding clear, concise articles explaining how to actually do this very important task. If you’ve ever gone down a Google black hole to resolve a technical problem, you’ve probably discovered that very technical people like to use technical language in order to explain how to perform the given task. The problem with that is, if you’re self-taught, as I am, you not only have to learn how to do the task you’ve been asked to do but also learn a new technical language. This can be incredibly frustrating. If you want to avoid learning technical jargon and just get straight to the point, you’ve come to the right place. In this article, I’m going to show you how to pull data from an API and then automate the task to re-pull every 24 hours. For this example, I will utilize the Microsoft Graph API and demonstrate how to pull text from emails. I will refrain from using pre-prepared API packages and rely on HTTP requests using the Python Requests package — this way you can apply what you learn here to nearly any other RESTful API that you’d need to work on. If you're having trouble with API requests in this tutorial, here’s a tip: Use Postman. Postman is a fantastic app that allows you to set up and make API calls through a clean interface. The beauty of it is once you get the API call working, you can export the code in Python and then paste it right into your script. It’s amazing. *Note: This tutorial is meant to be a simple and easy to understand method to access an API, that’s it. It will likely not be robust to your exact situation or data needs, but should hopefully set you down the right path. I’ve found the below method to be the simplest to understand to quickly get to pulling data. If you have suggestions to make things even easier, sound off in the comments. There’s no way around navigating API documentation. For working with Outlook, you go here. If you are successful in following this tutorial and want to do more with the API, use that link for a reference. Most APIs, including the Microsoft Graph, require authorization before they’ll give you an access token that will allow you to call the API. This is often the most difficult part for someone new to pulling data from APIs (it was for me). Register your App Follow the instructions here to register your app (these are pretty straightforward and use the Azure GUI) You’ll need a school, work, or personal Microsoft account to register. If you use a work email, you’ll need admin access to your Azure instance. If you’re doing this for work, contact your IT department and they’ll likely be able to register the app for you. Select ‘web’ as your app type and use a trusted URL for your redirect URI (one that only you have access to the underlying web data. I used franklinsports.com as only my team can access the web data for that site. If you were building an app, you would redirect to your app to a place where your app could pick up the code and authorize the user). Enable Microsft Graph Permissions Once your app is registered, go to the App Registration portal: Click where it displays the name of your app: On the following page, click on ‘View API Permissions’. Finally, select the Microsoft Graph and then check all the boxes under Messages for ‘Delegated Permissions.’ (Note for this example I’ll only be pulling emails from a single signed-in user, to pull email data for an organization you’ll need application permissions — follow the flow here). Ok — you’re ready to start making API calls. Authorization Step 1: Get an access code You’ll need an access code to get the access token that will allow you to make calls to the MS Graph API. To do this, enter the following URL into your browser, swapping the appropriate credentials with the information shown on your app page. Goes in the URL: Take the URL that outputs from the code snippet and paste it into your browser. Hit enter, and you’ll be asked to authorize your Microsoft account for delegated access. Use the Microsoft account that you used to register your app. If the authorization doesn’t work, there’s something wrong with the redirect URL you’ve chosen or with the app registration. I’ve had trouble with this part before — so don’t fret if it doesn’t work on your first try. If the authorization is successful, you’ll be redirected to the URL that you used in the App registration. Appended to the URL will be parameters that contain the code you’ll use in our next step — it should look like this: Take the full code and save it in your python script. Authorization Step 2: Use your access code to get a refresh token. Before proceeding, make sure you have the latest version of the Python Requests package installed. The simplest way to do that is by using pip: In this step, you will take the code generated in step 1 and send a POST request to the MS Graph OAuth authorization endpoint in order to acquire a refresh token. (*Note: For security purposes, I recommend storing your client_secret on a different script than the one you use to call the API. You can store the secret in a variable and then import it (or by using pickle, which you’ll see below). Swap the ####### in the code snippet with your own app information and the code you received in step 1, and then run it. (*Note: The redirect URI must be url encoded which means it’ll look like this: “https%3A%2F%2Ffranklinsports.com”) You should receive a JSON response that looks something like this: {‘access_token’:’#######################’,’refresh_token’:’###################’} Authorization Step 3: Use your refresh token to get an access token At this point you already have an access token and could begin calling the API, however, that access token will expire after a set amount of time. Therefore we want to set up our script to acquire a fresh access token each time we run it so that our automation will not break. I like to store the new refresh_token from step 2 in a pickle object, and then load it in to get the fresh access_token when the script is run: filename = ####path to the name of your pickle file#######print(filename) filehandler = open(filename, ‘rb’) refresh_token = pickle.load(filehandler)url = “https://login.microsoftonline.com/common/oauth2/v2.0/token" payload = “””client_id%0A=##########& redirect_uri=##################& client_secret=##################& code={}& refresh_token={}& grant_type=refresh_token”””.format(code,refresh_token) headers = { ‘Content-Type’: “application/x-www-form-urlencoded”, ‘cache-control’: “no-cache” } response = requests.request(“POST”, url, data=payload, headers=headers)r = response.json() access_token = r.get(‘access_token’) refresh_token = r.get(‘refresh_token’) with open(filename, ‘wb’) as f: pickle.dump(refresh_token, f) With your access_token in tow, you’re ready to call the API and start pulling data. The below code snippet will demonstrate how to retrieve the last 5 email messages with specific subject paramaters. Place the access_token (bolded below) in the headers and pass it in the get request to the email messages endpoint. import jsonimport requestsurl = ‘https://graph.microsoft.com/v1.0/me/messages$search="subject:###SUBJECT YOU WANT TO SEARCH FOR###”’headers = { ‘Authorization’: ‘Bearer ‘ +access_token, ‘Content-Type’: ‘application/json; charset=utf-8’ }r = requests.get(url, headers=headers)files = r.json()print(files) The code above will return a json output that contains your data. If you want more than 5 emails, you’ll need to paginate through the results. Most APIs have thier own methods for how to best paginate results (in english, most APIs will not give you all the data you want with just one API call, so they give you ways to make multiple calls that allow you to move through the results in chunks to get all or as much as you want). The MS Graph is nice in that it provides the exact endpoint you need to go to to get the next page of results, making pagination easy. In the below code snippet, I demonstrate how to use a while loop to make successive calls to the api and add the subject and text of each email message to a list of lists. emails = []while True: try: url = files[‘@odata.nextLink’] for item in range (0,len(files[‘value’])): emails.append(files['value'][item]['Subject'],[files[‘value’] [item][‘bodyPreview’]) r = requests.get(url, headers=headers) print(r.text) files = r.json() except: break Finally, I’ll show an example of how put the JSON data into a CSV text file, which could then be analyzed with excel or pushed into a database. This code snippet will demonstrate how to write each row of our list of lists into a CSV file. import csv write_file =‘###LOCATION WHERE YOU WANT TO PUT THE CSV FILE###’ with open(write_file,’w’, newline = ‘’) as f: writer = csv.writer(f, lineterminator = ‘\n’) writer.writerows(emails) Now that our script is written. We want to automate it so we can get new messages within our parameters as they come in daily. I’ve done this in two ways, however, there are many ways to automate: Using Crontab on an Ubuntu Server Using Crontab on an Ubuntu Server This is quite simple. If your on Ubuntu, type into your console ‘crontab -e’ and it will open up your cronjobs in a text file. Go to a new line and type in: 0 1 * * * /full path to python environment/python /full path to file/example.py Assuming cron is set up correctly, the above would set the script to automatically run at 1 UTC every day (or whatever timezone your server is on). You can change that time to whatever you need it to by changing the 1 in the code. If you want to get complex with your cron timing, this site is a nice resource. 2. Using Windows Task Scheduler This is a nice and easy way to automate in windows that uses the Task Scheduler App. Simply open Task Scheduler and click ‘Create Task’ on the right hand side. This app is quite straightforward and allows you to set the schedule and what program you want to run using the GUI. When your in the ‘Actions’ pain, select Python as the program and then in the Add Arguments tab (the one with ‘(optional)’ next to it), put the path to your .py file. Thats it! In this walkthrough, I’ve shown you how to pull your email data from the Microsoft Graph API. The principles demonstrated here can be used to work with nearly any RESTful API or to do much more complex tasks with the Microsoft Graph (I’ve used the MS Graph API to push files in and out of our corporate sharepoint, push data from sharepoint folders into our database, and send automated emails and reports). Questions or comments? You can email me at cwarren@stitcher.tech. Or, follow me on Linkedin at https://www.linkedin.com/in/cameronwarren/ I also provide Data services, which you can learn more about at http://stitcher.tech/.
[ { "code": null, "e": 380, "s": 47, "text": "The thing that I’m asked to do over and over again is automate pulling data from an API. Despite holding the title “Data Scientist” I’m on a small team, so I’m not only responsible for building models, but also pulling data, cleaning it, and pushing and pulling it wherever it needs to go. Many of you are probably in the same boat." }, { "code": null, "e": 1047, "s": 380, "text": "When I first began my journey for learning how to make HTTP requests, pull back a JSON string, parse it, and then push it into a database I had a very hard time finding clear, concise articles explaining how to actually do this very important task. If you’ve ever gone down a Google black hole to resolve a technical problem, you’ve probably discovered that very technical people like to use technical language in order to explain how to perform the given task. The problem with that is, if you’re self-taught, as I am, you not only have to learn how to do the task you’ve been asked to do but also learn a new technical language. This can be incredibly frustrating." }, { "code": null, "e": 1604, "s": 1047, "text": "If you want to avoid learning technical jargon and just get straight to the point, you’ve come to the right place. In this article, I’m going to show you how to pull data from an API and then automate the task to re-pull every 24 hours. For this example, I will utilize the Microsoft Graph API and demonstrate how to pull text from emails. I will refrain from using pre-prepared API packages and rely on HTTP requests using the Python Requests package — this way you can apply what you learn here to nearly any other RESTful API that you’d need to work on." }, { "code": null, "e": 1936, "s": 1604, "text": "If you're having trouble with API requests in this tutorial, here’s a tip: Use Postman. Postman is a fantastic app that allows you to set up and make API calls through a clean interface. The beauty of it is once you get the API call working, you can export the code in Python and then paste it right into your script. It’s amazing." }, { "code": null, "e": 2330, "s": 1936, "text": "*Note: This tutorial is meant to be a simple and easy to understand method to access an API, that’s it. It will likely not be robust to your exact situation or data needs, but should hopefully set you down the right path. I’ve found the below method to be the simplest to understand to quickly get to pulling data. If you have suggestions to make things even easier, sound off in the comments." }, { "code": null, "e": 2535, "s": 2330, "text": "There’s no way around navigating API documentation. For working with Outlook, you go here. If you are successful in following this tutorial and want to do more with the API, use that link for a reference." }, { "code": null, "e": 2773, "s": 2535, "text": "Most APIs, including the Microsoft Graph, require authorization before they’ll give you an access token that will allow you to call the API. This is often the most difficult part for someone new to pulling data from APIs (it was for me)." }, { "code": null, "e": 2791, "s": 2773, "text": "Register your App" }, { "code": null, "e": 3505, "s": 2791, "text": "Follow the instructions here to register your app (these are pretty straightforward and use the Azure GUI) You’ll need a school, work, or personal Microsoft account to register. If you use a work email, you’ll need admin access to your Azure instance. If you’re doing this for work, contact your IT department and they’ll likely be able to register the app for you. Select ‘web’ as your app type and use a trusted URL for your redirect URI (one that only you have access to the underlying web data. I used franklinsports.com as only my team can access the web data for that site. If you were building an app, you would redirect to your app to a place where your app could pick up the code and authorize the user)." }, { "code": null, "e": 3539, "s": 3505, "text": "Enable Microsft Graph Permissions" }, { "code": null, "e": 3603, "s": 3539, "text": "Once your app is registered, go to the App Registration portal:" }, { "code": null, "e": 3649, "s": 3603, "text": "Click where it displays the name of your app:" }, { "code": null, "e": 3705, "s": 3649, "text": "On the following page, click on ‘View API Permissions’." }, { "code": null, "e": 3995, "s": 3705, "text": "Finally, select the Microsoft Graph and then check all the boxes under Messages for ‘Delegated Permissions.’ (Note for this example I’ll only be pulling emails from a single signed-in user, to pull email data for an organization you’ll need application permissions — follow the flow here)." }, { "code": null, "e": 4040, "s": 3995, "text": "Ok — you’re ready to start making API calls." }, { "code": null, "e": 4081, "s": 4040, "text": "Authorization Step 1: Get an access code" }, { "code": null, "e": 4324, "s": 4081, "text": "You’ll need an access code to get the access token that will allow you to make calls to the MS Graph API. To do this, enter the following URL into your browser, swapping the appropriate credentials with the information shown on your app page." }, { "code": null, "e": 4341, "s": 4324, "text": "Goes in the URL:" }, { "code": null, "e": 4572, "s": 4341, "text": "Take the URL that outputs from the code snippet and paste it into your browser. Hit enter, and you’ll be asked to authorize your Microsoft account for delegated access. Use the Microsoft account that you used to register your app." }, { "code": null, "e": 5014, "s": 4572, "text": "If the authorization doesn’t work, there’s something wrong with the redirect URL you’ve chosen or with the app registration. I’ve had trouble with this part before — so don’t fret if it doesn’t work on your first try. If the authorization is successful, you’ll be redirected to the URL that you used in the App registration. Appended to the URL will be parameters that contain the code you’ll use in our next step — it should look like this:" }, { "code": null, "e": 5068, "s": 5014, "text": "Take the full code and save it in your python script." }, { "code": null, "e": 5135, "s": 5068, "text": "Authorization Step 2: Use your access code to get a refresh token." }, { "code": null, "e": 5279, "s": 5135, "text": "Before proceeding, make sure you have the latest version of the Python Requests package installed. The simplest way to do that is by using pip:" }, { "code": null, "e": 5676, "s": 5279, "text": "In this step, you will take the code generated in step 1 and send a POST request to the MS Graph OAuth authorization endpoint in order to acquire a refresh token. (*Note: For security purposes, I recommend storing your client_secret on a different script than the one you use to call the API. You can store the secret in a variable and then import it (or by using pickle, which you’ll see below)." }, { "code": null, "e": 5912, "s": 5676, "text": "Swap the ####### in the code snippet with your own app information and the code you received in step 1, and then run it. (*Note: The redirect URI must be url encoded which means it’ll look like this: “https%3A%2F%2Ffranklinsports.com”)" }, { "code": null, "e": 5979, "s": 5912, "text": "You should receive a JSON response that looks something like this:" }, { "code": null, "e": 6060, "s": 5979, "text": "{‘access_token’:’#######################’,’refresh_token’:’###################’}" }, { "code": null, "e": 6128, "s": 6060, "text": "Authorization Step 3: Use your refresh token to get an access token" }, { "code": null, "e": 6549, "s": 6128, "text": "At this point you already have an access token and could begin calling the API, however, that access token will expire after a set amount of time. Therefore we want to set up our script to acquire a fresh access token each time we run it so that our automation will not break. I like to store the new refresh_token from step 2 in a pickle object, and then load it in to get the fresh access_token when the script is run:" }, { "code": null, "e": 7282, "s": 6549, "text": "filename = ####path to the name of your pickle file#######print(filename) filehandler = open(filename, ‘rb’) refresh_token = pickle.load(filehandler)url = “https://login.microsoftonline.com/common/oauth2/v2.0/token\" payload = “””client_id%0A=##########& redirect_uri=##################& client_secret=##################& code={}& refresh_token={}& grant_type=refresh_token”””.format(code,refresh_token) headers = { ‘Content-Type’: “application/x-www-form-urlencoded”, ‘cache-control’: “no-cache” } response = requests.request(“POST”, url, data=payload, headers=headers)r = response.json() access_token = r.get(‘access_token’) refresh_token = r.get(‘refresh_token’) with open(filename, ‘wb’) as f: pickle.dump(refresh_token, f)" }, { "code": null, "e": 7598, "s": 7282, "text": "With your access_token in tow, you’re ready to call the API and start pulling data. The below code snippet will demonstrate how to retrieve the last 5 email messages with specific subject paramaters. Place the access_token (bolded below) in the headers and pass it in the get request to the email messages endpoint." }, { "code": null, "e": 7902, "s": 7598, "text": "import jsonimport requestsurl = ‘https://graph.microsoft.com/v1.0/me/messages$search=\"subject:###SUBJECT YOU WANT TO SEARCH FOR###”’headers = { ‘Authorization’: ‘Bearer ‘ +access_token, ‘Content-Type’: ‘application/json; charset=utf-8’ }r = requests.get(url, headers=headers)files = r.json()print(files)" }, { "code": null, "e": 7968, "s": 7902, "text": "The code above will return a json output that contains your data." }, { "code": null, "e": 8639, "s": 7968, "text": "If you want more than 5 emails, you’ll need to paginate through the results. Most APIs have thier own methods for how to best paginate results (in english, most APIs will not give you all the data you want with just one API call, so they give you ways to make multiple calls that allow you to move through the results in chunks to get all or as much as you want). The MS Graph is nice in that it provides the exact endpoint you need to go to to get the next page of results, making pagination easy. In the below code snippet, I demonstrate how to use a while loop to make successive calls to the api and add the subject and text of each email message to a list of lists." }, { "code": null, "e": 8930, "s": 8639, "text": "emails = []while True: try: url = files[‘@odata.nextLink’] for item in range (0,len(files[‘value’])): emails.append(files['value'][item]['Subject'],[files[‘value’] [item][‘bodyPreview’]) r = requests.get(url, headers=headers) print(r.text) files = r.json() except: break" }, { "code": null, "e": 9169, "s": 8930, "text": "Finally, I’ll show an example of how put the JSON data into a CSV text file, which could then be analyzed with excel or pushed into a database. This code snippet will demonstrate how to write each row of our list of lists into a CSV file." }, { "code": null, "e": 9365, "s": 9169, "text": "import csv write_file =‘###LOCATION WHERE YOU WANT TO PUT THE CSV FILE###’ with open(write_file,’w’, newline = ‘’) as f: writer = csv.writer(f, lineterminator = ‘\\n’) writer.writerows(emails)" }, { "code": null, "e": 9492, "s": 9365, "text": "Now that our script is written. We want to automate it so we can get new messages within our parameters as they come in daily." }, { "code": null, "e": 9562, "s": 9492, "text": "I’ve done this in two ways, however, there are many ways to automate:" }, { "code": null, "e": 9596, "s": 9562, "text": "Using Crontab on an Ubuntu Server" }, { "code": null, "e": 9630, "s": 9596, "text": "Using Crontab on an Ubuntu Server" }, { "code": null, "e": 9787, "s": 9630, "text": "This is quite simple. If your on Ubuntu, type into your console ‘crontab -e’ and it will open up your cronjobs in a text file. Go to a new line and type in:" }, { "code": null, "e": 9867, "s": 9787, "text": "0 1 * * * /full path to python environment/python /full path to file/example.py" }, { "code": null, "e": 10178, "s": 9867, "text": "Assuming cron is set up correctly, the above would set the script to automatically run at 1 UTC every day (or whatever timezone your server is on). You can change that time to whatever you need it to by changing the 1 in the code. If you want to get complex with your cron timing, this site is a nice resource." }, { "code": null, "e": 10210, "s": 10178, "text": "2. Using Windows Task Scheduler" }, { "code": null, "e": 10487, "s": 10210, "text": "This is a nice and easy way to automate in windows that uses the Task Scheduler App. Simply open Task Scheduler and click ‘Create Task’ on the right hand side. This app is quite straightforward and allows you to set the schedule and what program you want to run using the GUI." }, { "code": null, "e": 10654, "s": 10487, "text": "When your in the ‘Actions’ pain, select Python as the program and then in the Add Arguments tab (the one with ‘(optional)’ next to it), put the path to your .py file." }, { "code": null, "e": 10664, "s": 10654, "text": "Thats it!" }, { "code": null, "e": 11072, "s": 10664, "text": "In this walkthrough, I’ve shown you how to pull your email data from the Microsoft Graph API. The principles demonstrated here can be used to work with nearly any RESTful API or to do much more complex tasks with the Microsoft Graph (I’ve used the MS Graph API to push files in and out of our corporate sharepoint, push data from sharepoint folders into our database, and send automated emails and reports)." }, { "code": null, "e": 11210, "s": 11072, "text": "Questions or comments? You can email me at cwarren@stitcher.tech. Or, follow me on Linkedin at https://www.linkedin.com/in/cameronwarren/" } ]
Probabilistic Programming and Bayesian Inference for Time Series Analysis and Forecasting in Python | by Yuefeng Zhang, PhD | Towards Data Science
As described in [1][2], time series data includes many kinds of real experimental data taken from various domains such as finance, medicine, scientific research (e.g., global warming, speech analysis, earthquakes), etc. Time series forecasting has many real applications in various areas such as forecasting of business (e.g., sales, stock), weather, decease, and others [2]. Statistical modeling and inference (e.g., ARIMA model) [1][2] is one of the popular methods for time series analysis and forecasting. There are two statistical inference methods: Bayesian inference Frequentist inference The philosophy of Bayesian inference is to consider probability as a measure of believability in an event [3][4][5] and use Bayes’ theorem to update the probability as more evidence or information becomes available, while the philosophy of frequentist inference considers probability as the long-run frequency of events [3]. Generally speaking, we can use the Frequentist inference only when a large number of data samples are available. In contrast, the Bayesian inference can be applied to both large and small datasets. In this article, I use a small (only 36 data samples) Sales of Shampoo time series dataset from Kaggle [6] to demonstrate how to use probabilistic programming to implement Bayesian analysis and inference for time series analysis and forecasting. The rest of the article is arranged as follows: Bayes’ theorem Basics of MCMC (Markov chain Monte Carlo) Probabilistic programming Time series model and forecasting [3] Summary Let H be the hypothesis that an event will occur, D be new observed data (i.e., evidence), and p be the probability, the Bayes’ theorem can be described as follows [5]: p(H | D) = p(H) x p(D | H) / p(D) p(H): the prior probability of the hypothesis before we see any data p(H | D): the posterior probability of the hypothesis after we observe new data p(D | H): likelihood, the probability of data under the hypothesis p(D): the probability of data under any hypothesis MCMC consists of a class of algorithms for sampling from a probability distribution. One of the widely used algorithm is the Metropolis–Hastings algorithm. The essential idea is to randomly generate a large number of representative samples to approximate the continuous distribution over a multidimensional continuous parameter space [4]. A high-level description of the Metropolis algorithm can be expressed as follows [3]: Step 1: Start at the current position (i.e., a vector of n-parameter values) in a n-parameters space Step 2: Propose to move to a new position (a new vector of n-parameter values) Step 3: Accept or reject the proposed movement based on the prior probability at the previous position, the data, and the posterior probability calculated from the data and its prior distributions according to Bayes’ theorem [3]. Step 4: If the propose is accepted, then move to the new position. Otherwise, don’t move. Step 5: If a pre-specified number of steps has not yet been reached, go back to Step 1 to repeat the process. Otherwise, return all accepted positions. The foundation of MCMC is Bayes’ theorem. Starting with a given prior distribution of the hypothesis and the data, each iteration of the Metropolis process above accumulates new data and uses it to update hypothesis for selecting next step in a random walking manner [4]. The accepted steps are samples of the posterior distribution of the hypothesis. There are multiple Python libraries that can be used to program Bayesian analysis and inference [3][5][7][8]. Such type of programming is called probabilistic programming [3][8] and the corresponding library is called probabilistic programming language. PyMC [3][7] and Tensorflow probability [8] are two examples. In this article, I use PyMC [3][7] as the probabilistic programming language to analyze and forecast the sales of Shampoo [6] for demonstration purpose. This section describes how to use PyMC [7] to program Bayesian analysis and inference for time series forecasting. Once the dataset of three-year sales of shampoo in Kaggle [6] has been downloaded onto a local machine, the dataset csv file can be loaded into a Pandas DataFrame as follows: df = pd.read_csv('./data/sales-of-shampoo-over-a-three-ye.csv')df.head(12) The column of sales in the DataFrame can be extracted as a time series dataset: sales = df['Sales of shampoo over a three year period']sales.plot(figsize=(16,5)) The following plot shows the sales of shampoo in three years (36 months): A good start to Bayesian modeling [3] is to think about how a given dataset might have been generated. Taking the sales of shampoo time series data in Figure 1 as an example, we can start by thinking: The dataset might have been generated by a linear function of time with random errors in sales since the dataset roughly forms a straight line from lower left corner to upper right corner. the random errors might follow a normal distribution with zero mean and an unknown standard deviation std. We know that a linear function is determined by two parameters: slope beta and intercept alpha: sales = beta x t + alpha + error To estimate what the linear function of time might be, we can fit a linear regression machine learning model into the given dataset to find the slope and intercept: import numpy as npfrom sklearn.linear_model import LinearRegressionX1 = sales.index.valuesY1 = sales.valuesX = X1.reshape(-1, 1)Y = Y1.reshape(-1, 1)reg = LinearRegression().fit(X, Y)reg.coef_, reg.intercept_ where reg.coef_ = 12.08 is the slope and reg.intercept_ = 101.22 is the intercept. Y_reg = 12.08 * X1 + 101.22def plot_df(x, y, y_reg, title="", xlabel='Date', ylabel='Value', dpi=100): plt.figure(figsize=(16,5), dpi=dpi) plt.plot(x, y, color='tab:blue') plt.plot(x, y_reg, color='tab:red') plt.gca().set(title=title, xlabel=xlabel, ylabel=ylabel) plt.show()plot_df(x=X1, y=Y1, y_reg=Y_reg, title='Sales') The above code plots the regression line in red over the sales curves in blue: The slope and intercept of the regression line are just estimations based on limited data. To take care of uncertainty, we can represent them as normal random variables with the identified slope and intercept as mean values. This is achieved in PyMC [7] as below: beta = pm.Normal("beta", mu=12, sd=10)alpha = pm.Normal("alpha", mu=101, sd=10) Similarly, to handle uncertainty, we can use PyMC to represent the standard deviation of errors as a uniform random variable in the range of [0, 100]: std = pm.Uniform("std", 0, 100) With the random variables of std, beta, and alpha, the regression line with uncertainty can be represented in PyMC [7]: mean = pm.Deterministic("mean", alpha + beta * X) With the regression line with uncertainty, the prior distribution of the sales of shampoo time series data can be programmed in PyMC: obs = pm.Normal("obs", mu=mean, sd=std, observed=Y) Using the above prior distribution as the start position in the parameters (i.e., alpha, beta, std) space, we can perform MCMC using the Metropolis–Hastings algorithm in PyMC: import pymc3 as pmwith pm.Model() as model: std = pm.Uniform("std", 0, 100) beta = pm.Normal("beta", mu=12, sd=10) alpha = pm.Normal("alpha", mu=101, sd=10) mean = pm.Deterministic("mean", alpha + beta * X) obs = pm.Normal("obs", mu=mean, sd=std, observed=Y) trace = pm.sample(100000, step=pm.Metropolis()) burned_trace = trace[20000:] There are 100,000 accepted steps, called trace, in total. We ignore the first 20,000 accepted steps to avoid the burn-in period before convergence [3][4]. In other words, we only use the accepted steps after the burn-in period for Bayesian inference. The following code plots the traces of std, alpha, and beta after the burn-in period: pm.plots.traceplot(burned_trace, varnames=["std", "beta", "alpha"]) The posterior distributions of std, alpha, and beta can be plotted as follows: pm.plot_posterior(burned_trace, varnames=["std", "beta", "alpha"]) The individual traces of std, alpha, and beta can be extracted for analysis: std_trace = burned_trace['std']beta_trace = burned_trace['beta']alpha_trace = burned_trace['alpha'] We can zoom into the details of the trace of std with any specified number of steps (e.g., 1,000): pd.Series(std_trace[:1000]).plot() Similarly we can zoom into the details of the traces of alpha and beta respectively: pd.Series(beta_trace[:1000]).plot() pd.Series(alpha_trace[:1000]).plot() Figures 5, 6, and 7 show that the posterior distributions of std, alpha, and beta have well mixed frequencies and thus low autocorrelations, which indicate MCMC convergence [3]. The mean values of the posterior distributions of std, alpha, and beta can be calculated: std_mean = std_trace.mean()beta_mean = beta_trace.mean()alpha_mean = alpha_trace.mean() std_mean = 79.41 beta_mean = 12.09 alpha_mean = 101.03 The forecasting of the sales of shampoo can be modeled as follows: Sale(t) = beta_mean x t + alpha_mean + error where error follows normal distribution with mean of 0 and standard deviation of std_mean. Using the model above, given any number of time steps (e.g., 72), we can generate a time series of sales: length = 72x1 = np.arange(length)mean_trace = alpha_mean + beta_mean * x1normal_dist = pm.Normal.dist(0, sd=std_mean)errors = normal_dist.random(size=length)Y_gen = mean_trace + errorsY_reg1 = mean_trace Given 36 months of data, the code below plots the forecasting of sales in the next 36 months (from Month 37 to Moth 72). plot_df(x=x1, y=Y_gen, y_reg=Y_reg1, title='Sales') In this article, I used the small Sales of Shampoo [6] time series dataset from Kaggle [6] to show how to use PyMC [3][7] as a Python probabilistic programming language to implement Bayesian analysis and inference for time series forecasting. The other alternative of probabilistic programming language is the Tensorflow probability [8]. I chose PyMC in this article for two reasons. One is that PyMC is easier to understand compared with Tensorflow probability. The other reason is that Tensorflow probability is in the process of migrating from Tensorflow 1.x to Tensorflow 2.x, and the documentation of Tensorflow probability for Tensorflow 2.x is lacking. Common Time Series Data Analysis Methods and Forecasting Models in PythonR.H. Shumway and D.S. Stoffer, Time Series Analysis and Its Applications with R Examples, 4th Edition, Springer, 2017C. Davidson-Pilon, Bayesian Methods for Hackers, Probabilistic Programming and Bayesian Inference, Addison-Wesley, 2016J.K. Kruschke, Doing Bayesian Data Analysis, A Tutorial with R, JAGS, and Stan, Academic Press, 2015A.B. Downey, Think Bayes, O’Reilly, 2013Sales of Shampoo Over a Three Year PeriodPyMC3Tensorflow ProbabilityJupyter notebook in Github Common Time Series Data Analysis Methods and Forecasting Models in Python R.H. Shumway and D.S. Stoffer, Time Series Analysis and Its Applications with R Examples, 4th Edition, Springer, 2017 C. Davidson-Pilon, Bayesian Methods for Hackers, Probabilistic Programming and Bayesian Inference, Addison-Wesley, 2016 J.K. Kruschke, Doing Bayesian Data Analysis, A Tutorial with R, JAGS, and Stan, Academic Press, 2015 A.B. Downey, Think Bayes, O’Reilly, 2013 Sales of Shampoo Over a Three Year Period PyMC3 Tensorflow Probability Jupyter notebook in Github
[ { "code": null, "e": 681, "s": 171, "text": "As described in [1][2], time series data includes many kinds of real experimental data taken from various domains such as finance, medicine, scientific research (e.g., global warming, speech analysis, earthquakes), etc. Time series forecasting has many real applications in various areas such as forecasting of business (e.g., sales, stock), weather, decease, and others [2]. Statistical modeling and inference (e.g., ARIMA model) [1][2] is one of the popular methods for time series analysis and forecasting." }, { "code": null, "e": 726, "s": 681, "text": "There are two statistical inference methods:" }, { "code": null, "e": 745, "s": 726, "text": "Bayesian inference" }, { "code": null, "e": 767, "s": 745, "text": "Frequentist inference" }, { "code": null, "e": 1092, "s": 767, "text": "The philosophy of Bayesian inference is to consider probability as a measure of believability in an event [3][4][5] and use Bayes’ theorem to update the probability as more evidence or information becomes available, while the philosophy of frequentist inference considers probability as the long-run frequency of events [3]." }, { "code": null, "e": 1290, "s": 1092, "text": "Generally speaking, we can use the Frequentist inference only when a large number of data samples are available. In contrast, the Bayesian inference can be applied to both large and small datasets." }, { "code": null, "e": 1536, "s": 1290, "text": "In this article, I use a small (only 36 data samples) Sales of Shampoo time series dataset from Kaggle [6] to demonstrate how to use probabilistic programming to implement Bayesian analysis and inference for time series analysis and forecasting." }, { "code": null, "e": 1584, "s": 1536, "text": "The rest of the article is arranged as follows:" }, { "code": null, "e": 1599, "s": 1584, "text": "Bayes’ theorem" }, { "code": null, "e": 1641, "s": 1599, "text": "Basics of MCMC (Markov chain Monte Carlo)" }, { "code": null, "e": 1667, "s": 1641, "text": "Probabilistic programming" }, { "code": null, "e": 1705, "s": 1667, "text": "Time series model and forecasting [3]" }, { "code": null, "e": 1713, "s": 1705, "text": "Summary" }, { "code": null, "e": 1882, "s": 1713, "text": "Let H be the hypothesis that an event will occur, D be new observed data (i.e., evidence), and p be the probability, the Bayes’ theorem can be described as follows [5]:" }, { "code": null, "e": 1916, "s": 1882, "text": "p(H | D) = p(H) x p(D | H) / p(D)" }, { "code": null, "e": 1985, "s": 1916, "text": "p(H): the prior probability of the hypothesis before we see any data" }, { "code": null, "e": 2065, "s": 1985, "text": "p(H | D): the posterior probability of the hypothesis after we observe new data" }, { "code": null, "e": 2132, "s": 2065, "text": "p(D | H): likelihood, the probability of data under the hypothesis" }, { "code": null, "e": 2183, "s": 2132, "text": "p(D): the probability of data under any hypothesis" }, { "code": null, "e": 2522, "s": 2183, "text": "MCMC consists of a class of algorithms for sampling from a probability distribution. One of the widely used algorithm is the Metropolis–Hastings algorithm. The essential idea is to randomly generate a large number of representative samples to approximate the continuous distribution over a multidimensional continuous parameter space [4]." }, { "code": null, "e": 2608, "s": 2522, "text": "A high-level description of the Metropolis algorithm can be expressed as follows [3]:" }, { "code": null, "e": 2709, "s": 2608, "text": "Step 1: Start at the current position (i.e., a vector of n-parameter values) in a n-parameters space" }, { "code": null, "e": 2788, "s": 2709, "text": "Step 2: Propose to move to a new position (a new vector of n-parameter values)" }, { "code": null, "e": 3018, "s": 2788, "text": "Step 3: Accept or reject the proposed movement based on the prior probability at the previous position, the data, and the posterior probability calculated from the data and its prior distributions according to Bayes’ theorem [3]." }, { "code": null, "e": 3108, "s": 3018, "text": "Step 4: If the propose is accepted, then move to the new position. Otherwise, don’t move." }, { "code": null, "e": 3260, "s": 3108, "text": "Step 5: If a pre-specified number of steps has not yet been reached, go back to Step 1 to repeat the process. Otherwise, return all accepted positions." }, { "code": null, "e": 3612, "s": 3260, "text": "The foundation of MCMC is Bayes’ theorem. Starting with a given prior distribution of the hypothesis and the data, each iteration of the Metropolis process above accumulates new data and uses it to update hypothesis for selecting next step in a random walking manner [4]. The accepted steps are samples of the posterior distribution of the hypothesis." }, { "code": null, "e": 3927, "s": 3612, "text": "There are multiple Python libraries that can be used to program Bayesian analysis and inference [3][5][7][8]. Such type of programming is called probabilistic programming [3][8] and the corresponding library is called probabilistic programming language. PyMC [3][7] and Tensorflow probability [8] are two examples." }, { "code": null, "e": 4080, "s": 3927, "text": "In this article, I use PyMC [3][7] as the probabilistic programming language to analyze and forecast the sales of Shampoo [6] for demonstration purpose." }, { "code": null, "e": 4195, "s": 4080, "text": "This section describes how to use PyMC [7] to program Bayesian analysis and inference for time series forecasting." }, { "code": null, "e": 4370, "s": 4195, "text": "Once the dataset of three-year sales of shampoo in Kaggle [6] has been downloaded onto a local machine, the dataset csv file can be loaded into a Pandas DataFrame as follows:" }, { "code": null, "e": 4445, "s": 4370, "text": "df = pd.read_csv('./data/sales-of-shampoo-over-a-three-ye.csv')df.head(12)" }, { "code": null, "e": 4525, "s": 4445, "text": "The column of sales in the DataFrame can be extracted as a time series dataset:" }, { "code": null, "e": 4607, "s": 4525, "text": "sales = df['Sales of shampoo over a three year period']sales.plot(figsize=(16,5))" }, { "code": null, "e": 4681, "s": 4607, "text": "The following plot shows the sales of shampoo in three years (36 months):" }, { "code": null, "e": 4882, "s": 4681, "text": "A good start to Bayesian modeling [3] is to think about how a given dataset might have been generated. Taking the sales of shampoo time series data in Figure 1 as an example, we can start by thinking:" }, { "code": null, "e": 5071, "s": 4882, "text": "The dataset might have been generated by a linear function of time with random errors in sales since the dataset roughly forms a straight line from lower left corner to upper right corner." }, { "code": null, "e": 5178, "s": 5071, "text": "the random errors might follow a normal distribution with zero mean and an unknown standard deviation std." }, { "code": null, "e": 5274, "s": 5178, "text": "We know that a linear function is determined by two parameters: slope beta and intercept alpha:" }, { "code": null, "e": 5307, "s": 5274, "text": "sales = beta x t + alpha + error" }, { "code": null, "e": 5472, "s": 5307, "text": "To estimate what the linear function of time might be, we can fit a linear regression machine learning model into the given dataset to find the slope and intercept:" }, { "code": null, "e": 5681, "s": 5472, "text": "import numpy as npfrom sklearn.linear_model import LinearRegressionX1 = sales.index.valuesY1 = sales.valuesX = X1.reshape(-1, 1)Y = Y1.reshape(-1, 1)reg = LinearRegression().fit(X, Y)reg.coef_, reg.intercept_" }, { "code": null, "e": 5764, "s": 5681, "text": "where reg.coef_ = 12.08 is the slope and reg.intercept_ = 101.22 is the intercept." }, { "code": null, "e": 6102, "s": 5764, "text": "Y_reg = 12.08 * X1 + 101.22def plot_df(x, y, y_reg, title=\"\", xlabel='Date', ylabel='Value', dpi=100): plt.figure(figsize=(16,5), dpi=dpi) plt.plot(x, y, color='tab:blue') plt.plot(x, y_reg, color='tab:red') plt.gca().set(title=title, xlabel=xlabel, ylabel=ylabel) plt.show()plot_df(x=X1, y=Y1, y_reg=Y_reg, title='Sales')" }, { "code": null, "e": 6181, "s": 6102, "text": "The above code plots the regression line in red over the sales curves in blue:" }, { "code": null, "e": 6445, "s": 6181, "text": "The slope and intercept of the regression line are just estimations based on limited data. To take care of uncertainty, we can represent them as normal random variables with the identified slope and intercept as mean values. This is achieved in PyMC [7] as below:" }, { "code": null, "e": 6525, "s": 6445, "text": "beta = pm.Normal(\"beta\", mu=12, sd=10)alpha = pm.Normal(\"alpha\", mu=101, sd=10)" }, { "code": null, "e": 6676, "s": 6525, "text": "Similarly, to handle uncertainty, we can use PyMC to represent the standard deviation of errors as a uniform random variable in the range of [0, 100]:" }, { "code": null, "e": 6708, "s": 6676, "text": "std = pm.Uniform(\"std\", 0, 100)" }, { "code": null, "e": 6828, "s": 6708, "text": "With the random variables of std, beta, and alpha, the regression line with uncertainty can be represented in PyMC [7]:" }, { "code": null, "e": 6878, "s": 6828, "text": "mean = pm.Deterministic(\"mean\", alpha + beta * X)" }, { "code": null, "e": 7012, "s": 6878, "text": "With the regression line with uncertainty, the prior distribution of the sales of shampoo time series data can be programmed in PyMC:" }, { "code": null, "e": 7064, "s": 7012, "text": "obs = pm.Normal(\"obs\", mu=mean, sd=std, observed=Y)" }, { "code": null, "e": 7240, "s": 7064, "text": "Using the above prior distribution as the start position in the parameters (i.e., alpha, beta, std) space, we can perform MCMC using the Metropolis–Hastings algorithm in PyMC:" }, { "code": null, "e": 7613, "s": 7240, "text": "import pymc3 as pmwith pm.Model() as model: std = pm.Uniform(\"std\", 0, 100) beta = pm.Normal(\"beta\", mu=12, sd=10) alpha = pm.Normal(\"alpha\", mu=101, sd=10) mean = pm.Deterministic(\"mean\", alpha + beta * X) obs = pm.Normal(\"obs\", mu=mean, sd=std, observed=Y) trace = pm.sample(100000, step=pm.Metropolis()) burned_trace = trace[20000:]" }, { "code": null, "e": 7864, "s": 7613, "text": "There are 100,000 accepted steps, called trace, in total. We ignore the first 20,000 accepted steps to avoid the burn-in period before convergence [3][4]. In other words, we only use the accepted steps after the burn-in period for Bayesian inference." }, { "code": null, "e": 7950, "s": 7864, "text": "The following code plots the traces of std, alpha, and beta after the burn-in period:" }, { "code": null, "e": 8018, "s": 7950, "text": "pm.plots.traceplot(burned_trace, varnames=[\"std\", \"beta\", \"alpha\"])" }, { "code": null, "e": 8097, "s": 8018, "text": "The posterior distributions of std, alpha, and beta can be plotted as follows:" }, { "code": null, "e": 8164, "s": 8097, "text": "pm.plot_posterior(burned_trace, varnames=[\"std\", \"beta\", \"alpha\"])" }, { "code": null, "e": 8241, "s": 8164, "text": "The individual traces of std, alpha, and beta can be extracted for analysis:" }, { "code": null, "e": 8341, "s": 8241, "text": "std_trace = burned_trace['std']beta_trace = burned_trace['beta']alpha_trace = burned_trace['alpha']" }, { "code": null, "e": 8440, "s": 8341, "text": "We can zoom into the details of the trace of std with any specified number of steps (e.g., 1,000):" }, { "code": null, "e": 8475, "s": 8440, "text": "pd.Series(std_trace[:1000]).plot()" }, { "code": null, "e": 8560, "s": 8475, "text": "Similarly we can zoom into the details of the traces of alpha and beta respectively:" }, { "code": null, "e": 8596, "s": 8560, "text": "pd.Series(beta_trace[:1000]).plot()" }, { "code": null, "e": 8633, "s": 8596, "text": "pd.Series(alpha_trace[:1000]).plot()" }, { "code": null, "e": 8811, "s": 8633, "text": "Figures 5, 6, and 7 show that the posterior distributions of std, alpha, and beta have well mixed frequencies and thus low autocorrelations, which indicate MCMC convergence [3]." }, { "code": null, "e": 8901, "s": 8811, "text": "The mean values of the posterior distributions of std, alpha, and beta can be calculated:" }, { "code": null, "e": 8989, "s": 8901, "text": "std_mean = std_trace.mean()beta_mean = beta_trace.mean()alpha_mean = alpha_trace.mean()" }, { "code": null, "e": 9006, "s": 8989, "text": "std_mean = 79.41" }, { "code": null, "e": 9024, "s": 9006, "text": "beta_mean = 12.09" }, { "code": null, "e": 9044, "s": 9024, "text": "alpha_mean = 101.03" }, { "code": null, "e": 9111, "s": 9044, "text": "The forecasting of the sales of shampoo can be modeled as follows:" }, { "code": null, "e": 9156, "s": 9111, "text": "Sale(t) = beta_mean x t + alpha_mean + error" }, { "code": null, "e": 9247, "s": 9156, "text": "where error follows normal distribution with mean of 0 and standard deviation of std_mean." }, { "code": null, "e": 9353, "s": 9247, "text": "Using the model above, given any number of time steps (e.g., 72), we can generate a time series of sales:" }, { "code": null, "e": 9557, "s": 9353, "text": "length = 72x1 = np.arange(length)mean_trace = alpha_mean + beta_mean * x1normal_dist = pm.Normal.dist(0, sd=std_mean)errors = normal_dist.random(size=length)Y_gen = mean_trace + errorsY_reg1 = mean_trace" }, { "code": null, "e": 9678, "s": 9557, "text": "Given 36 months of data, the code below plots the forecasting of sales in the next 36 months (from Month 37 to Moth 72)." }, { "code": null, "e": 9730, "s": 9678, "text": "plot_df(x=x1, y=Y_gen, y_reg=Y_reg1, title='Sales')" }, { "code": null, "e": 9973, "s": 9730, "text": "In this article, I used the small Sales of Shampoo [6] time series dataset from Kaggle [6] to show how to use PyMC [3][7] as a Python probabilistic programming language to implement Bayesian analysis and inference for time series forecasting." }, { "code": null, "e": 10390, "s": 9973, "text": "The other alternative of probabilistic programming language is the Tensorflow probability [8]. I chose PyMC in this article for two reasons. One is that PyMC is easier to understand compared with Tensorflow probability. The other reason is that Tensorflow probability is in the process of migrating from Tensorflow 1.x to Tensorflow 2.x, and the documentation of Tensorflow probability for Tensorflow 2.x is lacking." }, { "code": null, "e": 10934, "s": 10390, "text": "Common Time Series Data Analysis Methods and Forecasting Models in PythonR.H. Shumway and D.S. Stoffer, Time Series Analysis and Its Applications with R Examples, 4th Edition, Springer, 2017C. Davidson-Pilon, Bayesian Methods for Hackers, Probabilistic Programming and Bayesian Inference, Addison-Wesley, 2016J.K. Kruschke, Doing Bayesian Data Analysis, A Tutorial with R, JAGS, and Stan, Academic Press, 2015A.B. Downey, Think Bayes, O’Reilly, 2013Sales of Shampoo Over a Three Year PeriodPyMC3Tensorflow ProbabilityJupyter notebook in Github" }, { "code": null, "e": 11008, "s": 10934, "text": "Common Time Series Data Analysis Methods and Forecasting Models in Python" }, { "code": null, "e": 11126, "s": 11008, "text": "R.H. Shumway and D.S. Stoffer, Time Series Analysis and Its Applications with R Examples, 4th Edition, Springer, 2017" }, { "code": null, "e": 11246, "s": 11126, "text": "C. Davidson-Pilon, Bayesian Methods for Hackers, Probabilistic Programming and Bayesian Inference, Addison-Wesley, 2016" }, { "code": null, "e": 11347, "s": 11246, "text": "J.K. Kruschke, Doing Bayesian Data Analysis, A Tutorial with R, JAGS, and Stan, Academic Press, 2015" }, { "code": null, "e": 11388, "s": 11347, "text": "A.B. Downey, Think Bayes, O’Reilly, 2013" }, { "code": null, "e": 11430, "s": 11388, "text": "Sales of Shampoo Over a Three Year Period" }, { "code": null, "e": 11436, "s": 11430, "text": "PyMC3" }, { "code": null, "e": 11459, "s": 11436, "text": "Tensorflow Probability" } ]
MySQLi - PHP Syntax
MySQL works very well in combination of various programming languages like PERL, C, C++, JAVA and PHP. Out of these languages, PHP is the most popular one because of its web application development capabilities. This tutorial focuses heavily on using MySQL in a PHP environment. If you are interested in MySQL with PERL, then you can consider reading the PERL Tutorial. PHP provides various functions to access the MySQL database and to manipulate the data records inside the MySQL database. You would require to call the PHP functions in the same way you call any other PHP function. The PHP functions for use with MySQL have the following general format − mysqli function(value,value,...); The second part of the function name is specific to the function, usually a word that describes what the function does. The following are two of the functions, which we will use in our tutorial − $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); mysqli→query(,"SQL statement"); The following example shows a generic syntax of PHP to call any MySQL function. <html> <head> <title>PHP with MySQL</title> </head> <body> <?php $retval = mysqli - > <i>function</i>(value, [value,...]); if( !$retval ) { die ( "Error: a related error message" ); } // Otherwise MySQL or PHP Statements ?> </body> </html> Starting from the next chapter, we will see all the important MySQL functionality along with PHP. 14 Lectures 1.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2475, "s": 2263, "text": "MySQL works very well in combination of various programming languages like PERL, C, C++, JAVA and PHP. Out of these languages, PHP is the most popular one because of its web application development capabilities." }, { "code": null, "e": 2633, "s": 2475, "text": "This tutorial focuses heavily on using MySQL in a PHP environment. If you are interested in MySQL with PERL, then you can consider reading the PERL Tutorial." }, { "code": null, "e": 2848, "s": 2633, "text": "PHP provides various functions to access the MySQL database and to manipulate the data records inside the MySQL database. You would require to call the PHP functions in the same way you call any other PHP function." }, { "code": null, "e": 2921, "s": 2848, "text": "The PHP functions for use with MySQL have the following general format −" }, { "code": null, "e": 2956, "s": 2921, "text": "mysqli function(value,value,...);\n" }, { "code": null, "e": 3152, "s": 2956, "text": "The second part of the function name is specific to the function, usually a word that describes what the function does. The following are two of the functions, which we will use in our tutorial −" }, { "code": null, "e": 3243, "s": 3152, "text": "$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);\nmysqli→query(,\"SQL statement\");\n" }, { "code": null, "e": 3323, "s": 3243, "text": "The following example shows a generic syntax of PHP to call any MySQL function." }, { "code": null, "e": 3642, "s": 3323, "text": "<html>\n <head>\n <title>PHP with MySQL</title>\n </head>\n <body>\n <?php\n $retval = mysqli - > <i>function</i>(value, [value,...]);\n if( !$retval ) {\n die ( \"Error: a related error message\" );\n }\n // Otherwise MySQL or PHP Statements\n ?>\n </body>\n</html>" }, { "code": null, "e": 3740, "s": 3642, "text": "Starting from the next chapter, we will see all the important MySQL functionality along with PHP." }, { "code": null, "e": 3775, "s": 3740, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3798, "s": 3775, "text": " Stone River ELearning" }, { "code": null, "e": 3805, "s": 3798, "text": " Print" }, { "code": null, "e": 3816, "s": 3805, "text": " Add Notes" } ]
Remove Element From List in R Language - GeeksforGeeks
21 Apr, 2021 R is an open-source programming language that is widely used as a statistical software and data analysis tool. R generally comes with the Command-line interface. R is available across widely used platforms like Windows, Linux, and macOS. Also, the R programming language is the latest cutting-edge tool. This article specifies how to remove one or more elements from a given list in R language. It will specify the number of elements to be removed from the list and print the rest elements. As a result, it will return a list of data after performing the operation. You will learn how to remove certain elements from the list. Syntax: To remove elements using minus sign my_list[- number] Parameters: number – Specifies the number of elements to be removed from the list Return: Return list after removing elements Approach Create a vector. Remove one specific element using the (-) method. Delete multiple elements using the same method as illustrated in examples. Example: R # Create example listmy_list <- list(a = c(1, 4, 2, 7), b = "geeksforgeeks", c = 2)my_list # remove elements my_list[- 1] Output: Here, in the above example, my_list[- 1] will remove the data stored in the first list, and after removal of the first data list print the rest data on the screen. Syntax: my_list_2[number] <- NULL Example: R my_list <- list(a = c(1, 4, 2, 7), # Create example list b = "geeksforgeeks", c = 2)my_listmy_list_2 <- my_list # Replicate listmy_list_2[1] <- NULL # Remove list elements with NULLmy_list_2 Output : The above example will remove elements by making them NULL in the list by using the my_list_2[] <- NULL method. It will clear specific data and print the rest data on the screen. Syntax: my_list[names(my_list) %in% "number" == FALSE] Example: R # Create example listmy_list <- list(a = c(1, 4, 2, 7), b = "geeksforgeeks", c = 2)my_list # Remove elementsmy_list[names(my_list) %in% "c" == FALSE] Output: my_list[names(my_list) %in% “c” == FALSE], with this method the list of data which are declared as false, which get removed from the data list and other will be printed on the screen. Syntax: my_list[names(my_list) != "number"] Example: R # Create example listmy_list <- list(a = c(1, 4, 2, 7), b = "geeksforgeeks", c = 2)my_listmy_list[names(my_list) != "a"] Output: my_list[names(my_list) != ” ” In above code the data list number which is entered between double quote will get removed . Example: R # Create example listmy_list <- list(a = c(1, 4, 2, 7), b = "geeksforgeeks", c = 2)my_listmy_list[- c(1, 3)] Output: R-List R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? 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? R - if statement How to import an Excel File into R ? How to change the order of bars in bar chart in R ?
[ { "code": null, "e": 24851, "s": 24823, "text": "\n21 Apr, 2021" }, { "code": null, "e": 25478, "s": 24851, "text": "R is an open-source programming language that is widely used as a statistical software and data analysis tool. R generally comes with the Command-line interface. R is available across widely used platforms like Windows, Linux, and macOS. Also, the R programming language is the latest cutting-edge tool. This article specifies how to remove one or more elements from a given list in R language. It will specify the number of elements to be removed from the list and print the rest elements. As a result, it will return a list of data after performing the operation. You will learn how to remove certain elements from the list." }, { "code": null, "e": 25522, "s": 25478, "text": "Syntax: To remove elements using minus sign" }, { "code": null, "e": 25543, "s": 25522, "text": "my_list[- number] " }, { "code": null, "e": 25556, "s": 25543, "text": "Parameters: " }, { "code": null, "e": 25627, "s": 25556, "text": "number – Specifies the number of elements to be removed from the list " }, { "code": null, "e": 25635, "s": 25627, "text": "Return:" }, { "code": null, "e": 25672, "s": 25635, "text": "Return list after removing elements " }, { "code": null, "e": 25681, "s": 25672, "text": "Approach" }, { "code": null, "e": 25698, "s": 25681, "text": "Create a vector." }, { "code": null, "e": 25748, "s": 25698, "text": "Remove one specific element using the (-) method." }, { "code": null, "e": 25823, "s": 25748, "text": "Delete multiple elements using the same method as illustrated in examples." }, { "code": null, "e": 25833, "s": 25823, "text": "Example: " }, { "code": null, "e": 25835, "s": 25833, "text": "R" }, { "code": "# Create example listmy_list <- list(a = c(1, 4, 2, 7), b = \"geeksforgeeks\", c = 2)my_list # remove elements my_list[- 1]", "e": 26005, "s": 25835, "text": null }, { "code": null, "e": 26013, "s": 26005, "text": "Output:" }, { "code": null, "e": 26177, "s": 26013, "text": "Here, in the above example, my_list[- 1] will remove the data stored in the first list, and after removal of the first data list print the rest data on the screen." }, { "code": null, "e": 26185, "s": 26177, "text": "Syntax:" }, { "code": null, "e": 26213, "s": 26185, "text": "my_list_2[number] <- NULL " }, { "code": null, "e": 26222, "s": 26213, "text": "Example:" }, { "code": null, "e": 26224, "s": 26222, "text": "R" }, { "code": "my_list <- list(a = c(1, 4, 2, 7), # Create example list b = \"geeksforgeeks\", c = 2)my_listmy_list_2 <- my_list # Replicate listmy_list_2[1] <- NULL # Remove list elements with NULLmy_list_2", "e": 26521, "s": 26224, "text": null }, { "code": null, "e": 26530, "s": 26521, "text": "Output :" }, { "code": null, "e": 26711, "s": 26530, "text": "The above example will remove elements by making them NULL in the list by using the my_list_2[] <- NULL method. It will clear specific data and print the rest data on the screen." }, { "code": null, "e": 26720, "s": 26711, "text": "Syntax: " }, { "code": null, "e": 26771, "s": 26720, "text": "my_list[names(my_list) %in% \"number\" == FALSE] " }, { "code": null, "e": 26780, "s": 26771, "text": "Example:" }, { "code": null, "e": 26782, "s": 26780, "text": "R" }, { "code": "# Create example listmy_list <- list(a = c(1, 4, 2, 7), b = \"geeksforgeeks\", c = 2)my_list # Remove elementsmy_list[names(my_list) %in% \"c\" == FALSE]", "e": 26980, "s": 26782, "text": null }, { "code": null, "e": 26988, "s": 26980, "text": "Output:" }, { "code": null, "e": 27172, "s": 26988, "text": "my_list[names(my_list) %in% “c” == FALSE], with this method the list of data which are declared as false, which get removed from the data list and other will be printed on the screen." }, { "code": null, "e": 27181, "s": 27172, "text": "Syntax: " }, { "code": null, "e": 27217, "s": 27181, "text": "my_list[names(my_list) != \"number\"]" }, { "code": null, "e": 27226, "s": 27217, "text": "Example:" }, { "code": null, "e": 27228, "s": 27226, "text": "R" }, { "code": "# Create example listmy_list <- list(a = c(1, 4, 2, 7), b = \"geeksforgeeks\", c = 2)my_listmy_list[names(my_list) != \"a\"]", "e": 27395, "s": 27228, "text": null }, { "code": null, "e": 27404, "s": 27395, "text": "Output: " }, { "code": null, "e": 27528, "s": 27404, "text": "my_list[names(my_list) != ” ” In above code the data list number which is entered between double quote will get removed ." }, { "code": null, "e": 27539, "s": 27528, "text": "Example: " }, { "code": null, "e": 27541, "s": 27539, "text": "R" }, { "code": "# Create example listmy_list <- list(a = c(1, 4, 2, 7), b = \"geeksforgeeks\", c = 2)my_listmy_list[- c(1, 3)]", "e": 27697, "s": 27541, "text": null }, { "code": null, "e": 27705, "s": 27697, "text": "Output:" }, { "code": null, "e": 27712, "s": 27705, "text": "R-List" }, { "code": null, "e": 27723, "s": 27712, "text": "R Language" }, { "code": null, "e": 27821, "s": 27723, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27830, "s": 27821, "text": "Comments" }, { "code": null, "e": 27843, "s": 27830, "text": "Old Comments" }, { "code": null, "e": 27895, "s": 27843, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27933, "s": 27895, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27968, "s": 27933, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28026, "s": 27968, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28075, "s": 28026, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28118, "s": 28075, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28168, "s": 28118, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 28185, "s": 28168, "text": "R - if statement" }, { "code": null, "e": 28222, "s": 28185, "text": "How to import an Excel File into R ?" } ]
Aho-Corasick Algorithm for Pattern Searching - GeeksforGeeks
05 Nov, 2021 Given an input text and an array of k words, arr[], find all occurrences of all words in the input text. Let n be the length of text and m be the total number characters in all words, i.e. m = length(arr[0]) + length(arr[1]) + ... + length(arr[k-1]). Here k is total numbers of input words. Example: Input: text = "ahishers" arr[] = {"he", "she", "hers", "his"} Output: Word his appears from 1 to 3 Word he appears from 4 to 5 Word she appears from 3 to 5 Word hers appears from 4 to 7 If we use a linear time searching algorithm like KMP, then we need to one by one search all words in text[]. This gives us total time complexity as O(n + length(word[0]) + O(n + length(word[1]) + O(n + length(word[2]) + ... O(n + length(word[k-1]). This time complexity can be written as O(n*k + m). Aho-Corasick Algorithm finds all words in O(n + m + z) time where z is total number of occurrences of words in text. The Aho–Corasick string matching algorithm formed the basis of the original Unix command fgrep. Preprocessing : Build an automaton of all words in arr[] The automaton has mainly three functions: Go To : This function simply follows edges of Trie of all words in arr[]. It is represented as 2D array g[][] where we store next state for current state and character. Failure : This function stores all edges that are followed when current character doesn't have edge in Trie. It is represented as 1D array f[] where we store next state for current state. Output : Stores indexes of all words that end at current state. It is represented as 1D array o[] where we store indexes of all matching words as a bitmap for current state. Matching : Traverse the given text over built automaton to find all matching words. Preprocessing: We first Build a Trie (or Keyword Tree) of all words. Trie This part fills entries in goto g[][] and output o[]. Next we extend Trie into an automaton to support linear time matching. This part fills entries in failure f[] and output o[]. Go to : We build Trie. And for all characters which don’t have an edge at root, we add an edge back to root.Failure : For a state s, we find the longest proper suffix which is a proper prefix of some pattern. This is done using Breadth First Traversal of Trie.Output : For a state s, indexes of all words ending at s are stored. These indexes are stored as bitwise map (by doing bitwise OR of values). This is also computing using Breadth First Traversal with Failure. Below is the implementation of Aho-Corasick Algorithm C++ Java Python3 C# // C++ program for implementation of Aho Corasick algorithm// for string matchingusing namespace std;#include <bits/stdc++.h> // Max number of states in the matching machine.// Should be equal to the sum of the length of all keywords.const int MAXS = 500; // Maximum number of characters in input alphabetconst int MAXC = 26; // OUTPUT FUNCTION IS IMPLEMENTED USING out[]// Bit i in this mask is one if the word with index i// appears when the machine enters this state.int out[MAXS]; // FAILURE FUNCTION IS IMPLEMENTED USING f[]int f[MAXS]; // GOTO FUNCTION (OR TRIE) IS IMPLEMENTED USING g[][]int g[MAXS][MAXC]; // Builds the string matching machine.// arr - array of words. The index of each keyword is important:// "out[state] & (1 << i)" is > 0 if we just found word[i]// in the text.// Returns the number of states that the built machine has.// States are numbered 0 up to the return value - 1, inclusive.int buildMatchingMachine(string arr[], int k){ // Initialize all values in output function as 0. memset(out, 0, sizeof out); // Initialize all values in goto function as -1. memset(g, -1, sizeof g); // Initially, we just have the 0 state int states = 1; // Construct values for goto function, i.e., fill g[][] // This is same as building a Trie for arr[] for (int i = 0; i < k; ++i) { const string &word = arr[i]; int currentState = 0; // Insert all characters of current word in arr[] for (int j = 0; j < word.size(); ++j) { int ch = word[j] - 'a'; // Allocate a new node (create a new state) if a // node for ch doesn't exist. if (g[currentState][ch] == -1) g[currentState][ch] = states++; currentState = g[currentState][ch]; } // Add current word in output function out[currentState] |= (1 << i); } // For all characters which don't have an edge from // root (or state 0) in Trie, add a goto edge to state // 0 itself for (int ch = 0; ch < MAXC; ++ch) if (g[0][ch] == -1) g[0][ch] = 0; // Now, let's build the failure function // Initialize values in fail function memset(f, -1, sizeof f); // Failure function is computed in breadth first order // using a queue queue<int> q; // Iterate over every possible input for (int ch = 0; ch < MAXC; ++ch) { // All nodes of depth 1 have failure function value // as 0. For example, in above diagram we move to 0 // from states 1 and 3. if (g[0][ch] != 0) { f[g[0][ch]] = 0; q.push(g[0][ch]); } } // Now queue has states 1 and 3 while (q.size()) { // Remove the front state from queue int state = q.front(); q.pop(); // For the removed state, find failure function for // all those characters for which goto function is // not defined. for (int ch = 0; ch <= MAXC; ++ch) { // If goto function is defined for character 'ch' // and 'state' if (g[state][ch] != -1) { // Find failure state of removed state int failure = f[state]; // Find the deepest node labeled by proper // suffix of string from root to current // state. while (g[failure][ch] == -1) failure = f[failure]; failure = g[failure][ch]; f[g[state][ch]] = failure; // Merge output values out[g[state][ch]] |= out[failure]; // Insert the next level node (of Trie) in Queue q.push(g[state][ch]); } } } return states;} // Returns the next state the machine will transition to using goto// and failure functions.// currentState - The current state of the machine. Must be between// 0 and the number of states - 1, inclusive.// nextInput - The next character that enters into the machine.int findNextState(int currentState, char nextInput){ int answer = currentState; int ch = nextInput - 'a'; // If goto is not defined, use failure function while (g[answer][ch] == -1) answer = f[answer]; return g[answer][ch];} // This function finds all occurrences of all array words// in text.void searchWords(string arr[], int k, string text){ // Preprocess patterns. // Build machine with goto, failure and output functions buildMatchingMachine(arr, k); // Initialize current state int currentState = 0; // Traverse the text through the built machine to find // all occurrences of words in arr[] for (int i = 0; i < text.size(); ++i) { currentState = findNextState(currentState, text[i]); // If match not found, move to next state if (out[currentState] == 0) continue; // Match found, print all matching words of arr[] // using output function. for (int j = 0; j < k; ++j) { if (out[currentState] & (1 << j)) { cout << "Word " << arr[j] << " appears from " << i - arr[j].size() + 1 << " to " << i << endl; } } }} // Driver program to test aboveint main(){ string arr[] = {"he", "she", "hers", "his"}; string text = "ahishers"; int k = sizeof(arr)/sizeof(arr[0]); searchWords(arr, k, text); return 0;} // Java program for implementation of // Aho Corasick algorithm for String// matchingimport java.util.*; class GFG{ // Max number of states in the matching// machine. Should be equal to the sum // of the length of all keywords.static int MAXS = 500; // Maximum number of characters// in input alphabetstatic int MAXC = 26; // OUTPUT FUNCTION IS IMPLEMENTED USING out[]// Bit i in this mask is one if the word with // index i appears when the machine enters // this state.static int []out = new int[MAXS]; // FAILURE FUNCTION IS IMPLEMENTED USING f[]static int []f = new int[MAXS]; // GOTO FUNCTION (OR TRIE) IS// IMPLEMENTED USING g[][]static int [][]g = new int[MAXS][MAXC]; // Builds the String matching machine.// arr - array of words. The index of each keyword is important:// "out[state] & (1 << i)" is > 0 if we just found word[i]// in the text.// Returns the number of states that the built machine has.// States are numbered 0 up to the return value - 1, inclusive.static int buildMatchingMachine(String arr[], int k){ // Initialize all values in output function as 0. Arrays.fill(out, 0); // Initialize all values in goto function as -1. for(int i = 0; i < MAXS; i++) Arrays.fill(g[i], -1); // Initially, we just have the 0 state int states = 1; // Convalues for goto function, i.e., fill g[][] // This is same as building a Trie for arr[] for(int i = 0; i < k; ++i) { String word = arr[i]; int currentState = 0; // Insert all characters of current // word in arr[] for(int j = 0; j < word.length(); ++j) { int ch = word.charAt(j) - 'a'; // Allocate a new node (create a new state) // if a node for ch doesn't exist. if (g[currentState][ch] == -1) g[currentState][ch] = states++; currentState = g[currentState][ch]; } // Add current word in output function out[currentState] |= (1 << i); } // For all characters which don't have // an edge from root (or state 0) in Trie, // add a goto edge to state 0 itself for(int ch = 0; ch < MAXC; ++ch) if (g[0][ch] == -1) g[0][ch] = 0; // Now, let's build the failure function // Initialize values in fail function Arrays.fill(f, -1); // Failure function is computed in // breadth first order // using a queue Queue<Integer> q = new LinkedList<>(); // Iterate over every possible input for(int ch = 0; ch < MAXC; ++ch) { // All nodes of depth 1 have failure // function value as 0. For example, // in above diagram we move to 0 // from states 1 and 3. if (g[0][ch] != 0) { f[g[0][ch]] = 0; q.add(g[0][ch]); } } // Now queue has states 1 and 3 while (!q.isEmpty()) { // Remove the front state from queue int state = q.peek(); q.remove(); // For the removed state, find failure // function for all those characters // for which goto function is // not defined. for(int ch = 0; ch < MAXC; ++ch) { // If goto function is defined for // character 'ch' and 'state' if (g[state][ch] != -1) { // Find failure state of removed state int failure = f[state]; // Find the deepest node labeled by proper // suffix of String from root to current // state. while (g[failure][ch] == -1) failure = f[failure]; failure = g[failure][ch]; f[g[state][ch]] = failure; // Merge output values out[g[state][ch]] |= out[failure]; // Insert the next level node // (of Trie) in Queue q.add(g[state][ch]); } } } return states;} // Returns the next state the machine will transition to using goto// and failure functions.// currentState - The current state of the machine. Must be between// 0 and the number of states - 1, inclusive.// nextInput - The next character that enters into the machine.static int findNextState(int currentState, char nextInput){ int answer = currentState; int ch = nextInput - 'a'; // If goto is not defined, use // failure function while (g[answer][ch] == -1) answer = f[answer]; return g[answer][ch];} // This function finds all occurrences of// all array words in text.static void searchWords(String arr[], int k, String text){ // Preprocess patterns. // Build machine with goto, failure // and output functions buildMatchingMachine(arr, k); // Initialize current state int currentState = 0; // Traverse the text through the // built machine to find all // occurrences of words in arr[] for(int i = 0; i < text.length(); ++i) { currentState = findNextState(currentState, text.charAt(i)); // If match not found, move to next state if (out[currentState] == 0) continue; // Match found, print all matching // words of arr[] // using output function. for(int j = 0; j < k; ++j) { if ((out[currentState] & (1 << j)) > 0) { System.out.print("Word " + arr[j] + " appears from " + (i - arr[j].length() + 1) + " to " + i + "\n"); } } }} // Driver codepublic static void main(String[] args){ String arr[] = { "he", "she", "hers", "his" }; String text = "ahishers"; int k = arr.length; searchWords(arr, k, text);}} // This code is contributed by Princi Singh # Python program for implementation of# Aho-Corasick algorithm for string matching # defaultdict is used only for storing the final output# We will return a dictionary where key is the matched word# and value is the list of indexes of matched wordfrom collections import defaultdict # For simplicity, Arrays and Queues have been implemented using lists. # If you want to improve performance try using them insteadclass AhoCorasick: def __init__(self, words): # Max number of states in the matching machine. # Should be equal to the sum of the length of all keywords. self.max_states = sum([len(word) for word in words]) # Maximum number of characters. # Currently supports only alphabets [a,z] self.max_characters = 26 # OUTPUT FUNCTION IS IMPLEMENTED USING out [] # Bit i in this mask is 1 if the word with # index i appears when the machine enters this state. # Lets say, a state outputs two words "he" and "she" and # in our provided words list, he has index 0 and she has index 3 # so value of out[state] for this state will be 1001 # It has been initialized to all 0. # We have taken one extra state for the root. self.out = [0]*(self.max_states+1) # FAILURE FUNCTION IS IMPLEMENTED USING fail [] # There is one value for each state + 1 for the root # It has been initialized to all -1 # This will contain the fail state value for each state self.fail = [-1]*(self.max_states+1) # GOTO FUNCTION (OR TRIE) IS IMPLEMENTED USING goto [[]] # Number of rows = max_states + 1 # Number of columns = max_characters i.e 26 in our case # It has been initialized to all -1. self.goto = [[-1]*self.max_characters for _ in range(self.max_states+1)] # Convert all words to lowercase # so that our search is case insensitive for i in range(len(words)): words[i] = words[i].lower() # All the words in dictionary which will be used to create Trie # The index of each keyword is important: # "out[state] & (1 << i)" is > 0 if we just found word[i] # in the text. self.words = words # Once the Trie has been built, it will contain the number # of nodes in Trie which is total number of states required <= max_states self.states_count = self.__build_matching_machine() # Builds the String matching machine. # Returns the number of states that the built machine has. # States are numbered 0 up to the return value - 1, inclusive. def __build_matching_machine(self): k = len(self.words) # Initially, we just have the 0 state states = 1 # Convalues for goto function, i.e., fill goto # This is same as building a Trie for words[] for i in range(k): word = self.words[i] current_state = 0 # Process all the characters of the current word for character in word: ch = ord(character) - 97 # Ascii value of 'a' = 97 # Allocate a new node (create a new state) # if a node for ch doesn't exist. if self.goto[current_state][ch] == -1: self.goto[current_state][ch] = states states += 1 current_state = self.goto[current_state][ch] # Add current word in output function self.out[current_state] |= (1<<i) # For all characters which don't have # an edge from root (or state 0) in Trie, # add a goto edge to state 0 itself for ch in range(self.max_characters): if self.goto[0][ch] == -1: self.goto[0][ch] = 0 # Failure function is computed in # breadth first order using a queue queue = [] # Iterate over every possible input for ch in range(self.max_characters): # All nodes of depth 1 have failure # function value as 0. For example, # in above diagram we move to 0 # from states 1 and 3. if self.goto[0][ch] != 0: self.fail[self.goto[0][ch]] = 0 queue.append(self.goto[0][ch]) # Now queue has states 1 and 3 while queue: # Remove the front state from queue state = queue.pop(0) # For the removed state, find failure # function for all those characters # for which goto function is not defined. for ch in range(self.max_characters): # If goto function is defined for # character 'ch' and 'state' if self.goto[state][ch] != -1: # Find failure state of removed state failure = self.fail[state] # Find the deepest node labeled by proper # suffix of String from root to current state. while self.goto[failure][ch] == -1: failure = self.fail[failure] failure = self.goto[failure][ch] self.fail[self.goto[state][ch]] = failure # Merge output values self.out[self.goto[state][ch]] |= self.out[failure] # Insert the next level node (of Trie) in Queue queue.append(self.goto[state][ch]) return states # Returns the next state the machine will transition to using goto # and failure functions. # current_state - The current state of the machine. Must be between # 0 and the number of states - 1, inclusive. # next_input - The next character that enters into the machine. def __find_next_state(self, current_state, next_input): answer = current_state ch = ord(next_input) - 97 # Ascii value of 'a' is 97 # If goto is not defined, use # failure function while self.goto[answer][ch] == -1: answer = self.fail[answer] return self.goto[answer][ch] # This function finds all occurrences of all words in text. def search_words(self, text): # Convert the text to lowercase to make search case insensitive text = text.lower() # Initialize current_state to 0 current_state = 0 # A dictionary to store the result. # Key here is the found word # Value is a list of all occurrences start index result = defaultdict(list) # Traverse the text through the built machine # to find all occurrences of words for i in range(len(text)): current_state = self.__find_next_state(current_state, text[i]) # If match not found, move to next state if self.out[current_state] == 0: continue # Match found, store the word in result dictionary for j in range(len(self.words)): if (self.out[current_state] & (1<<j)) > 0: word = self.words[j] # Start index of word is (i-len(word)+1) result[word].append(i-len(word)+1) # Return the final result dictionary return result # Driver codeif __name__ == "__main__": words = ["he", "she", "hers", "his"] text = "ahishers" # Create an Object to initialize the Trie aho_chorasick = AhoCorasick(words) # Get the result result = aho_chorasick.search_words(text) # Print the result for word in result: for i in result[word]: print("Word", word, "appears from", i, "to", i+len(word)-1) # This code is contributed by Md Azharuddin // C# program for implementation of// Aho Corasick algorithm for String// matchingusing System;using System.Collections.Generic; class GFG{ // Max number of states in the matching// machine. Should be equal to the sum// of the length of all keywords.static int MAXS = 500; // Maximum number of characters// in input alphabetstatic int MAXC = 26; // OUTPUT FUNCTION IS IMPLEMENTED USING out[]// Bit i in this mask is one if the word with// index i appears when the machine enters// this state.static int[] out = new int[MAXS]; // FAILURE FUNCTION IS IMPLEMENTED USING f[]static int[] f = new int[MAXS]; // GOTO FUNCTION (OR TRIE) IS// IMPLEMENTED USING g[,]static int[,] g = new int[MAXS, MAXC]; // Builds the String matching machine.// arr - array of words. The index of each keyword is// important:// "out[state] & (1 << i)" is > 0 if we just// found word[i] in the text.// Returns the number of states that the built machine// has. States are numbered 0 up to the return value -// 1, inclusive.static int buildMatchingMachine(String[] arr, int k){ // Initialize all values in output function as 0. for(int i = 0; i < outt.Length; i++) outt[i] = 0; // Initialize all values in goto function as -1. for(int i = 0; i < MAXS; i++) for(int j = 0; j < MAXC; j++) g[i, j] = -1; // Initially, we just have the 0 state int states = 1; // Convalues for goto function, i.e., fill g[,] // This is same as building a Trie for []arr for(int i = 0; i < k; ++i) { String word = arr[i]; int currentState = 0; // Insert all characters of current // word in []arr for(int j = 0; j < word.Length; ++j) { int ch = word[j] - 'a'; // Allocate a new node (create a new state) // if a node for ch doesn't exist. if (g[currentState, ch] == -1) g[currentState, ch] = states++; currentState = g[currentState, ch]; } // Add current word in output function outt[currentState] |= (1 << i); } // For all characters which don't have // an edge from root (or state 0) in Trie, // add a goto edge to state 0 itself for(int ch = 0; ch < MAXC; ++ch) if (g[0, ch] == -1) g[0, ch] = 0; // Now, let's build the failure function // Initialize values in fail function for(int i = 0; i < MAXC; i++) f[i] = 0; // Failure function is computed in // breadth first order // using a queue Queue<int> q = new Queue<int>(); // Iterate over every possible input for(int ch = 0; ch < MAXC; ++ch) { // All nodes of depth 1 have failure // function value as 0. For example, // in above diagram we move to 0 // from states 1 and 3. if (g[0, ch] != 0) { f[g[0, ch]] = 0; q.Enqueue(g[0, ch]); } } // Now queue has states 1 and 3 while (q.Count != 0) { // Remove the front state from queue int state = q.Peek(); q.Dequeue(); // For the removed state, find failure // function for all those characters // for which goto function is // not defined. for(int ch = 0; ch < MAXC; ++ch) { // If goto function is defined for // character 'ch' and 'state' if (g[state, ch] != -1) { // Find failure state of removed state int failure = f[state]; // Find the deepest node labeled by // proper suffix of String from root to // current state. while (g[failure, ch] == -1) failure = f[failure]; failure = g[failure, ch]; f[g[state, ch]] = failure; // Merge output values outt[g[state, ch]] |= outt[failure]; // Insert the next level node // (of Trie) in Queue q.Enqueue(g[state, ch]); } } } return states;} // Returns the next state the machine will transition to// using goto and failure functions. currentState - The// current state of the machine. Must be between// 0 and the number of states - 1,// inclusive.// nextInput - The next character that enters into the// machine.static int findNextState(int currentState, char nextInput){ int answer = currentState; int ch = nextInput - 'a'; // If goto is not defined, use // failure function while (g[answer, ch] == -1) answer = f[answer]; return g[answer, ch];} // This function finds all occurrences of// all array words in text.static void searchWords(String[] arr, int k, String text){ // Preprocess patterns. // Build machine with goto, failure // and output functions buildMatchingMachine(arr, k); // Initialize current state int currentState = 0; // Traverse the text through the // built machine to find all // occurrences of words in []arr for(int i = 0; i < text.Length; ++i) { currentState = findNextState(currentState, text[i]); // If match not found, move to next state if (outt[currentState] == 0) continue; // Match found, print all matching // words of []arr // using output function. for(int j = 0; j < k; ++j) { if ((outt[currentState] & (1 << j)) > 0) { Console.Write("Word " + arr[j] + " appears from " + (i - arr[j].Length + 1) + " to " + i + "\n"); } } }} // Driver codepublic static void Main(String[] args){ String[] arr = { "he", "she", "hers", "his" }; String text = "ahishers"; int k = arr.Length; searchWords(arr, k, text);}} // This code is contributed by Amit Katiyar Word his appears from 1 to 3 Word he appears from 4 to 5 Word she appears from 3 to 5 Word hers appears from 4 to 7 Source: http://www.cs.uku.fi/~kilpelai/BSA05/lectures/slides04.pdfThis article is contributed by Ayush Govil. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above PawelWolowiec 2001guljain princi singh amit143katiyar mdAzharuddin adnanirshad158 arorakashish0911 unmeshkamleshkumar surindertarika1234 Pattern Searching Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Minimize number of cuts required to break N length stick into N unit length sticks Check if a string contains uppercase, lowercase, special characters and numeric values String matching where one string contains wildcard characters Pattern Searching using Suffix Tree Remove leading zeros from a Number given as a string Applications of String Matching Algorithms How to validate a domain name using Regular Expression Check if a string consists only of special characters Suffix Array | Set 1 (Introduction) Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 1
[ { "code": null, "e": 24838, "s": 24810, "text": "\n05 Nov, 2021" }, { "code": null, "e": 25129, "s": 24838, "text": "Given an input text and an array of k words, arr[], find all occurrences of all words in the input text. Let n be the length of text and m be the total number characters in all words, i.e. m = length(arr[0]) + length(arr[1]) + ... + length(arr[k-1]). Here k is total numbers of input words." }, { "code": null, "e": 25140, "s": 25129, "text": "Example: " }, { "code": null, "e": 25350, "s": 25140, "text": "Input: text = \"ahishers\" \n arr[] = {\"he\", \"she\", \"hers\", \"his\"}\n\nOutput:\n Word his appears from 1 to 3\n Word he appears from 4 to 5\n Word she appears from 3 to 5\n Word hers appears from 4 to 7" }, { "code": null, "e": 25651, "s": 25350, "text": "If we use a linear time searching algorithm like KMP, then we need to one by one search all words in text[]. This gives us total time complexity as O(n + length(word[0]) + O(n + length(word[1]) + O(n + length(word[2]) + ... O(n + length(word[k-1]). This time complexity can be written as O(n*k + m). " }, { "code": null, "e": 25865, "s": 25651, "text": "Aho-Corasick Algorithm finds all words in O(n + m + z) time where z is total number of occurrences of words in text. The Aho–Corasick string matching algorithm formed the basis of the original Unix command fgrep. " }, { "code": null, "e": 25964, "s": 25865, "text": "Preprocessing : Build an automaton of all words in arr[] The automaton has mainly three functions:" }, { "code": null, "e": 26626, "s": 25964, "text": "Go To : This function simply follows edges\n of Trie of all words in arr[]. It is\n represented as 2D array g[][] where\n we store next state for current state \n and character.\n\nFailure : This function stores all edges that are\n followed when current character doesn't\n have edge in Trie. It is represented as\n 1D array f[] where we store next state for\n current state. \n\nOutput : Stores indexes of all words that end at \n current state. It is represented as 1D \n array o[] where we store indexes\n of all matching words as a bitmap for \n current state." }, { "code": null, "e": 26710, "s": 26626, "text": "Matching : Traverse the given text over built automaton to find all matching words." }, { "code": null, "e": 26726, "s": 26710, "text": "Preprocessing: " }, { "code": null, "e": 26782, "s": 26726, "text": "We first Build a Trie (or Keyword Tree) of all words. " }, { "code": null, "e": 26787, "s": 26782, "text": "Trie" }, { "code": null, "e": 26841, "s": 26787, "text": "This part fills entries in goto g[][] and output o[]." }, { "code": null, "e": 26914, "s": 26841, "text": "Next we extend Trie into an automaton to support linear time matching. " }, { "code": null, "e": 26969, "s": 26914, "text": "This part fills entries in failure f[] and output o[]." }, { "code": null, "e": 27438, "s": 26969, "text": "Go to : We build Trie. And for all characters which don’t have an edge at root, we add an edge back to root.Failure : For a state s, we find the longest proper suffix which is a proper prefix of some pattern. This is done using Breadth First Traversal of Trie.Output : For a state s, indexes of all words ending at s are stored. These indexes are stored as bitwise map (by doing bitwise OR of values). This is also computing using Breadth First Traversal with Failure." }, { "code": null, "e": 27493, "s": 27438, "text": "Below is the implementation of Aho-Corasick Algorithm " }, { "code": null, "e": 27497, "s": 27493, "text": "C++" }, { "code": null, "e": 27502, "s": 27497, "text": "Java" }, { "code": null, "e": 27510, "s": 27502, "text": "Python3" }, { "code": null, "e": 27513, "s": 27510, "text": "C#" }, { "code": "// C++ program for implementation of Aho Corasick algorithm// for string matchingusing namespace std;#include <bits/stdc++.h> // Max number of states in the matching machine.// Should be equal to the sum of the length of all keywords.const int MAXS = 500; // Maximum number of characters in input alphabetconst int MAXC = 26; // OUTPUT FUNCTION IS IMPLEMENTED USING out[]// Bit i in this mask is one if the word with index i// appears when the machine enters this state.int out[MAXS]; // FAILURE FUNCTION IS IMPLEMENTED USING f[]int f[MAXS]; // GOTO FUNCTION (OR TRIE) IS IMPLEMENTED USING g[][]int g[MAXS][MAXC]; // Builds the string matching machine.// arr - array of words. The index of each keyword is important:// \"out[state] & (1 << i)\" is > 0 if we just found word[i]// in the text.// Returns the number of states that the built machine has.// States are numbered 0 up to the return value - 1, inclusive.int buildMatchingMachine(string arr[], int k){ // Initialize all values in output function as 0. memset(out, 0, sizeof out); // Initialize all values in goto function as -1. memset(g, -1, sizeof g); // Initially, we just have the 0 state int states = 1; // Construct values for goto function, i.e., fill g[][] // This is same as building a Trie for arr[] for (int i = 0; i < k; ++i) { const string &word = arr[i]; int currentState = 0; // Insert all characters of current word in arr[] for (int j = 0; j < word.size(); ++j) { int ch = word[j] - 'a'; // Allocate a new node (create a new state) if a // node for ch doesn't exist. if (g[currentState][ch] == -1) g[currentState][ch] = states++; currentState = g[currentState][ch]; } // Add current word in output function out[currentState] |= (1 << i); } // For all characters which don't have an edge from // root (or state 0) in Trie, add a goto edge to state // 0 itself for (int ch = 0; ch < MAXC; ++ch) if (g[0][ch] == -1) g[0][ch] = 0; // Now, let's build the failure function // Initialize values in fail function memset(f, -1, sizeof f); // Failure function is computed in breadth first order // using a queue queue<int> q; // Iterate over every possible input for (int ch = 0; ch < MAXC; ++ch) { // All nodes of depth 1 have failure function value // as 0. For example, in above diagram we move to 0 // from states 1 and 3. if (g[0][ch] != 0) { f[g[0][ch]] = 0; q.push(g[0][ch]); } } // Now queue has states 1 and 3 while (q.size()) { // Remove the front state from queue int state = q.front(); q.pop(); // For the removed state, find failure function for // all those characters for which goto function is // not defined. for (int ch = 0; ch <= MAXC; ++ch) { // If goto function is defined for character 'ch' // and 'state' if (g[state][ch] != -1) { // Find failure state of removed state int failure = f[state]; // Find the deepest node labeled by proper // suffix of string from root to current // state. while (g[failure][ch] == -1) failure = f[failure]; failure = g[failure][ch]; f[g[state][ch]] = failure; // Merge output values out[g[state][ch]] |= out[failure]; // Insert the next level node (of Trie) in Queue q.push(g[state][ch]); } } } return states;} // Returns the next state the machine will transition to using goto// and failure functions.// currentState - The current state of the machine. Must be between// 0 and the number of states - 1, inclusive.// nextInput - The next character that enters into the machine.int findNextState(int currentState, char nextInput){ int answer = currentState; int ch = nextInput - 'a'; // If goto is not defined, use failure function while (g[answer][ch] == -1) answer = f[answer]; return g[answer][ch];} // This function finds all occurrences of all array words// in text.void searchWords(string arr[], int k, string text){ // Preprocess patterns. // Build machine with goto, failure and output functions buildMatchingMachine(arr, k); // Initialize current state int currentState = 0; // Traverse the text through the built machine to find // all occurrences of words in arr[] for (int i = 0; i < text.size(); ++i) { currentState = findNextState(currentState, text[i]); // If match not found, move to next state if (out[currentState] == 0) continue; // Match found, print all matching words of arr[] // using output function. for (int j = 0; j < k; ++j) { if (out[currentState] & (1 << j)) { cout << \"Word \" << arr[j] << \" appears from \" << i - arr[j].size() + 1 << \" to \" << i << endl; } } }} // Driver program to test aboveint main(){ string arr[] = {\"he\", \"she\", \"hers\", \"his\"}; string text = \"ahishers\"; int k = sizeof(arr)/sizeof(arr[0]); searchWords(arr, k, text); return 0;}", "e": 33030, "s": 27513, "text": null }, { "code": "// Java program for implementation of // Aho Corasick algorithm for String// matchingimport java.util.*; class GFG{ // Max number of states in the matching// machine. Should be equal to the sum // of the length of all keywords.static int MAXS = 500; // Maximum number of characters// in input alphabetstatic int MAXC = 26; // OUTPUT FUNCTION IS IMPLEMENTED USING out[]// Bit i in this mask is one if the word with // index i appears when the machine enters // this state.static int []out = new int[MAXS]; // FAILURE FUNCTION IS IMPLEMENTED USING f[]static int []f = new int[MAXS]; // GOTO FUNCTION (OR TRIE) IS// IMPLEMENTED USING g[][]static int [][]g = new int[MAXS][MAXC]; // Builds the String matching machine.// arr - array of words. The index of each keyword is important:// \"out[state] & (1 << i)\" is > 0 if we just found word[i]// in the text.// Returns the number of states that the built machine has.// States are numbered 0 up to the return value - 1, inclusive.static int buildMatchingMachine(String arr[], int k){ // Initialize all values in output function as 0. Arrays.fill(out, 0); // Initialize all values in goto function as -1. for(int i = 0; i < MAXS; i++) Arrays.fill(g[i], -1); // Initially, we just have the 0 state int states = 1; // Convalues for goto function, i.e., fill g[][] // This is same as building a Trie for arr[] for(int i = 0; i < k; ++i) { String word = arr[i]; int currentState = 0; // Insert all characters of current // word in arr[] for(int j = 0; j < word.length(); ++j) { int ch = word.charAt(j) - 'a'; // Allocate a new node (create a new state) // if a node for ch doesn't exist. if (g[currentState][ch] == -1) g[currentState][ch] = states++; currentState = g[currentState][ch]; } // Add current word in output function out[currentState] |= (1 << i); } // For all characters which don't have // an edge from root (or state 0) in Trie, // add a goto edge to state 0 itself for(int ch = 0; ch < MAXC; ++ch) if (g[0][ch] == -1) g[0][ch] = 0; // Now, let's build the failure function // Initialize values in fail function Arrays.fill(f, -1); // Failure function is computed in // breadth first order // using a queue Queue<Integer> q = new LinkedList<>(); // Iterate over every possible input for(int ch = 0; ch < MAXC; ++ch) { // All nodes of depth 1 have failure // function value as 0. For example, // in above diagram we move to 0 // from states 1 and 3. if (g[0][ch] != 0) { f[g[0][ch]] = 0; q.add(g[0][ch]); } } // Now queue has states 1 and 3 while (!q.isEmpty()) { // Remove the front state from queue int state = q.peek(); q.remove(); // For the removed state, find failure // function for all those characters // for which goto function is // not defined. for(int ch = 0; ch < MAXC; ++ch) { // If goto function is defined for // character 'ch' and 'state' if (g[state][ch] != -1) { // Find failure state of removed state int failure = f[state]; // Find the deepest node labeled by proper // suffix of String from root to current // state. while (g[failure][ch] == -1) failure = f[failure]; failure = g[failure][ch]; f[g[state][ch]] = failure; // Merge output values out[g[state][ch]] |= out[failure]; // Insert the next level node // (of Trie) in Queue q.add(g[state][ch]); } } } return states;} // Returns the next state the machine will transition to using goto// and failure functions.// currentState - The current state of the machine. Must be between// 0 and the number of states - 1, inclusive.// nextInput - The next character that enters into the machine.static int findNextState(int currentState, char nextInput){ int answer = currentState; int ch = nextInput - 'a'; // If goto is not defined, use // failure function while (g[answer][ch] == -1) answer = f[answer]; return g[answer][ch];} // This function finds all occurrences of// all array words in text.static void searchWords(String arr[], int k, String text){ // Preprocess patterns. // Build machine with goto, failure // and output functions buildMatchingMachine(arr, k); // Initialize current state int currentState = 0; // Traverse the text through the // built machine to find all // occurrences of words in arr[] for(int i = 0; i < text.length(); ++i) { currentState = findNextState(currentState, text.charAt(i)); // If match not found, move to next state if (out[currentState] == 0) continue; // Match found, print all matching // words of arr[] // using output function. for(int j = 0; j < k; ++j) { if ((out[currentState] & (1 << j)) > 0) { System.out.print(\"Word \" + arr[j] + \" appears from \" + (i - arr[j].length() + 1) + \" to \" + i + \"\\n\"); } } }} // Driver codepublic static void main(String[] args){ String arr[] = { \"he\", \"she\", \"hers\", \"his\" }; String text = \"ahishers\"; int k = arr.length; searchWords(arr, k, text);}} // This code is contributed by Princi Singh", "e": 39008, "s": 33030, "text": null }, { "code": "# Python program for implementation of# Aho-Corasick algorithm for string matching # defaultdict is used only for storing the final output# We will return a dictionary where key is the matched word# and value is the list of indexes of matched wordfrom collections import defaultdict # For simplicity, Arrays and Queues have been implemented using lists. # If you want to improve performance try using them insteadclass AhoCorasick: def __init__(self, words): # Max number of states in the matching machine. # Should be equal to the sum of the length of all keywords. self.max_states = sum([len(word) for word in words]) # Maximum number of characters. # Currently supports only alphabets [a,z] self.max_characters = 26 # OUTPUT FUNCTION IS IMPLEMENTED USING out [] # Bit i in this mask is 1 if the word with # index i appears when the machine enters this state. # Lets say, a state outputs two words \"he\" and \"she\" and # in our provided words list, he has index 0 and she has index 3 # so value of out[state] for this state will be 1001 # It has been initialized to all 0. # We have taken one extra state for the root. self.out = [0]*(self.max_states+1) # FAILURE FUNCTION IS IMPLEMENTED USING fail [] # There is one value for each state + 1 for the root # It has been initialized to all -1 # This will contain the fail state value for each state self.fail = [-1]*(self.max_states+1) # GOTO FUNCTION (OR TRIE) IS IMPLEMENTED USING goto [[]] # Number of rows = max_states + 1 # Number of columns = max_characters i.e 26 in our case # It has been initialized to all -1. self.goto = [[-1]*self.max_characters for _ in range(self.max_states+1)] # Convert all words to lowercase # so that our search is case insensitive for i in range(len(words)): words[i] = words[i].lower() # All the words in dictionary which will be used to create Trie # The index of each keyword is important: # \"out[state] & (1 << i)\" is > 0 if we just found word[i] # in the text. self.words = words # Once the Trie has been built, it will contain the number # of nodes in Trie which is total number of states required <= max_states self.states_count = self.__build_matching_machine() # Builds the String matching machine. # Returns the number of states that the built machine has. # States are numbered 0 up to the return value - 1, inclusive. def __build_matching_machine(self): k = len(self.words) # Initially, we just have the 0 state states = 1 # Convalues for goto function, i.e., fill goto # This is same as building a Trie for words[] for i in range(k): word = self.words[i] current_state = 0 # Process all the characters of the current word for character in word: ch = ord(character) - 97 # Ascii value of 'a' = 97 # Allocate a new node (create a new state) # if a node for ch doesn't exist. if self.goto[current_state][ch] == -1: self.goto[current_state][ch] = states states += 1 current_state = self.goto[current_state][ch] # Add current word in output function self.out[current_state] |= (1<<i) # For all characters which don't have # an edge from root (or state 0) in Trie, # add a goto edge to state 0 itself for ch in range(self.max_characters): if self.goto[0][ch] == -1: self.goto[0][ch] = 0 # Failure function is computed in # breadth first order using a queue queue = [] # Iterate over every possible input for ch in range(self.max_characters): # All nodes of depth 1 have failure # function value as 0. For example, # in above diagram we move to 0 # from states 1 and 3. if self.goto[0][ch] != 0: self.fail[self.goto[0][ch]] = 0 queue.append(self.goto[0][ch]) # Now queue has states 1 and 3 while queue: # Remove the front state from queue state = queue.pop(0) # For the removed state, find failure # function for all those characters # for which goto function is not defined. for ch in range(self.max_characters): # If goto function is defined for # character 'ch' and 'state' if self.goto[state][ch] != -1: # Find failure state of removed state failure = self.fail[state] # Find the deepest node labeled by proper # suffix of String from root to current state. while self.goto[failure][ch] == -1: failure = self.fail[failure] failure = self.goto[failure][ch] self.fail[self.goto[state][ch]] = failure # Merge output values self.out[self.goto[state][ch]] |= self.out[failure] # Insert the next level node (of Trie) in Queue queue.append(self.goto[state][ch]) return states # Returns the next state the machine will transition to using goto # and failure functions. # current_state - The current state of the machine. Must be between # 0 and the number of states - 1, inclusive. # next_input - The next character that enters into the machine. def __find_next_state(self, current_state, next_input): answer = current_state ch = ord(next_input) - 97 # Ascii value of 'a' is 97 # If goto is not defined, use # failure function while self.goto[answer][ch] == -1: answer = self.fail[answer] return self.goto[answer][ch] # This function finds all occurrences of all words in text. def search_words(self, text): # Convert the text to lowercase to make search case insensitive text = text.lower() # Initialize current_state to 0 current_state = 0 # A dictionary to store the result. # Key here is the found word # Value is a list of all occurrences start index result = defaultdict(list) # Traverse the text through the built machine # to find all occurrences of words for i in range(len(text)): current_state = self.__find_next_state(current_state, text[i]) # If match not found, move to next state if self.out[current_state] == 0: continue # Match found, store the word in result dictionary for j in range(len(self.words)): if (self.out[current_state] & (1<<j)) > 0: word = self.words[j] # Start index of word is (i-len(word)+1) result[word].append(i-len(word)+1) # Return the final result dictionary return result # Driver codeif __name__ == \"__main__\": words = [\"he\", \"she\", \"hers\", \"his\"] text = \"ahishers\" # Create an Object to initialize the Trie aho_chorasick = AhoCorasick(words) # Get the result result = aho_chorasick.search_words(text) # Print the result for word in result: for i in result[word]: print(\"Word\", word, \"appears from\", i, \"to\", i+len(word)-1) # This code is contributed by Md Azharuddin", "e": 46751, "s": 39008, "text": null }, { "code": "// C# program for implementation of// Aho Corasick algorithm for String// matchingusing System;using System.Collections.Generic; class GFG{ // Max number of states in the matching// machine. Should be equal to the sum// of the length of all keywords.static int MAXS = 500; // Maximum number of characters// in input alphabetstatic int MAXC = 26; // OUTPUT FUNCTION IS IMPLEMENTED USING out[]// Bit i in this mask is one if the word with// index i appears when the machine enters// this state.static int[] out = new int[MAXS]; // FAILURE FUNCTION IS IMPLEMENTED USING f[]static int[] f = new int[MAXS]; // GOTO FUNCTION (OR TRIE) IS// IMPLEMENTED USING g[,]static int[,] g = new int[MAXS, MAXC]; // Builds the String matching machine.// arr - array of words. The index of each keyword is// important:// \"out[state] & (1 << i)\" is > 0 if we just// found word[i] in the text.// Returns the number of states that the built machine// has. States are numbered 0 up to the return value -// 1, inclusive.static int buildMatchingMachine(String[] arr, int k){ // Initialize all values in output function as 0. for(int i = 0; i < outt.Length; i++) outt[i] = 0; // Initialize all values in goto function as -1. for(int i = 0; i < MAXS; i++) for(int j = 0; j < MAXC; j++) g[i, j] = -1; // Initially, we just have the 0 state int states = 1; // Convalues for goto function, i.e., fill g[,] // This is same as building a Trie for []arr for(int i = 0; i < k; ++i) { String word = arr[i]; int currentState = 0; // Insert all characters of current // word in []arr for(int j = 0; j < word.Length; ++j) { int ch = word[j] - 'a'; // Allocate a new node (create a new state) // if a node for ch doesn't exist. if (g[currentState, ch] == -1) g[currentState, ch] = states++; currentState = g[currentState, ch]; } // Add current word in output function outt[currentState] |= (1 << i); } // For all characters which don't have // an edge from root (or state 0) in Trie, // add a goto edge to state 0 itself for(int ch = 0; ch < MAXC; ++ch) if (g[0, ch] == -1) g[0, ch] = 0; // Now, let's build the failure function // Initialize values in fail function for(int i = 0; i < MAXC; i++) f[i] = 0; // Failure function is computed in // breadth first order // using a queue Queue<int> q = new Queue<int>(); // Iterate over every possible input for(int ch = 0; ch < MAXC; ++ch) { // All nodes of depth 1 have failure // function value as 0. For example, // in above diagram we move to 0 // from states 1 and 3. if (g[0, ch] != 0) { f[g[0, ch]] = 0; q.Enqueue(g[0, ch]); } } // Now queue has states 1 and 3 while (q.Count != 0) { // Remove the front state from queue int state = q.Peek(); q.Dequeue(); // For the removed state, find failure // function for all those characters // for which goto function is // not defined. for(int ch = 0; ch < MAXC; ++ch) { // If goto function is defined for // character 'ch' and 'state' if (g[state, ch] != -1) { // Find failure state of removed state int failure = f[state]; // Find the deepest node labeled by // proper suffix of String from root to // current state. while (g[failure, ch] == -1) failure = f[failure]; failure = g[failure, ch]; f[g[state, ch]] = failure; // Merge output values outt[g[state, ch]] |= outt[failure]; // Insert the next level node // (of Trie) in Queue q.Enqueue(g[state, ch]); } } } return states;} // Returns the next state the machine will transition to// using goto and failure functions. currentState - The// current state of the machine. Must be between// 0 and the number of states - 1,// inclusive.// nextInput - The next character that enters into the// machine.static int findNextState(int currentState, char nextInput){ int answer = currentState; int ch = nextInput - 'a'; // If goto is not defined, use // failure function while (g[answer, ch] == -1) answer = f[answer]; return g[answer, ch];} // This function finds all occurrences of// all array words in text.static void searchWords(String[] arr, int k, String text){ // Preprocess patterns. // Build machine with goto, failure // and output functions buildMatchingMachine(arr, k); // Initialize current state int currentState = 0; // Traverse the text through the // built machine to find all // occurrences of words in []arr for(int i = 0; i < text.Length; ++i) { currentState = findNextState(currentState, text[i]); // If match not found, move to next state if (outt[currentState] == 0) continue; // Match found, print all matching // words of []arr // using output function. for(int j = 0; j < k; ++j) { if ((outt[currentState] & (1 << j)) > 0) { Console.Write(\"Word \" + arr[j] + \" appears from \" + (i - arr[j].Length + 1) + \" to \" + i + \"\\n\"); } } }} // Driver codepublic static void Main(String[] args){ String[] arr = { \"he\", \"she\", \"hers\", \"his\" }; String text = \"ahishers\"; int k = arr.Length; searchWords(arr, k, text);}} // This code is contributed by Amit Katiyar", "e": 52854, "s": 46751, "text": null }, { "code": null, "e": 52970, "s": 52854, "text": "Word his appears from 1 to 3\nWord he appears from 4 to 5\nWord she appears from 3 to 5\nWord hers appears from 4 to 7" }, { "code": null, "e": 53205, "s": 52970, "text": "Source: http://www.cs.uku.fi/~kilpelai/BSA05/lectures/slides04.pdfThis article is contributed by Ayush Govil. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 53219, "s": 53205, "text": "PawelWolowiec" }, { "code": null, "e": 53231, "s": 53219, "text": "2001guljain" }, { "code": null, "e": 53244, "s": 53231, "text": "princi singh" }, { "code": null, "e": 53259, "s": 53244, "text": "amit143katiyar" }, { "code": null, "e": 53272, "s": 53259, "text": "mdAzharuddin" }, { "code": null, "e": 53287, "s": 53272, "text": "adnanirshad158" }, { "code": null, "e": 53304, "s": 53287, "text": "arorakashish0911" }, { "code": null, "e": 53323, "s": 53304, "text": "unmeshkamleshkumar" }, { "code": null, "e": 53342, "s": 53323, "text": "surindertarika1234" }, { "code": null, "e": 53360, "s": 53342, "text": "Pattern Searching" }, { "code": null, "e": 53378, "s": 53360, "text": "Pattern Searching" }, { "code": null, "e": 53476, "s": 53378, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 53559, "s": 53476, "text": "Minimize number of cuts required to break N length stick into N unit length sticks" }, { "code": null, "e": 53646, "s": 53559, "text": "Check if a string contains uppercase, lowercase, special characters and numeric values" }, { "code": null, "e": 53708, "s": 53646, "text": "String matching where one string contains wildcard characters" }, { "code": null, "e": 53744, "s": 53708, "text": "Pattern Searching using Suffix Tree" }, { "code": null, "e": 53797, "s": 53744, "text": "Remove leading zeros from a Number given as a string" }, { "code": null, "e": 53840, "s": 53797, "text": "Applications of String Matching Algorithms" }, { "code": null, "e": 53895, "s": 53840, "text": "How to validate a domain name using Regular Expression" }, { "code": null, "e": 53949, "s": 53895, "text": "Check if a string consists only of special characters" }, { "code": null, "e": 53985, "s": 53949, "text": "Suffix Array | Set 1 (Introduction)" } ]
HSQLDB - Create Table
The basic mandatory requirements to create a table are table name, field names, and the data types to those fields. Optionally, you can also provide the key constraints to the table. Take a look at the following syntax. CREATE TABLE table_name (column_name column_type); Let us create a table named tutorials_tbl with the field-names such as id, title, author, and submission_date. Take a look at the following query. CREATE TABLE tutorials_tbl ( id INT NOT NULL, title VARCHAR(50) NOT NULL, author VARCHAR(20) NOT NULL, submission_date DATE, PRIMARY KEY (id) ); After execution of the above query, you will receive the following output − (0) rows effected Following is the JDBC program used to create a table named tutorials_tbl into the HSQLDB database. Save the program into CreateTable.java file. import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class CreateTable { public static void main(String[] args) { Connection con = null; Statement stmt = null; int result = 0; try { Class.forName("org.hsqldb.jdbc.JDBCDriver"); con = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/testdb", "SA", ""); stmt = con.createStatement(); result = stmt.executeUpdate("CREATE TABLE tutorials_tbl ( id INT NOT NULL, title VARCHAR(50) NOT NULL, author VARCHAR(20) NOT NULL, submission_date DATE, PRIMARY KEY (id)); "); } catch (Exception e) { e.printStackTrace(System.out); } System.out.println("Table created successfully"); } } You can start the database using the following command. \>cd C:\hsqldb-2.3.4\hsqldb hsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0 file:hsqldb/demodb --dbname.0 testdb Compile and execute the above program using the following command. \>javac CreateTable.java \>java CreateTable After execution of the above command, you will receive the following output − Table created successfully Print Add Notes Bookmark this page
[ { "code": null, "e": 2165, "s": 1982, "text": "The basic mandatory requirements to create a table are table name, field names, and the data types to those fields. Optionally, you can also provide the key constraints to the table." }, { "code": null, "e": 2202, "s": 2165, "text": "Take a look at the following syntax." }, { "code": null, "e": 2254, "s": 2202, "text": "CREATE TABLE table_name (column_name column_type);\n" }, { "code": null, "e": 2401, "s": 2254, "text": "Let us create a table named tutorials_tbl with the field-names such as id, title, author, and submission_date. Take a look at the following query." }, { "code": null, "e": 2562, "s": 2401, "text": "CREATE TABLE tutorials_tbl (\n id INT NOT NULL,\n title VARCHAR(50) NOT NULL,\n author VARCHAR(20) NOT NULL,\n submission_date DATE,\n PRIMARY KEY (id) \n);" }, { "code": null, "e": 2638, "s": 2562, "text": "After execution of the above query, you will receive the following output −" }, { "code": null, "e": 2657, "s": 2638, "text": "(0) rows effected\n" }, { "code": null, "e": 2801, "s": 2657, "text": "Following is the JDBC program used to create a table named tutorials_tbl into the HSQLDB database. Save the program into CreateTable.java file." }, { "code": null, "e": 3642, "s": 2801, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.Statement;\n\npublic class CreateTable {\n \n public static void main(String[] args) {\n \n Connection con = null;\n Statement stmt = null;\n int result = 0;\n \n try {\n Class.forName(\"org.hsqldb.jdbc.JDBCDriver\");\n con = DriverManager.getConnection(\"jdbc:hsqldb:hsql://localhost/testdb\", \"SA\", \"\");\n stmt = con.createStatement();\n \n result = stmt.executeUpdate(\"CREATE TABLE tutorials_tbl (\n id INT NOT NULL, title VARCHAR(50) NOT NULL,\n author VARCHAR(20) NOT NULL, submission_date DATE,\n PRIMARY KEY (id));\n \");\n\t\t\t\n } catch (Exception e) {\n e.printStackTrace(System.out);\n }\n System.out.println(\"Table created successfully\");\n }\n}" }, { "code": null, "e": 3698, "s": 3642, "text": "You can start the database using the following command." }, { "code": null, "e": 3839, "s": 3698, "text": "\\>cd C:\\hsqldb-2.3.4\\hsqldb\nhsqldb>java -classpath lib/hsqldb.jar org.hsqldb.server.Server --database.0\nfile:hsqldb/demodb --dbname.0 testdb" }, { "code": null, "e": 3906, "s": 3839, "text": "Compile and execute the above program using the following command." }, { "code": null, "e": 3951, "s": 3906, "text": "\\>javac CreateTable.java\n\\>java CreateTable\n" }, { "code": null, "e": 4029, "s": 3951, "text": "After execution of the above command, you will receive the following output −" }, { "code": null, "e": 4057, "s": 4029, "text": "Table created successfully\n" }, { "code": null, "e": 4064, "s": 4057, "text": " Print" }, { "code": null, "e": 4075, "s": 4064, "text": " Add Notes" } ]
Print all subsequences of a string using Iterative Method in C++
In this problem, we are given a string and we have to find the substring from the given string. The substring to be found should start with a vowel and end with constant character. A string is an array of characters. The substring that is to be generated in this problem can be generated by deleting some characters of the string. And without changing the order of the string. Input: ‘abc’ Output: ab, ac, abc To solve this problem, we will iterate the string and fix vowels and check for the next sequence. Let’s see an algorithm to find a solution − Step 1: Iterate of each character of the string, with variable i. Step 2: If the ith character is a vowel. Step 3: If the jth character is a consonant. Step 4: Add to the HashSet, substring from 1st character to jth character. Step 5: Repeat the following steps and find substrings from the string. In the iterative approach, we will iterate over all string. From 1 to 2legth(string)−1. Live Demo #include <bits/stdc++.h> using namespace std; string subString(string s, int binary){ string sub = ""; int pos; while(binary>0){ pos=log2(binary&-binary)+1; sub=s[pos-1]+sub; binary= (binary & ~(1 << (pos-1))); } reverse(sub.begin(),sub.end()); return sub; } void findAllSubStrings(string s){ map<int, set<string> > sorted_subsequence; int len = s.size(); int limit = pow(2, len); for (int i = 1; i <= limit - 1; i++) { string sub = subString(s, i); sorted_subsequence[sub.length()].insert(sub); } for (auto it : sorted_subsequence) { for (auto ii : it.second) cout<<ii<<" "; cout<<"\t"; } } int main() { string s = "wxyz"; cout<<"The substring are :\n"; findAllSubStrings(s); return 0; } The substring is − w x y z wx wy wz xy xz yz wxy wxz wyz xyz wxyz
[ { "code": null, "e": 1243, "s": 1062, "text": "In this problem, we are given a string and we have to find the substring from the given string. The substring to be found should start with a vowel and end\nwith constant character." }, { "code": null, "e": 1279, "s": 1243, "text": "A string is an array of characters." }, { "code": null, "e": 1439, "s": 1279, "text": "The substring that is to be generated in this problem can be generated by\ndeleting some characters of the string. And without changing the order of the string." }, { "code": null, "e": 1472, "s": 1439, "text": "Input: ‘abc’\nOutput: ab, ac, abc" }, { "code": null, "e": 1614, "s": 1472, "text": "To solve this problem, we will iterate the string and fix vowels and check for\nthe next sequence. Let’s see an algorithm to find a solution −" }, { "code": null, "e": 1913, "s": 1614, "text": "Step 1: Iterate of each character of the string, with variable i.\nStep 2: If the ith character is a vowel.\nStep 3: If the jth character is a consonant.\nStep 4: Add to the HashSet, substring from 1st character to jth character.\nStep 5: Repeat the following steps and find substrings from the string." }, { "code": null, "e": 2001, "s": 1913, "text": "In the iterative approach, we will iterate over all string. From 1 to 2legth(string)−1." }, { "code": null, "e": 2012, "s": 2001, "text": " Live Demo" }, { "code": null, "e": 2803, "s": 2012, "text": "#include <bits/stdc++.h>\nusing namespace std;\nstring subString(string s, int binary){\n string sub = \"\";\n int pos;\n while(binary>0){\n pos=log2(binary&-binary)+1;\n sub=s[pos-1]+sub;\n binary= (binary & ~(1 << (pos-1)));\n }\n reverse(sub.begin(),sub.end());\n return sub;\n}\nvoid findAllSubStrings(string s){\n map<int, set<string> > sorted_subsequence;\n int len = s.size();\n int limit = pow(2, len);\n for (int i = 1; i <= limit - 1; i++) {\n string sub = subString(s, i);\n sorted_subsequence[sub.length()].insert(sub);\n }\n for (auto it : sorted_subsequence) {\n for (auto ii : it.second)\n cout<<ii<<\" \";\n cout<<\"\\t\";\n }\n}\nint main() {\n string s = \"wxyz\";\n cout<<\"The substring are :\\n\";\n findAllSubStrings(s);\n return 0;\n}" }, { "code": null, "e": 2822, "s": 2803, "text": "The substring is −" }, { "code": null, "e": 2869, "s": 2822, "text": "w x y z wx wy wz xy xz yz wxy wxz wyz xyz wxyz" } ]
Count digits in a factorial in C++
We are given an integer value and the task is to first calculate the factorial of a number and then calculate the total number of digits in a result. Factorial of a number is calculated by multiplying the digits in a number while decrementing the value of digit by 1. It is denoted by the symbol ‘!’ i.e. 0!, 1!, 2!, 3!, 5!,....,etc. Factorial of 0! and 1! is always 1. I.e. factorial of 2 = 2 * (2-1) = 2 * 1 = 2 factorial of 3 = 3 * (3-1) * (2-1) = 3 * 2 * 1 = 6 Input − factorial(6) Output − number of digits in factorial(6) is: 3 Explanation − since the factorial value of 6 is 720 and it contains 3 digits therefore, the result is 3 Input − factorial(12) Output− number of digits in factorial(12) is: 9 Explanation − since the factorial value of 12 is 479001600 and it contains 9 digits therefore, the result is 9. Input the number of which factorial needs to be calculated . Input the number of which factorial needs to be calculated . If the number is less than 0 then return 0 because negative number don’t have any factorial value If the number is less than 0 then return 0 because negative number don’t have any factorial value If the number is 1 then return 1 because 1! Is 1 and it has 1 digit. If the number is 1 then return 1 because 1! Is 1 and it has 1 digit. If the number is greater than 1 i.e. starts with 2 or more than create one loop, starting from 2 till it is less than or equals to number If the number is greater than 1 i.e. starts with 2 or more than create one loop, starting from 2 till it is less than or equals to number Take one temporary variable let’s say d and initialise it with 0 outside the loop and inside the loop keep adding it with the value of log10(i) till every iteration of i. Take one temporary variable let’s say d and initialise it with 0 outside the loop and inside the loop keep adding it with the value of log10(i) till every iteration of i. After that, return the floor value of ‘floor(d)+1’ After that, return the floor value of ‘floor(d)+1’ Print the result. Print the result. Live Demo #include <iostream> #include <cmath> using namespace std; // This function returns the number of digits present in num! int count_digits(int num){ // factorial exists only if num <= 0 if (num < 0){ return 0; } // base case if (num <= 1){ return 1; } // else iterate through num and calculate the // value double d = 0; for (int i=2; i<=num; i++){ d += log10(i); } return floor(d) + 1; } int main(){ cout<<"number of digits in factorial(1) is: "<<count_digits(1)<< endl; cout<<"number of digits in factorial(6) is: "<<count_digits(6) << endl; cout<<"number of digits in factorial(106) is: "<<count_digits(106) << endl; return 0; } If we run the above code it will generate the following output − number of digits in factorial(1) is: 1 number of digits in factorial(6) is: 3 number of digits in factorial(106) is: 171
[ { "code": null, "e": 1212, "s": 1062, "text": "We are given an integer value and the task is to first calculate the factorial of a number and then calculate the total number of digits in a result." }, { "code": null, "e": 1432, "s": 1212, "text": "Factorial of a number is calculated by multiplying the digits in a number while decrementing the value of digit by 1. It is denoted by the symbol ‘!’ i.e. 0!, 1!, 2!, 3!, 5!,....,etc. Factorial of 0! and 1! is always 1." }, { "code": null, "e": 1533, "s": 1432, "text": "I.e. factorial of 2 = 2 * (2-1) = 2 * 1 = 2\n factorial of 3 = 3 * (3-1) * (2-1) = 3 * 2 * 1 = 6" }, { "code": null, "e": 1602, "s": 1533, "text": "Input − factorial(6)\nOutput − number of digits in factorial(6) is: 3" }, { "code": null, "e": 1706, "s": 1602, "text": "Explanation − since the factorial value of 6 is 720 and it contains 3 digits therefore, the result is 3" }, { "code": null, "e": 1776, "s": 1706, "text": "Input − factorial(12)\nOutput− number of digits in factorial(12) is: 9" }, { "code": null, "e": 1888, "s": 1776, "text": "Explanation − since the factorial value of 12 is 479001600 and it contains 9 digits therefore, the result is 9." }, { "code": null, "e": 1949, "s": 1888, "text": "Input the number of which factorial needs to be calculated ." }, { "code": null, "e": 2010, "s": 1949, "text": "Input the number of which factorial needs to be calculated ." }, { "code": null, "e": 2108, "s": 2010, "text": "If the number is less than 0 then return 0 because negative number don’t have any\nfactorial value" }, { "code": null, "e": 2206, "s": 2108, "text": "If the number is less than 0 then return 0 because negative number don’t have any\nfactorial value" }, { "code": null, "e": 2275, "s": 2206, "text": "If the number is 1 then return 1 because 1! Is 1 and it has 1 digit." }, { "code": null, "e": 2344, "s": 2275, "text": "If the number is 1 then return 1 because 1! Is 1 and it has 1 digit." }, { "code": null, "e": 2482, "s": 2344, "text": "If the number is greater than 1 i.e. starts with 2 or more than create one loop, starting from 2 till it is less than or equals to number" }, { "code": null, "e": 2620, "s": 2482, "text": "If the number is greater than 1 i.e. starts with 2 or more than create one loop, starting from 2 till it is less than or equals to number" }, { "code": null, "e": 2791, "s": 2620, "text": "Take one temporary variable let’s say d and initialise it with 0 outside the loop and inside the loop keep adding it with the value of log10(i) till every iteration of i." }, { "code": null, "e": 2962, "s": 2791, "text": "Take one temporary variable let’s say d and initialise it with 0 outside the loop and inside the loop keep adding it with the value of log10(i) till every iteration of i." }, { "code": null, "e": 3013, "s": 2962, "text": "After that, return the floor value of ‘floor(d)+1’" }, { "code": null, "e": 3064, "s": 3013, "text": "After that, return the floor value of ‘floor(d)+1’" }, { "code": null, "e": 3082, "s": 3064, "text": "Print the result." }, { "code": null, "e": 3100, "s": 3082, "text": "Print the result." }, { "code": null, "e": 3111, "s": 3100, "text": " Live Demo" }, { "code": null, "e": 3807, "s": 3111, "text": "#include <iostream>\n#include <cmath>\nusing namespace std;\n// This function returns the number of digits present in num!\nint count_digits(int num){\n // factorial exists only if num <= 0\n if (num < 0){\n return 0;\n }\n // base case\n if (num <= 1){\n return 1;\n }\n // else iterate through num and calculate the\n // value\n double d = 0;\n for (int i=2; i<=num; i++){\n d += log10(i);\n }\n return floor(d) + 1;\n}\nint main(){\n cout<<\"number of digits in factorial(1) is: \"<<count_digits(1)<< endl;\n cout<<\"number of digits in factorial(6) is: \"<<count_digits(6) << endl;\n cout<<\"number of digits in factorial(106) is: \"<<count_digits(106) << endl;\n return 0;\n}" }, { "code": null, "e": 3872, "s": 3807, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 3993, "s": 3872, "text": "number of digits in factorial(1) is: 1\nnumber of digits in factorial(6) is: 3\nnumber of digits in factorial(106) is: 171" } ]
Number of sub-sequence such that it has one consecutive element with difference less than or equal to 1 - GeeksforGeeks
26 Sep, 2021 Given an array arr[] of N elements. The task is to find the number of sub-sequences which have at least two consecutive elements such that absolute difference between them is ≤ 1. Examples: Input: arr[] = {1, 6, 2, 1} Output: 6 {1, 2}, {1, 2, 1}, {2, 1}, {6, 2, 1}, {1, 1} and {1, 6, 2, 1} are the sub-sequences that have at least one consecutive pair with difference less than or equal to 1. Input: arr[] = {1, 6, 2, 1, 9} Output: 12 Naive approach: The idea is to find all the possible sub-sequences and check if there exists a sub-sequence with any consecutive pair with difference ≤1 and increase the count. Efficient approach: The idea is to iterate over the given array and for each ith-element, try to find the required sub-sequence ending with ith element as its last element. For every i, we want to use arr[i], arr[i] -1, arr[i] + 1, so we will define 2D array, dp[][], where dp[i][0] will contain the number of sub sequence that do not have any consecutive pair with difference less than 1 and dp[i][1] contain the number of sub sequence having any consecutive pair with difference ≤1. Also, we will maintain two variables required_subsequence and not_required_subsdequence to maintain the count of subsequences which have at least one consecutive element with difference ≤1 and count of sub-sequences which do not contain any consecutive element pair with difference ≤1. Now, considering the sub-array arr[1] .... arr[i], we will perform the following steps: Compute the number of sub sequences which do not have any consecutive pair with difference less than 1 but will have by adding the ith element in the sub sequence. These are basically sum of dp[arr[i] + 1][0], dp[arr[i] – 1][0] and dp[arr[i]][0].Total number of subsequences have at least one consecutive pair with difference at least 1 and ending at i is equal to total sub-sequences found till i (just append arr[i] at the last) + subsequences which turns into subsequence have at least consecutive pair with difference less than 1 on adding arr[i].Total subsequence which do not have any consecutive pair with difference less than 1 and ending at i = total sub-sequence which do not have any consecutive pair with difference less than 1 before i + 1 (just the current element as a subsequence).Update required_sub-sequence, not_required_subsequence and dp[arr[i][0]] and the final answer will be required_subsequence. Compute the number of sub sequences which do not have any consecutive pair with difference less than 1 but will have by adding the ith element in the sub sequence. These are basically sum of dp[arr[i] + 1][0], dp[arr[i] – 1][0] and dp[arr[i]][0]. Total number of subsequences have at least one consecutive pair with difference at least 1 and ending at i is equal to total sub-sequences found till i (just append arr[i] at the last) + subsequences which turns into subsequence have at least consecutive pair with difference less than 1 on adding arr[i]. Total subsequence which do not have any consecutive pair with difference less than 1 and ending at i = total sub-sequence which do not have any consecutive pair with difference less than 1 before i + 1 (just the current element as a subsequence). Update required_sub-sequence, not_required_subsequence and dp[arr[i][0]] and the final answer will be required_subsequence. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std;const int N = 10000; // Function to return the number of subsequences// which have at least one consecutive pair// with difference less than or equal to 1int count_required_sequence(int n, int arr[]){ int total_required_subsequence = 0; int total_n_required_subsequence = 0; int dp[N][2]; for (int i = 0; i < n; i++) { // Not required sub-sequences which // turn required on adding i int turn_required = 0; for (int j = -1; j <= 1; j++) turn_required += dp[arr[i] + j][0]; // Required sub-sequence till now will be // required sequence plus sub-sequence // which turns required int required_end_i = (total_required_subsequence + turn_required); // Similarly for not required int n_required_end_i = (1 + total_n_required_subsequence - turn_required); // Also updating total required and // not required sub-sequences total_required_subsequence += required_end_i; total_n_required_subsequence += n_required_end_i; // Also, storing values in dp dp[arr[i]][1] += required_end_i; dp[arr[i]][0] += n_required_end_i; } return total_required_subsequence;} // Driver codeint main(){ int arr[] = { 1, 6, 2, 1, 9 }; int n = sizeof(arr) / sizeof(int); cout << count_required_sequence(n, arr) << "\n"; return 0;} // Java implementation of above approachpublic class GFG{ static int N = 10000; // Function to return the number of subsequences// which have at least one consecutive pair// with difference less than or equal to 1static int count_required_sequence(int n, int arr[]){ int total_required_subsequence = 0; int total_n_required_subsequence = 0; int [][]dp = new int[N][2]; for (int i = 0; i < n; i++) { // Not required sub-sequences which // turn required on adding i int turn_required = 0; for (int j = -1; j <= 1; j++) turn_required += dp[arr[i] + j][0]; // Required sub-sequence till now will be // required sequence plus sub-sequence // which turns required int required_end_i = (total_required_subsequence + turn_required); // Similarly for not required int n_required_end_i = (1 + total_n_required_subsequence - turn_required); // Also updating total required and // not required sub-sequences total_required_subsequence += required_end_i; total_n_required_subsequence += n_required_end_i; // Also, storing values in dp dp[arr[i]][1] += required_end_i; dp[arr[i]][0] += n_required_end_i; } return total_required_subsequence;} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 6, 2, 1, 9 }; int n = arr.length; System.out.println(count_required_sequence(n, arr));}} // This code has been contributed by 29AjayKumar # Python3 implementation of the approachimport numpy as np; N = 10000; # Function to return the number of subsequences# which have at least one consecutive pair# with difference less than or equal to 1def count_required_sequence(n, arr) : total_required_subsequence = 0; total_n_required_subsequence = 0; dp = np.zeros((N,2)); for i in range(n) : # Not required sub-sequences which # turn required on adding i turn_required = 0; for j in range(-1, 2,1) : turn_required += dp[arr[i] + j][0]; # Required sub-sequence till now will be # required sequence plus sub-sequence # which turns required required_end_i = (total_required_subsequence + turn_required); # Similarly for not required n_required_end_i = (1 + total_n_required_subsequence - turn_required); # Also updating total required and # not required sub-sequences total_required_subsequence += required_end_i; total_n_required_subsequence += n_required_end_i; # Also, storing values in dp dp[arr[i]][1] += required_end_i; dp[arr[i]][0] += n_required_end_i; return total_required_subsequence; # Driver codeif __name__ == "__main__" : arr = [ 1, 6, 2, 1, 9 ]; n = len(arr); print(count_required_sequence(n, arr)) ; # This code is contributed by AnkitRai01 using System; public class GFG{ static int N = 10000; // Function to return the number of subsequences// which have at least one consecutive pair// with difference less than or equal to 1static int count_required_sequence(int n, int[] arr){ int total_required_subsequence = 0; int total_n_required_subsequence = 0; int [,]dp = new int[N,2]; for (int i = 0; i < n; i++) { // Not required sub-sequences which // turn required on adding i int turn_required = 0; for (int j = -1; j <= 1; j++) turn_required += dp[arr[i] + j,0]; // Required sub-sequence till now will be // required sequence plus sub-sequence // which turns required int required_end_i = (total_required_subsequence + turn_required); // Similarly for not required int n_required_end_i = (1 + total_n_required_subsequence - turn_required); // Also updating total required and // not required sub-sequences total_required_subsequence += required_end_i; total_n_required_subsequence += n_required_end_i; // Also, storing values in dp dp[arr[i],1] += required_end_i; dp[arr[i],0] += n_required_end_i; } return total_required_subsequence;} // Driver code static public void Main () { int[] arr = { 1, 6, 2, 1, 9 }; int n = arr.Length; Console.WriteLine(count_required_sequence(n, arr)); }} // This code is contributed by rag2127. <script> // Javascript implementation of the approachvar N = 10000; // Function to return the number of subsequences// which have at least one consecutive pair// with difference less than or equal to 1function count_required_sequence(n, arr){ var total_required_subsequence = 0; var total_n_required_subsequence = 0; var dp = Array.from(Array(N), ()=> Array(2).fill(0)); for (var i = 0; i < n; i++) { // Not required sub-sequences which // turn required on adding i var turn_required = 0; for (var j = -1; j <= 1; j++) turn_required += dp[arr[i] + j][0]; // Required sub-sequence till now will be // required sequence plus sub-sequence // which turns required var required_end_i = (total_required_subsequence + turn_required); // Similarly for not required var n_required_end_i = (1 + total_n_required_subsequence - turn_required); // Also updating total required and // not required sub-sequences total_required_subsequence += required_end_i; total_n_required_subsequence += n_required_end_i; // Also, storing values in dp dp[arr[i]][1] += required_end_i; dp[arr[i]][0] += n_required_end_i; } return total_required_subsequence;} // Driver codevar arr = [ 1, 6, 2, 1, 9 ];var n = arr.length;document.write( count_required_sequence(n, arr) + "<br>"); </script> 12 29AjayKumar ihritik ankthon Akanksha_Rai nidhi_biet itsok rag2127 sweetyty sooda367 subsequence Arrays Dynamic Programming Arrays Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Window Sliding Technique Building Heap from Array Trapping Rain Water Reversal algorithm for array rotation Program to find sum of elements in a given array 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Bellman–Ford Algorithm | DP-23 Longest Common Subsequence | DP-4 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 24820, "s": 24792, "text": "\n26 Sep, 2021" }, { "code": null, "e": 25001, "s": 24820, "text": "Given an array arr[] of N elements. The task is to find the number of sub-sequences which have at least two consecutive elements such that absolute difference between them is ≤ 1. " }, { "code": null, "e": 25012, "s": 25001, "text": "Examples: " }, { "code": null, "e": 25215, "s": 25012, "text": "Input: arr[] = {1, 6, 2, 1} Output: 6 {1, 2}, {1, 2, 1}, {2, 1}, {6, 2, 1}, {1, 1} and {1, 6, 2, 1} are the sub-sequences that have at least one consecutive pair with difference less than or equal to 1." }, { "code": null, "e": 25258, "s": 25215, "text": "Input: arr[] = {1, 6, 2, 1, 9} Output: 12 " }, { "code": null, "e": 25435, "s": 25258, "text": "Naive approach: The idea is to find all the possible sub-sequences and check if there exists a sub-sequence with any consecutive pair with difference ≤1 and increase the count." }, { "code": null, "e": 26206, "s": 25435, "text": "Efficient approach: The idea is to iterate over the given array and for each ith-element, try to find the required sub-sequence ending with ith element as its last element. For every i, we want to use arr[i], arr[i] -1, arr[i] + 1, so we will define 2D array, dp[][], where dp[i][0] will contain the number of sub sequence that do not have any consecutive pair with difference less than 1 and dp[i][1] contain the number of sub sequence having any consecutive pair with difference ≤1. Also, we will maintain two variables required_subsequence and not_required_subsdequence to maintain the count of subsequences which have at least one consecutive element with difference ≤1 and count of sub-sequences which do not contain any consecutive element pair with difference ≤1." }, { "code": null, "e": 26296, "s": 26206, "text": "Now, considering the sub-array arr[1] .... arr[i], we will perform the following steps: " }, { "code": null, "e": 27217, "s": 26296, "text": "Compute the number of sub sequences which do not have any consecutive pair with difference less than 1 but will have by adding the ith element in the sub sequence. These are basically sum of dp[arr[i] + 1][0], dp[arr[i] – 1][0] and dp[arr[i]][0].Total number of subsequences have at least one consecutive pair with difference at least 1 and ending at i is equal to total sub-sequences found till i (just append arr[i] at the last) + subsequences which turns into subsequence have at least consecutive pair with difference less than 1 on adding arr[i].Total subsequence which do not have any consecutive pair with difference less than 1 and ending at i = total sub-sequence which do not have any consecutive pair with difference less than 1 before i + 1 (just the current element as a subsequence).Update required_sub-sequence, not_required_subsequence and dp[arr[i][0]] and the final answer will be required_subsequence." }, { "code": null, "e": 27464, "s": 27217, "text": "Compute the number of sub sequences which do not have any consecutive pair with difference less than 1 but will have by adding the ith element in the sub sequence. These are basically sum of dp[arr[i] + 1][0], dp[arr[i] – 1][0] and dp[arr[i]][0]." }, { "code": null, "e": 27770, "s": 27464, "text": "Total number of subsequences have at least one consecutive pair with difference at least 1 and ending at i is equal to total sub-sequences found till i (just append arr[i] at the last) + subsequences which turns into subsequence have at least consecutive pair with difference less than 1 on adding arr[i]." }, { "code": null, "e": 28017, "s": 27770, "text": "Total subsequence which do not have any consecutive pair with difference less than 1 and ending at i = total sub-sequence which do not have any consecutive pair with difference less than 1 before i + 1 (just the current element as a subsequence)." }, { "code": null, "e": 28141, "s": 28017, "text": "Update required_sub-sequence, not_required_subsequence and dp[arr[i][0]] and the final answer will be required_subsequence." }, { "code": null, "e": 28194, "s": 28141, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 28198, "s": 28194, "text": "C++" }, { "code": null, "e": 28203, "s": 28198, "text": "Java" }, { "code": null, "e": 28211, "s": 28203, "text": "Python3" }, { "code": null, "e": 28214, "s": 28211, "text": "C#" }, { "code": null, "e": 28225, "s": 28214, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;const int N = 10000; // Function to return the number of subsequences// which have at least one consecutive pair// with difference less than or equal to 1int count_required_sequence(int n, int arr[]){ int total_required_subsequence = 0; int total_n_required_subsequence = 0; int dp[N][2]; for (int i = 0; i < n; i++) { // Not required sub-sequences which // turn required on adding i int turn_required = 0; for (int j = -1; j <= 1; j++) turn_required += dp[arr[i] + j][0]; // Required sub-sequence till now will be // required sequence plus sub-sequence // which turns required int required_end_i = (total_required_subsequence + turn_required); // Similarly for not required int n_required_end_i = (1 + total_n_required_subsequence - turn_required); // Also updating total required and // not required sub-sequences total_required_subsequence += required_end_i; total_n_required_subsequence += n_required_end_i; // Also, storing values in dp dp[arr[i]][1] += required_end_i; dp[arr[i]][0] += n_required_end_i; } return total_required_subsequence;} // Driver codeint main(){ int arr[] = { 1, 6, 2, 1, 9 }; int n = sizeof(arr) / sizeof(int); cout << count_required_sequence(n, arr) << \"\\n\"; return 0;}", "e": 29734, "s": 28225, "text": null }, { "code": "// Java implementation of above approachpublic class GFG{ static int N = 10000; // Function to return the number of subsequences// which have at least one consecutive pair// with difference less than or equal to 1static int count_required_sequence(int n, int arr[]){ int total_required_subsequence = 0; int total_n_required_subsequence = 0; int [][]dp = new int[N][2]; for (int i = 0; i < n; i++) { // Not required sub-sequences which // turn required on adding i int turn_required = 0; for (int j = -1; j <= 1; j++) turn_required += dp[arr[i] + j][0]; // Required sub-sequence till now will be // required sequence plus sub-sequence // which turns required int required_end_i = (total_required_subsequence + turn_required); // Similarly for not required int n_required_end_i = (1 + total_n_required_subsequence - turn_required); // Also updating total required and // not required sub-sequences total_required_subsequence += required_end_i; total_n_required_subsequence += n_required_end_i; // Also, storing values in dp dp[arr[i]][1] += required_end_i; dp[arr[i]][0] += n_required_end_i; } return total_required_subsequence;} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 6, 2, 1, 9 }; int n = arr.length; System.out.println(count_required_sequence(n, arr));}} // This code has been contributed by 29AjayKumar", "e": 31300, "s": 29734, "text": null }, { "code": "# Python3 implementation of the approachimport numpy as np; N = 10000; # Function to return the number of subsequences# which have at least one consecutive pair# with difference less than or equal to 1def count_required_sequence(n, arr) : total_required_subsequence = 0; total_n_required_subsequence = 0; dp = np.zeros((N,2)); for i in range(n) : # Not required sub-sequences which # turn required on adding i turn_required = 0; for j in range(-1, 2,1) : turn_required += dp[arr[i] + j][0]; # Required sub-sequence till now will be # required sequence plus sub-sequence # which turns required required_end_i = (total_required_subsequence + turn_required); # Similarly for not required n_required_end_i = (1 + total_n_required_subsequence - turn_required); # Also updating total required and # not required sub-sequences total_required_subsequence += required_end_i; total_n_required_subsequence += n_required_end_i; # Also, storing values in dp dp[arr[i]][1] += required_end_i; dp[arr[i]][0] += n_required_end_i; return total_required_subsequence; # Driver codeif __name__ == \"__main__\" : arr = [ 1, 6, 2, 1, 9 ]; n = len(arr); print(count_required_sequence(n, arr)) ; # This code is contributed by AnkitRai01", "e": 32749, "s": 31300, "text": null }, { "code": "using System; public class GFG{ static int N = 10000; // Function to return the number of subsequences// which have at least one consecutive pair// with difference less than or equal to 1static int count_required_sequence(int n, int[] arr){ int total_required_subsequence = 0; int total_n_required_subsequence = 0; int [,]dp = new int[N,2]; for (int i = 0; i < n; i++) { // Not required sub-sequences which // turn required on adding i int turn_required = 0; for (int j = -1; j <= 1; j++) turn_required += dp[arr[i] + j,0]; // Required sub-sequence till now will be // required sequence plus sub-sequence // which turns required int required_end_i = (total_required_subsequence + turn_required); // Similarly for not required int n_required_end_i = (1 + total_n_required_subsequence - turn_required); // Also updating total required and // not required sub-sequences total_required_subsequence += required_end_i; total_n_required_subsequence += n_required_end_i; // Also, storing values in dp dp[arr[i],1] += required_end_i; dp[arr[i],0] += n_required_end_i; } return total_required_subsequence;} // Driver code static public void Main () { int[] arr = { 1, 6, 2, 1, 9 }; int n = arr.Length; Console.WriteLine(count_required_sequence(n, arr)); }} // This code is contributed by rag2127.", "e": 34321, "s": 32749, "text": null }, { "code": "<script> // Javascript implementation of the approachvar N = 10000; // Function to return the number of subsequences// which have at least one consecutive pair// with difference less than or equal to 1function count_required_sequence(n, arr){ var total_required_subsequence = 0; var total_n_required_subsequence = 0; var dp = Array.from(Array(N), ()=> Array(2).fill(0)); for (var i = 0; i < n; i++) { // Not required sub-sequences which // turn required on adding i var turn_required = 0; for (var j = -1; j <= 1; j++) turn_required += dp[arr[i] + j][0]; // Required sub-sequence till now will be // required sequence plus sub-sequence // which turns required var required_end_i = (total_required_subsequence + turn_required); // Similarly for not required var n_required_end_i = (1 + total_n_required_subsequence - turn_required); // Also updating total required and // not required sub-sequences total_required_subsequence += required_end_i; total_n_required_subsequence += n_required_end_i; // Also, storing values in dp dp[arr[i]][1] += required_end_i; dp[arr[i]][0] += n_required_end_i; } return total_required_subsequence;} // Driver codevar arr = [ 1, 6, 2, 1, 9 ];var n = arr.length;document.write( count_required_sequence(n, arr) + \"<br>\"); </script>", "e": 35795, "s": 34321, "text": null }, { "code": null, "e": 35798, "s": 35795, "text": "12" }, { "code": null, "e": 35812, "s": 35800, "text": "29AjayKumar" }, { "code": null, "e": 35820, "s": 35812, "text": "ihritik" }, { "code": null, "e": 35828, "s": 35820, "text": "ankthon" }, { "code": null, "e": 35841, "s": 35828, "text": "Akanksha_Rai" }, { "code": null, "e": 35852, "s": 35841, "text": "nidhi_biet" }, { "code": null, "e": 35858, "s": 35852, "text": "itsok" }, { "code": null, "e": 35866, "s": 35858, "text": "rag2127" }, { "code": null, "e": 35875, "s": 35866, "text": "sweetyty" }, { "code": null, "e": 35884, "s": 35875, "text": "sooda367" }, { "code": null, "e": 35896, "s": 35884, "text": "subsequence" }, { "code": null, "e": 35903, "s": 35896, "text": "Arrays" }, { "code": null, "e": 35923, "s": 35903, "text": "Dynamic Programming" }, { "code": null, "e": 35930, "s": 35923, "text": "Arrays" }, { "code": null, "e": 35950, "s": 35930, "text": "Dynamic Programming" }, { "code": null, "e": 36048, "s": 35950, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36073, "s": 36048, "text": "Window Sliding Technique" }, { "code": null, "e": 36098, "s": 36073, "text": "Building Heap from Array" }, { "code": null, "e": 36118, "s": 36098, "text": "Trapping Rain Water" }, { "code": null, "e": 36156, "s": 36118, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 36205, "s": 36156, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 36234, "s": 36205, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 36264, "s": 36234, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 36295, "s": 36264, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 36329, "s": 36295, "text": "Longest Common Subsequence | DP-4" } ]
Python | Check for Nth index existence in list - GeeksforGeeks
27 Aug, 2019 Sometimes, while working with lists, we can have a problem in which we require to insert a particular element at an index. But, before that it is essential to know that particular index is part of list or not. Let’s discuss certain shorthands that can perform this task error free. Method #1 : Using len()This task can be performed easily by finding the length of list using len(). We can check if the desired index is smaller than length which would prove it’s existence. # Python3 code to demonstrate working of# Check for Nth index existence in list# Using len() # initializing listtest_list = [4, 5, 6, 7, 10] # printing original listprint("The original list is : " + str(test_list)) # initializing N N = 6 # Check for Nth index existence in list# Using len()res = len(test_list) >= N # printing result print("Is Nth index available? : " + str(res)) The original list is : [4, 5, 6, 7, 10] Is Nth index available? : False Method #2 : Using try-except block + IndexError exceptionThis task can also be solved using the try except block which raises a IndexError exception if we try to access an index not a part of list i.e out of bound. # Python3 code to demonstrate working of# Check for Nth index existence in list# Using try-except block + IndexError exception # initializing listtest_list = [4, 5, 6, 7, 10] # printing original listprint("The original list is : " + str(test_list)) # initializing N N = 6 # Check for Nth index existence in list# Using try-except block + IndexError exceptiontry: val = test_list[N] res = Trueexcept IndexError: res = False # printing result print("Is Nth index available? : " + str(res)) The original list is : [4, 5, 6, 7, 10] Is Nth index available? : False 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 ? How to drop one or multiple columns in Pandas Dataframe Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON? Check if element exists in list in Python 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": 24317, "s": 24289, "text": "\n27 Aug, 2019" }, { "code": null, "e": 24599, "s": 24317, "text": "Sometimes, while working with lists, we can have a problem in which we require to insert a particular element at an index. But, before that it is essential to know that particular index is part of list or not. Let’s discuss certain shorthands that can perform this task error free." }, { "code": null, "e": 24790, "s": 24599, "text": "Method #1 : Using len()This task can be performed easily by finding the length of list using len(). We can check if the desired index is smaller than length which would prove it’s existence." }, { "code": "# Python3 code to demonstrate working of# Check for Nth index existence in list# Using len() # initializing listtest_list = [4, 5, 6, 7, 10] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing N N = 6 # Check for Nth index existence in list# Using len()res = len(test_list) >= N # printing result print(\"Is Nth index available? : \" + str(res))", "e": 25176, "s": 24790, "text": null }, { "code": null, "e": 25249, "s": 25176, "text": "The original list is : [4, 5, 6, 7, 10]\nIs Nth index available? : False\n" }, { "code": null, "e": 25466, "s": 25251, "text": "Method #2 : Using try-except block + IndexError exceptionThis task can also be solved using the try except block which raises a IndexError exception if we try to access an index not a part of list i.e out of bound." }, { "code": "# Python3 code to demonstrate working of# Check for Nth index existence in list# Using try-except block + IndexError exception # initializing listtest_list = [4, 5, 6, 7, 10] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing N N = 6 # Check for Nth index existence in list# Using try-except block + IndexError exceptiontry: val = test_list[N] res = Trueexcept IndexError: res = False # printing result print(\"Is Nth index available? : \" + str(res))", "e": 25970, "s": 25466, "text": null }, { "code": null, "e": 26043, "s": 25970, "text": "The original list is : [4, 5, 6, 7, 10]\nIs Nth index available? : False\n" }, { "code": null, "e": 26064, "s": 26043, "text": "Python list-programs" }, { "code": null, "e": 26071, "s": 26064, "text": "Python" }, { "code": null, "e": 26087, "s": 26071, "text": "Python Programs" }, { "code": null, "e": 26185, "s": 26087, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26194, "s": 26185, "text": "Comments" }, { "code": null, "e": 26207, "s": 26194, "text": "Old Comments" }, { "code": null, "e": 26239, "s": 26207, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26295, "s": 26239, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26350, "s": 26295, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26392, "s": 26350, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26434, "s": 26392, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26456, "s": 26434, "text": "Defaultdict in Python" }, { "code": null, "e": 26502, "s": 26456, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26541, "s": 26502, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26579, "s": 26541, "text": "Python | Convert a list to dictionary" } ]
MySQL - Queries on Date Manipulation - GeeksforGeeks
09 May, 2021 In MySQL date is a data type and by default follows the format ‘YYYY-MM-DD’ but by using date formatting functions we can format date and can get the required format of date in the tables and can even manipulate the date by using different date functions. In this article let us execute some queries on date formatting in detail step-by-step: Creating a database student by using the following SQL query as follows. CREATE DATABASE orders; Using the database student using the following SQL query as follows. USE orders; Table –Creating a table order_details with 3 columns using the following SQL query as follows. CREATE TABLE order_details( order_id varchar(8), customer_name varchar(20), order_date DATE); To view the description of the tables in the database using the following SQL query as follows. DESCRIBE order_details; Inserting rows into order_details table using the following SQL query as follows. INSERT INTO order_details VALUES ('O0001','PRADEEP','2021-04-11'), ('O0002','KOUSHIK','2021-04-09'), ('O0003','SRINIVAS','2021-04-05'), ('O0004','SATWIK','2021-04-08'), ('O0005','LOKESH','2021-04-03'); Viewing the table order_details after inserting rows by using the following SQL query as follows. SELECT* FROM order_details; 1.Query to format order_date as ‘DD-MM-YY’. The default date can be formatted from the default date by using the DATE_FORMAT( ) function: SYNTAX: DATE_FORMAT(date,new_format); In this query, we are using %d to get day then %b to get abbreviated month and %y to get the year. SELECT *,DATE_FORMAT(order_date,'%d-%b-%y') AS formatted_date FROM order_details; 2. Query to get the estimated delivery date after 15 days from the order date. The days required can be added by using the DATE_ADD( ) function: SYNTAX: DATE_ADD(date, INTERVAL no_of_days DAY); SELECT *,DATE_ADD(order_date,INTERVAL 15 DAY) AS estimated_delivery FROM order_details; 3.Query to get the estimated delivery day. This can be done by using both DATE_FORMAT( ) and DATE_ADD( ) functions. SELECT *,DATE_FORMAT(DATE_ADD(order_date,INTERVAL 15 DAY),'%W') AS delivery_day FROM order_details; Here %W to format the date as a weekday. 4. Query to get the order_id and customer name of the persons who are getting their order delivered before 2021-04-23. Here DATE_ADD( ) function is used to get the estimated delivery and check if it is less than 2021-04-23. SELECT order_id,customer_name FROM order_details WHERE DATE_ADD(order_date,INTERVAL 15 DAY)<'2021-04-23'; mysql SQL-Query 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": 24304, "s": 24276, "text": "\n09 May, 2021" }, { "code": null, "e": 24560, "s": 24304, "text": "In MySQL date is a data type and by default follows the format ‘YYYY-MM-DD’ but by using date formatting functions we can format date and can get the required format of date in the tables and can even manipulate the date by using different date functions." }, { "code": null, "e": 24647, "s": 24560, "text": "In this article let us execute some queries on date formatting in detail step-by-step:" }, { "code": null, "e": 24720, "s": 24647, "text": "Creating a database student by using the following SQL query as follows." }, { "code": null, "e": 24744, "s": 24720, "text": "CREATE DATABASE orders;" }, { "code": null, "e": 24813, "s": 24744, "text": "Using the database student using the following SQL query as follows." }, { "code": null, "e": 24825, "s": 24813, "text": "USE orders;" }, { "code": null, "e": 24920, "s": 24825, "text": "Table –Creating a table order_details with 3 columns using the following SQL query as follows." }, { "code": null, "e": 25014, "s": 24920, "text": "CREATE TABLE order_details(\norder_id varchar(8),\ncustomer_name varchar(20),\norder_date DATE);" }, { "code": null, "e": 25110, "s": 25014, "text": "To view the description of the tables in the database using the following SQL query as follows." }, { "code": null, "e": 25135, "s": 25110, "text": " DESCRIBE order_details;" }, { "code": null, "e": 25217, "s": 25135, "text": "Inserting rows into order_details table using the following SQL query as follows." }, { "code": null, "e": 25445, "s": 25217, "text": " INSERT INTO order_details VALUES\n ('O0001','PRADEEP','2021-04-11'),\n ('O0002','KOUSHIK','2021-04-09'),\n ('O0003','SRINIVAS','2021-04-05'),\n ('O0004','SATWIK','2021-04-08'),\n ('O0005','LOKESH','2021-04-03');" }, { "code": null, "e": 25543, "s": 25445, "text": "Viewing the table order_details after inserting rows by using the following SQL query as follows." }, { "code": null, "e": 25572, "s": 25543, "text": " SELECT* FROM order_details;" }, { "code": null, "e": 25616, "s": 25572, "text": "1.Query to format order_date as ‘DD-MM-YY’." }, { "code": null, "e": 25710, "s": 25616, "text": "The default date can be formatted from the default date by using the DATE_FORMAT( ) function:" }, { "code": null, "e": 25748, "s": 25710, "text": "SYNTAX:\nDATE_FORMAT(date,new_format);" }, { "code": null, "e": 25847, "s": 25748, "text": "In this query, we are using %d to get day then %b to get abbreviated month and %y to get the year." }, { "code": null, "e": 25931, "s": 25847, "text": " SELECT *,DATE_FORMAT(order_date,'%d-%b-%y') AS formatted_date\n FROM order_details;" }, { "code": null, "e": 26010, "s": 25931, "text": "2. Query to get the estimated delivery date after 15 days from the order date." }, { "code": null, "e": 26076, "s": 26010, "text": "The days required can be added by using the DATE_ADD( ) function:" }, { "code": null, "e": 26125, "s": 26076, "text": "SYNTAX:\nDATE_ADD(date, INTERVAL no_of_days DAY);" }, { "code": null, "e": 26216, "s": 26125, "text": " SELECT *,DATE_ADD(order_date,INTERVAL 15 DAY)\n AS estimated_delivery\n FROM order_details;" }, { "code": null, "e": 26259, "s": 26216, "text": "3.Query to get the estimated delivery day." }, { "code": null, "e": 26332, "s": 26259, "text": "This can be done by using both DATE_FORMAT( ) and DATE_ADD( ) functions." }, { "code": null, "e": 26435, "s": 26332, "text": " SELECT *,DATE_FORMAT(DATE_ADD(order_date,INTERVAL 15 DAY),'%W')\n AS delivery_day\n FROM order_details;" }, { "code": null, "e": 26476, "s": 26435, "text": "Here %W to format the date as a weekday." }, { "code": null, "e": 26596, "s": 26476, "text": "4. Query to get the order_id and customer name of the persons who are getting their order delivered before 2021-04-23." }, { "code": null, "e": 26701, "s": 26596, "text": "Here DATE_ADD( ) function is used to get the estimated delivery and check if it is less than 2021-04-23." }, { "code": null, "e": 26814, "s": 26701, "text": " SELECT order_id,customer_name\n FROM order_details\n WHERE DATE_ADD(order_date,INTERVAL 15 DAY)<'2021-04-23';" }, { "code": null, "e": 26820, "s": 26814, "text": "mysql" }, { "code": null, "e": 26830, "s": 26820, "text": "SQL-Query" }, { "code": null, "e": 26835, "s": 26830, "text": "DBMS" }, { "code": null, "e": 26839, "s": 26835, "text": "SQL" }, { "code": null, "e": 26844, "s": 26839, "text": "DBMS" }, { "code": null, "e": 26848, "s": 26844, "text": "SQL" }, { "code": null, "e": 26946, "s": 26848, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26987, "s": 26946, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 27030, "s": 26987, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 27062, "s": 27030, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27089, "s": 27062, "text": "Two Phase Locking Protocol" }, { "code": null, "e": 27116, "s": 27089, "text": "KDD Process in Data Mining" }, { "code": null, "e": 27158, "s": 27116, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 27202, "s": 27158, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 27223, "s": 27202, "text": "SQL | ALTER (RENAME)" }, { "code": null, "e": 27289, "s": 27223, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" } ]
How to add group labels for bar charts in Matplotlib?
To make grouped labels for bar charts, we can take the following steps − Create lists for labels, men_means and women_means with different data elements. Create lists for labels, men_means and women_means with different data elements. Return evenly spaced values within a given interval, using numpy.arrange() method. Return evenly spaced values within a given interval, using numpy.arrange() method. Set the width variable, i.e., width=0.35. Set the width variable, i.e., width=0.35. Create fig and ax variables using subplots method, where default nrows and ncols are 1. Create fig and ax variables using subplots method, where default nrows and ncols are 1. The bars are positioned at *x* with the given *align*\ment. Their dimensions are given by *height* and *width*. The vertical baseline is *bottom* (default 0), so create rect1 and rect2 using plt.bar() method. The bars are positioned at *x* with the given *align*\ment. Their dimensions are given by *height* and *width*. The vertical baseline is *bottom* (default 0), so create rect1 and rect2 using plt.bar() method. Set the Y-Axis label using plt.ylabel() method. Set the Y-Axis label using plt.ylabel() method. Set a title for the axes using set_title() method. Set a title for the axes using set_title() method. Get or set the current tick locations and labels of the X-axis, using set_xticks() method. Get or set the current tick locations and labels of the X-axis, using set_xticks() method. Set X-axis tick labels of the grid, using set_xticklabels() method. Set X-axis tick labels of the grid, using set_xticklabels() method. Place a legend on the figure, using legend() method. Place a legend on the figure, using legend() method. Annotate created bars (rect1 and rect2) with some label using autolabel() method, that is userdefined method. Annotate created bars (rect1 and rect2) with some label using autolabel() method, that is userdefined method. To show the figure, use the plt.show() method. To show the figure, use the plt.show() method. import matplotlib.pyplot as plt import numpy as np plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True labels = ['G1', 'G2', 'G3', 'G4', 'G5'] men_means = [20, 34, 30, 35, 27] women_means = [25, 32, 34, 20, 25] x = np.arange(len(labels)) width = 0.35 fig, ax = plt.subplots() rects1 = ax.bar(x - width / 2, men_means, width, label='Men') rects2 = ax.bar(x + width / 2, women_means, width, label='Women') ax.set_ylabel('Scores') ax.set_title('Scores by group and gender') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() def autolabel(rects): for rect in rects: height = rect.get_height() ax.annotate('{}'.format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 3), # 3 points vertical offset textcoords="offset points", ha='center', va='bottom') autolabel(rects1) autolabel(rects2) plt.show()
[ { "code": null, "e": 1135, "s": 1062, "text": "To make grouped labels for bar charts, we can take the following steps −" }, { "code": null, "e": 1216, "s": 1135, "text": "Create lists for labels, men_means and women_means with different data elements." }, { "code": null, "e": 1297, "s": 1216, "text": "Create lists for labels, men_means and women_means with different data elements." }, { "code": null, "e": 1380, "s": 1297, "text": "Return evenly spaced values within a given interval, using numpy.arrange() method." }, { "code": null, "e": 1463, "s": 1380, "text": "Return evenly spaced values within a given interval, using numpy.arrange() method." }, { "code": null, "e": 1505, "s": 1463, "text": "Set the width variable, i.e., width=0.35." }, { "code": null, "e": 1547, "s": 1505, "text": "Set the width variable, i.e., width=0.35." }, { "code": null, "e": 1635, "s": 1547, "text": "Create fig and ax variables using subplots method, where default nrows and ncols are 1." }, { "code": null, "e": 1723, "s": 1635, "text": "Create fig and ax variables using subplots method, where default nrows and ncols are 1." }, { "code": null, "e": 1932, "s": 1723, "text": "The bars are positioned at *x* with the given *align*\\ment. Their dimensions are given by *height* and *width*. The vertical baseline is *bottom* (default 0), so create rect1 and rect2 using plt.bar() method." }, { "code": null, "e": 2141, "s": 1932, "text": "The bars are positioned at *x* with the given *align*\\ment. Their dimensions are given by *height* and *width*. The vertical baseline is *bottom* (default 0), so create rect1 and rect2 using plt.bar() method." }, { "code": null, "e": 2189, "s": 2141, "text": "Set the Y-Axis label using plt.ylabel() method." }, { "code": null, "e": 2237, "s": 2189, "text": "Set the Y-Axis label using plt.ylabel() method." }, { "code": null, "e": 2288, "s": 2237, "text": "Set a title for the axes using set_title() method." }, { "code": null, "e": 2339, "s": 2288, "text": "Set a title for the axes using set_title() method." }, { "code": null, "e": 2430, "s": 2339, "text": "Get or set the current tick locations and labels of the X-axis, using set_xticks() method." }, { "code": null, "e": 2521, "s": 2430, "text": "Get or set the current tick locations and labels of the X-axis, using set_xticks() method." }, { "code": null, "e": 2589, "s": 2521, "text": "Set X-axis tick labels of the grid, using set_xticklabels() method." }, { "code": null, "e": 2657, "s": 2589, "text": "Set X-axis tick labels of the grid, using set_xticklabels() method." }, { "code": null, "e": 2710, "s": 2657, "text": "Place a legend on the figure, using legend() method." }, { "code": null, "e": 2763, "s": 2710, "text": "Place a legend on the figure, using legend() method." }, { "code": null, "e": 2873, "s": 2763, "text": "Annotate created bars (rect1 and rect2) with some label using autolabel() method, that is userdefined method." }, { "code": null, "e": 2983, "s": 2873, "text": "Annotate created bars (rect1 and rect2) with some label using autolabel() method, that is userdefined method." }, { "code": null, "e": 3030, "s": 2983, "text": "To show the figure, use the plt.show() method." }, { "code": null, "e": 3077, "s": 3030, "text": "To show the figure, use the plt.show() method." }, { "code": null, "e": 3987, "s": 3077, "text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nlabels = ['G1', 'G2', 'G3', 'G4', 'G5']\nmen_means = [20, 34, 30, 35, 27]\nwomen_means = [25, 32, 34, 20, 25]\nx = np.arange(len(labels))\nwidth = 0.35\nfig, ax = plt.subplots()\nrects1 = ax.bar(x - width / 2, men_means, width, label='Men')\nrects2 = ax.bar(x + width / 2, women_means, width, label='Women')\nax.set_ylabel('Scores')\nax.set_title('Scores by group and gender')\nax.set_xticks(x)\nax.set_xticklabels(labels)\nax.legend()\n\ndef autolabel(rects):\n for rect in rects:\n height = rect.get_height()\n ax.annotate('{}'.format(height),\n xy=(rect.get_x() + rect.get_width() / 2, height),\n xytext=(0, 3), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='bottom')\n\nautolabel(rects1)\nautolabel(rects2)\nplt.show()" } ]
Kubernetes - Dashboard Setup
Setting up Kubernetes dashboard involves several steps with a set of tools required as the prerequisites to set it up. Docker (1.3+) go (1.5+) nodejs (4.2.2+) npm (1.3+) java (7+) gulp (3.9+) Kubernetes (1.1.2+) $ sudo apt-get update && sudo apt-get upgrade Installing Python $ sudo apt-get install python $ sudo apt-get install python3 Installing GCC $ sudo apt-get install gcc-4.8 g++-4.8 Installing make $ sudo apt-get install make Installing Java $ sudo apt-get install openjdk-7-jdk Installing Node.js $ wget https://nodejs.org/dist/v4.2.2/node-v4.2.2.tar.gz $ tar -xzf node-v4.2.2.tar.gz $ cd node-v4.2.2 $ ./configure $ make $ sudo make install Installing gulp $ npm install -g gulp $ npm install gulp Java Version $ java –version java version "1.7.0_91" OpenJDK Runtime Environment (IcedTea 2.6.3) (7u91-2.6.3-1~deb8u1+rpi1) OpenJDK Zero VM (build 24.91-b01, mixed mode) $ node –v V4.2.2 $ npn -v 2.14.7 $ gulp -v [09:51:28] CLI version 3.9.0 $ sudo gcc --version gcc (Raspbian 4.8.4-1) 4.8.4 Copyright (C) 2013 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. $ git clone https://go.googlesource.com/go $ cd go $ git checkout go1.4.3 $ cd src Building GO $ ./all.bash $ vi /root/.bashrc In the .bashrc export GOROOT = $HOME/go export PATH = $PATH:$GOROOT/bin $ go version go version go1.4.3 linux/arm $ git clone https://github.com/kubernetes/dashboard.git $ cd dashboard $ npm install -g bower $ git clone https://github.com/kubernetes/dashboard.git $ cd dashboard $ npm install -g bower $ gulp serve [11:19:12] Requiring external module babel-core/register [11:20:50] Using gulpfile ~/dashboard/gulpfile.babel.js [11:20:50] Starting 'package-backend-source'... [11:20:50] Starting 'kill-backend'... [11:20:50] Finished 'kill-backend' after 1.39 ms [11:20:50] Starting 'scripts'... [11:20:53] Starting 'styles'... [11:21:41] Finished 'scripts' after 50 s [11:21:42] Finished 'package-backend-source' after 52 s [11:21:42] Starting 'backend'... [11:21:43] Finished 'styles' after 49 s [11:21:43] Starting 'index'... [11:21:44] Finished 'index' after 1.43 s [11:21:44] Starting 'watch'... [11:21:45] Finished 'watch' after 1.41 s [11:23:27] Finished 'backend' after 1.73 min [11:23:27] Starting 'spawn-backend'... [11:23:27] Finished 'spawn-backend' after 88 ms [11:23:27] Starting 'serve'... 2016/02/01 11:23:27 Starting HTTP server on port 9091 2016/02/01 11:23:27 Creating API client for 2016/02/01 11:23:27 Creating Heapster REST client for http://localhost:8082 [11:23:27] Finished 'serve' after 312 ms [BS] [BrowserSync SPA] Running... [BS] Access URLs: -------------------------------------- Local: http://localhost:9090/ External: http://192.168.1.21:9090/ -------------------------------------- UI: http://localhost:3001 UI External: http://192.168.1.21:3001 -------------------------------------- [BS] Serving files from: /root/dashboard/.tmp/serve [BS] Serving files from: /root/dashboard/src/app/frontend [BS] Serving files from: /root/dashboard/src/app 41 Lectures 5 hours AR Shankar 15 Lectures 2 hours Harshit Srivastava, Pranjal Srivastava 18 Lectures 1.5 hours Nigel Poulton 25 Lectures 1.5 hours Pranjal Srivastava 18 Lectures 1 hours Pranjal Srivastava 26 Lectures 1.5 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2314, "s": 2195, "text": "Setting up Kubernetes dashboard involves several steps with a set of tools required as the prerequisites to set it up." }, { "code": null, "e": 2328, "s": 2314, "text": "Docker (1.3+)" }, { "code": null, "e": 2338, "s": 2328, "text": "go (1.5+)" }, { "code": null, "e": 2354, "s": 2338, "text": "nodejs (4.2.2+)" }, { "code": null, "e": 2365, "s": 2354, "text": "npm (1.3+)" }, { "code": null, "e": 2375, "s": 2365, "text": "java (7+)" }, { "code": null, "e": 2387, "s": 2375, "text": "gulp (3.9+)" }, { "code": null, "e": 2407, "s": 2387, "text": "Kubernetes (1.1.2+)" }, { "code": null, "e": 2911, "s": 2407, "text": "$ sudo apt-get update && sudo apt-get upgrade\n\nInstalling Python\n$ sudo apt-get install python\n$ sudo apt-get install python3\n\nInstalling GCC\n$ sudo apt-get install gcc-4.8 g++-4.8\n\nInstalling make\n$ sudo apt-get install make\n\nInstalling Java\n$ sudo apt-get install openjdk-7-jdk\n\nInstalling Node.js\n$ wget https://nodejs.org/dist/v4.2.2/node-v4.2.2.tar.gz\n$ tar -xzf node-v4.2.2.tar.gz\n$ cd node-v4.2.2\n$ ./configure\n$ make\n$ sudo make install\n\nInstalling gulp\n$ npm install -g gulp\n$ npm install gulp\n" }, { "code": null, "e": 3410, "s": 2911, "text": "Java Version\n$ java –version\njava version \"1.7.0_91\"\nOpenJDK Runtime Environment (IcedTea 2.6.3) (7u91-2.6.3-1~deb8u1+rpi1)\nOpenJDK Zero VM (build 24.91-b01, mixed mode)\n\n$ node –v\nV4.2.2\n\n$ npn -v\n2.14.7\n\n$ gulp -v\n[09:51:28] CLI version 3.9.0\n\n$ sudo gcc --version\ngcc (Raspbian 4.8.4-1) 4.8.4\nCopyright (C) 2013 Free Software Foundation, Inc. This is free software; \nsee the source for copying conditions. There is NO warranty; not even for \nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n" }, { "code": null, "e": 3663, "s": 3410, "text": "$ git clone https://go.googlesource.com/go\n$ cd go\n$ git checkout go1.4.3\n$ cd src\n\nBuilding GO\n$ ./all.bash\n$ vi /root/.bashrc\nIn the .bashrc\n export GOROOT = $HOME/go\n export PATH = $PATH:$GOROOT/bin\n \n$ go version\ngo version go1.4.3 linux/arm\n" }, { "code": null, "e": 3758, "s": 3663, "text": "$ git clone https://github.com/kubernetes/dashboard.git\n$ cd dashboard\n$ npm install -g bower\n" }, { "code": null, "e": 5329, "s": 3758, "text": "$ git clone https://github.com/kubernetes/dashboard.git\n$ cd dashboard\n$ npm install -g bower\n$ gulp serve\n[11:19:12] Requiring external module babel-core/register\n[11:20:50] Using gulpfile ~/dashboard/gulpfile.babel.js\n[11:20:50] Starting 'package-backend-source'...\n[11:20:50] Starting 'kill-backend'...\n[11:20:50] Finished 'kill-backend' after 1.39 ms\n[11:20:50] Starting 'scripts'...\n[11:20:53] Starting 'styles'...\n[11:21:41] Finished 'scripts' after 50 s\n[11:21:42] Finished 'package-backend-source' after 52 s\n[11:21:42] Starting 'backend'...\n[11:21:43] Finished 'styles' after 49 s\n[11:21:43] Starting 'index'...\n[11:21:44] Finished 'index' after 1.43 s\n[11:21:44] Starting 'watch'...\n[11:21:45] Finished 'watch' after 1.41 s\n[11:23:27] Finished 'backend' after 1.73 min\n[11:23:27] Starting 'spawn-backend'...\n[11:23:27] Finished 'spawn-backend' after 88 ms\n[11:23:27] Starting 'serve'...\n2016/02/01 11:23:27 Starting HTTP server on port 9091\n2016/02/01 11:23:27 Creating API client for\n2016/02/01 11:23:27 Creating Heapster REST client for http://localhost:8082\n[11:23:27] Finished 'serve' after 312 ms\n[BS] [BrowserSync SPA] Running...\n[BS] Access URLs:\n--------------------------------------\nLocal: http://localhost:9090/\nExternal: http://192.168.1.21:9090/\n--------------------------------------\nUI: http://localhost:3001\nUI External: http://192.168.1.21:3001\n--------------------------------------\n[BS] Serving files from: /root/dashboard/.tmp/serve\n[BS] Serving files from: /root/dashboard/src/app/frontend\n[BS] Serving files from: /root/dashboard/src/app\n" }, { "code": null, "e": 5362, "s": 5329, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 5374, "s": 5362, "text": " AR Shankar" }, { "code": null, "e": 5407, "s": 5374, "text": "\n 15 Lectures \n 2 hours \n" }, { "code": null, "e": 5447, "s": 5407, "text": " Harshit Srivastava, Pranjal Srivastava" }, { "code": null, "e": 5482, "s": 5447, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5497, "s": 5482, "text": " Nigel Poulton" }, { "code": null, "e": 5532, "s": 5497, "text": "\n 25 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5552, "s": 5532, "text": " Pranjal Srivastava" }, { "code": null, "e": 5585, "s": 5552, "text": "\n 18 Lectures \n 1 hours \n" }, { "code": null, "e": 5605, "s": 5585, "text": " Pranjal Srivastava" }, { "code": null, "e": 5640, "s": 5605, "text": "\n 26 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5660, "s": 5640, "text": " Pranjal Srivastava" }, { "code": null, "e": 5667, "s": 5660, "text": " Print" }, { "code": null, "e": 5678, "s": 5667, "text": " Add Notes" } ]
C# Program to perform Currency Conversion
Let’s say you need to get the value of 10 dollars in INR. Firstly, set the variables: double usd, inr, val; Now set the dollars and convert it to INR. // how many dpllars usd = 10; // current value of US$ val = 69; inr = usd * val; Let us see the complete code − Live Demo using System; namespace Demo { public class Program { public static void Main(string[] args) { Double usd, inr, val; // how many dpllars usd = 10; // current value of US$ val = 69; inr = usd * val; Console.WriteLine("{0} Dollar = {1} INR", usd, inr); } } } 10 Dollar = 690 INR
[ { "code": null, "e": 1120, "s": 1062, "text": "Let’s say you need to get the value of 10 dollars in INR." }, { "code": null, "e": 1170, "s": 1120, "text": "Firstly, set the variables:\ndouble usd, inr, val;" }, { "code": null, "e": 1213, "s": 1170, "text": "Now set the dollars and convert it to INR." }, { "code": null, "e": 1294, "s": 1213, "text": "// how many dpllars\nusd = 10;\n// current value of US$\nval = 69;\ninr = usd * val;" }, { "code": null, "e": 1325, "s": 1294, "text": "Let us see the complete code −" }, { "code": null, "e": 1336, "s": 1325, "text": " Live Demo" }, { "code": null, "e": 1674, "s": 1336, "text": "using System;\nnamespace Demo {\n public class Program {\n public static void Main(string[] args) {\n Double usd, inr, val;\n // how many dpllars\n usd = 10;\n // current value of US$\n val = 69;\n inr = usd * val;\n Console.WriteLine(\"{0} Dollar = {1} INR\", usd, inr);\n }\n }\n}" }, { "code": null, "e": 1694, "s": 1674, "text": "10 Dollar = 690 INR" } ]
Aptitude - Discounts Online Quiz
Following quiz provides Multiple Choice Questions (MCQs) related to Discounts. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz. Q 1 - Find the single discount which is equivalent to successive discounts of 15% and 16%. A - 36.6% B - 31% C - 28.6% D - 28.6% Successive discount is calculated as X+Y-XY/100 % Successive discount =15+16-15*16/100=31-240/100=28.6 % Q 2 - Rs. 40 is the true discount on Rs. 520 due after a certain time. What will be the true discount on the same sum due after half of the former time, the rate of interest being the same? A - Rs. 19.66 B - Rs. 20.66 C - Rs. 21.66 D - Rs. 22.66 S.I. on Rs. (520 - 40) for a given time = Rs. 40. S.I. on Rs. 480 for half the time = Rs. 20. T.D. on Rs. 500 = Rs. 20 T.D. on Rs. 520 =Rs. ( 20/480 * 520)= Rs. 21.66 Q 3 - The present worth of a certain bill due sometime hence is Rs. 1600 and the true discount is Rs. 40. The banker's discount is: A - 41 B - 50 C - 51 D - 41.6 (T.D.)2 = P.W. * B.G => B.G=(T.D.)2/ P.W.=402/1600=1 =>B.D =T.D. + B.G. = 40+1 =41 Q 4 - A man buys a watch for Rs. 2825 in cash and sells it for Rs. 3300 at a credit of 1 year. If the rate of interest is 15% per annum, the man: A - Rs. 150 B - Rs. 175. C - Rs. 475 D - Rs. 500 S.P. = P.W. of Rs. 3300 due 1 year hence = 3300*100/( 100+(10*1))=Rs.3000 So Gain = Rs. (3000-2825) =Rs. 175. Q 5 - Find a single discount which is equivalent to three successive discounts of 15%, 16% & 20%. A - 40.0% B - 41.58% C - 42.88% D - 43.76% Successive discount is calculated as X+Y-XY/100 % Successive discount =15+16-15*16/100=31- 240/100=28.6 % Successive discount =28.6+20-28.6*20/100=48.6-5.72=42.88% Q 6 - The genuine markdown on an aggregate due 3 years consequently at 8% p.a. is Rs 252. The total due is: A - Rs 798 B - Rs 1050 C - Rs 1302 D - None of these P.W. = (100*T.D.)/(R*T) = Rs ((100*252))/((8*3)) = Rs 1050 Sum due = (P.W.)+(T.D.) = Rs (1050+252) = Rs 1302 Q 7 - The straightforward hobby and the genuine rebate on a sure total due 6 months subsequently are Rs 25 and Rs 24 individually. The rate of interest per annum is: A - 8% B - 17/2% C - 35/4% D - 25/3% ((S.I.)*(T.D.))/((S.I.)-(T.D.))=Rs ((25*24))/((25-24))= Rs 600 S.I. on Rs 600 for 6 months is Rs 25 ∴ Rate = (100*125)/(600*6/12)% p.a. = 25/3% p.a. Q 8 - A man acquired a look for Rs 1950 in real money and sold it for Rs 2160 at a credit of 1 year. On the off chance that the rate of hobby is 8% p.a., then the man has: A - an increase of Rs 210 B - a addition of Rs 50 C - an addition of Rs 60 D - lost Rs 30 C.P. = Rs. 1950 S.P. = P.W. of Rs. 2160 due 1 year hence = Rs ((100*2160))/(100+(8*1)) = Rs 2000 in cash. ∴ Gain = Rs (2000-1950) = Rs 50 Q 9 - In the event that Rs 20 be permitted as genuine rebate on a bill of Rs 260 due after at some point, what will be the genuine markdown on the same bill for half of the time? A - Rs 10 B - Rs 10.40 C - Rs 13 D - Rs 15.20 S.I. on Rs (260-20) for a fixed time = Rs 20 S.I. on Rs 240 for half the time = Rs 10 T.D. on Rs 250 = Rs 10 T.D. on Rs 260 = Rs (10/250*260) = Rs 10.40 Q 10 - The basic enthusiasm on Rs 750 for a long time is equivalent to the genuine rebate on Rs 810 for the same time and at the same rate. The rate of interest per annum is: A - 4% B - 13/3% C - 5% D - 31/6% S.I. on Rs 750 for 2 years = T.D. on Rs 810 due 2 years hence ∴ P.W. of Rs. 810 due 2 years hence = Rs 750 ∴ T.D. = Rs (810-750) = Rs 60 Rate = ((100*60)/(750*2))% p.a. = 4% p.a. 87 Lectures 22.5 hours Programming Line Print Add Notes Bookmark this page
[ { "code": null, "e": 4215, "s": 3892, "text": "Following quiz provides Multiple Choice Questions (MCQs) related to Discounts. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz." }, { "code": null, "e": 4307, "s": 4215, "text": "Q 1 - Find the single discount which is equivalent to successive discounts of 15% and 16%. " }, { "code": null, "e": 4317, "s": 4307, "text": "A - 36.6%" }, { "code": null, "e": 4325, "s": 4317, "text": "B - 31%" }, { "code": null, "e": 4335, "s": 4325, "text": "C - 28.6%" }, { "code": null, "e": 4345, "s": 4335, "text": "D - 28.6%" }, { "code": null, "e": 4450, "s": 4345, "text": "Successive discount is calculated as X+Y-XY/100 %\nSuccessive discount =15+16-15*16/100=31-240/100=28.6 %" }, { "code": null, "e": 4640, "s": 4450, "text": "Q 2 - Rs. 40 is the true discount on Rs. 520 due after a certain time. What will be the true discount on the same sum due after half of the former time, the rate of interest being the same?" }, { "code": null, "e": 4654, "s": 4640, "text": "A - Rs. 19.66" }, { "code": null, "e": 4668, "s": 4654, "text": "B - Rs. 20.66" }, { "code": null, "e": 4682, "s": 4668, "text": "C - Rs. 21.66" }, { "code": null, "e": 4696, "s": 4682, "text": "D - Rs. 22.66" }, { "code": null, "e": 4865, "s": 4696, "text": "S.I. on Rs. (520 - 40) for a given time = Rs. 40.\nS.I. on Rs. 480 for half the time = Rs. 20.\nT.D. on Rs. 500 = Rs. 20\nT.D. on Rs. 520 =Rs. ( 20/480 * 520)= Rs. 21.66 " }, { "code": null, "e": 4999, "s": 4865, "text": "Q 3 - The present worth of a certain bill due sometime hence is Rs. 1600 and the true discount is Rs. 40. The banker's discount is: " }, { "code": null, "e": 5006, "s": 4999, "text": "A - 41" }, { "code": null, "e": 5013, "s": 5006, "text": "B - 50" }, { "code": null, "e": 5020, "s": 5013, "text": "C - 51" }, { "code": null, "e": 5029, "s": 5020, "text": "D - 41.6" }, { "code": null, "e": 5115, "s": 5029, "text": "(T.D.)2 = P.W. * B.G\n=> B.G=(T.D.)2/\nP.W.=402/1600=1\n=>B.D =T.D. + B.G. \n= 40+1 \n=41" }, { "code": null, "e": 5262, "s": 5115, "text": "Q 4 - A man buys a watch for Rs. 2825 in cash and sells it for Rs. 3300 at a credit of 1 year. If the rate of interest is 15% per annum, the man: " }, { "code": null, "e": 5274, "s": 5262, "text": "A - Rs. 150" }, { "code": null, "e": 5287, "s": 5274, "text": "B - Rs. 175." }, { "code": null, "e": 5300, "s": 5287, "text": "C - Rs. 475 " }, { "code": null, "e": 5312, "s": 5300, "text": "D - Rs. 500" }, { "code": null, "e": 5422, "s": 5312, "text": "S.P. = P.W. of Rs. 3300 due 1 year hence = 3300*100/( 100+(10*1))=Rs.3000\nSo Gain = Rs. (3000-2825) =Rs. 175." }, { "code": null, "e": 5520, "s": 5422, "text": "Q 5 - Find a single discount which is equivalent to three successive discounts of 15%, 16% & 20%." }, { "code": null, "e": 5530, "s": 5520, "text": "A - 40.0%" }, { "code": null, "e": 5541, "s": 5530, "text": "B - 41.58%" }, { "code": null, "e": 5552, "s": 5541, "text": "C - 42.88%" }, { "code": null, "e": 5563, "s": 5552, "text": "D - 43.76%" }, { "code": null, "e": 5727, "s": 5563, "text": "Successive discount is calculated as X+Y-XY/100 %\nSuccessive discount =15+16-15*16/100=31- 240/100=28.6 %\nSuccessive discount =28.6+20-28.6*20/100=48.6-5.72=42.88%" }, { "code": null, "e": 5835, "s": 5727, "text": "Q 6 - The genuine markdown on an aggregate due 3 years consequently at 8% p.a. is Rs 252. The total due is:" }, { "code": null, "e": 5846, "s": 5835, "text": "A - Rs 798" }, { "code": null, "e": 5858, "s": 5846, "text": "B - Rs 1050" }, { "code": null, "e": 5870, "s": 5858, "text": "C - Rs 1302" }, { "code": null, "e": 5889, "s": 5870, "text": "D - None of these " }, { "code": null, "e": 5998, "s": 5889, "text": "P.W. = (100*T.D.)/(R*T) = Rs ((100*252))/((8*3)) = Rs 1050\nSum due = (P.W.)+(T.D.) = Rs (1050+252) = Rs 1302" }, { "code": null, "e": 6164, "s": 5998, "text": "Q 7 - The straightforward hobby and the genuine rebate on a sure total due 6 months subsequently are Rs 25 and Rs 24 individually. The rate of interest per annum is:" }, { "code": null, "e": 6171, "s": 6164, "text": "A - 8%" }, { "code": null, "e": 6182, "s": 6171, "text": "B - 17/2% " }, { "code": null, "e": 6192, "s": 6182, "text": "C - 35/4%" }, { "code": null, "e": 6202, "s": 6192, "text": "D - 25/3%" }, { "code": null, "e": 6351, "s": 6202, "text": "((S.I.)*(T.D.))/((S.I.)-(T.D.))=Rs ((25*24))/((25-24))= Rs 600\nS.I. on Rs 600 for 6 months is Rs 25\n∴ Rate = (100*125)/(600*6/12)% p.a. = 25/3% p.a." }, { "code": null, "e": 6523, "s": 6351, "text": "Q 8 - A man acquired a look for Rs 1950 in real money and sold it for Rs 2160 at a credit of 1 year. On the off chance that the rate of hobby is 8% p.a., then the man has:" }, { "code": null, "e": 6550, "s": 6523, "text": "A - an increase of Rs 210 " }, { "code": null, "e": 6575, "s": 6550, "text": "B - a addition of Rs 50 " }, { "code": null, "e": 6601, "s": 6575, "text": "C - an addition of Rs 60 " }, { "code": null, "e": 6617, "s": 6601, "text": "D - lost Rs 30 " }, { "code": null, "e": 6755, "s": 6617, "text": "C.P. = Rs. 1950\nS.P. = P.W. of Rs. 2160 due 1 year hence\n= Rs ((100*2160))/(100+(8*1)) = Rs 2000 in cash.\n∴ Gain = Rs (2000-1950) = Rs 50" }, { "code": null, "e": 6934, "s": 6755, "text": "Q 9 - In the event that Rs 20 be permitted as genuine rebate on a bill of Rs 260 due after at some point, what will be the genuine markdown on the same bill for half of the time?" }, { "code": null, "e": 6944, "s": 6934, "text": "A - Rs 10" }, { "code": null, "e": 6957, "s": 6944, "text": "B - Rs 10.40" }, { "code": null, "e": 6967, "s": 6957, "text": "C - Rs 13" }, { "code": null, "e": 6980, "s": 6967, "text": "D - Rs 15.20" }, { "code": null, "e": 7133, "s": 6980, "text": "S.I. on Rs (260-20) for a fixed time = Rs 20\nS.I. on Rs 240 for half the time = Rs 10\nT.D. on Rs 250 = Rs 10\nT.D. on Rs 260 = Rs (10/250*260) = Rs 10.40" }, { "code": null, "e": 7308, "s": 7133, "text": "Q 10 - The basic enthusiasm on Rs 750 for a long time is equivalent to the genuine rebate on Rs 810 for the same time and at the same rate. The rate of interest per annum is:" }, { "code": null, "e": 7315, "s": 7308, "text": "A - 4%" }, { "code": null, "e": 7325, "s": 7315, "text": "B - 13/3%" }, { "code": null, "e": 7332, "s": 7325, "text": "C - 5%" }, { "code": null, "e": 7342, "s": 7332, "text": "D - 31/6%" }, { "code": null, "e": 7521, "s": 7342, "text": "S.I. on Rs 750 for 2 years = T.D. on Rs 810 due 2 years hence\n∴ P.W. of Rs. 810 due 2 years hence = Rs 750\n∴ T.D. = Rs (810-750) = Rs 60\nRate = ((100*60)/(750*2))% p.a. = 4% p.a." }, { "code": null, "e": 7557, "s": 7521, "text": "\n 87 Lectures \n 22.5 hours \n" }, { "code": null, "e": 7575, "s": 7557, "text": " Programming Line" }, { "code": null, "e": 7582, "s": 7575, "text": " Print" }, { "code": null, "e": 7593, "s": 7582, "text": " Add Notes" } ]
Print all nodes that don't have sibling | Practice | GeeksforGeeks
Given a Binary Tree of size N, find all the nodes which don't have any sibling. You need to return a list of integers containing all the nodes that don't have a sibling in sorted order. Note: Root node can not have a sibling so it cannot be included in our answer. Example 1: Input : 37 / 20 / 113 Output: 20 113 Explanation: 20 and 113 dont have any siblings. Example 2: Input : 1 / \ 2 3 Output: -1 Explanation: Every node has a sibling. Your Task: You dont need to read input or print anything. Complete the function noSibling() which takes the root of the tree as input parameter and returns a list of integers containing all the nodes that don't have a sibling in sorted order. If all nodes have a sibling, then the returning list should contain only one element -1. Expected Time Complexity: O(NlogN) Expected Auxiliary Space: O(Height of the tree) Constraints: 1 ≤ N ≤ 10^4 All nodes have distinct values. 0 utkarshagarwal10112 hours ago void solve(Node* node, vector<int>&ans){ if(!node)return; if(node->left&&node->right){ solve(node->left,ans); solve(node->right,ans); } if(node->left&&!node->right){ ans.push_back(node->left->data); solve(node->left,ans); } if(!node->left&&node->right){ ans.push_back(node->right->data); solve(node->right,ans); } } vector<int> noSibling(Node* node) { // code here vector<int>ans; solve(node,ans); if(ans.size()==0) { ans.push_back(-1); return ans; } else { sort(ans.begin(),ans.end()); return ans; } } 0 keshavlad211 week ago class Tree { ArrayList<Integer> noSibling(Node root) { ArrayList<Integer>ans=new ArrayList<>(); if( root==null || root.left== null && root.right==null){ ans.add(-1); return ans; } noSib(root,ans); Collections.sort(ans); if(ans.size()==0)ans.add(-1); return ans; } public void noSib(Node root,ArrayList<Integer>a){ if(root == null ){ return; } if(root.left==null && root.right!=null){ a.add(root.right.data); } if(root.right==null && root.left!=null){ a.add(root.left.data); } noSib(root.left,a); noSib(root.right,a); } } 0 satyamksingh021 week ago class Tree { ArrayList<Integer> noSibling(Node node) { // code here ArrayList<Integer> result=new ArrayList<>(); if(node==null || (node.left==null && node.right==null)){ result.add(-1); return result; } Queue<Node> q=new LinkedList<>(); q.add(node); while(!q.isEmpty()){ Node temp=q.poll(); if(temp.left!=null){ q.add(temp.left); if(temp.right==null){ result.add(temp.left.data); } } if(temp.right!=null){ q.add(temp.right); if(temp.left==null){ result.add(temp.right.data); } } } Collections.sort(result); if(result.size()==0){ result.add(-1); } return result; } } 0 anshulgupta966262 weeks ago void check(Node *root, vector<int> &ans){ if(root->left == NULL && root->right != NULL){ ans.push_back(root->right->data); check(root->right, ans); } if(root->left != NULL && root->right == NULL){ ans.push_back(root->left->data); check(root->left, ans); } if(root->right == NULL && root->left == NULL){ return; } if(root->left != NULL && root->right != NULL){ check(root->left, ans); check(root->right, ans); return; } } vector<int> noSibling(Node* node) { // code here vector<int> v1; check(node, v1); if(v1.empty()){ v1.push_back(-1); } sort(v1.begin(), v1.end()); return v1; } 0 kumaarsahab4323 weeks ago //Dont forget to sort the vector void solve(Node* root, vector<int> &ans) { if(root==NULL) return ; if(root->left==NULL and root->right!=NULL) ans.push_back(root->right->data) ; else if(root->right==NULL and root->left!=NULL) ans.push_back(root->left->data) ; solve(root->left,ans) ; solve(root->right,ans) ; } vector<int> noSibling(Node* node) { vector<int> ans ; solve(node,ans) ; if(ans.size()==0) return {-1} ; sort(ans.begin(),ans.end()) ; return ans ; } 0 navneet05082002kuswaha1 month ago #python code def solve(root,res): if not root: return if root.right is None and root.left is not None: res.append(root.left.data) elif root.right is not None and root.left is None: res.append(root.right.data) solve(root.left,res) solve(root.right,res)def noSibling(root): res = [] solve(root,res) if res: res.sort() return res return [-1] 0 roopsaisurampudi1 month ago void noSibling(Node node, ArrayList<Integer> ans) { if (node == null) return; if (node.right == null && node.left != null) { ans.add(node.left.data); } else if (node.right != null && node.left == null) { ans.add(node.right.data); } noSibling(node.left, ans); noSibling(node.right, ans); } ArrayList<Integer> noSibling(Node node) { ArrayList<Integer> ans = new ArrayList<Integer>(); noSibling(node, ans); if (ans.isEmpty()) ans.add(-1); Collections.sort(ans); return ans; +1 sambitmishra1991 month ago SIMPLE JAVA SOLUTION & EASY TO UNDERSTAND TIME COMPLEXITY: o(n) SPACE COMPLEXITY: o(H) where n is the no. of nodes in tree. & H is the height of the tree. H is equal to log(n) for a balanced tree. ArrayList<Integer> noSibling(Node node) { ArrayList<Integer> arr = new ArrayList<>(); noSibling(node , arr); Collections.sort(arr); if(arr.isEmpty()){ arr.add(-1); } return arr; } public void noSibling(Node root , ArrayList<Integer> arr){ if(root == null){ return ; } if(root.left!=null && root.right==null){ arr.add(root.left.data); } else if(root.left==null && root.right!=null){ arr.add(root.right.data); } noSibling(root.left , arr); noSibling(root.right , arr); return ; } 0 preranasingh20011 month ago class Tree { public ArrayList<Integer> list = new ArrayList<>(); ArrayList<Integer> noSibling(Node root) { answer(root.left,root.right); if(list.size()>0){ Collections.sort(list); return list; } list.add(-1); return list; // code here } public void answer(Node n1,Node n2){ if(n1==null && n2==null){ return; } if((n1!=null && n2==null) ||(n2!=null && n1==null)){ int x=(n1==null)?n2.data:n1.data; list.add(x); } if(n1!=null){ answer(n1.left,n1.right); } if(n2!=null){ answer(n2.left,n2.right); } return; } } +1 akashpoojari1 month ago Simple Java Solution ArrayList<Integer> noSibling(Node node) { ArrayList<Integer> arr = new ArrayList<>(); check(node , arr); Collections.sort(arr); if(arr.isEmpty()){ arr.add(-1); } return arr; } public boolean check(Node root , ArrayList<Integer> arr){ if(root == null){ return false; } boolean left = check(root.left , arr); boolean right = check(root.right , arr); if(left && !right){ arr.add(root.left.data); }else if(!left && right){ arr.add(root.right.data); } return true; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 424, "s": 238, "text": "Given a Binary Tree of size N, find all the nodes which don't have any sibling. You need to return a list of integers containing all the nodes that don't have a sibling in sorted order." }, { "code": null, "e": 503, "s": 424, "text": "Note: Root node can not have a sibling so it cannot be included in our answer." }, { "code": null, "e": 514, "s": 503, "text": "Example 1:" }, { "code": null, "e": 632, "s": 514, "text": "Input :\n 37\n / \n 20\n / \n 113 \n\nOutput: 20 113\nExplanation: 20 and 113 dont have any siblings." }, { "code": null, "e": 644, "s": 632, "text": "\nExample 2:" }, { "code": null, "e": 734, "s": 644, "text": "Input :\n 1\n / \\\n 2 3 \n\nOutput: -1\nExplanation: Every node has a sibling." }, { "code": null, "e": 1069, "s": 734, "text": "\nYour Task: \nYou dont need to read input or print anything. Complete the function noSibling() which takes the root of the tree as input parameter and returns a list of integers containing all the nodes that don't have a sibling in sorted order. If all nodes have a sibling, then the returning list should contain only one element -1." }, { "code": null, "e": 1153, "s": 1069, "text": "\nExpected Time Complexity: O(NlogN)\nExpected Auxiliary Space: O(Height of the tree)" }, { "code": null, "e": 1212, "s": 1153, "text": "\nConstraints:\n1 ≤ N ≤ 10^4\nAll nodes have distinct values." }, { "code": null, "e": 1214, "s": 1212, "text": "0" }, { "code": null, "e": 1244, "s": 1214, "text": "utkarshagarwal10112 hours ago" }, { "code": null, "e": 1888, "s": 1244, "text": "void solve(Node* node, vector<int>&ans){\n if(!node)return;\n \n if(node->left&&node->right){\n solve(node->left,ans);\n solve(node->right,ans);\n }\n if(node->left&&!node->right){\n ans.push_back(node->left->data);\n solve(node->left,ans);\n }\n if(!node->left&&node->right){\n ans.push_back(node->right->data);\n solve(node->right,ans);\n }\n}\nvector<int> noSibling(Node* node)\n{\n // code here\n vector<int>ans;\n solve(node,ans);\n if(ans.size()==0)\n {\n ans.push_back(-1);\n return ans;\n }\n else\n { sort(ans.begin(),ans.end());\n return ans;\n }\n \n}" }, { "code": null, "e": 1890, "s": 1888, "text": "0" }, { "code": null, "e": 1912, "s": 1890, "text": "keshavlad211 week ago" }, { "code": null, "e": 2662, "s": 1912, "text": "class Tree\n{\n ArrayList<Integer> noSibling(Node root)\n {\n \n ArrayList<Integer>ans=new ArrayList<>();\n \n if( root==null || root.left== null && root.right==null){\n ans.add(-1);\n return ans;\n }\n noSib(root,ans);\n Collections.sort(ans);\n if(ans.size()==0)ans.add(-1);\n return ans;\n }\n public void noSib(Node root,ArrayList<Integer>a){\n if(root == null ){\n return;\n }\n if(root.left==null && root.right!=null){\n a.add(root.right.data);\n\n }\n if(root.right==null && root.left!=null){\n a.add(root.left.data);\n }\n noSib(root.left,a);\n noSib(root.right,a);\n }\n}" }, { "code": null, "e": 2664, "s": 2662, "text": "0" }, { "code": null, "e": 2689, "s": 2664, "text": "satyamksingh021 week ago" }, { "code": null, "e": 3572, "s": 2689, "text": "class Tree\n{\n ArrayList<Integer> noSibling(Node node)\n {\n // code here\n ArrayList<Integer> result=new ArrayList<>();\n if(node==null || (node.left==null && node.right==null)){\n result.add(-1);\n return result;\n }\n Queue<Node> q=new LinkedList<>();\n q.add(node);\n while(!q.isEmpty()){\n Node temp=q.poll();\n if(temp.left!=null){\n q.add(temp.left);\n if(temp.right==null){\n result.add(temp.left.data);\n }\n }\n if(temp.right!=null){\n q.add(temp.right);\n if(temp.left==null){\n result.add(temp.right.data);\n }\n }\n }\n \n Collections.sort(result);\n if(result.size()==0){\n result.add(-1);\n }\n return result;\n }\n}" }, { "code": null, "e": 3574, "s": 3572, "text": "0" }, { "code": null, "e": 3602, "s": 3574, "text": "anshulgupta966262 weeks ago" }, { "code": null, "e": 4314, "s": 3602, "text": "void check(Node *root, vector<int> &ans){\n if(root->left == NULL && root->right != NULL){\n ans.push_back(root->right->data);\n check(root->right, ans);\n }\n if(root->left != NULL && root->right == NULL){\n ans.push_back(root->left->data);\n check(root->left, ans);\n }\n if(root->right == NULL && root->left == NULL){\n return;\n }\n if(root->left != NULL && root->right != NULL){\n check(root->left, ans);\n check(root->right, ans);\n return;\n }\n}\nvector<int> noSibling(Node* node)\n{\n // code here\n vector<int> v1;\n check(node, v1);\n if(v1.empty()){\n v1.push_back(-1);\n }\n sort(v1.begin(), v1.end());\n return v1;\n}" }, { "code": null, "e": 4316, "s": 4314, "text": "0" }, { "code": null, "e": 4342, "s": 4316, "text": "kumaarsahab4323 weeks ago" }, { "code": null, "e": 4842, "s": 4342, "text": "//Dont forget to sort the vector\nvoid solve(Node* root, vector<int> &ans)\n{\n if(root==NULL) return ;\n if(root->left==NULL and root->right!=NULL) ans.push_back(root->right->data) ;\n else if(root->right==NULL and root->left!=NULL) ans.push_back(root->left->data) ;\n solve(root->left,ans) ;\n solve(root->right,ans) ;\n}\nvector<int> noSibling(Node* node)\n{\n vector<int> ans ;\n solve(node,ans) ;\n if(ans.size()==0) return {-1} ;\n sort(ans.begin(),ans.end()) ;\n return ans ;\n}" }, { "code": null, "e": 4844, "s": 4842, "text": "0" }, { "code": null, "e": 4878, "s": 4844, "text": "navneet05082002kuswaha1 month ago" }, { "code": null, "e": 4891, "s": 4878, "text": "#python code" }, { "code": null, "e": 5266, "s": 4891, "text": "def solve(root,res): if not root: return if root.right is None and root.left is not None: res.append(root.left.data) elif root.right is not None and root.left is None: res.append(root.right.data) solve(root.left,res) solve(root.right,res)def noSibling(root): res = [] solve(root,res) if res: res.sort() return res return [-1] " }, { "code": null, "e": 5268, "s": 5266, "text": "0" }, { "code": null, "e": 5296, "s": 5268, "text": "roopsaisurampudi1 month ago" }, { "code": null, "e": 5904, "s": 5296, "text": "void noSibling(Node node, ArrayList<Integer> ans) {\n if (node == null) return;\n if (node.right == null && node.left != null) {\n ans.add(node.left.data);\n }\n else if (node.right != null && node.left == null) {\n ans.add(node.right.data);\n }\n noSibling(node.left, ans);\n noSibling(node.right, ans);\n }\n ArrayList<Integer> noSibling(Node node)\n {\n ArrayList<Integer> ans = new ArrayList<Integer>();\n noSibling(node, ans);\n if (ans.isEmpty()) ans.add(-1);\n Collections.sort(ans);\n \n return ans;" }, { "code": null, "e": 5907, "s": 5904, "text": "+1" }, { "code": null, "e": 5934, "s": 5907, "text": "sambitmishra1991 month ago" }, { "code": null, "e": 5977, "s": 5934, "text": "SIMPLE JAVA SOLUTION & EASY TO UNDERSTAND " }, { "code": null, "e": 6001, "s": 5979, "text": "TIME COMPLEXITY: o(n)" }, { "code": null, "e": 6024, "s": 6001, "text": "SPACE COMPLEXITY: o(H)" }, { "code": null, "e": 6063, "s": 6026, "text": "where n is the no. of nodes in tree." }, { "code": null, "e": 6094, "s": 6063, "text": "& H is the height of the tree." }, { "code": null, "e": 6136, "s": 6094, "text": "H is equal to log(n) for a balanced tree." }, { "code": null, "e": 6810, "s": 6138, "text": " ArrayList<Integer> noSibling(Node node) { ArrayList<Integer> arr = new ArrayList<>(); noSibling(node , arr); Collections.sort(arr); if(arr.isEmpty()){ arr.add(-1); } return arr; } public void noSibling(Node root , ArrayList<Integer> arr){ if(root == null){ return ; } if(root.left!=null && root.right==null){ arr.add(root.left.data); } else if(root.left==null && root.right!=null){ arr.add(root.right.data); } noSibling(root.left , arr); noSibling(root.right , arr); return ; }" }, { "code": null, "e": 6812, "s": 6810, "text": "0" }, { "code": null, "e": 6840, "s": 6812, "text": "preranasingh20011 month ago" }, { "code": null, "e": 7566, "s": 6840, "text": "class Tree\n{\n public ArrayList<Integer> list = new ArrayList<>();\n ArrayList<Integer> noSibling(Node root)\n {\n \n answer(root.left,root.right);\n if(list.size()>0){\n Collections.sort(list);\n return list;\n }\n list.add(-1);\n return list;\n \n // code here\n }\n public void answer(Node n1,Node n2){\n if(n1==null && n2==null){\n return;\n }\n \n if((n1!=null && n2==null) ||(n2!=null && n1==null)){\n int x=(n1==null)?n2.data:n1.data;\n list.add(x);\n }\n \n if(n1!=null){\n answer(n1.left,n1.right);\n }\n if(n2!=null){\n answer(n2.left,n2.right);\n }\n return;\n }\n}" }, { "code": null, "e": 7569, "s": 7566, "text": "+1" }, { "code": null, "e": 7593, "s": 7569, "text": "akashpoojari1 month ago" }, { "code": null, "e": 7614, "s": 7593, "text": "Simple Java Solution" }, { "code": null, "e": 8252, "s": 7614, "text": "ArrayList<Integer> noSibling(Node node)\n {\n ArrayList<Integer> arr = new ArrayList<>();\n check(node , arr);\n Collections.sort(arr);\n if(arr.isEmpty()){\n arr.add(-1);\n }\n return arr;\n }\n public boolean check(Node root , ArrayList<Integer> arr){\n if(root == null){\n return false;\n }\n boolean left = check(root.left , arr);\n boolean right = check(root.right , arr);\n if(left && !right){\n arr.add(root.left.data);\n }else if(!left && right){\n arr.add(root.right.data);\n }\n return true;\n }" }, { "code": null, "e": 8398, "s": 8252, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 8434, "s": 8398, "text": " Login to access your submissions. " }, { "code": null, "e": 8444, "s": 8434, "text": "\nProblem\n" }, { "code": null, "e": 8454, "s": 8444, "text": "\nContest\n" }, { "code": null, "e": 8517, "s": 8454, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8665, "s": 8517, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 8873, "s": 8665, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 8979, "s": 8873, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
CMD Commands to Gather Information of a System - GeeksforGeeks
26 Nov, 2020 Some say that gathering information is only possible in Linux, but it can be done with windows using a command prompt. These are some useful commands used by hackers for gathering system information that every Geek should be aware of. To execute all these commands, run the Command Prompt as Administrator to get access to the system information. This article is using wmic commands. Wmic is a tool of the command prompt to get system information. The full form of wmic is the Windows Management Interface command. The list of Commands for gathering information are mentioned below. Serial Number The command is used to get the computer’s serial number. This is very helpful to get the serial number of our bios. We will get our serial number instead of O.E.M. wmic bios get serialnumber wmic bios get serialnumber command Mac Address The command is used to get Mac Address is given below but there other be other ways also by which we can get our Mac Address. wmic nic get macaddress :: Method 1 getmac :: Method getmac CPU This command helps to gather all information about a CPU i.e. name, device id, number of cores, max clock speed, status. This can also help us in figuring out our CPU specs. wmic cpu We can also send attributes to get the particular details of a CPU in a better view. You may use a particular attribute to get particular details of CP. wmic cpu get caption, name, deviceid, numberofcores, maxclockspeed, status get cpu command RAM There are many times when we need to know the RAM size of a machine. The following command helps us to get the total size of the ram in the number of bits. We can convert the size from bits to bytes if we want to know by dividing the size by 8. Given_Ram_Size (in bits) / 8 = New_Ram_Size (int bytes) wmic computersystem get totalphysicalmemory totalphysicalmemory command Partition Details In many cases, we need to know the size of the disc as well as the partition of our/someone’s disk. Here is the command to get the details of the partition of the disc. Here also, like in CPU, we can get the particular detail of the disc, like getting the name or size or type or getting everything in one shot. The size given here is also in terms of bits. We can convert it into byte by dividing the given size by 8. Given_Ram_Size (in bits) / 8 = New_Ram_Size (int bytes) wmic partition get name,size,type wmic partition get name,size,type Process These are the commands which can help us to get the list of all processes running on our computer, and we can also close them by using these commands. These commands are very useful to get to know what tasks are running on someone’s machine. It gives us a list of processes that are running in our background. wmic process list wmic process list command We can terminate these tasks by using the command: wmic process where name="name_of_file" call terminate Note: Put the name of the ‘.exe file’ in place of “name_of_file” Let’s say, we want to terminate the calculator. So, open a calculator in the system and terminate the process by using the following steps: 1. After opening the calculator, execute the following command. wmic process list calculator.exe 2. Now, execute the following command and it will terminate the ‘Calculator.exe’ process. wmic process where name="Calculator.exe" call terminate terminate calculator using cmd Product This command gives/returns us the list of all products/software installed on a computer that is developed by a well-known developer and is recognized by the windows[Microsoft]. wmic product ::OR wmic product get name,version wmic product get name, version Basic Volume Details This command gives us the details of a particular volume of the disc. This also gives us the serial number of the volume of that disc. vol volume_letter: Note: Replace volume_letter with the letter of the volume you wish to use. Window’s Version This command gives us the window’s version. This helps us figure out that if the updates are installed in our system or what is our window’s version. The command pop up a new window about windows where we can see our Windows version. winver winver command Check Disk This command gives us a list of all large files and files which are harmful. This can also help us to figure out which file is taking more space and we can also delete those files to clean some memory in the disc. chkdsk chkdsk System Information This command gives us all the basic information about our computer such as: Host Name OS Name OS Version OS Manufacturer OS Configuration Os Build Type Registered Owner Product ID Original Install Date Bios Version Processor Input Locale Time Zone & many more systeminfo system info system info Disk Details This command gives us whole details of our hard disk where we can select volume get whole details of that volume. diskpart ::'disk part' will get us to an infinite loop. list disk ::'list disk' will give us the status and the size of the hard disk partition select disk_name ::Enter our disk name instead of 'disk_name' and our disk will be selected detail disk ::This will give us option which we can use to manipute our disk exit ::This will finally help us to exit the infinite loop diskpart command list disk select disk_name disk detail exiting disk Technical Scripter 2020 Technical Scripter TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Find the Wi-Fi Password Using CMD in Windows? Docker - COPY Instruction How to Run a Python Script using Docker? Top Programming Languages for Android App Development Running Python script on GPU. Setting up the environment in Java 'dd' command in Linux How to set up Command Prompt for Python in Windows10 ? How to setup cron jobs in Ubuntu How to Add External JAR File to an IntelliJ IDEA Project?
[ { "code": null, "e": 24107, "s": 24079, "text": "\n26 Nov, 2020" }, { "code": null, "e": 24454, "s": 24107, "text": "Some say that gathering information is only possible in Linux, but it can be done with windows using a command prompt. These are some useful commands used by hackers for gathering system information that every Geek should be aware of. To execute all these commands, run the Command Prompt as Administrator to get access to the system information." }, { "code": null, "e": 24690, "s": 24454, "text": "This article is using wmic commands. Wmic is a tool of the command prompt to get system information. The full form of wmic is the Windows Management Interface command. The list of Commands for gathering information are mentioned below." }, { "code": null, "e": 24704, "s": 24690, "text": "Serial Number" }, { "code": null, "e": 24868, "s": 24704, "text": "The command is used to get the computer’s serial number. This is very helpful to get the serial number of our bios. We will get our serial number instead of O.E.M." }, { "code": null, "e": 24895, "s": 24868, "text": "wmic bios get serialnumber" }, { "code": null, "e": 24930, "s": 24895, "text": "wmic bios get serialnumber command" }, { "code": null, "e": 24942, "s": 24930, "text": "Mac Address" }, { "code": null, "e": 25069, "s": 24942, "text": "The command is used to get Mac Address is given below but there other be other ways also by which we can get our Mac Address. " }, { "code": null, "e": 25122, "s": 25069, "text": "wmic nic get macaddress :: Method 1\ngetmac :: Method" }, { "code": null, "e": 25129, "s": 25122, "text": "getmac" }, { "code": null, "e": 25133, "s": 25129, "text": "CPU" }, { "code": null, "e": 25308, "s": 25133, "text": "This command helps to gather all information about a CPU i.e. name, device id, number of cores, max clock speed, status. This can also help us in figuring out our CPU specs. " }, { "code": null, "e": 25317, "s": 25308, "text": "wmic cpu" }, { "code": null, "e": 25470, "s": 25317, "text": "We can also send attributes to get the particular details of a CPU in a better view. You may use a particular attribute to get particular details of CP." }, { "code": null, "e": 25545, "s": 25470, "text": "wmic cpu get caption, name, deviceid, numberofcores, maxclockspeed, status" }, { "code": null, "e": 25561, "s": 25545, "text": "get cpu command" }, { "code": null, "e": 25565, "s": 25561, "text": "RAM" }, { "code": null, "e": 25810, "s": 25565, "text": "There are many times when we need to know the RAM size of a machine. The following command helps us to get the total size of the ram in the number of bits. We can convert the size from bits to bytes if we want to know by dividing the size by 8." }, { "code": null, "e": 25866, "s": 25810, "text": "Given_Ram_Size (in bits) / 8 = New_Ram_Size (int bytes)" }, { "code": null, "e": 25910, "s": 25866, "text": "wmic computersystem get totalphysicalmemory" }, { "code": null, "e": 25938, "s": 25910, "text": "totalphysicalmemory command" }, { "code": null, "e": 25956, "s": 25938, "text": "Partition Details" }, { "code": null, "e": 26268, "s": 25956, "text": "In many cases, we need to know the size of the disc as well as the partition of our/someone’s disk. Here is the command to get the details of the partition of the disc. Here also, like in CPU, we can get the particular detail of the disc, like getting the name or size or type or getting everything in one shot." }, { "code": null, "e": 26376, "s": 26268, "text": " The size given here is also in terms of bits. We can convert it into byte by dividing the given size by 8." }, { "code": null, "e": 26432, "s": 26376, "text": "Given_Ram_Size (in bits) / 8 = New_Ram_Size (int bytes)" }, { "code": null, "e": 26466, "s": 26432, "text": "wmic partition get name,size,type" }, { "code": null, "e": 26500, "s": 26466, "text": "wmic partition get name,size,type" }, { "code": null, "e": 26508, "s": 26500, "text": "Process" }, { "code": null, "e": 26818, "s": 26508, "text": "These are the commands which can help us to get the list of all processes running on our computer, and we can also close them by using these commands. These commands are very useful to get to know what tasks are running on someone’s machine. It gives us a list of processes that are running in our background." }, { "code": null, "e": 26836, "s": 26818, "text": "wmic process list" }, { "code": null, "e": 26862, "s": 26836, "text": "wmic process list command" }, { "code": null, "e": 26914, "s": 26862, "text": "We can terminate these tasks by using the command: " }, { "code": null, "e": 26968, "s": 26914, "text": "wmic process where name=\"name_of_file\" call terminate" }, { "code": null, "e": 27034, "s": 26968, "text": "Note: Put the name of the ‘.exe file’ in place of “name_of_file” " }, { "code": null, "e": 27174, "s": 27034, "text": "Let’s say, we want to terminate the calculator. So, open a calculator in the system and terminate the process by using the following steps:" }, { "code": null, "e": 27238, "s": 27174, "text": "1. After opening the calculator, execute the following command." }, { "code": null, "e": 27256, "s": 27238, "text": "wmic process list" }, { "code": null, "e": 27271, "s": 27256, "text": "calculator.exe" }, { "code": null, "e": 27361, "s": 27271, "text": "2. Now, execute the following command and it will terminate the ‘Calculator.exe’ process." }, { "code": null, "e": 27417, "s": 27361, "text": "wmic process where name=\"Calculator.exe\" call terminate" }, { "code": null, "e": 27448, "s": 27417, "text": "terminate calculator using cmd" }, { "code": null, "e": 27456, "s": 27448, "text": "Product" }, { "code": null, "e": 27634, "s": 27456, "text": "This command gives/returns us the list of all products/software installed on a computer that is developed by a well-known developer and is recognized by the windows[Microsoft]. " }, { "code": null, "e": 27682, "s": 27634, "text": "wmic product\n::OR\nwmic product get name,version" }, { "code": null, "e": 27713, "s": 27682, "text": "wmic product get name, version" }, { "code": null, "e": 27734, "s": 27713, "text": "Basic Volume Details" }, { "code": null, "e": 27869, "s": 27734, "text": "This command gives us the details of a particular volume of the disc. This also gives us the serial number of the volume of that disc." }, { "code": null, "e": 27888, "s": 27869, "text": "vol volume_letter:" }, { "code": null, "e": 27963, "s": 27888, "text": "Note: Replace volume_letter with the letter of the volume you wish to use." }, { "code": null, "e": 27980, "s": 27963, "text": "Window’s Version" }, { "code": null, "e": 28214, "s": 27980, "text": "This command gives us the window’s version. This helps us figure out that if the updates are installed in our system or what is our window’s version. The command pop up a new window about windows where we can see our Windows version." }, { "code": null, "e": 28221, "s": 28214, "text": "winver" }, { "code": null, "e": 28236, "s": 28221, "text": "winver command" }, { "code": null, "e": 28247, "s": 28236, "text": "Check Disk" }, { "code": null, "e": 28461, "s": 28247, "text": "This command gives us a list of all large files and files which are harmful. This can also help us to figure out which file is taking more space and we can also delete those files to clean some memory in the disc." }, { "code": null, "e": 28468, "s": 28461, "text": "chkdsk" }, { "code": null, "e": 28475, "s": 28468, "text": "chkdsk" }, { "code": null, "e": 28494, "s": 28475, "text": "System Information" }, { "code": null, "e": 28570, "s": 28494, "text": "This command gives us all the basic information about our computer such as:" }, { "code": null, "e": 28580, "s": 28570, "text": "Host Name" }, { "code": null, "e": 28588, "s": 28580, "text": "OS Name" }, { "code": null, "e": 28599, "s": 28588, "text": "OS Version" }, { "code": null, "e": 28615, "s": 28599, "text": "OS Manufacturer" }, { "code": null, "e": 28632, "s": 28615, "text": "OS Configuration" }, { "code": null, "e": 28646, "s": 28632, "text": "Os Build Type" }, { "code": null, "e": 28663, "s": 28646, "text": "Registered Owner" }, { "code": null, "e": 28674, "s": 28663, "text": "Product ID" }, { "code": null, "e": 28696, "s": 28674, "text": "Original Install Date" }, { "code": null, "e": 28709, "s": 28696, "text": "Bios Version" }, { "code": null, "e": 28719, "s": 28709, "text": "Processor" }, { "code": null, "e": 28732, "s": 28719, "text": "Input Locale" }, { "code": null, "e": 28742, "s": 28732, "text": "Time Zone" }, { "code": null, "e": 28754, "s": 28742, "text": "& many more" }, { "code": null, "e": 28765, "s": 28754, "text": "systeminfo" }, { "code": null, "e": 28777, "s": 28765, "text": "system info" }, { "code": null, "e": 28789, "s": 28777, "text": "system info" }, { "code": null, "e": 28802, "s": 28789, "text": "Disk Details" }, { "code": null, "e": 28916, "s": 28802, "text": "This command gives us whole details of our hard disk where we can select volume get whole details of that volume." }, { "code": null, "e": 29308, "s": 28916, "text": " diskpart\n::'disk part' will get us to an infinite loop.\n list disk\n::'list disk' will give us the status and the size of the hard disk partition\n select disk_name\n::Enter our disk name instead of 'disk_name' and our disk will be selected\n detail disk\n::This will give us option which we can use to manipute our disk\n exit\n::This will finally help us to exit the infinite loop" }, { "code": null, "e": 29325, "s": 29308, "text": "diskpart command" }, { "code": null, "e": 29335, "s": 29325, "text": "list disk" }, { "code": null, "e": 29352, "s": 29335, "text": "select disk_name" }, { "code": null, "e": 29364, "s": 29352, "text": "disk detail" }, { "code": null, "e": 29377, "s": 29364, "text": "exiting disk" }, { "code": null, "e": 29401, "s": 29377, "text": "Technical Scripter 2020" }, { "code": null, "e": 29420, "s": 29401, "text": "Technical Scripter" }, { "code": null, "e": 29429, "s": 29420, "text": "TechTips" }, { "code": null, "e": 29527, "s": 29429, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29536, "s": 29527, "text": "Comments" }, { "code": null, "e": 29549, "s": 29536, "text": "Old Comments" }, { "code": null, "e": 29602, "s": 29549, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 29628, "s": 29602, "text": "Docker - COPY Instruction" }, { "code": null, "e": 29669, "s": 29628, "text": "How to Run a Python Script using Docker?" }, { "code": null, "e": 29723, "s": 29669, "text": "Top Programming Languages for Android App Development" }, { "code": null, "e": 29753, "s": 29723, "text": "Running Python script on GPU." }, { "code": null, "e": 29788, "s": 29753, "text": "Setting up the environment in Java" }, { "code": null, "e": 29810, "s": 29788, "text": "'dd' command in Linux" }, { "code": null, "e": 29865, "s": 29810, "text": "How to set up Command Prompt for Python in Windows10 ?" }, { "code": null, "e": 29898, "s": 29865, "text": "How to setup cron jobs in Ubuntu" } ]
Python program to check if a string is palindrome or not
Given a string, our task is to check weather this string is palindrome or not. Step1: Enter string as an input. Step2: Using string slicing we reverse the string and compare it back to the original string. Step3: Then display the result. my_string=input("Enter string:") if(my_string==my_string[::-1]): print("The string is a palindrome") else: print("The string isn't a palindrome") Enter string:madam The string is a palindrome Enter string:python The string isn't a palindrome
[ { "code": null, "e": 1141, "s": 1062, "text": "Given a string, our task is to check weather this string is palindrome or not." }, { "code": null, "e": 1300, "s": 1141, "text": "Step1: Enter string as an input.\nStep2: Using string slicing we reverse the string and compare it back to the original string.\nStep3: Then display the result." }, { "code": null, "e": 1452, "s": 1300, "text": "my_string=input(\"Enter string:\")\nif(my_string==my_string[::-1]):\n print(\"The string is a palindrome\")\nelse:\n print(\"The string isn't a palindrome\")" }, { "code": null, "e": 1548, "s": 1452, "text": "Enter string:madam\nThe string is a palindrome\nEnter string:python\nThe string isn't a palindrome" } ]
Java Program to fill elements in an int array
Elements can be filled in an int array using the java.util.Arrays.fill() method. This method assigns the required int value to the int array in Java. The two parameters required are the array name and the value that is to be stored in the array elements. A program that demonstrates this is given as follows − Live Demo import java.util.Arrays; public class Demo { public static void main(String[] argv) throws Exception { int[] intArray = new int[5]; int intValue = 9; Arrays.fill(intArray, intValue); System.out.println("The int array content is: " + Arrays.toString(intArray)); } } The int array content is: [9, 9, 9, 9, 9] Now let us understand the above program. First the int array intArray[] is defined. Then the value 9 is filled in the int array using the Arrays.fill() method. Finally, the int array is printed using the Arrays.toString() method. A code snippet which demonstrates this is as follows − int[] intArray = new int[5]; int intValue = 9; Arrays.fill(intArray, intValue); System.out.println("The int array content is: " + Arrays.toString(intArray));
[ { "code": null, "e": 1317, "s": 1062, "text": "Elements can be filled in an int array using the java.util.Arrays.fill() method. This method assigns the required int value to the int array in Java. The two parameters required are the array name and the value that is to be stored in the array elements." }, { "code": null, "e": 1372, "s": 1317, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1383, "s": 1372, "text": " Live Demo" }, { "code": null, "e": 1678, "s": 1383, "text": "import java.util.Arrays;\npublic class Demo {\n public static void main(String[] argv) throws Exception {\n int[] intArray = new int[5];\n int intValue = 9;\n Arrays.fill(intArray, intValue);\n System.out.println(\"The int array content is: \" + Arrays.toString(intArray));\n }\n}" }, { "code": null, "e": 1720, "s": 1678, "text": "The int array content is: [9, 9, 9, 9, 9]" }, { "code": null, "e": 1761, "s": 1720, "text": "Now let us understand the above program." }, { "code": null, "e": 2005, "s": 1761, "text": "First the int array intArray[] is defined. Then the value 9 is filled in the int array using the Arrays.fill() method. Finally, the int array is printed using the Arrays.toString() method. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 2163, "s": 2005, "text": "int[] intArray = new int[5];\nint intValue = 9;\nArrays.fill(intArray, intValue);\nSystem.out.println(\"The int array content is: \" + Arrays.toString(intArray));" } ]
Set up R Server on Cloud | Towards Data Science
Objective: To set up a fully operational machine learning Server on Google Cloud Compute Engine’s virtual machine instance. In a real-world scenario, cloud computing and machine learning go hand-in-hand to build, transform and scale predictive modelling projects. Being a Linux server application, R Studio server is one of the best solutions that could be hosted on Google Cloud (or Amazon Web Service or Azure) to automatically process large volumes of data in SQL/ R/ Python in a centralized manner. Here’s a step-by-step approach on how to configure a fully functional R Studio Server on Google Cloud: Configure a virtual machine instance (Ubuntu OS) on Google Cloud.Install R and R Studio Server on the Virtual Machine.Create users and groups.Schedule and run R scripts using cronR package. Configure a virtual machine instance (Ubuntu OS) on Google Cloud. Install R and R Studio Server on the Virtual Machine. Create users and groups. Schedule and run R scripts using cronR package. Step 1. Configure a virtual machine instance (Ubuntu OS) on Google Cloud: Step 1.1. Create a Google Cloud Project: Sign in to Google Cloud Console and create a project. Step 1.2. Create a firewall rule: Create a firewall rule in the Google Cloud Compute Engine by navigating to the ‘Firewall rules’ under ‘Menu’ > ‘Networking’. Configure the following settings: Step 1.3. Create a Virtual Machine Instance: Set up a new virtual machine on Google Cloud by navigating to ‘VM Instances’ under ‘Menu’ > ‘Compute Engine’. Step 1.4. Virtual Machine Configurations: Give a name to the new VM instance (ex: “rstudio”) and choose a zone that’s close to the zone of operation to reduce the network latency. Since R stores all of its working datasets in memory, try to give the VM instance as much memory as we can afford. Under “OS images”, choose one of the latest versions of Ubuntu that supports the OpenSSL 1.0. R Studio Server connects always through an unsecured HTTP connection. Therefore, under Firewall, “Allow HTTP traffic”. Lastly, click “Create” to launch the instance. Step 2. Install R and R Studio Server on the Virtual Machine: Step 2.1. SSH Connection: Click on “SSH” next to the new instance from Google Compute Engine’s VM instances window. This will launch the command prompt. Step 2.2. Update apt: Update apt to make sure that we have the latest packages to use with Ubuntu. sudo apt-get updatesudo apt-get upgrade Step 2.3. Install R and R Studio Server: sudo apt-get install r-base r-base-dev Check out the latest version of the RStudio Server before running the following lines of code. Install all the supporting packages: sudo apt-get install gdebi-corewget https://download2.rstudio.org/server/bionic/amd64/rstudio-server-1.2.5019-amd64.debsudo gdebi rstudio-server-1.2.5019-amd64.debsudo apt-get install libcurl4-openssl-dev libssl-dev libxml2-dev Step 3. Create users and groups One of the biggest benefits of using R studio server is that it gives us a window to collaborate with peers in a centralized cloud framework. Add users to the virtual machine instance so that others can work with the R Studio Server simultaneously. Step 3.1. Create a group: Creating a group (ex: “marketing”) will make it easier to manage shared folders and files with the team. sudo addgroup marketing Step 3.2. Create a master user: The whole idea behind creating a master user is that while colleagues and peers will join or leave us, the “master user” would remain to own all the shared files. sudo adduser master Step 3.3. Create the shared folder: cd /home/mastersudo mkdir shared_foldersudo chown -R master:marketing shared_folder/sudo chmod -R 770 shared_folder/ Step 3.4. Add users and link them to a shared folder: Here I am adding Steve as an example to the recently created “marketing” group. Steve’s home folder has been linked to the ‘master user’s shared folder. sudo adduser stevesudo gpasswd -a steve marketingsu - steveln -s /home/master/shared_folder /home/steve/shared_folderexit That’s it! We are good to use R Studio Server on Google Cloud. In order to open R studio Server on the browser, follow the URL syntax: http://[External IP]:8787. For example, if the External IP of the newly configured virtual machine instance is 35.185.161.49, then our R Studio Server URL would be: http://35.199.10.210:8787/ Step 4. Schedule and run R scripts using cronR package: Install cronR package to generate the task scheduler in R Studio Server. Use the add-in to automate any scripts in the virtual machine instance. install.packages("cronR")install.packages("shinyFiles") Step 5: What’s Next? We just finished setting up the machine learning framework in the cloud. Here are some recommendations on what we could potentially do to scale up this data modeling and predictive analytics workflow: 1) Extract, transform, and load datasets from internal (CRM databases) or external data sources (third-party vendors like Nielsen Ratings or Facebook & Google Ad sets) into the Google Cloud Compute Engine. 2) Build data models in SQL, R, or Python (Use Reticulate and sqldf packages to source python/SQL scripts into R studio server). 3) Build supervised or unsupervised or reinforcement machine learning algorithms over the cloud-sourced data model. Productionize the end-to-end workflow using cronR package. Store the dataset in a cloud database. 4) Lastly, build a BI dashboard that visualizes the predictive model (could be anything from predicting the next month sales or churn rate to classifying the customer database using unsupervised cluster models). If interested, embed this live predictive BI model as a widget in web/mobile applications via REST API. About the Author srees.org Feel free to reach out to me if you need any help in understanding the aforesaid configurations. Happy to share what I know! Hope this helps:)
[ { "code": null, "e": 296, "s": 172, "text": "Objective: To set up a fully operational machine learning Server on Google Cloud Compute Engine’s virtual machine instance." }, { "code": null, "e": 778, "s": 296, "text": "In a real-world scenario, cloud computing and machine learning go hand-in-hand to build, transform and scale predictive modelling projects. Being a Linux server application, R Studio server is one of the best solutions that could be hosted on Google Cloud (or Amazon Web Service or Azure) to automatically process large volumes of data in SQL/ R/ Python in a centralized manner. Here’s a step-by-step approach on how to configure a fully functional R Studio Server on Google Cloud:" }, { "code": null, "e": 968, "s": 778, "text": "Configure a virtual machine instance (Ubuntu OS) on Google Cloud.Install R and R Studio Server on the Virtual Machine.Create users and groups.Schedule and run R scripts using cronR package." }, { "code": null, "e": 1034, "s": 968, "text": "Configure a virtual machine instance (Ubuntu OS) on Google Cloud." }, { "code": null, "e": 1088, "s": 1034, "text": "Install R and R Studio Server on the Virtual Machine." }, { "code": null, "e": 1113, "s": 1088, "text": "Create users and groups." }, { "code": null, "e": 1161, "s": 1113, "text": "Schedule and run R scripts using cronR package." }, { "code": null, "e": 1235, "s": 1161, "text": "Step 1. Configure a virtual machine instance (Ubuntu OS) on Google Cloud:" }, { "code": null, "e": 1330, "s": 1235, "text": "Step 1.1. Create a Google Cloud Project: Sign in to Google Cloud Console and create a project." }, { "code": null, "e": 1523, "s": 1330, "text": "Step 1.2. Create a firewall rule: Create a firewall rule in the Google Cloud Compute Engine by navigating to the ‘Firewall rules’ under ‘Menu’ > ‘Networking’. Configure the following settings:" }, { "code": null, "e": 1678, "s": 1523, "text": "Step 1.3. Create a Virtual Machine Instance: Set up a new virtual machine on Google Cloud by navigating to ‘VM Instances’ under ‘Menu’ > ‘Compute Engine’." }, { "code": null, "e": 2233, "s": 1678, "text": "Step 1.4. Virtual Machine Configurations: Give a name to the new VM instance (ex: “rstudio”) and choose a zone that’s close to the zone of operation to reduce the network latency. Since R stores all of its working datasets in memory, try to give the VM instance as much memory as we can afford. Under “OS images”, choose one of the latest versions of Ubuntu that supports the OpenSSL 1.0. R Studio Server connects always through an unsecured HTTP connection. Therefore, under Firewall, “Allow HTTP traffic”. Lastly, click “Create” to launch the instance." }, { "code": null, "e": 2295, "s": 2233, "text": "Step 2. Install R and R Studio Server on the Virtual Machine:" }, { "code": null, "e": 2448, "s": 2295, "text": "Step 2.1. SSH Connection: Click on “SSH” next to the new instance from Google Compute Engine’s VM instances window. This will launch the command prompt." }, { "code": null, "e": 2547, "s": 2448, "text": "Step 2.2. Update apt: Update apt to make sure that we have the latest packages to use with Ubuntu." }, { "code": null, "e": 2587, "s": 2547, "text": "sudo apt-get updatesudo apt-get upgrade" }, { "code": null, "e": 2628, "s": 2587, "text": "Step 2.3. Install R and R Studio Server:" }, { "code": null, "e": 2667, "s": 2628, "text": "sudo apt-get install r-base r-base-dev" }, { "code": null, "e": 2799, "s": 2667, "text": "Check out the latest version of the RStudio Server before running the following lines of code. Install all the supporting packages:" }, { "code": null, "e": 3027, "s": 2799, "text": "sudo apt-get install gdebi-corewget https://download2.rstudio.org/server/bionic/amd64/rstudio-server-1.2.5019-amd64.debsudo gdebi rstudio-server-1.2.5019-amd64.debsudo apt-get install libcurl4-openssl-dev libssl-dev libxml2-dev" }, { "code": null, "e": 3059, "s": 3027, "text": "Step 3. Create users and groups" }, { "code": null, "e": 3308, "s": 3059, "text": "One of the biggest benefits of using R studio server is that it gives us a window to collaborate with peers in a centralized cloud framework. Add users to the virtual machine instance so that others can work with the R Studio Server simultaneously." }, { "code": null, "e": 3439, "s": 3308, "text": "Step 3.1. Create a group: Creating a group (ex: “marketing”) will make it easier to manage shared folders and files with the team." }, { "code": null, "e": 3463, "s": 3439, "text": "sudo addgroup marketing" }, { "code": null, "e": 3658, "s": 3463, "text": "Step 3.2. Create a master user: The whole idea behind creating a master user is that while colleagues and peers will join or leave us, the “master user” would remain to own all the shared files." }, { "code": null, "e": 3678, "s": 3658, "text": "sudo adduser master" }, { "code": null, "e": 3714, "s": 3678, "text": "Step 3.3. Create the shared folder:" }, { "code": null, "e": 3831, "s": 3714, "text": "cd /home/mastersudo mkdir shared_foldersudo chown -R master:marketing shared_folder/sudo chmod -R 770 shared_folder/" }, { "code": null, "e": 4038, "s": 3831, "text": "Step 3.4. Add users and link them to a shared folder: Here I am adding Steve as an example to the recently created “marketing” group. Steve’s home folder has been linked to the ‘master user’s shared folder." }, { "code": null, "e": 4160, "s": 4038, "text": "sudo adduser stevesudo gpasswd -a steve marketingsu - steveln -s /home/master/shared_folder /home/steve/shared_folderexit" }, { "code": null, "e": 4487, "s": 4160, "text": "That’s it! We are good to use R Studio Server on Google Cloud. In order to open R studio Server on the browser, follow the URL syntax: http://[External IP]:8787. For example, if the External IP of the newly configured virtual machine instance is 35.185.161.49, then our R Studio Server URL would be: http://35.199.10.210:8787/" }, { "code": null, "e": 4543, "s": 4487, "text": "Step 4. Schedule and run R scripts using cronR package:" }, { "code": null, "e": 4688, "s": 4543, "text": "Install cronR package to generate the task scheduler in R Studio Server. Use the add-in to automate any scripts in the virtual machine instance." }, { "code": null, "e": 4744, "s": 4688, "text": "install.packages(\"cronR\")install.packages(\"shinyFiles\")" }, { "code": null, "e": 4765, "s": 4744, "text": "Step 5: What’s Next?" }, { "code": null, "e": 4966, "s": 4765, "text": "We just finished setting up the machine learning framework in the cloud. Here are some recommendations on what we could potentially do to scale up this data modeling and predictive analytics workflow:" }, { "code": null, "e": 5172, "s": 4966, "text": "1) Extract, transform, and load datasets from internal (CRM databases) or external data sources (third-party vendors like Nielsen Ratings or Facebook & Google Ad sets) into the Google Cloud Compute Engine." }, { "code": null, "e": 5301, "s": 5172, "text": "2) Build data models in SQL, R, or Python (Use Reticulate and sqldf packages to source python/SQL scripts into R studio server)." }, { "code": null, "e": 5515, "s": 5301, "text": "3) Build supervised or unsupervised or reinforcement machine learning algorithms over the cloud-sourced data model. Productionize the end-to-end workflow using cronR package. Store the dataset in a cloud database." }, { "code": null, "e": 5831, "s": 5515, "text": "4) Lastly, build a BI dashboard that visualizes the predictive model (could be anything from predicting the next month sales or churn rate to classifying the customer database using unsupervised cluster models). If interested, embed this live predictive BI model as a widget in web/mobile applications via REST API." }, { "code": null, "e": 5848, "s": 5831, "text": "About the Author" }, { "code": null, "e": 5858, "s": 5848, "text": "srees.org" } ]
WebSockets - Communicating with Server
The Web has been largely built around the request/response paradigm of HTTP. A client loads up a web page and then nothing happens until the user clicks onto the next page. Around 2005, AJAX started to make the web feel more dynamic. Still, all HTTP communication is steered by the client, which requires user interaction or periodic polling to load new data from the server. Technologies that enable the server to send the data to a client in the very moment when it knows that new data is available have been around for quite some time. They go by names such as "Push" or “Comet”. With long polling, the client opens an HTTP connection to the server, which keeps it open until sending response. Whenever the server actually has new data, it sends the response. Long polling and the other techniques work quite well. However, all of these share one problem, they carry the overhead of HTTP, which does not make them well suited for low latency applications. For example, a multiplayer shooter game in the browser or any other online game with a real-time component. The Web Socket specification defines an API establishing "socket" connections between a web browser and a server. In layman terms, there is a persistent connection between the client and the server and both parties can start sending data at any time. Web socket connection can be simply opened using a constructor − var connection = new WebSocket('ws://html5rocks.websocket.org/echo', ['soap', 'xmpp']); ws is the new URL schema for WebSocket connections. There is also wss, for secure WebSocket connection the same way https is used for secure HTTP connections. Attaching some event handlers immediately to the connection allows you to know when the connection is opened, received incoming messages, or there is an error. The second argument accepts optional subprotocols. It can be a string or an array of strings. Each string should represent a subprotocol name and server accepts only one of passed subprotocols in the array. Accepted subprotocol can be determined by accessing protocol property of WebSocket object. // When the connection is open, send some data to the server connection.onopen = function () { connection.send('Ping'); // Send the message 'Ping' to the server }; // Log errors connection.onerror = function (error) { console.log('WebSocket Error ' + error); }; // Log messages from the server connection.onmessage = function (e) { console.log('Server: ' + e.data); }; As soon as we have a connection to the server (when the open event is fired) we can start sending data to the server using the send (your message) method on the connection object. It used to support only strings, but in the latest specification, it now can send binary messages too. To send binary data, Blob or ArrayBuffer object is used. // Sending String connection.send('your message'); // Sending canvas ImageData as ArrayBuffer var img = canvas_context.getImageData(0, 0, 400, 320); var binary = new Uint8Array(img.data.length); for (var i = 0; i < img.data.length; i++) { binary[i] = img.data[i]; } connection.send(binary.buffer); // Sending file as Blob var file = document.querySelector('input[type = "file"]').files[0]; connection.send(file); Equally, the server might send us messages at any time. Whenever this happens the onmessage callback fires. The callback receives an event object and the actual message is accessible via the data property. WebSocket can also receive binary messages in the latest spec. Binary frames can be received in Blob or ArrayBuffer format. To specify the format of the received binary, set the binaryType property of WebSocket object to either 'blob' or 'arraybuffer'. The default format is 'blob'. // Setting binaryType to accept received binary as either 'blob' or 'arraybuffer' connection.binaryType = 'arraybuffer'; connection.onmessage = function(e) { console.log(e.data.byteLength); // ArrayBuffer object if binary }; Another newly added feature of WebSocket is extensions. Using extensions, it will be possible to send frames compressed, multiplexed, etc. // Determining accepted extensions console.log(connection.extensions); Being a modern protocol, cross-origin communication is baked right into WebSocket. WebSocket enables communication between parties on any domain. The server decides whether to make its service available to all clients or only those that reside on a set of well-defined domains. Every new technology comes with a new set of problems. In the case of WebSocket it is the compatibility with proxy servers, which mediate HTTP connections in most company networks. The WebSocket protocol uses the HTTP upgrade system (which is normally used for HTTP/SSL) to "upgrade" an HTTP connection to a WebSocket connection. Some proxy servers do not like this and will drop the connection. Thus, even if a given client uses the WebSocket protocol, it may not be possible to establish a connection. This makes the next section even more important :) Using WebSocket creates a whole new usage pattern for server side applications. While traditional server stacks such as LAMP are designed around the HTTP request/response cycle they often do not deal well with a large number of open WebSocket connections. Keeping a large number of connections open at the same time requires an architecture that receives high concurrency at a low performance cost. Print Add Notes Bookmark this page
[ { "code": null, "e": 2495, "s": 2119, "text": "The Web has been largely built around the request/response paradigm of HTTP. A client loads up a web page and then nothing happens until the user clicks onto the next page. Around 2005, AJAX started to make the web feel more dynamic. Still, all HTTP communication is steered by the client, which requires user interaction or periodic polling to load new data from the server." }, { "code": null, "e": 2702, "s": 2495, "text": "Technologies that enable the server to send the data to a client in the very moment when it knows that new data is available have been around for quite some time. They go by names such as \"Push\" or “Comet”." }, { "code": null, "e": 3186, "s": 2702, "text": "With long polling, the client opens an HTTP connection to the server, which keeps it open until sending response. Whenever the server actually has new data, it sends the response. Long polling and the other techniques work quite well. However, all of these share one problem, they carry the overhead of HTTP, which does not make them well suited for low latency applications. For example, a multiplayer shooter game in the browser or any other online game with a real-time component." }, { "code": null, "e": 3437, "s": 3186, "text": "The Web Socket specification defines an API establishing \"socket\" connections between a web browser and a server. In layman terms, there is a persistent connection between the client and the server and both parties can start sending data at any time." }, { "code": null, "e": 3502, "s": 3437, "text": "Web socket connection can be simply opened using a constructor −" }, { "code": null, "e": 3591, "s": 3502, "text": "var connection = new WebSocket('ws://html5rocks.websocket.org/echo', ['soap', 'xmpp']);\n" }, { "code": null, "e": 3750, "s": 3591, "text": "ws is the new URL schema for WebSocket connections. There is also wss, for secure WebSocket connection the same way https is used for secure HTTP connections." }, { "code": null, "e": 3910, "s": 3750, "text": "Attaching some event handlers immediately to the connection allows you to know when the connection is opened, received incoming messages, or there is an error." }, { "code": null, "e": 4208, "s": 3910, "text": "The second argument accepts optional subprotocols. It can be a string or an array of strings. Each string should represent a subprotocol name and server accepts only one of passed subprotocols in the array. Accepted subprotocol can be determined by accessing protocol property of WebSocket object." }, { "code": null, "e": 4588, "s": 4208, "text": "// When the connection is open, send some data to the server\nconnection.onopen = function () {\n connection.send('Ping'); // Send the message 'Ping' to the server\n};\n\n// Log errors\nconnection.onerror = function (error) {\n console.log('WebSocket Error ' + error);\n};\n\n// Log messages from the server\nconnection.onmessage = function (e) {\n console.log('Server: ' + e.data);\n};" }, { "code": null, "e": 4928, "s": 4588, "text": "As soon as we have a connection to the server (when the open event is fired) we can start sending data to the server using the send (your message) method on the connection object. It used to support only strings, but in the latest specification, it now can send binary messages too. To send binary data, Blob or ArrayBuffer object is used." }, { "code": null, "e": 5348, "s": 4928, "text": "// Sending String\nconnection.send('your message');\n\n// Sending canvas ImageData as ArrayBuffer\nvar img = canvas_context.getImageData(0, 0, 400, 320);\nvar binary = new Uint8Array(img.data.length);\n\nfor (var i = 0; i < img.data.length; i++) {\n binary[i] = img.data[i];\n}\n\nconnection.send(binary.buffer);\n\n// Sending file as Blob\nvar file = document.querySelector('input[type = \"file\"]').files[0];\nconnection.send(file);" }, { "code": null, "e": 5554, "s": 5348, "text": "Equally, the server might send us messages at any time. Whenever this happens the onmessage callback fires. The callback receives an event object and the actual message is accessible via the data property." }, { "code": null, "e": 5837, "s": 5554, "text": "WebSocket can also receive binary messages in the latest spec. Binary frames can be received in Blob or ArrayBuffer format. To specify the format of the received binary, set the binaryType property of WebSocket object to either 'blob' or 'arraybuffer'. The default format is 'blob'." }, { "code": null, "e": 6065, "s": 5837, "text": "// Setting binaryType to accept received binary as either 'blob' or 'arraybuffer'\nconnection.binaryType = 'arraybuffer';\nconnection.onmessage = function(e) {\n console.log(e.data.byteLength); // ArrayBuffer object if binary\n};" }, { "code": null, "e": 6204, "s": 6065, "text": "Another newly added feature of WebSocket is extensions. Using extensions, it will be possible to send frames compressed, multiplexed, etc." }, { "code": null, "e": 6276, "s": 6204, "text": "// Determining accepted extensions\nconsole.log(connection.extensions);\n" }, { "code": null, "e": 6554, "s": 6276, "text": "Being a modern protocol, cross-origin communication is baked right into WebSocket. WebSocket enables communication between parties on any domain. The server decides whether to make its service available to all clients or only those that reside on a set of well-defined domains." }, { "code": null, "e": 7109, "s": 6554, "text": "Every new technology comes with a new set of problems. In the case of WebSocket it is the compatibility with proxy servers, which mediate HTTP connections in most company networks. The WebSocket protocol uses the HTTP upgrade system (which is normally used for HTTP/SSL) to \"upgrade\" an HTTP connection to a WebSocket connection. Some proxy servers do not like this and will drop the connection. Thus, even if a given client uses the WebSocket protocol, it may not be possible to establish a connection. This makes the next section even more important :)" }, { "code": null, "e": 7508, "s": 7109, "text": "Using WebSocket creates a whole new usage pattern for server side applications. While traditional server stacks such as LAMP are designed around the HTTP request/response cycle they often do not deal well with a large number of open WebSocket connections. Keeping a large number of connections open at the same time requires an architecture that receives high concurrency at a low performance cost." }, { "code": null, "e": 7515, "s": 7508, "text": " Print" }, { "code": null, "e": 7526, "s": 7515, "text": " Add Notes" } ]
Neural Network Embeddings Explained | by Will Koehrsen | Towards Data Science
Applications of neural networks have expanded significantly in recent years from image segmentation to natural language processing to time-series forecasting. One notably successful use of deep learning is embedding, a method used to represent discrete variables as continuous vectors. This technique has found practical applications with word embeddings for machine translation and entity embeddings for categorical variables. In this article, I’ll explain what neural network embeddings are, why we want to use them, and how they are learned. We’ll go through these concepts in the context of a real problem I’m working on: representing all the books on Wikipedia as vectors to create a book recommendation system. An embedding is a mapping of a discrete — categorical — variable to a vector of continuous numbers. In the context of neural networks, embeddings are low-dimensional, learned continuous vector representations of discrete variables. Neural network embeddings are useful because they can reduce the dimensionality of categorical variables and meaningfully represent categories in the transformed space. Neural network embeddings have 3 primary purposes: Finding nearest neighbors in the embedding space. These can be used to make recommendations based on user interests or cluster categories.As input to a machine learning model for a supervised task.For visualization of concepts and relations between categories. Finding nearest neighbors in the embedding space. These can be used to make recommendations based on user interests or cluster categories. As input to a machine learning model for a supervised task. For visualization of concepts and relations between categories. This means in terms of the book project, using neural network embeddings, we can take all 37,000 book articles on Wikipedia and represent each one using only 50 numbers in a vector. Moreover, because embeddings are learned, books that are more similar in the context of our learning problem are closer to one another in the embedding space. Neural network embeddings overcome the two limitations of a common method for representing categorical variables: one-hot encoding. The operation of one-hot encoding categorical variables is actually a simple embedding where each category is mapped to a different vector. This process takes discrete entities and maps each observation to a vector of 0s and a single 1 signaling the specific category. The one-hot encoding technique has two main drawbacks: For high-cardinality variables — those with many unique categories — the dimensionality of the transformed vector becomes unmanageable.The mapping is completely uninformed: “similar” categories are not placed closer to each other in embedding space. For high-cardinality variables — those with many unique categories — the dimensionality of the transformed vector becomes unmanageable. The mapping is completely uninformed: “similar” categories are not placed closer to each other in embedding space. The first problem is well-understood: for each additional category — referred to as an entity — we have to add another number to the one-hot encoded vector. If we have 37,000 books on Wikipedia, then representing these requires a 37,000-dimensional vector for each book, which makes training any machine learning model on this representation infeasible. The second problem is equally limiting: one-hot encoding does not place similar entities closer to one another in vector space. If we measure similarity between vectors using the cosine distance, then after one-hot encoding, the similarity is 0 for every comparison between entities. This means that entities such as War and Peace and Anna Karenina (both classic books by Leo Tolstoy) are no closer to one another than War and Peace is to The Hitchhiker’s Guide to the Galaxy if we use one-hot encoding. # One Hot Encoding Categoricalsbooks = ["War and Peace", "Anna Karenina", "The Hitchhiker's Guide to the Galaxy"]books_encoded = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]Similarity (dot product) between First and Second = 0Similarity (dot product) between Second and Third = 0Similarity (dot product) between First and Third = 0 Considering these two problems, the ideal solution for representing categorical variables would require fewer numbers than the number of unique categories and would place similar categories closer to one another. # Idealized Representation of Embeddingbooks = ["War and Peace", "Anna Karenina", "The Hitchhiker's Guide to the Galaxy"]books_encoded_ideal = [[0.53, 0.85], [0.60, 0.80], [-0.78, -0.62]]Similarity (dot product) between First and Second = 0.99Similarity (dot product) between Second and Third = -0.94Similarity (dot product) between First and Third = -0.97 To construct a better representation of categorical entities, we can use an embedding neural network and a supervised task to learn embeddings. The main issue with one-hot encoding is that the transformation does not rely on any supervision. We can greatly improve embeddings by learning them using a neural network on a supervised task. The embeddings form the parameters — weights — of the network which are adjusted to minimize loss on the task. The resulting embedded vectors are representations of categories where similar categories — relative to the task — are closer to one another. For example, if we have a vocabulary of 50,000 words used in a collection of movie reviews, we could learn 100-dimensional embeddings for each word using an embedding neural network trained to predict the sentimentality of the reviews. (For exactly this application see this Google Colab Notebook). Words in the vocabulary that are associated with positive reviews such as “brilliant” or “excellent” will come out closer in the embedding space because the network has learned these are both associated with positive reviews. In the book example given above, our supervised task could be “identify whether or not a book was written by Leo Tolstoy” and the resulting embeddings would place books written by Tolstoy closer to each other. Figuring out how to create the supervised task to produce relevant representations is the toughest part of making embeddings. In the Wikipedia book project (complete notebook here), the supervised learning task is set as predicting whether a given link to a Wikipedia page appears in the article for a book. We feed in pairs of (book title, link) training examples with a mix of positive — true — and negative — false — pairs. This set-up is based on the assumption that books which link to similar Wikipedia pages are similar to one another. The resulting embeddings should therefore place alike books closer together in vector space. The network I used has two parallel embedding layers that map the book and wikilink to separate 50-dimensional vectors and a dot product layer that combines the embeddings into a single number for a prediction. The embeddings are the parameters, or weights, of the network that are adjusted during training to minimize the loss on the supervised task. In Keras code, this looks like the following (don’t worry if you don’t completely understand the code, just skip to the images): Although in a supervised machine learning task the goal is usually to train a model to make predictions on new data, in this embedding model, the predictions can be just a means to an end. What we want is the embedding weights, the representation of the books and links as continuous vectors. The embeddings by themselves are not that interesting: they are simply vectors of numbers: However, the embeddings can be used for the 3 purposes listed previously, and for this project, we are primarily interested in recommending books based on the nearest neighbors. To compute similarity, we take a query book and find the dot product between its vector and those of all the other books. (If our embeddings are normalized, this dot product is the cosine distance between vectors that ranges from -1, most dissimilar, to +1, most similar. We could also use the Euclidean distance to measure similarity). This is the output of the book embedding model I built: Books closest to War and Peace.Book: War and Peace Similarity: 1.0Book: Anna Karenina Similarity: 0.79Book: The Master and Margarita Similarity: 0.77Book: Doctor Zhivago (novel) Similarity: 0.76Book: Dead Souls Similarity: 0.75 (The cosine similarity between a vector and itself must be 1.0). After some dimensionality reduction (see below), we can make figures like the following: We can clearly see the value of learning embeddings! We now have a 50-number representation of every single book on Wikipedia, with similar books closer to one another. One of the coolest parts about embeddings are that they can be used to visualize concepts such as novel or non-fiction relative to one another. This requires a further dimension reduction technique to get the dimensions to 2 or 3. The most popular technique for reduction is itself an embedding method: t-Distributed Stochastic Neighbor Embedding (TSNE). We can take the original 37,000 dimensions of all the books on Wikipedia, map them to 50 dimensions using neural network embeddings, and then map them to 2 dimensions using TSNE. The result is below: (TSNE is a manifold learning technique which means that it tries to map high-dimensional data to a lower-dimensional manifold, creating an embedding that attempts to maintain local structure within the data. It’s almost exclusively used for visualization because the output is stochastic and it does not support transforming new data. An up and coming alternative is Uniform Manifold Approximation and Projection, UMAP, which is much faster and does support transform new data into the embedding space). By itself this isn’t very useful, but it can be insightful once we start coloring it based on different book characteristics. We can clearly see groupings of books belonging to the same genre. It’s not perfect, but it’s still impressive that we can represent all books on Wikipedia using just 2 numbers that still capture the variability between genres. The book example (full article coming soon) shows the value of neural network embeddings: we have a vector representation of categorical objects that is both low-dimensional and places similar entities closer to one another in the embedded space. The problem with static graphs is that we can’t really explore the data and investigate groupings or relationships between variables. To solve this problem, TensorFlow developed projector, an online application that lets us visualize and interact with embeddings. I’ll release an article on how to use this tool shortly, but for now, here’s the results: Neural network embeddings are learned low-dimensional representations of discrete data as continuous vectors. These embeddings overcome the limitations of traditional encoding methods and can be used for purposes such as finding nearest neighbors, input into another model, and visualizations. Although many deep learning concepts are talked about in academic terms, neural network embeddings are both intuitive and relatively simple to implement. I firmly believe that anyone can learn deep learning and use libraries such as Keras to build deep learning solutions. Embeddings are an effective tool for handling discrete variables and present a useful application of deep learning. Google-Produced tutorial on embeddings TensorFlow Guide to Embeddings Book Recommendation System Using Embeddings Tutorial on Word Embeddings in Keras As always, I welcome feedback and constructive criticism. I can be reached on Twitter @koehrsen_will or on my personal website at willk.online.
[ { "code": null, "e": 599, "s": 171, "text": "Applications of neural networks have expanded significantly in recent years from image segmentation to natural language processing to time-series forecasting. One notably successful use of deep learning is embedding, a method used to represent discrete variables as continuous vectors. This technique has found practical applications with word embeddings for machine translation and entity embeddings for categorical variables." }, { "code": null, "e": 888, "s": 599, "text": "In this article, I’ll explain what neural network embeddings are, why we want to use them, and how they are learned. We’ll go through these concepts in the context of a real problem I’m working on: representing all the books on Wikipedia as vectors to create a book recommendation system." }, { "code": null, "e": 1289, "s": 888, "text": "An embedding is a mapping of a discrete — categorical — variable to a vector of continuous numbers. In the context of neural networks, embeddings are low-dimensional, learned continuous vector representations of discrete variables. Neural network embeddings are useful because they can reduce the dimensionality of categorical variables and meaningfully represent categories in the transformed space." }, { "code": null, "e": 1340, "s": 1289, "text": "Neural network embeddings have 3 primary purposes:" }, { "code": null, "e": 1601, "s": 1340, "text": "Finding nearest neighbors in the embedding space. These can be used to make recommendations based on user interests or cluster categories.As input to a machine learning model for a supervised task.For visualization of concepts and relations between categories." }, { "code": null, "e": 1740, "s": 1601, "text": "Finding nearest neighbors in the embedding space. These can be used to make recommendations based on user interests or cluster categories." }, { "code": null, "e": 1800, "s": 1740, "text": "As input to a machine learning model for a supervised task." }, { "code": null, "e": 1864, "s": 1800, "text": "For visualization of concepts and relations between categories." }, { "code": null, "e": 2205, "s": 1864, "text": "This means in terms of the book project, using neural network embeddings, we can take all 37,000 book articles on Wikipedia and represent each one using only 50 numbers in a vector. Moreover, because embeddings are learned, books that are more similar in the context of our learning problem are closer to one another in the embedding space." }, { "code": null, "e": 2337, "s": 2205, "text": "Neural network embeddings overcome the two limitations of a common method for representing categorical variables: one-hot encoding." }, { "code": null, "e": 2606, "s": 2337, "text": "The operation of one-hot encoding categorical variables is actually a simple embedding where each category is mapped to a different vector. This process takes discrete entities and maps each observation to a vector of 0s and a single 1 signaling the specific category." }, { "code": null, "e": 2661, "s": 2606, "text": "The one-hot encoding technique has two main drawbacks:" }, { "code": null, "e": 2911, "s": 2661, "text": "For high-cardinality variables — those with many unique categories — the dimensionality of the transformed vector becomes unmanageable.The mapping is completely uninformed: “similar” categories are not placed closer to each other in embedding space." }, { "code": null, "e": 3047, "s": 2911, "text": "For high-cardinality variables — those with many unique categories — the dimensionality of the transformed vector becomes unmanageable." }, { "code": null, "e": 3162, "s": 3047, "text": "The mapping is completely uninformed: “similar” categories are not placed closer to each other in embedding space." }, { "code": null, "e": 3516, "s": 3162, "text": "The first problem is well-understood: for each additional category — referred to as an entity — we have to add another number to the one-hot encoded vector. If we have 37,000 books on Wikipedia, then representing these requires a 37,000-dimensional vector for each book, which makes training any machine learning model on this representation infeasible." }, { "code": null, "e": 3800, "s": 3516, "text": "The second problem is equally limiting: one-hot encoding does not place similar entities closer to one another in vector space. If we measure similarity between vectors using the cosine distance, then after one-hot encoding, the similarity is 0 for every comparison between entities." }, { "code": null, "e": 4020, "s": 3800, "text": "This means that entities such as War and Peace and Anna Karenina (both classic books by Leo Tolstoy) are no closer to one another than War and Peace is to The Hitchhiker’s Guide to the Galaxy if we use one-hot encoding." }, { "code": null, "e": 4383, "s": 4020, "text": "# One Hot Encoding Categoricalsbooks = [\"War and Peace\", \"Anna Karenina\", \"The Hitchhiker's Guide to the Galaxy\"]books_encoded = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]Similarity (dot product) between First and Second = 0Similarity (dot product) between Second and Third = 0Similarity (dot product) between First and Third = 0" }, { "code": null, "e": 4596, "s": 4383, "text": "Considering these two problems, the ideal solution for representing categorical variables would require fewer numbers than the number of unique categories and would place similar categories closer to one another." }, { "code": null, "e": 5009, "s": 4596, "text": "# Idealized Representation of Embeddingbooks = [\"War and Peace\", \"Anna Karenina\", \"The Hitchhiker's Guide to the Galaxy\"]books_encoded_ideal = [[0.53, 0.85], [0.60, 0.80], [-0.78, -0.62]]Similarity (dot product) between First and Second = 0.99Similarity (dot product) between Second and Third = -0.94Similarity (dot product) between First and Third = -0.97" }, { "code": null, "e": 5153, "s": 5009, "text": "To construct a better representation of categorical entities, we can use an embedding neural network and a supervised task to learn embeddings." }, { "code": null, "e": 5600, "s": 5153, "text": "The main issue with one-hot encoding is that the transformation does not rely on any supervision. We can greatly improve embeddings by learning them using a neural network on a supervised task. The embeddings form the parameters — weights — of the network which are adjusted to minimize loss on the task. The resulting embedded vectors are representations of categories where similar categories — relative to the task — are closer to one another." }, { "code": null, "e": 6125, "s": 5600, "text": "For example, if we have a vocabulary of 50,000 words used in a collection of movie reviews, we could learn 100-dimensional embeddings for each word using an embedding neural network trained to predict the sentimentality of the reviews. (For exactly this application see this Google Colab Notebook). Words in the vocabulary that are associated with positive reviews such as “brilliant” or “excellent” will come out closer in the embedding space because the network has learned these are both associated with positive reviews." }, { "code": null, "e": 6461, "s": 6125, "text": "In the book example given above, our supervised task could be “identify whether or not a book was written by Leo Tolstoy” and the resulting embeddings would place books written by Tolstoy closer to each other. Figuring out how to create the supervised task to produce relevant representations is the toughest part of making embeddings." }, { "code": null, "e": 6971, "s": 6461, "text": "In the Wikipedia book project (complete notebook here), the supervised learning task is set as predicting whether a given link to a Wikipedia page appears in the article for a book. We feed in pairs of (book title, link) training examples with a mix of positive — true — and negative — false — pairs. This set-up is based on the assumption that books which link to similar Wikipedia pages are similar to one another. The resulting embeddings should therefore place alike books closer together in vector space." }, { "code": null, "e": 7323, "s": 6971, "text": "The network I used has two parallel embedding layers that map the book and wikilink to separate 50-dimensional vectors and a dot product layer that combines the embeddings into a single number for a prediction. The embeddings are the parameters, or weights, of the network that are adjusted during training to minimize the loss on the supervised task." }, { "code": null, "e": 7452, "s": 7323, "text": "In Keras code, this looks like the following (don’t worry if you don’t completely understand the code, just skip to the images):" }, { "code": null, "e": 7745, "s": 7452, "text": "Although in a supervised machine learning task the goal is usually to train a model to make predictions on new data, in this embedding model, the predictions can be just a means to an end. What we want is the embedding weights, the representation of the books and links as continuous vectors." }, { "code": null, "e": 7836, "s": 7745, "text": "The embeddings by themselves are not that interesting: they are simply vectors of numbers:" }, { "code": null, "e": 8351, "s": 7836, "text": "However, the embeddings can be used for the 3 purposes listed previously, and for this project, we are primarily interested in recommending books based on the nearest neighbors. To compute similarity, we take a query book and find the dot product between its vector and those of all the other books. (If our embeddings are normalized, this dot product is the cosine distance between vectors that ranges from -1, most dissimilar, to +1, most similar. We could also use the Euclidean distance to measure similarity)." }, { "code": null, "e": 8407, "s": 8351, "text": "This is the output of the book embedding model I built:" }, { "code": null, "e": 8683, "s": 8407, "text": "Books closest to War and Peace.Book: War and Peace Similarity: 1.0Book: Anna Karenina Similarity: 0.79Book: The Master and Margarita Similarity: 0.77Book: Doctor Zhivago (novel) Similarity: 0.76Book: Dead Souls Similarity: 0.75" }, { "code": null, "e": 8837, "s": 8683, "text": "(The cosine similarity between a vector and itself must be 1.0). After some dimensionality reduction (see below), we can make figures like the following:" }, { "code": null, "e": 9006, "s": 8837, "text": "We can clearly see the value of learning embeddings! We now have a 50-number representation of every single book on Wikipedia, with similar books closer to one another." }, { "code": null, "e": 9361, "s": 9006, "text": "One of the coolest parts about embeddings are that they can be used to visualize concepts such as novel or non-fiction relative to one another. This requires a further dimension reduction technique to get the dimensions to 2 or 3. The most popular technique for reduction is itself an embedding method: t-Distributed Stochastic Neighbor Embedding (TSNE)." }, { "code": null, "e": 9561, "s": 9361, "text": "We can take the original 37,000 dimensions of all the books on Wikipedia, map them to 50 dimensions using neural network embeddings, and then map them to 2 dimensions using TSNE. The result is below:" }, { "code": null, "e": 10065, "s": 9561, "text": "(TSNE is a manifold learning technique which means that it tries to map high-dimensional data to a lower-dimensional manifold, creating an embedding that attempts to maintain local structure within the data. It’s almost exclusively used for visualization because the output is stochastic and it does not support transforming new data. An up and coming alternative is Uniform Manifold Approximation and Projection, UMAP, which is much faster and does support transform new data into the embedding space)." }, { "code": null, "e": 10191, "s": 10065, "text": "By itself this isn’t very useful, but it can be insightful once we start coloring it based on different book characteristics." }, { "code": null, "e": 10419, "s": 10191, "text": "We can clearly see groupings of books belonging to the same genre. It’s not perfect, but it’s still impressive that we can represent all books on Wikipedia using just 2 numbers that still capture the variability between genres." }, { "code": null, "e": 10666, "s": 10419, "text": "The book example (full article coming soon) shows the value of neural network embeddings: we have a vector representation of categorical objects that is both low-dimensional and places similar entities closer to one another in the embedded space." }, { "code": null, "e": 11020, "s": 10666, "text": "The problem with static graphs is that we can’t really explore the data and investigate groupings or relationships between variables. To solve this problem, TensorFlow developed projector, an online application that lets us visualize and interact with embeddings. I’ll release an article on how to use this tool shortly, but for now, here’s the results:" }, { "code": null, "e": 11314, "s": 11020, "text": "Neural network embeddings are learned low-dimensional representations of discrete data as continuous vectors. These embeddings overcome the limitations of traditional encoding methods and can be used for purposes such as finding nearest neighbors, input into another model, and visualizations." }, { "code": null, "e": 11703, "s": 11314, "text": "Although many deep learning concepts are talked about in academic terms, neural network embeddings are both intuitive and relatively simple to implement. I firmly believe that anyone can learn deep learning and use libraries such as Keras to build deep learning solutions. Embeddings are an effective tool for handling discrete variables and present a useful application of deep learning." }, { "code": null, "e": 11742, "s": 11703, "text": "Google-Produced tutorial on embeddings" }, { "code": null, "e": 11773, "s": 11742, "text": "TensorFlow Guide to Embeddings" }, { "code": null, "e": 11817, "s": 11773, "text": "Book Recommendation System Using Embeddings" }, { "code": null, "e": 11854, "s": 11817, "text": "Tutorial on Word Embeddings in Keras" } ]
MySQL Tryit Editor v1.0
SELECT CustomerName, LENGTH(CustomerName) AS LengthOfName FROM Customers; ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, and Opera. If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 58, "s": 0, "text": "SELECT CustomerName, LENGTH(CustomerName) AS LengthOfName" }, { "code": null, "e": 74, "s": 58, "text": "FROM Customers;" }, { "code": null, "e": 76, "s": 74, "text": "​" }, { "code": null, "e": 148, "s": 85, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 208, "s": 148, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 276, "s": 208, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 314, "s": 276, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 399, "s": 314, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 573, "s": 399, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 624, "s": 573, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 692, "s": 624, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 863, "s": 692, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 963, "s": 863, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 1013, "s": 963, "text": "WebSQL is supported in Chrome, Safari, and Opera." } ]
How to share x axes of two subplots after they have been created in Matplotlib?
First, we can create two axes using the subplot method where nrows=2, ncols=1. That means, we can have two indices to plot the desired plot. We can use ax1.get_shared_x_axes().join(ax1,ax2) method for our plot. Create two lists of the numbers. Create two lists of the numbers. Add a subplot to the current figure, ax1, where nrows = 2, ncols = 1, and index is 1 for ax1. Add a subplot to the current figure, ax1, where nrows = 2, ncols = 1, and index is 1 for ax1. Add a subplot to the current figure, ax2, where nrows = 2, ncols = 1, and index is 2 for ax2. Add a subplot to the current figure, ax2, where nrows = 2, ncols = 1, and index is 2 for ax2. Plot x and y using points that are created in step 1. Plot x and y using points that are created in step 1. Using get_shared_x_axes().join(ax1, ax2), return a reference to the shared axes Grouper object for axes. Using get_shared_x_axes().join(ax1, ax2), return a reference to the shared axes Grouper object for axes. Set X-axis tick labels of the grid, with empty list, using set_xticklabels method. Set X-axis tick labels of the grid, with empty list, using set_xticklabels method. Use plt.show() to show the figure. Use plt.show() to show the figure. import matplotlib.pyplot as plt x = [2, 4, 6, 8, 9] y = [12, 40, 16, 81, 19] ax1 = plt.subplot(211) ax2 = plt.subplot(212) ax1.plot(y, x) ax2.plot(x, y) ax1.get_shared_x_axes().join(ax1, ax2) ax1.set_xticklabels([]) plt.show()
[ { "code": null, "e": 1273, "s": 1062, "text": "First, we can create two axes using the subplot method where nrows=2, ncols=1. That means, we can have two indices to plot the desired plot. We can use ax1.get_shared_x_axes().join(ax1,ax2) method for our plot." }, { "code": null, "e": 1306, "s": 1273, "text": "Create two lists of the numbers." }, { "code": null, "e": 1339, "s": 1306, "text": "Create two lists of the numbers." }, { "code": null, "e": 1433, "s": 1339, "text": "Add a subplot to the current figure, ax1, where nrows = 2, ncols = 1, and index is 1 for ax1." }, { "code": null, "e": 1527, "s": 1433, "text": "Add a subplot to the current figure, ax1, where nrows = 2, ncols = 1, and index is 1 for ax1." }, { "code": null, "e": 1621, "s": 1527, "text": "Add a subplot to the current figure, ax2, where nrows = 2, ncols = 1, and index is 2 for ax2." }, { "code": null, "e": 1715, "s": 1621, "text": "Add a subplot to the current figure, ax2, where nrows = 2, ncols = 1, and index is 2 for ax2." }, { "code": null, "e": 1769, "s": 1715, "text": "Plot x and y using points that are created in step 1." }, { "code": null, "e": 1823, "s": 1769, "text": "Plot x and y using points that are created in step 1." }, { "code": null, "e": 1928, "s": 1823, "text": "Using get_shared_x_axes().join(ax1, ax2), return a reference to the shared axes Grouper object for axes." }, { "code": null, "e": 2033, "s": 1928, "text": "Using get_shared_x_axes().join(ax1, ax2), return a reference to the shared axes Grouper object for axes." }, { "code": null, "e": 2116, "s": 2033, "text": "Set X-axis tick labels of the grid, with empty list, using set_xticklabels method." }, { "code": null, "e": 2199, "s": 2116, "text": "Set X-axis tick labels of the grid, with empty list, using set_xticklabels method." }, { "code": null, "e": 2234, "s": 2199, "text": "Use plt.show() to show the figure." }, { "code": null, "e": 2269, "s": 2234, "text": "Use plt.show() to show the figure." }, { "code": null, "e": 2501, "s": 2269, "text": "import matplotlib.pyplot as plt\n\nx = [2, 4, 6, 8, 9]\ny = [12, 40, 16, 81, 19]\n\nax1 = plt.subplot(211)\nax2 = plt.subplot(212)\n\nax1.plot(y, x)\nax2.plot(x, y)\n\nax1.get_shared_x_axes().join(ax1, ax2)\nax1.set_xticklabels([])\n\nplt.show()" } ]
Longest balanced binary substring with equal count of 1s and 0s - GeeksforGeeks
06 Dec, 2021 Given a binary string str[] of size N. The task is to find the longest balanced substring. A substring is balanced if it contains an equal number of 0 and 1. Examples: Input: str = “110101010”Output: 10101010Explanation: The formed substring contain equal count of 1 and 0 i.e, count of 1 and 0 is same equal to 4. Input: str = “0000”Output: -1 Naive Approach: A simple solution is to use two nested loops to generate every substring. And a third loop to count a number of 0s and 1s in the current substring. Then print the longest substring among them. Time Complexity: O(N^3)Auxiliary Space: O(1) Efficient solution: With the help of precomputation, store the difference between the count of 0s and the count of 1s from start till current index. This difference can then be used to determine the longest substring with equal 0s and 1s, as the longest distance between any duplicate values in the difference array. Use a Map-based hashing to do precomputation. Follow the steps below to solve the problem: Initialize the map<int, int> m[]. Set the value of m[0] as -1. Initialize the variables count_0, count_1, res, start and end. Traverse the string str[] using the variable i and perform the following tasks:Keep the track of counts of 1s and 0s as count_1 and count_0 respectively.See if the current difference between count_1 and count_0 is already there in the map m[] or not. If yes, then perform the following tasks:The substring from the previous appearance and current index has same number of 0s and 1s.If the current found substring’s length is greater than res then set the found substring as the answer so far.If it is appearing for the first time, store the current difference and the current index in the map i.e, m[count_1 – count_0] equals i. Keep the track of counts of 1s and 0s as count_1 and count_0 respectively. See if the current difference between count_1 and count_0 is already there in the map m[] or not. If yes, then perform the following tasks:The substring from the previous appearance and current index has same number of 0s and 1s.If the current found substring’s length is greater than res then set the found substring as the answer so far. The substring from the previous appearance and current index has same number of 0s and 1s. If the current found substring’s length is greater than res then set the found substring as the answer so far. If it is appearing for the first time, store the current difference and the current index in the map i.e, m[count_1 – count_0] equals i. If count_0 and count_1 are both 0, then print -1. Otherwise, print the substring from start to end. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ for finding length// of longest balanced substring#include <bits/stdc++.h>using namespace std; // Returns length of the longest substring// with equal number of zeros and ones.string stringLen(string str){ // Create a map to store differences // between counts of 1s and 0s. map<int, int> m; // Initially difference is 0. m[0] = -1; int count_0 = 0, count_1 = 0; int start, end, res = 0; for (int i = 0; i < str.size(); i++) { // Keeping track of counts of // 0s and 1s. if (str[i] == '0') count_0++; else count_1++; // If difference between current counts // already exists, then substring between // previous and current index has same // no. of 0s and 1s. Update result if this // substring is more than current result. if (m.find(count_1 - count_0) != m.end()) { if ((i - m[count_1 - count_0]) > res) { start = m.find( count_1 - count_0) ->second; end = i; res = end - start; } } // If current difference // is seen first time. else m[count_1 - count_0] = i; } if (count_0 == 0 || count_1 == 0) return "-1"; // Return the substring // between found indices return str.substr(start + 1, end + 1);} // Driver Codeint main(){ string str = "110101010"; cout << stringLen(str); return 0;} // Java code for the above approachimport java.io.*;class GFG{ // Returns length of the longest substring // with equal number of zeros and ones. static String stringLen(String str) { // Create a map to store differences // between counts of 1s and 0s. int [] m = new int[100000]; // Initially difference is 0. m[0] = -1; int count_0 = 0; int count_1 = 0; int start = 0; int end = 0; int res = 0; for (int i = 0; i < str.length(); i++) { // Keeping track of counts of // 0s and 1s. if (str.charAt(i) == '0') count_0++; else count_1++; // If difference between current counts // already exists, then substring between // previous and current index has same // no. of 0s and 1s. Update result if this // substring is more than current result. if (m[count_1 - count_0]!= 0) { if ((i - m[count_1 - count_0]) > res) { start = m[count_1 - count_0]; end = i; res = end - start; } } // If current difference // is seen first time. else m[count_1 - count_0] = i; } if (count_0 == 0 || count_1 == 0) return "-1"; // Return the substring // between found indices return str.substring(start , end + 2); } // Driver Code public static void main (String[] args) { String str = "110101010"; System.out.println(stringLen(str)); }} // This code is contributed by Potta Lokesh # Python for finding length# of longest balanced substring # Returns length of the longest substring# with equal number of zeros and ones.def stringLen (str) : # Create a map to store differences # between counts of 1s and 0s. m = {} # Initially difference is 0. m[0] = -1 count_0 = 0 count_1 = 0 res = 0 for i in range(len(str)): # Keeping track of counts of # 0s and 1s. if (str[i] == '0'): count_0 += 1 else: count_1 += 1 # If difference between current counts # already exists, then substring between # previous and current index has same # no. of 0s and 1s. Update result if this # substring is more than current result. if ((count_1 - count_0) in m): if ((i - m[count_1 - count_0]) > res): start = m[(count_1 - count_0)] end = i res = end - start # If current difference # is seen first time. else: m[count_1 - count_0] = i if (count_0 == 0 or count_1 == 0): return "-1" # Return the substring # between found indices return str[start + 1 : start + 1 + end + 1] # Driver Codestr = "110101010"print(stringLen(str)) # This code is contributed by Saurabh Jaiswal // C# code for the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Returns length of the longest substring // with equal number of zeros and ones. static string stringLen(string str) { // Create a map to store differences // between counts of 1s and 0s. int []m = new int[100000]; // Initially difference is 0. m[0] = -1; int count_0 = 0; int count_1 = 0; int start = 0; int end = 0; int res = 0; for (int i = 0; i < str.Length; i++) { // Keeping track of counts of // 0s and 1s. if (str[i] == '0') count_0++; else count_1++; // If difference between current counts // already exists, then substring between // previous and current index has same // no. of 0s and 1s. Update result if this // substring is more than current result. if (m[count_1 - count_0]!= 0) { if ((i - m[count_1 - count_0]) > res) { start = m[count_1 - count_0]; end = i; res = end - start; } } // If current difference // is seen first time. else m[count_1 - count_0] = i; } if (count_0 == 0 || count_1 == 0) return "-1"; // Return the substring // between found indices return str.Substring(start, end - start + 2); } // Driver Code public static void Main () { string str = "110101010"; Console.Write(stringLen(str)); }} // This code is contributed by Samim Hossain Mondal. <script> // JavaScript for finding length // of longest balanced substring // Returns length of the longest substring // with equal number of zeros and ones. const stringLen = (str) => { // Create a map to store differences // between counts of 1s and 0s. let m = {}; // Initially difference is 0. m[0] = -1; let count_0 = 0, count_1 = 0; let start, end, res = 0; for (let i = 0; i < str.length; i++) { // Keeping track of counts of // 0s and 1s. if (str[i] == '0') count_0++; else count_1++; // If difference between current counts // already exists, then substring between // previous and current index has same // no. of 0s and 1s. Update result if this // substring is more than current result. if ((count_1 - count_0) in m) { if ((i - m[count_1 - count_0]) > res) { start = m[(count_1 - count_0)]; end = i; res = end - start; } } // If current difference // is seen first time. else m[count_1 - count_0] = i; } if (count_0 == 0 || count_1 == 0) return "-1"; // Return the substring // between found indices return str.substring(start + 1, start + 1 + end + 1); } // Driver Code let str = "110101010"; document.write(stringLen(str)); // This code is contributed by rakeshsahni</script> 10101010 Time Complexity: O(N)Auxiliary Space: O(N) rakeshsahni lokeshpotta20 _saurabh_jaiswal samim2000 binary-string Arrays Bit Magic Hash Mathematical Strings Arrays Hash Strings Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Window Sliding Technique Program to find sum of elements in a given array Reversal algorithm for array rotation Find duplicates in O(n) time and O(1) extra space | Set 1 Trapping Rain Water Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Cyclic Redundancy Check and Modulo-2 Division Count set bits in an integer
[ { "code": null, "e": 24716, "s": 24688, "text": "\n06 Dec, 2021" }, { "code": null, "e": 24874, "s": 24716, "text": "Given a binary string str[] of size N. The task is to find the longest balanced substring. A substring is balanced if it contains an equal number of 0 and 1." }, { "code": null, "e": 24886, "s": 24874, "text": "Examples: " }, { "code": null, "e": 25033, "s": 24886, "text": "Input: str = “110101010”Output: 10101010Explanation: The formed substring contain equal count of 1 and 0 i.e, count of 1 and 0 is same equal to 4." }, { "code": null, "e": 25063, "s": 25033, "text": "Input: str = “0000”Output: -1" }, { "code": null, "e": 25317, "s": 25063, "text": "Naive Approach: A simple solution is to use two nested loops to generate every substring. And a third loop to count a number of 0s and 1s in the current substring. Then print the longest substring among them. Time Complexity: O(N^3)Auxiliary Space: O(1)" }, { "code": null, "e": 25725, "s": 25317, "text": "Efficient solution: With the help of precomputation, store the difference between the count of 0s and the count of 1s from start till current index. This difference can then be used to determine the longest substring with equal 0s and 1s, as the longest distance between any duplicate values in the difference array. Use a Map-based hashing to do precomputation. Follow the steps below to solve the problem:" }, { "code": null, "e": 25759, "s": 25725, "text": "Initialize the map<int, int> m[]." }, { "code": null, "e": 25788, "s": 25759, "text": "Set the value of m[0] as -1." }, { "code": null, "e": 25851, "s": 25788, "text": "Initialize the variables count_0, count_1, res, start and end." }, { "code": null, "e": 26480, "s": 25851, "text": "Traverse the string str[] using the variable i and perform the following tasks:Keep the track of counts of 1s and 0s as count_1 and count_0 respectively.See if the current difference between count_1 and count_0 is already there in the map m[] or not. If yes, then perform the following tasks:The substring from the previous appearance and current index has same number of 0s and 1s.If the current found substring’s length is greater than res then set the found substring as the answer so far.If it is appearing for the first time, store the current difference and the current index in the map i.e, m[count_1 – count_0] equals i." }, { "code": null, "e": 26555, "s": 26480, "text": "Keep the track of counts of 1s and 0s as count_1 and count_0 respectively." }, { "code": null, "e": 26895, "s": 26555, "text": "See if the current difference between count_1 and count_0 is already there in the map m[] or not. If yes, then perform the following tasks:The substring from the previous appearance and current index has same number of 0s and 1s.If the current found substring’s length is greater than res then set the found substring as the answer so far." }, { "code": null, "e": 26986, "s": 26895, "text": "The substring from the previous appearance and current index has same number of 0s and 1s." }, { "code": null, "e": 27097, "s": 26986, "text": "If the current found substring’s length is greater than res then set the found substring as the answer so far." }, { "code": null, "e": 27234, "s": 27097, "text": "If it is appearing for the first time, store the current difference and the current index in the map i.e, m[count_1 – count_0] equals i." }, { "code": null, "e": 27284, "s": 27234, "text": "If count_0 and count_1 are both 0, then print -1." }, { "code": null, "e": 27334, "s": 27284, "text": "Otherwise, print the substring from start to end." }, { "code": null, "e": 27385, "s": 27334, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 27389, "s": 27385, "text": "C++" }, { "code": null, "e": 27394, "s": 27389, "text": "Java" }, { "code": null, "e": 27402, "s": 27394, "text": "Python3" }, { "code": null, "e": 27405, "s": 27402, "text": "C#" }, { "code": null, "e": 27416, "s": 27405, "text": "Javascript" }, { "code": "// C++ for finding length// of longest balanced substring#include <bits/stdc++.h>using namespace std; // Returns length of the longest substring// with equal number of zeros and ones.string stringLen(string str){ // Create a map to store differences // between counts of 1s and 0s. map<int, int> m; // Initially difference is 0. m[0] = -1; int count_0 = 0, count_1 = 0; int start, end, res = 0; for (int i = 0; i < str.size(); i++) { // Keeping track of counts of // 0s and 1s. if (str[i] == '0') count_0++; else count_1++; // If difference between current counts // already exists, then substring between // previous and current index has same // no. of 0s and 1s. Update result if this // substring is more than current result. if (m.find(count_1 - count_0) != m.end()) { if ((i - m[count_1 - count_0]) > res) { start = m.find( count_1 - count_0) ->second; end = i; res = end - start; } } // If current difference // is seen first time. else m[count_1 - count_0] = i; } if (count_0 == 0 || count_1 == 0) return \"-1\"; // Return the substring // between found indices return str.substr(start + 1, end + 1);} // Driver Codeint main(){ string str = \"110101010\"; cout << stringLen(str); return 0;}", "e": 28929, "s": 27416, "text": null }, { "code": "// Java code for the above approachimport java.io.*;class GFG{ // Returns length of the longest substring // with equal number of zeros and ones. static String stringLen(String str) { // Create a map to store differences // between counts of 1s and 0s. int [] m = new int[100000]; // Initially difference is 0. m[0] = -1; int count_0 = 0; int count_1 = 0; int start = 0; int end = 0; int res = 0; for (int i = 0; i < str.length(); i++) { // Keeping track of counts of // 0s and 1s. if (str.charAt(i) == '0') count_0++; else count_1++; // If difference between current counts // already exists, then substring between // previous and current index has same // no. of 0s and 1s. Update result if this // substring is more than current result. if (m[count_1 - count_0]!= 0) { if ((i - m[count_1 - count_0]) > res) { start = m[count_1 - count_0]; end = i; res = end - start; } } // If current difference // is seen first time. else m[count_1 - count_0] = i; } if (count_0 == 0 || count_1 == 0) return \"-1\"; // Return the substring // between found indices return str.substring(start , end + 2); } // Driver Code public static void main (String[] args) { String str = \"110101010\"; System.out.println(stringLen(str)); }} // This code is contributed by Potta Lokesh", "e": 30393, "s": 28929, "text": null }, { "code": "# Python for finding length# of longest balanced substring # Returns length of the longest substring# with equal number of zeros and ones.def stringLen (str) : # Create a map to store differences # between counts of 1s and 0s. m = {} # Initially difference is 0. m[0] = -1 count_0 = 0 count_1 = 0 res = 0 for i in range(len(str)): # Keeping track of counts of # 0s and 1s. if (str[i] == '0'): count_0 += 1 else: count_1 += 1 # If difference between current counts # already exists, then substring between # previous and current index has same # no. of 0s and 1s. Update result if this # substring is more than current result. if ((count_1 - count_0) in m): if ((i - m[count_1 - count_0]) > res): start = m[(count_1 - count_0)] end = i res = end - start # If current difference # is seen first time. else: m[count_1 - count_0] = i if (count_0 == 0 or count_1 == 0): return \"-1\" # Return the substring # between found indices return str[start + 1 : start + 1 + end + 1] # Driver Codestr = \"110101010\"print(stringLen(str)) # This code is contributed by Saurabh Jaiswal", "e": 31711, "s": 30393, "text": null }, { "code": "// C# code for the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Returns length of the longest substring // with equal number of zeros and ones. static string stringLen(string str) { // Create a map to store differences // between counts of 1s and 0s. int []m = new int[100000]; // Initially difference is 0. m[0] = -1; int count_0 = 0; int count_1 = 0; int start = 0; int end = 0; int res = 0; for (int i = 0; i < str.Length; i++) { // Keeping track of counts of // 0s and 1s. if (str[i] == '0') count_0++; else count_1++; // If difference between current counts // already exists, then substring between // previous and current index has same // no. of 0s and 1s. Update result if this // substring is more than current result. if (m[count_1 - count_0]!= 0) { if ((i - m[count_1 - count_0]) > res) { start = m[count_1 - count_0]; end = i; res = end - start; } } // If current difference // is seen first time. else m[count_1 - count_0] = i; } if (count_0 == 0 || count_1 == 0) return \"-1\"; // Return the substring // between found indices return str.Substring(start, end - start + 2); } // Driver Code public static void Main () { string str = \"110101010\"; Console.Write(stringLen(str)); }} // This code is contributed by Samim Hossain Mondal.", "e": 33216, "s": 31711, "text": null }, { "code": "<script> // JavaScript for finding length // of longest balanced substring // Returns length of the longest substring // with equal number of zeros and ones. const stringLen = (str) => { // Create a map to store differences // between counts of 1s and 0s. let m = {}; // Initially difference is 0. m[0] = -1; let count_0 = 0, count_1 = 0; let start, end, res = 0; for (let i = 0; i < str.length; i++) { // Keeping track of counts of // 0s and 1s. if (str[i] == '0') count_0++; else count_1++; // If difference between current counts // already exists, then substring between // previous and current index has same // no. of 0s and 1s. Update result if this // substring is more than current result. if ((count_1 - count_0) in m) { if ((i - m[count_1 - count_0]) > res) { start = m[(count_1 - count_0)]; end = i; res = end - start; } } // If current difference // is seen first time. else m[count_1 - count_0] = i; } if (count_0 == 0 || count_1 == 0) return \"-1\"; // Return the substring // between found indices return str.substring(start + 1, start + 1 + end + 1); } // Driver Code let str = \"110101010\"; document.write(stringLen(str)); // This code is contributed by rakeshsahni</script>", "e": 34837, "s": 33216, "text": null }, { "code": null, "e": 34846, "s": 34837, "text": "10101010" }, { "code": null, "e": 34889, "s": 34846, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 34901, "s": 34889, "text": "rakeshsahni" }, { "code": null, "e": 34915, "s": 34901, "text": "lokeshpotta20" }, { "code": null, "e": 34932, "s": 34915, "text": "_saurabh_jaiswal" }, { "code": null, "e": 34942, "s": 34932, "text": "samim2000" }, { "code": null, "e": 34956, "s": 34942, "text": "binary-string" }, { "code": null, "e": 34963, "s": 34956, "text": "Arrays" }, { "code": null, "e": 34973, "s": 34963, "text": "Bit Magic" }, { "code": null, "e": 34978, "s": 34973, "text": "Hash" }, { "code": null, "e": 34991, "s": 34978, "text": "Mathematical" }, { "code": null, "e": 34999, "s": 34991, "text": "Strings" }, { "code": null, "e": 35006, "s": 34999, "text": "Arrays" }, { "code": null, "e": 35011, "s": 35006, "text": "Hash" }, { "code": null, "e": 35019, "s": 35011, "text": "Strings" }, { "code": null, "e": 35032, "s": 35019, "text": "Mathematical" }, { "code": null, "e": 35042, "s": 35032, "text": "Bit Magic" }, { "code": null, "e": 35140, "s": 35042, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35149, "s": 35140, "text": "Comments" }, { "code": null, "e": 35162, "s": 35149, "text": "Old Comments" }, { "code": null, "e": 35187, "s": 35162, "text": "Window Sliding Technique" }, { "code": null, "e": 35236, "s": 35187, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 35274, "s": 35236, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 35332, "s": 35274, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 35352, "s": 35332, "text": "Trapping Rain Water" }, { "code": null, "e": 35379, "s": 35352, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 35425, "s": 35379, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 35493, "s": 35425, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 35539, "s": 35493, "text": "Cyclic Redundancy Check and Modulo-2 Division" } ]
Linux Admin - Traffic Monitoring in CentOS
There are several third party tools that can add enhanced capabilities for CentOS traffic monitoring. In this tutorial, we will focus on those that are packaged in the main CentOS distribution repositories and the Fedora EPEL repository. There will always be situations where an Administrator (for one reason or another) is left with only tools in the main CentOS repositories. Most utilities discussed are designed to be used by an Administrator with the shell of physical access. When traffic monitoring with an accessible web-gui, using third party utilities such as ntop-ng or Nagios is the best choice (versus re-creating such facilities from scratch). For further research on both configurable web-gui solutions, following are a few links to get started on research. Nagios Nagios has been around for a long time, therefore, it is both tried and tested. At one point it was all free and open-source, but has since advanced into an Enterprise solution with paid licensing models to support the need of Enterprise sophistication. Hence, before planning any rollouts with Nagios, make sure the open-source licensed versions will meet your needs or plan on spending with an Enterprise Budget in mind. Most open-source Nagios traffic monitoring software can be found at − https://www.nagios.org For a summarized history of Nagious, here is the official Nagios History page − https://www.nagios.org/about/history/ ntopng Another great tool allowing bandwidth and traffic monitoring via a web-gui is called ntopng. ntopng is similar to the Unix utility ntop, and can collect data for an entire LAN or WAN. Providing a web-gui for administration, configuration, and charting makes it easy to use for the entire IT Departments. Like Nagious, ntopng has both open-source and paid enterprise versions available. For more information about ntopng, please visit the website: http://www.ntop.org/ To access some of the needed tools for traffic monitoring, we will need to configure our CentOS system to use the EPEL Repository. The EPEL Repository is not officially maintained or supported by CentOS. However, it is maintained by a group of Fedora Core volunteers to address the packages commonly used by Enterprise Linux professionals not included in either CentOS, Fedora Core, or Red Hat Linux Enterprise. Caution Remember, the EPEL Repository is not official for CentOS and may break compatibility and functionality on production servers with common dependencies. With that in mind, it is advised to always test on a non-production server running the same services as production before deploying on a system critical box. Really, the biggest advantage of using the EHEL Repository over any other third party repository with CentOS is that we can be sure the binaries are not tainted. It is considered a best practice to not use the repositories from an untrusted source. With all that said, the official EPEL Repository is so common with CentOS that it can be easily installed via YUM. [root@CentOS rdc]# yum -y install epel-release Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: repo1.dal.innoscale.net * extras: repo1.dal.innoscale.net * updates: mirror.hmc.edu Resolving Dependencies --> Running transaction check ---> Package epel-release.noarch 0:7-9 will be installed --> Finished Dependency Resolution Dependencies Resolved --{ condensed output }-- After installing the EPEL Repository, we will want to update it. [root@CentOS rdc]# yum repolist Loaded plugins: fastestmirror, langpacks epel/x86_64/metalink | 11 kB 00:00:00 epel | 4.3 kB 00:00:00 (1/3): epel/x86_64/group_gz | 170 kB 00:00:00 (2/3): epel/x86_64/updateinfo | 753 kB 00:00:01 (3/3): epel/x86_64/primary_db --{ condensed output }-- At this point, our EPEL repository should be configured and ready to use. Let's start by installing nload for interface bandwidth monitoring. The tools we will focus on in this tutorial are − nload ntop ifstst iftop vnstat net hogs Wireshark TCP Dump Traceroute These are all standard for monitoring traffic in Linux Enterprises. The usage of each range from simple to advanced, so we will only briefly discuss tools such as Wireshark and TCP Dump. With our EPEL Repositories installed and configured in CentOS, we now should be able to install and use nload. This utility is designed to chart bandwidth per interface in real-time. Like most other basic installs nload is installed via the YUM package manager. [root@CentOS rdc]# yum -y install nload Resolving Dependencies --> Running transaction check ---> Package nload.x86_64 0:0.7.4-4.el7 will be installed --> Finished Dependency Resolution Dependencies Resolved =============================================================================== =============================================================================== Package Arch Version Repository Size =============================================================================== =============================================================================== Installing: nload x86_64 0.7.4-4.el7 epel 70 k Transaction Summary =============================================================================== =============================================================================== Install 1 Package Total download size: 70 k Installed size: 176 k Downloading packages: --{ condensed output }-- Now we have nload installed, and using it is pretty straight forward. [root@CentOS rdc]# nload enp0s5 nload will monitor the specified interface. In this case, enp0s5 an Ethernet interface, in real-time from the terminal for network traffic loads and total bandwidth usage. As seen, nload will chart both incoming and outgoing data from the specified interface, along with providing a physical representation of the data flow with hash marks "#". The depicted screenshot is of a simple webpage being loaded with some background daemon traffic. Common command line switches for nload are − The standard syntax for nload is − nload [options] <interface> If no interface is specified, nload will automatically grab the first Ethernet interface. Let's try measuring the total data in/out in Megabytes and current data-transfer speeds in Megabits. [root@CentOS rdc]# nload -U M -u m Data coming in/out the current interface is measured in megabits per second and each "Ttl" row, representing total data in/out is displayed in Megabytes. nload is useful for an administrator to see how much data has passed through an interface and how much data is currently coming in/out a specified interface. To see other interfaces without closing nload, simply use the left/right arrow keys. This will cycle through all available interfaces on the system. It is possible to monitor multiple interfaces simultaneously using the -m switch − [root@CentOS rdc]# nload -u K -U M -m lo -m enp0s5 load monitoring two interfaces simultaneously (lo and enp0s5) − 57 Lectures 7.5 hours Mamta Tripathi 25 Lectures 3 hours Lets Kode It 14 Lectures 1.5 hours Abhilash Nelson 58 Lectures 2.5 hours Frahaan Hussain 129 Lectures 23 hours Eduonix Learning Solutions 23 Lectures 5 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2495, "s": 2257, "text": "There are several third party tools that can add enhanced capabilities for CentOS traffic monitoring. In this tutorial, we will focus on those that are packaged in the main CentOS distribution repositories and the Fedora EPEL repository." }, { "code": null, "e": 2915, "s": 2495, "text": "There will always be situations where an Administrator (for one reason or another) is left with only tools in the main CentOS repositories. Most utilities discussed are designed to be used by an Administrator with the shell of physical access. When traffic monitoring with an accessible web-gui, using third party utilities such as ntop-ng or Nagios is the best choice (versus re-creating such facilities from scratch)." }, { "code": null, "e": 3030, "s": 2915, "text": "For further research on both configurable web-gui solutions, following are a few links to get started on research." }, { "code": null, "e": 3037, "s": 3030, "text": "Nagios" }, { "code": null, "e": 3460, "s": 3037, "text": "Nagios has been around for a long time, therefore, it is both tried and tested. At one point it was all free and open-source, but has since advanced into an Enterprise solution with paid licensing models to support the need of Enterprise sophistication. Hence, before planning any rollouts with Nagios, make sure the open-source licensed versions will meet your needs or plan on spending with an Enterprise Budget in mind." }, { "code": null, "e": 3553, "s": 3460, "text": "Most open-source Nagios traffic monitoring software can be found at − https://www.nagios.org" }, { "code": null, "e": 3671, "s": 3553, "text": "For a summarized history of Nagious, here is the official Nagios History page − https://www.nagios.org/about/history/" }, { "code": null, "e": 3678, "s": 3671, "text": "ntopng" }, { "code": null, "e": 3982, "s": 3678, "text": "Another great tool allowing bandwidth and traffic monitoring via a web-gui is called ntopng. ntopng is similar to the Unix utility ntop, and can collect data for an entire LAN or WAN. Providing a web-gui for administration, configuration, and charting makes it easy to use for the entire IT Departments." }, { "code": null, "e": 4146, "s": 3982, "text": "Like Nagious, ntopng has both open-source and paid enterprise versions available. For more information about ntopng, please visit the website: http://www.ntop.org/" }, { "code": null, "e": 4277, "s": 4146, "text": "To access some of the needed tools for traffic monitoring, we will need to configure our CentOS system to use the EPEL Repository." }, { "code": null, "e": 4558, "s": 4277, "text": "The EPEL Repository is not officially maintained or supported by CentOS. However, it is maintained by a group of Fedora Core volunteers to address the packages commonly used by Enterprise Linux professionals not included in either CentOS, Fedora Core, or Red Hat Linux Enterprise." }, { "code": null, "e": 4566, "s": 4558, "text": "Caution" }, { "code": null, "e": 4875, "s": 4566, "text": "Remember, the EPEL Repository is not official for CentOS and may break compatibility and functionality on production servers with common dependencies. With that in mind, it is advised to always test on a non-production server running the same services as production before deploying on a system critical box." }, { "code": null, "e": 5124, "s": 4875, "text": "Really, the biggest advantage of using the EHEL Repository over any other third party repository with CentOS is that we can be sure the binaries are not tainted. It is considered a best practice to not use the repositories from an untrusted source." }, { "code": null, "e": 5239, "s": 5124, "text": "With all that said, the official EPEL Repository is so common with CentOS that it can be easily installed via YUM." }, { "code": null, "e": 5669, "s": 5239, "text": "[root@CentOS rdc]# yum -y install epel-release\n Loaded plugins: fastestmirror, langpacks\n Loading mirror speeds from cached hostfile\n * base: repo1.dal.innoscale.net\n * extras: repo1.dal.innoscale.net\n * updates: mirror.hmc.edu\nResolving Dependencies\n --> Running transaction check\n ---> Package epel-release.noarch 0:7-9 will be installed\n --> Finished Dependency Resolution\nDependencies Resolved\n--{ condensed output }--\n" }, { "code": null, "e": 5734, "s": 5669, "text": "After installing the EPEL Repository, we will want to update it." }, { "code": null, "e": 6049, "s": 5734, "text": "[root@CentOS rdc]# yum repolist \nLoaded plugins: fastestmirror, langpacks \nepel/x86_64/metalink\n| 11 kB 00:00:00 \nepel\n| 4.3 kB 00:00:00 \n(1/3): epel/x86_64/group_gz\n| 170 kB 00:00:00 \n(2/3): epel/x86_64/updateinfo\n| 753 kB 00:00:01 \n(3/3): epel/x86_64/primary_db\n--{ condensed output }--\n" }, { "code": null, "e": 6191, "s": 6049, "text": "At this point, our EPEL repository should be configured and ready to use. Let's start by installing nload for interface bandwidth monitoring." }, { "code": null, "e": 6241, "s": 6191, "text": "The tools we will focus on in this tutorial are −" }, { "code": null, "e": 6247, "s": 6241, "text": "nload" }, { "code": null, "e": 6252, "s": 6247, "text": "ntop" }, { "code": null, "e": 6259, "s": 6252, "text": "ifstst" }, { "code": null, "e": 6265, "s": 6259, "text": "iftop" }, { "code": null, "e": 6272, "s": 6265, "text": "vnstat" }, { "code": null, "e": 6281, "s": 6272, "text": "net hogs" }, { "code": null, "e": 6291, "s": 6281, "text": "Wireshark" }, { "code": null, "e": 6300, "s": 6291, "text": "TCP Dump" }, { "code": null, "e": 6311, "s": 6300, "text": "Traceroute" }, { "code": null, "e": 6498, "s": 6311, "text": "These are all standard for monitoring traffic in Linux Enterprises. The usage of each range from simple to advanced, so we will only briefly discuss tools such as Wireshark and TCP Dump." }, { "code": null, "e": 6681, "s": 6498, "text": "With our EPEL Repositories installed and configured in CentOS, we now should be able to install and use nload. This utility is designed to chart bandwidth per interface in real-time." }, { "code": null, "e": 6760, "s": 6681, "text": "Like most other basic installs nload is installed via the YUM package manager." }, { "code": null, "e": 7844, "s": 6760, "text": "[root@CentOS rdc]# yum -y install nload\nResolving Dependencies\n--> Running transaction check\n---> Package nload.x86_64 0:0.7.4-4.el7 will be installed\n--> Finished Dependency Resolution\nDependencies Resolved\n=============================================================================== \n=============================================================================== \n Package Arch\n Version Repository Size \n=============================================================================== \n=============================================================================== \nInstalling: \n nload x86_64\n 0.7.4-4.el7 epel 70 k \nTransaction Summary\n=============================================================================== \n=============================================================================== \nInstall 1 Package\nTotal download size: 70 k\nInstalled size: 176 k\nDownloading packages:\n--{ condensed output }--\n" }, { "code": null, "e": 7914, "s": 7844, "text": "Now we have nload installed, and using it is pretty straight forward." }, { "code": null, "e": 7947, "s": 7914, "text": "[root@CentOS rdc]# nload enp0s5\n" }, { "code": null, "e": 8119, "s": 7947, "text": "nload will monitor the specified interface. In this case, enp0s5 an Ethernet interface, in real-time from the terminal for network traffic loads and total bandwidth usage." }, { "code": null, "e": 8292, "s": 8119, "text": "As seen, nload will chart both incoming and outgoing data from the specified interface, along with providing a physical representation of the data flow with hash marks \"#\"." }, { "code": null, "e": 8389, "s": 8292, "text": "The depicted screenshot is of a simple webpage being loaded with some background daemon traffic." }, { "code": null, "e": 8434, "s": 8389, "text": "Common command line switches for nload are −" }, { "code": null, "e": 8469, "s": 8434, "text": "The standard syntax for nload is −" }, { "code": null, "e": 8498, "s": 8469, "text": "nload [options] <interface>\n" }, { "code": null, "e": 8689, "s": 8498, "text": "If no interface is specified, nload will automatically grab the first Ethernet interface. Let's try measuring the total data in/out in Megabytes and current data-transfer speeds in Megabits." }, { "code": null, "e": 8725, "s": 8689, "text": "[root@CentOS rdc]# nload -U M -u m\n" }, { "code": null, "e": 8879, "s": 8725, "text": "Data coming in/out the current interface is measured in megabits per second and each \"Ttl\" row, representing total data in/out is displayed in Megabytes." }, { "code": null, "e": 9037, "s": 8879, "text": "nload is useful for an administrator to see how much data has passed through an interface and how much data is currently coming in/out a specified interface." }, { "code": null, "e": 9186, "s": 9037, "text": "To see other interfaces without closing nload, simply use the left/right arrow keys. This will cycle through all available interfaces on the system." }, { "code": null, "e": 9269, "s": 9186, "text": "It is possible to monitor multiple interfaces simultaneously using the -m switch −" }, { "code": null, "e": 9321, "s": 9269, "text": "[root@CentOS rdc]# nload -u K -U M -m lo -m enp0s5\n" }, { "code": null, "e": 9385, "s": 9321, "text": "load monitoring two interfaces simultaneously (lo and enp0s5) −" }, { "code": null, "e": 9420, "s": 9385, "text": "\n 57 Lectures \n 7.5 hours \n" }, { "code": null, "e": 9436, "s": 9420, "text": " Mamta Tripathi" }, { "code": null, "e": 9469, "s": 9436, "text": "\n 25 Lectures \n 3 hours \n" }, { "code": null, "e": 9483, "s": 9469, "text": " Lets Kode It" }, { "code": null, "e": 9518, "s": 9483, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9535, "s": 9518, "text": " Abhilash Nelson" }, { "code": null, "e": 9570, "s": 9535, "text": "\n 58 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9587, "s": 9570, "text": " Frahaan Hussain" }, { "code": null, "e": 9622, "s": 9587, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 9650, "s": 9622, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 9683, "s": 9650, "text": "\n 23 Lectures \n 5 hours \n" }, { "code": null, "e": 9723, "s": 9683, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 9730, "s": 9723, "text": " Print" }, { "code": null, "e": 9741, "s": 9730, "text": " Add Notes" } ]
Tryit Editor v3.7
Tryit: HTML table - set row height
[]
How to add a new column to a PySpark DataFrame ? - GeeksforGeeks
13 Jan, 2022 In this article, we will discuss how to add a new column to PySpark Dataframe. Create the first data frame for demonstration: Here, we will be creating the sample data frame which we will be used further to demonstrate the approach purpose. Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) dataframe.show() Output: In this approach to add a new column with constant values, the user needs to call the lit() function parameter of the withColumn() function and pass the required parameters into these functions. Here, the lit() is available in pyspark.sql. Functions module. Syntax: dataframe.withColumn("column_name", lit(value)) where, dataframe is the pyspark input dataframe column_name is the new column to be added value is the constant value to be assigned to this column Example: In this example, we add a column named salary with a value of 34000 to the above dataframe using the withColumn() function with the lit() function as its parameter in the python programming language. Python3 # importing moduleimport pyspark # import lit functionfrom pyspark.sql.functions import lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Add a column named salary with value as 34000dataframe.withColumn("salary", lit(34000)).show() Output: Under this approach, the user can add a new column based on an existing column in the given dataframe. Here, under this example, the user needs to specify the existing column using the withColumn() function with the required parameters passed in the python programming language. Syntax: dataframe.withColumn("column_name", dataframe.existing_column) where, dataframe is the input dataframe column_name is the new column existing_column is the column which is existed In this example, we are adding a column named salary from the ID column with multiply of 2300 using the withColumn() method in the python language, Python3 # importing moduleimport pyspark # import lit functionfrom pyspark.sql.functions import lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Add a column named salary from ID column with multiply of 2300dataframe.withColumn("salary", dataframe.ID*2300).show() Output: Under this example, the user has to concat the two existing columns and make them as a new column by importing this method from pyspark.sql.functions module. Syntax: dataframe.withColumn(“column_name”, concat_ws(“Separator”,”existing_column1′′,’existing_column2′)) where, dataframe is the input dataframe column_name is the new column name existing_column1 and existing_column2 are the two columns to be added with Separator to make values to the new column Separator is like the operator between values with two columns Example: In this example, we add a column named Details from Name and Company columns separated by “-” in the python language. Python3 # importing moduleimport pyspark # import concat_ws functionfrom pyspark.sql.functions import concat_ws # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Add a column named Details from Name and Company columns separated by -dataframe.withColumn("Details", concat_ws("-", "NAME", 'Company')).show() Output: In this method, the user can add a column when it is not existed by adding a column with the lit() function and checking using if the condition. Syntax: if 'column_name' not in dataframe.columns: dataframe.withColumn("column_name",lit(value)) where, dataframe. columns are used to get the column names Example: In this example, we add a column of the salary to 34000 using the if condition with the withColumn() and the lit() function. Python3 # importing moduleimport pyspark # import concat_ws and lit functionfrom pyspark.sql.functions import concat_ws, lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # add salary column by checking its existenceif 'salary' not in dataframe.columns: dataframe.withColumn("salary", lit(34000)).show() Output: In this method, to add a column to a data frame, the user needs to call the select() function to add a column with lit() function and select() method. It will also display the selected columns. Syntax: dataframe.select(lit(value).alias("column_name")) where, dataframe is the input dataframe column_name is the new column Example: In this example, we add a salary column with a constant value of 34000 using the select() function with the lit() function as its parameter. Python3 # importing moduleimport pyspark # import concat_ws and lit functionfrom pyspark.sql.functions import concat_ws, lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # add salary column with constant value - 34000dataframe.select(lit(34000).alias("salary")).show() Output: In this method, the user has to use SQL expression with SQL function to add a column. Before that, we have to create a temporary view, From that view, we have to add and select columns. Syntax: dataframe.createOrReplaceTempView("name") spark.sql("select 'value' as column_name from view") where, dataframe is the input dataframe name is the temporary view name sql function will take SQL expression as input to add a column column_name is the new column name value is the column value Example: Add new column named salary with 34000 value Python3 # importing moduleimport pyspark # import concat_ws and lit functionfrom pyspark.sql.functions import concat_ws, lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # create viewdataframe.createOrReplaceTempView("view") # add new column named salary with 34000 valuespark.sql("select '34000' as salary from view").show() Output: Under this method, the user needs to use the when function along with withcolumn() method used to check the condition and add the column values based on existing column values. So we have to import when() from pyspark.sql.functions to add a specific column based on the given condition. Syntax: dataframe.withColumn(“column_name”, when((dataframe.column_name condition1), lit(“value1”)). when((dataframe.column_name condition2), lit(“value2”)). ——————— ——————— when((dataframe.column_name conditionn), lit(“value3”)). .otherwise(lit(“value”)) ) where, column_name is the new column name condition1 is the condition to check and assign value1 using lit() through when otherwise, it is the keyword used to check when no condition satisfies. Example: In this example, we add a new column named salary and add value 34000 when the name is sravan and add value 31000 when the name is ojsawi, or bobby otherwise adds 78000 using the when() and the withColumn() function. Python3 # importing moduleimport pyspark # import when and lit functionfrom pyspark.sql.functions import when, lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # add a new column named salary# add value 34000 when name is sravan# add value 31000 when name is ojsawi or bobby# otherwise add 78000dataframe.withColumn("salary", when((dataframe.NAME == "sravan"), lit("34000")). when((dataframe.NAME == "ojsawi") | ( dataframe.NAME == "bobby"), lit("31000")) .otherwise(lit("78000"))).show() Output: clintra Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Defaultdict in Python Create a directory in Python Python Classes and Objects
[ { "code": null, "e": 24212, "s": 24184, "text": "\n13 Jan, 2022" }, { "code": null, "e": 24291, "s": 24212, "text": "In this article, we will discuss how to add a new column to PySpark Dataframe." }, { "code": null, "e": 24338, "s": 24291, "text": "Create the first data frame for demonstration:" }, { "code": null, "e": 24453, "s": 24338, "text": "Here, we will be creating the sample data frame which we will be used further to demonstrate the approach purpose." }, { "code": null, "e": 24461, "s": 24453, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 1\"], [\"3\", \"rohith\", \"company 2\"], [\"4\", \"sridevi\", \"company 1\"], [\"5\", \"bobby\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) dataframe.show()", "e": 25066, "s": 24461, "text": null }, { "code": null, "e": 25074, "s": 25066, "text": "Output:" }, { "code": null, "e": 25332, "s": 25074, "text": "In this approach to add a new column with constant values, the user needs to call the lit() function parameter of the withColumn() function and pass the required parameters into these functions. Here, the lit() is available in pyspark.sql. Functions module." }, { "code": null, "e": 25340, "s": 25332, "text": "Syntax:" }, { "code": null, "e": 25388, "s": 25340, "text": "dataframe.withColumn(\"column_name\", lit(value))" }, { "code": null, "e": 25395, "s": 25388, "text": "where," }, { "code": null, "e": 25436, "s": 25395, "text": "dataframe is the pyspark input dataframe" }, { "code": null, "e": 25478, "s": 25436, "text": "column_name is the new column to be added" }, { "code": null, "e": 25536, "s": 25478, "text": "value is the constant value to be assigned to this column" }, { "code": null, "e": 25545, "s": 25536, "text": "Example:" }, { "code": null, "e": 25745, "s": 25545, "text": "In this example, we add a column named salary with a value of 34000 to the above dataframe using the withColumn() function with the lit() function as its parameter in the python programming language." }, { "code": null, "e": 25753, "s": 25745, "text": "Python3" }, { "code": "# importing moduleimport pyspark # import lit functionfrom pyspark.sql.functions import lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 1\"], [\"3\", \"rohith\", \"company 2\"], [\"4\", \"sridevi\", \"company 1\"], [\"5\", \"bobby\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Add a column named salary with value as 34000dataframe.withColumn(\"salary\", lit(34000)).show()", "e": 26497, "s": 25753, "text": null }, { "code": null, "e": 26505, "s": 26497, "text": "Output:" }, { "code": null, "e": 26608, "s": 26505, "text": "Under this approach, the user can add a new column based on an existing column in the given dataframe." }, { "code": null, "e": 26784, "s": 26608, "text": "Here, under this example, the user needs to specify the existing column using the withColumn() function with the required parameters passed in the python programming language." }, { "code": null, "e": 26792, "s": 26784, "text": "Syntax:" }, { "code": null, "e": 26855, "s": 26792, "text": "dataframe.withColumn(\"column_name\", dataframe.existing_column)" }, { "code": null, "e": 26862, "s": 26855, "text": "where," }, { "code": null, "e": 26895, "s": 26862, "text": "dataframe is the input dataframe" }, { "code": null, "e": 26925, "s": 26895, "text": "column_name is the new column" }, { "code": null, "e": 26972, "s": 26925, "text": "existing_column is the column which is existed" }, { "code": null, "e": 27120, "s": 26972, "text": "In this example, we are adding a column named salary from the ID column with multiply of 2300 using the withColumn() method in the python language," }, { "code": null, "e": 27128, "s": 27120, "text": "Python3" }, { "code": "# importing moduleimport pyspark # import lit functionfrom pyspark.sql.functions import lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 1\"], [\"3\", \"rohith\", \"company 2\"], [\"4\", \"sridevi\", \"company 1\"], [\"5\", \"bobby\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Add a column named salary from ID column with multiply of 2300dataframe.withColumn(\"salary\", dataframe.ID*2300).show()", "e": 27896, "s": 27128, "text": null }, { "code": null, "e": 27904, "s": 27896, "text": "Output:" }, { "code": null, "e": 28062, "s": 27904, "text": "Under this example, the user has to concat the two existing columns and make them as a new column by importing this method from pyspark.sql.functions module." }, { "code": null, "e": 28070, "s": 28062, "text": "Syntax:" }, { "code": null, "e": 28169, "s": 28070, "text": "dataframe.withColumn(“column_name”, concat_ws(“Separator”,”existing_column1′′,’existing_column2′))" }, { "code": null, "e": 28176, "s": 28169, "text": "where," }, { "code": null, "e": 28209, "s": 28176, "text": "dataframe is the input dataframe" }, { "code": null, "e": 28244, "s": 28209, "text": "column_name is the new column name" }, { "code": null, "e": 28362, "s": 28244, "text": "existing_column1 and existing_column2 are the two columns to be added with Separator to make values to the new column" }, { "code": null, "e": 28425, "s": 28362, "text": "Separator is like the operator between values with two columns" }, { "code": null, "e": 28434, "s": 28425, "text": "Example:" }, { "code": null, "e": 28552, "s": 28434, "text": "In this example, we add a column named Details from Name and Company columns separated by “-” in the python language." }, { "code": null, "e": 28560, "s": 28552, "text": "Python3" }, { "code": "# importing moduleimport pyspark # import concat_ws functionfrom pyspark.sql.functions import concat_ws # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 1\"], [\"3\", \"rohith\", \"company 2\"], [\"4\", \"sridevi\", \"company 1\"], [\"5\", \"bobby\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Add a column named Details from Name and Company columns separated by -dataframe.withColumn(\"Details\", concat_ws(\"-\", \"NAME\", 'Company')).show()", "e": 29366, "s": 28560, "text": null }, { "code": null, "e": 29374, "s": 29366, "text": "Output:" }, { "code": null, "e": 29519, "s": 29374, "text": "In this method, the user can add a column when it is not existed by adding a column with the lit() function and checking using if the condition." }, { "code": null, "e": 29527, "s": 29519, "text": "Syntax:" }, { "code": null, "e": 29620, "s": 29527, "text": "if 'column_name' not in dataframe.columns:\n dataframe.withColumn(\"column_name\",lit(value))" }, { "code": null, "e": 29627, "s": 29620, "text": "where," }, { "code": null, "e": 29679, "s": 29627, "text": "dataframe. columns are used to get the column names" }, { "code": null, "e": 29688, "s": 29679, "text": "Example:" }, { "code": null, "e": 29813, "s": 29688, "text": "In this example, we add a column of the salary to 34000 using the if condition with the withColumn() and the lit() function." }, { "code": null, "e": 29821, "s": 29813, "text": "Python3" }, { "code": "# importing moduleimport pyspark # import concat_ws and lit functionfrom pyspark.sql.functions import concat_ws, lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 1\"], [\"3\", \"rohith\", \"company 2\"], [\"4\", \"sridevi\", \"company 1\"], [\"5\", \"bobby\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # add salary column by checking its existenceif 'salary' not in dataframe.columns: dataframe.withColumn(\"salary\", lit(34000)).show()", "e": 30629, "s": 29821, "text": null }, { "code": null, "e": 30637, "s": 30629, "text": "Output:" }, { "code": null, "e": 30831, "s": 30637, "text": "In this method, to add a column to a data frame, the user needs to call the select() function to add a column with lit() function and select() method. It will also display the selected columns." }, { "code": null, "e": 30839, "s": 30831, "text": "Syntax:" }, { "code": null, "e": 30889, "s": 30839, "text": "dataframe.select(lit(value).alias(\"column_name\"))" }, { "code": null, "e": 30896, "s": 30889, "text": "where," }, { "code": null, "e": 30929, "s": 30896, "text": "dataframe is the input dataframe" }, { "code": null, "e": 30959, "s": 30929, "text": "column_name is the new column" }, { "code": null, "e": 30968, "s": 30959, "text": "Example:" }, { "code": null, "e": 31109, "s": 30968, "text": "In this example, we add a salary column with a constant value of 34000 using the select() function with the lit() function as its parameter." }, { "code": null, "e": 31117, "s": 31109, "text": "Python3" }, { "code": "# importing moduleimport pyspark # import concat_ws and lit functionfrom pyspark.sql.functions import concat_ws, lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 1\"], [\"3\", \"rohith\", \"company 2\"], [\"4\", \"sridevi\", \"company 1\"], [\"5\", \"bobby\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # add salary column with constant value - 34000dataframe.select(lit(34000).alias(\"salary\")).show()", "e": 31888, "s": 31117, "text": null }, { "code": null, "e": 31896, "s": 31888, "text": "Output:" }, { "code": null, "e": 32082, "s": 31896, "text": "In this method, the user has to use SQL expression with SQL function to add a column. Before that, we have to create a temporary view, From that view, we have to add and select columns." }, { "code": null, "e": 32090, "s": 32082, "text": "Syntax:" }, { "code": null, "e": 32185, "s": 32090, "text": "dataframe.createOrReplaceTempView(\"name\")\nspark.sql(\"select 'value' as column_name from view\")" }, { "code": null, "e": 32192, "s": 32185, "text": "where," }, { "code": null, "e": 32225, "s": 32192, "text": "dataframe is the input dataframe" }, { "code": null, "e": 32257, "s": 32225, "text": "name is the temporary view name" }, { "code": null, "e": 32320, "s": 32257, "text": "sql function will take SQL expression as input to add a column" }, { "code": null, "e": 32355, "s": 32320, "text": "column_name is the new column name" }, { "code": null, "e": 32381, "s": 32355, "text": "value is the column value" }, { "code": null, "e": 32390, "s": 32381, "text": "Example:" }, { "code": null, "e": 32435, "s": 32390, "text": "Add new column named salary with 34000 value" }, { "code": null, "e": 32443, "s": 32435, "text": "Python3" }, { "code": "# importing moduleimport pyspark # import concat_ws and lit functionfrom pyspark.sql.functions import concat_ws, lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 1\"], [\"3\", \"rohith\", \"company 2\"], [\"4\", \"sridevi\", \"company 1\"], [\"5\", \"bobby\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # create viewdataframe.createOrReplaceTempView(\"view\") # add new column named salary with 34000 valuespark.sql(\"select '34000' as salary from view\").show()", "e": 33271, "s": 32443, "text": null }, { "code": null, "e": 33279, "s": 33271, "text": "Output:" }, { "code": null, "e": 33566, "s": 33279, "text": "Under this method, the user needs to use the when function along with withcolumn() method used to check the condition and add the column values based on existing column values. So we have to import when() from pyspark.sql.functions to add a specific column based on the given condition." }, { "code": null, "e": 33574, "s": 33566, "text": "Syntax:" }, { "code": null, "e": 33610, "s": 33574, "text": "dataframe.withColumn(“column_name”," }, { "code": null, "e": 33688, "s": 33610, "text": " when((dataframe.column_name condition1), lit(“value1”))." }, { "code": null, "e": 33767, "s": 33688, "text": " when((dataframe.column_name condition2), lit(“value2”)). " }, { "code": null, "e": 33796, "s": 33767, "text": " ———————" }, { "code": null, "e": 33825, "s": 33796, "text": " ———————" }, { "code": null, "e": 33923, "s": 33825, "text": " when((dataframe.column_name conditionn), lit(“value3”)). " }, { "code": null, "e": 33971, "s": 33923, "text": " .otherwise(lit(“value”)) )" }, { "code": null, "e": 33978, "s": 33971, "text": "where," }, { "code": null, "e": 34013, "s": 33978, "text": "column_name is the new column name" }, { "code": null, "e": 34093, "s": 34013, "text": "condition1 is the condition to check and assign value1 using lit() through when" }, { "code": null, "e": 34165, "s": 34093, "text": "otherwise, it is the keyword used to check when no condition satisfies." }, { "code": null, "e": 34174, "s": 34165, "text": "Example:" }, { "code": null, "e": 34391, "s": 34174, "text": "In this example, we add a new column named salary and add value 34000 when the name is sravan and add value 31000 when the name is ojsawi, or bobby otherwise adds 78000 using the when() and the withColumn() function." }, { "code": null, "e": 34399, "s": 34391, "text": "Python3" }, { "code": "# importing moduleimport pyspark # import when and lit functionfrom pyspark.sql.functions import when, lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 1\"], [\"3\", \"rohith\", \"company 2\"], [\"4\", \"sridevi\", \"company 1\"], [\"5\", \"bobby\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # add a new column named salary# add value 34000 when name is sravan# add value 31000 when name is ojsawi or bobby# otherwise add 78000dataframe.withColumn(\"salary\", when((dataframe.NAME == \"sravan\"), lit(\"34000\")). when((dataframe.NAME == \"ojsawi\") | ( dataframe.NAME == \"bobby\"), lit(\"31000\")) .otherwise(lit(\"78000\"))).show()", "e": 35474, "s": 34399, "text": null }, { "code": null, "e": 35482, "s": 35474, "text": "Output:" }, { "code": null, "e": 35490, "s": 35482, "text": "clintra" }, { "code": null, "e": 35497, "s": 35490, "text": "Picked" }, { "code": null, "e": 35512, "s": 35497, "text": "Python-Pyspark" }, { "code": null, "e": 35519, "s": 35512, "text": "Python" }, { "code": null, "e": 35617, "s": 35519, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35626, "s": 35617, "text": "Comments" }, { "code": null, "e": 35639, "s": 35626, "text": "Old Comments" }, { "code": null, "e": 35671, "s": 35639, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 35726, "s": 35671, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 35782, "s": 35726, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 35821, "s": 35782, "text": "Python | Get unique values from a list" }, { "code": null, "e": 35863, "s": 35821, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 35905, "s": 35863, "text": "Check if element exists in list in Python" }, { "code": null, "e": 35936, "s": 35905, "text": "Python | os.path.join() method" }, { "code": null, "e": 35958, "s": 35936, "text": "Defaultdict in Python" }, { "code": null, "e": 35987, "s": 35958, "text": "Create a directory in Python" } ]
How to work the timezone using PowerShell?
To get the timezone of the System, you can use the Get-TimeZone command. PS C:\> Get-TimeZone Id : Mountain Standard Time DisplayName : (UTC-07:00) Mountain Time (US & Canada) StandardName : Mountain Standard Time DaylightName : Mountain Daylight Time BaseUtcOffset : -07:00:00 SupportsDaylightSavingTime : True To Set the TimeZone of the System, you can you the ID or the Name of the timezone. PS C:\> Set-TimeZone -Id "Pacific Standard Time" -PassThru Id : Pacific Standard Time DisplayName : (UTC-08:00) Pacific Time (US & Canada) StandardName : Pacific Standard Time DaylightName : Pacific Daylight Time BaseUtcOffset : -08:00:00 SupportsDaylightSavingTime : True To retrieve the list of all the available timezones we need to use System.TimeZoneInfo .net class and method GetSystemTimeZones(). [System.TimeZoneInfo]::GetSystemTimeZones() |ft -AutoSize
[ { "code": null, "e": 1135, "s": 1062, "text": "To get the timezone of the System, you can use the Get-TimeZone command." }, { "code": null, "e": 1455, "s": 1135, "text": "PS C:\\> Get-TimeZone\n\nId : Mountain Standard Time\nDisplayName : (UTC-07:00) Mountain Time (US & Canada)\nStandardName : Mountain Standard Time\nDaylightName : Mountain Daylight Time\nBaseUtcOffset : -07:00:00\nSupportsDaylightSavingTime : True" }, { "code": null, "e": 1538, "s": 1455, "text": "To Set the TimeZone of the System, you can you the ID or the Name of the timezone." }, { "code": null, "e": 1891, "s": 1538, "text": "PS C:\\> Set-TimeZone -Id \"Pacific Standard Time\" -PassThru\nId : Pacific Standard Time\nDisplayName : (UTC-08:00) Pacific Time (US & Canada)\nStandardName : Pacific Standard Time\nDaylightName : Pacific Daylight Time\nBaseUtcOffset : -08:00:00\nSupportsDaylightSavingTime : True" }, { "code": null, "e": 2022, "s": 1891, "text": "To retrieve the list of all the available timezones we need to use System.TimeZoneInfo .net class and method GetSystemTimeZones()." }, { "code": null, "e": 2080, "s": 2022, "text": "[System.TimeZoneInfo]::GetSystemTimeZones() |ft -AutoSize" } ]
The Flawless Pipes of Python/ Pandas | by Dr. Gregor Scheithauer | Towards Data Science
By trade I am an R person. Especially the Tidyverse is such a powerful, clean, easy-to-understand and well documented data science platform. I highly recommend to every beginner the free online book R for Data Science. However, my team’s programming language of choice is Python/ Pandas — which is also a wonderful data science platform. One of the major differences (to me, at least) is how we write Python code, which is very different to R code — that has nothing to do with the syntax in itself. One of R’s elegances is using the pipe functionality programming metaphor. This allows you write more efficient and readable code. One good example is the post by Soner Yıldırım The Flawless Pipes of Tidyverse. I would like to recreate his post and to show you how to use pipes (or method chaining) for Pandas. According to the r magrittr package [1] pipes allow you to write code with the following benefits: structuring sequences of data operations left-to-right (as opposed to from the inside and out), avoiding nested function calls, minimizing the need for local variables and function definitions, and making it easy to add steps anywhere in the sequence of operations. R example without using pipes (cf. [2]) What you see in the code below is a typical example. We might save a result of a function call in a variable, e.g. foo_foo_1 with the only reason to pass it into the very next function call, e.g., scoop(). This results in a number of variables with maybe not so meaningful names and as a consequence might increase the complexity of your code. foo_foo_1 <- hop(foo_foo, through = forest)foo_foo_2 <- scoop(foo_foo_1, up = field_mice)foo_foo_3 <- bop(foo_foo_2, on = head) R example with pipes (cf. [2]) Pipes in R are used with the syntax %>%. It allows you to chain your functions. In the example below try to read it in the following manner: I want to evaluate/ manipulate variable foo_fooI want foo_foo to hop trough the forest, and then,I want foo_foo to scoop up a field mice, and finally,I want foo_foo to bop on its head I want to evaluate/ manipulate variable foo_foo I want foo_foo to hop trough the forest, and then, I want foo_foo to scoop up a field mice, and finally, I want foo_foo to bop on its head foo_foo %>% hop(through = forest) %>% scoop(up = field_mice) %>% bop(on = head) Please note, how the data set is a noun and the functions are verbs. You might get the idea how it increases the code’s readability. For a better understanding how the piped code works the interpreted version is shown below: bop( scoop( hop(foo_foo, through = forest), up = field_mice ), on = head) Since there is no magrittr package in Python it has to work in a different way. We will make use of the fact that in Pandas most data frame functions return the data set itself. This is called method chaining. Let’s stick with the foo_foo example. A possible Python code might look like this: foo_foo_1 = hop(foo_foo, through = forest)foo_foo_2 = scoop(foo_foo_1, up = field_mice)foo_foo_3 = bop(foo_foo_2, on = head) Chaining it would look like this: foo_foo.hop(through = forest).scoop(up = field_mice).bop(on = head) This is close, but not exactly. Add one little adjustment, i.e., () brackets around the code to make it the way we want it. Please see the code below that shows how this looks like. ( foo_foo .hop(through = forest) .scoop(up = field_mice) .bop(on = head)) I love using this way of coding. Here are some of the benefits I see in using this programming metaphor: Your code is much more readable for other data scientists in your team (and your future self)You avoid the need for more or less meaningless local variablesYou are able to add or remove functions in your data evaluation quicklyYour code follows you line of thoughts (noun-verb-paradigma) during data evaluation and analysis Your code is much more readable for other data scientists in your team (and your future self) You avoid the need for more or less meaningless local variables You are able to add or remove functions in your data evaluation quickly Your code follows you line of thoughts (noun-verb-paradigma) during data evaluation and analysis [1] magrittr package[2] Pipes chapter in R for Data Science book I will follow the article of Soner Yıldırım in order for you to compare how to use pipes/ method chaining in R as well as in Python. Soner uses the Kaggle data set on Melbourne housing. You may download it and follow along with me. # import libsimport pandas as pd# read datamelb = pd.read_csv("../01-data/melb_data.csv")# Have a quick look at the data( melb .head()) The next example filters houses by Distances below 2, groups them by Type, and calculates the averages Prices for each Type. Then do some formatting. ( melb .query("Distance < 2") # query equals filter in Pandas .filter(["Type", "Price"]) # select the columns Type and Price .groupby("Type") .agg("mean") .reset_index() .set_axis(["Type", "averagePrice"], axis = 1, inplace = False)) In the next example we will filter with more than one criteria and calculate additional features. Please note, it is possible to use the function agg (for aggregation). Personally, I mostly use assign in combination with lambda. Please see it here in action. ( melb .query("Distance < 2 & Rooms > 2") .filter(["Type", "Price"]) .groupby("Type") .agg(["mean", "count"]) .reset_index() .set_axis(["Type", "averagePrice", "numberOfHouses"], axis = 1, inplace = False) .assign(averagePriceRounded = lambda x: x["averagePrice"].round(1))) The next example shows how to sort the houses data frame by average distance by region (only regions beginning with the string South). ( melb .query('Regionname.str.startswith("South")', engine = 'python') .filter(["Type", "Regionname", "Distance"]) .groupby(["Regionname", "Type"]) .agg(["mean"]) .reset_index() .set_axis(["Regionname", "Type", "averageDistance"], axis = 1, inplace = False) .sort_values(by = ['averageDistance'], ascending = False)) The beauty is, this concept does not stop with evaluating or manipulating the data. You may also use it with plotting. Personally, I highly recommend the plotting library plotnine — a great implementation of the grammar of graphics in python that is more a less a clone of the wonderful ggplot2 r package. Please find an extended article about plotnine here on Medium. But for a first look at your data Pandas plot function is very worthwhile. ( melb #.query('Regionname.str.startswith("South")', engine = 'python') .filter(["Regionname", "Distance"]) .groupby(["Regionname"]) .agg(["mean"]) .reset_index() .set_axis(["Regionname", "averageDistance"], axis = 1, inplace = False) .set_index("Regionname") .sort_values(by = ['averageDistance'], ascending = False) .plot(kind = "bar")) ( melb .Price # getting one specific variable .hist()) In this article I motivated the usage of the pipes in R and method chaining in your Python code to improve readability and efficiency. I highlighted some benefits and together we applied the concept to a housing data frame. In particular I showed how to read data frames, filter and group data, calculating new variables, and how to plot. Again please make sure to check out the plotnine package for much nicer visualization results. Please feel free to reach out to me if you have ideas to improve this solution! Thank you! Find more articles from me here: Learn how I plan my articles for MediumLearn how to write clean code in Python using chaining (or pipes)Learn how to analyze your LinkedIn data using RLearn how to create charts in a descriptive way in Python using grammar of graphicsLearn how to set up logging in your python data science code in under 2 minutes Learn how I plan my articles for Medium Learn how to write clean code in Python using chaining (or pipes) Learn how to analyze your LinkedIn data using R Learn how to create charts in a descriptive way in Python using grammar of graphics Learn how to set up logging in your python data science code in under 2 minutes Gregor Scheithauer is a consultant, data scientist, and researcher. He is specialized in the topics of Process Mining, Business Process Management, and Analytics. You can connect with him on LinkedIn, Twitter, or here on Medium. Thank you! Melbourne Housing Snapshot | Kaggle Tidyverse The Flawless Pipes of Tidyverse. Exploratory data analysis made easy | by Soner Yıldırım | Mar, 2021 | Towards Data Science Welcome | R for Data Science (had.co.nz) 18 Pipes | R for Data Science (had.co.nz) Data visualization in Python like in R’s ggplot2 | by Dr. Gregor Scheithauer | Medium
[ { "code": null, "e": 390, "s": 171, "text": "By trade I am an R person. Especially the Tidyverse is such a powerful, clean, easy-to-understand and well documented data science platform. I highly recommend to every beginner the free online book R for Data Science." }, { "code": null, "e": 671, "s": 390, "text": "However, my team’s programming language of choice is Python/ Pandas — which is also a wonderful data science platform. One of the major differences (to me, at least) is how we write Python code, which is very different to R code — that has nothing to do with the syntax in itself." }, { "code": null, "e": 882, "s": 671, "text": "One of R’s elegances is using the pipe functionality programming metaphor. This allows you write more efficient and readable code. One good example is the post by Soner Yıldırım The Flawless Pipes of Tidyverse." }, { "code": null, "e": 982, "s": 882, "text": "I would like to recreate his post and to show you how to use pipes (or method chaining) for Pandas." }, { "code": null, "e": 1081, "s": 982, "text": "According to the r magrittr package [1] pipes allow you to write code with the following benefits:" }, { "code": null, "e": 1177, "s": 1081, "text": "structuring sequences of data operations left-to-right (as opposed to from the inside and out)," }, { "code": null, "e": 1209, "s": 1177, "text": "avoiding nested function calls," }, { "code": null, "e": 1279, "s": 1209, "text": "minimizing the need for local variables and function definitions, and" }, { "code": null, "e": 1347, "s": 1279, "text": "making it easy to add steps anywhere in the sequence of operations." }, { "code": null, "e": 1387, "s": 1347, "text": "R example without using pipes (cf. [2])" }, { "code": null, "e": 1593, "s": 1387, "text": "What you see in the code below is a typical example. We might save a result of a function call in a variable, e.g. foo_foo_1 with the only reason to pass it into the very next function call, e.g., scoop()." }, { "code": null, "e": 1731, "s": 1593, "text": "This results in a number of variables with maybe not so meaningful names and as a consequence might increase the complexity of your code." }, { "code": null, "e": 1859, "s": 1731, "text": "foo_foo_1 <- hop(foo_foo, through = forest)foo_foo_2 <- scoop(foo_foo_1, up = field_mice)foo_foo_3 <- bop(foo_foo_2, on = head)" }, { "code": null, "e": 1890, "s": 1859, "text": "R example with pipes (cf. [2])" }, { "code": null, "e": 2031, "s": 1890, "text": "Pipes in R are used with the syntax %>%. It allows you to chain your functions. In the example below try to read it in the following manner:" }, { "code": null, "e": 2215, "s": 2031, "text": "I want to evaluate/ manipulate variable foo_fooI want foo_foo to hop trough the forest, and then,I want foo_foo to scoop up a field mice, and finally,I want foo_foo to bop on its head" }, { "code": null, "e": 2263, "s": 2215, "text": "I want to evaluate/ manipulate variable foo_foo" }, { "code": null, "e": 2314, "s": 2263, "text": "I want foo_foo to hop trough the forest, and then," }, { "code": null, "e": 2368, "s": 2314, "text": "I want foo_foo to scoop up a field mice, and finally," }, { "code": null, "e": 2402, "s": 2368, "text": "I want foo_foo to bop on its head" }, { "code": null, "e": 2503, "s": 2402, "text": "foo_foo %>% hop(through = forest) %>% scoop(up = field_mice) %>% bop(on = head)" }, { "code": null, "e": 2636, "s": 2503, "text": "Please note, how the data set is a noun and the functions are verbs. You might get the idea how it increases the code’s readability." }, { "code": null, "e": 2728, "s": 2636, "text": "For a better understanding how the piped code works the interpreted version is shown below:" }, { "code": null, "e": 2812, "s": 2728, "text": "bop( scoop( hop(foo_foo, through = forest), up = field_mice ), on = head)" }, { "code": null, "e": 3060, "s": 2812, "text": "Since there is no magrittr package in Python it has to work in a different way. We will make use of the fact that in Pandas most data frame functions return the data set itself. This is called method chaining. Let’s stick with the foo_foo example." }, { "code": null, "e": 3105, "s": 3060, "text": "A possible Python code might look like this:" }, { "code": null, "e": 3230, "s": 3105, "text": "foo_foo_1 = hop(foo_foo, through = forest)foo_foo_2 = scoop(foo_foo_1, up = field_mice)foo_foo_3 = bop(foo_foo_2, on = head)" }, { "code": null, "e": 3264, "s": 3230, "text": "Chaining it would look like this:" }, { "code": null, "e": 3332, "s": 3264, "text": "foo_foo.hop(through = forest).scoop(up = field_mice).bop(on = head)" }, { "code": null, "e": 3514, "s": 3332, "text": "This is close, but not exactly. Add one little adjustment, i.e., () brackets around the code to make it the way we want it. Please see the code below that shows how this looks like." }, { "code": null, "e": 3600, "s": 3514, "text": "( foo_foo .hop(through = forest) .scoop(up = field_mice) .bop(on = head))" }, { "code": null, "e": 3705, "s": 3600, "text": "I love using this way of coding. Here are some of the benefits I see in using this programming metaphor:" }, { "code": null, "e": 4029, "s": 3705, "text": "Your code is much more readable for other data scientists in your team (and your future self)You avoid the need for more or less meaningless local variablesYou are able to add or remove functions in your data evaluation quicklyYour code follows you line of thoughts (noun-verb-paradigma) during data evaluation and analysis" }, { "code": null, "e": 4123, "s": 4029, "text": "Your code is much more readable for other data scientists in your team (and your future self)" }, { "code": null, "e": 4187, "s": 4123, "text": "You avoid the need for more or less meaningless local variables" }, { "code": null, "e": 4259, "s": 4187, "text": "You are able to add or remove functions in your data evaluation quickly" }, { "code": null, "e": 4356, "s": 4259, "text": "Your code follows you line of thoughts (noun-verb-paradigma) during data evaluation and analysis" }, { "code": null, "e": 4421, "s": 4356, "text": "[1] magrittr package[2] Pipes chapter in R for Data Science book" }, { "code": null, "e": 4653, "s": 4421, "text": "I will follow the article of Soner Yıldırım in order for you to compare how to use pipes/ method chaining in R as well as in Python. Soner uses the Kaggle data set on Melbourne housing. You may download it and follow along with me." }, { "code": null, "e": 4795, "s": 4653, "text": "# import libsimport pandas as pd# read datamelb = pd.read_csv(\"../01-data/melb_data.csv\")# Have a quick look at the data( melb .head())" }, { "code": null, "e": 4945, "s": 4795, "text": "The next example filters houses by Distances below 2, groups them by Type, and calculates the averages Prices for each Type. Then do some formatting." }, { "code": null, "e": 5201, "s": 4945, "text": "( melb .query(\"Distance < 2\") # query equals filter in Pandas .filter([\"Type\", \"Price\"]) # select the columns Type and Price .groupby(\"Type\") .agg(\"mean\") .reset_index() .set_axis([\"Type\", \"averagePrice\"], axis = 1, inplace = False))" }, { "code": null, "e": 5460, "s": 5201, "text": "In the next example we will filter with more than one criteria and calculate additional features. Please note, it is possible to use the function agg (for aggregation). Personally, I mostly use assign in combination with lambda. Please see it here in action." }, { "code": null, "e": 5762, "s": 5460, "text": "( melb .query(\"Distance < 2 & Rooms > 2\") .filter([\"Type\", \"Price\"]) .groupby(\"Type\") .agg([\"mean\", \"count\"]) .reset_index() .set_axis([\"Type\", \"averagePrice\", \"numberOfHouses\"], axis = 1, inplace = False) .assign(averagePriceRounded = lambda x: x[\"averagePrice\"].round(1)))" }, { "code": null, "e": 5897, "s": 5762, "text": "The next example shows how to sort the houses data frame by average distance by region (only regions beginning with the string South)." }, { "code": null, "e": 6239, "s": 5897, "text": "( melb .query('Regionname.str.startswith(\"South\")', engine = 'python') .filter([\"Type\", \"Regionname\", \"Distance\"]) .groupby([\"Regionname\", \"Type\"]) .agg([\"mean\"]) .reset_index() .set_axis([\"Regionname\", \"Type\", \"averageDistance\"], axis = 1, inplace = False) .sort_values(by = ['averageDistance'], ascending = False))" }, { "code": null, "e": 6608, "s": 6239, "text": "The beauty is, this concept does not stop with evaluating or manipulating the data. You may also use it with plotting. Personally, I highly recommend the plotting library plotnine — a great implementation of the grammar of graphics in python that is more a less a clone of the wonderful ggplot2 r package. Please find an extended article about plotnine here on Medium." }, { "code": null, "e": 6683, "s": 6608, "text": "But for a first look at your data Pandas plot function is very worthwhile." }, { "code": null, "e": 7053, "s": 6683, "text": "( melb #.query('Regionname.str.startswith(\"South\")', engine = 'python') .filter([\"Regionname\", \"Distance\"]) .groupby([\"Regionname\"]) .agg([\"mean\"]) .reset_index() .set_axis([\"Regionname\", \"averageDistance\"], axis = 1, inplace = False) .set_index(\"Regionname\") .sort_values(by = ['averageDistance'], ascending = False) .plot(kind = \"bar\"))" }, { "code": null, "e": 7118, "s": 7053, "text": "( melb .Price # getting one specific variable .hist())" }, { "code": null, "e": 7552, "s": 7118, "text": "In this article I motivated the usage of the pipes in R and method chaining in your Python code to improve readability and efficiency. I highlighted some benefits and together we applied the concept to a housing data frame. In particular I showed how to read data frames, filter and group data, calculating new variables, and how to plot. Again please make sure to check out the plotnine package for much nicer visualization results." }, { "code": null, "e": 7643, "s": 7552, "text": "Please feel free to reach out to me if you have ideas to improve this solution! Thank you!" }, { "code": null, "e": 7676, "s": 7643, "text": "Find more articles from me here:" }, { "code": null, "e": 7990, "s": 7676, "text": "Learn how I plan my articles for MediumLearn how to write clean code in Python using chaining (or pipes)Learn how to analyze your LinkedIn data using RLearn how to create charts in a descriptive way in Python using grammar of graphicsLearn how to set up logging in your python data science code in under 2 minutes" }, { "code": null, "e": 8030, "s": 7990, "text": "Learn how I plan my articles for Medium" }, { "code": null, "e": 8096, "s": 8030, "text": "Learn how to write clean code in Python using chaining (or pipes)" }, { "code": null, "e": 8144, "s": 8096, "text": "Learn how to analyze your LinkedIn data using R" }, { "code": null, "e": 8228, "s": 8144, "text": "Learn how to create charts in a descriptive way in Python using grammar of graphics" }, { "code": null, "e": 8308, "s": 8228, "text": "Learn how to set up logging in your python data science code in under 2 minutes" }, { "code": null, "e": 8548, "s": 8308, "text": "Gregor Scheithauer is a consultant, data scientist, and researcher. He is specialized in the topics of Process Mining, Business Process Management, and Analytics. You can connect with him on LinkedIn, Twitter, or here on Medium. Thank you!" }, { "code": null, "e": 8584, "s": 8548, "text": "Melbourne Housing Snapshot | Kaggle" }, { "code": null, "e": 8594, "s": 8584, "text": "Tidyverse" }, { "code": null, "e": 8718, "s": 8594, "text": "The Flawless Pipes of Tidyverse. Exploratory data analysis made easy | by Soner Yıldırım | Mar, 2021 | Towards Data Science" }, { "code": null, "e": 8759, "s": 8718, "text": "Welcome | R for Data Science (had.co.nz)" }, { "code": null, "e": 8801, "s": 8759, "text": "18 Pipes | R for Data Science (had.co.nz)" } ]
pod2html - Unix, Linux Command
pod2html --help --htmlroot=<name> --infile=<name> --outfile=<name> --podpath=<name>:...:<name> --podroot=<name> --libpods=<name>:...:<name> --recurse --norecurse --verbose --index --noindex --title=<name> --help Displays the usage message. --htmlroot=name Sets the base URL for the HTML files. When cross-references are made, the HTML root is prepended to the URL. --infile=name Specify the pod file to convert. Input is taken from STDIN if no infile is specified. --outfile=name Specify the HTML file to create. Output goes to STDOUT if no outfile is specified. --podroot=name Specify the base directory for finding library pods. --podpath=name:...:name Specify which subdirectories of the podroot contain pod files whose HTML converted forms can be linked-to in cross-references. --libpods=name:...:name List of page names (eg, perlfunc) which contain linkable =items. --netscape Use Netscape HTML directives when applicable. --nonetscape Do not use Netscape HTML directives (default). --index Generate an index at the top of the HTML file (default behaviour). --noindex Do not generate an index at the top of the HTML file. --recurse Recurse into subdirectories specified in podpath (default behaviour). --norecurse Do not recurse into subdirectories specified in podpath. --title=title Specify the title of the resulting HTML file. --verbose Display progress messages. Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10827, "s": 10577, "text": "\n pod2html --help --htmlroot=<name> --infile=<name> --outfile=<name>\n --podpath=<name>:...:<name> --podroot=<name>\n --libpods=<name>:...:<name> --recurse --norecurse --verbose\n --index --noindex --title=<name>\n" }, { "code": null, "e": 10838, "s": 10827, "text": "\n --help\n" }, { "code": null, "e": 10869, "s": 10838, "text": "\n\nDisplays the usage message.\n" }, { "code": null, "e": 10889, "s": 10869, "text": "\n --htmlroot=name\n" }, { "code": null, "e": 11002, "s": 10889, "text": "\n\nSets the base URL for the HTML files. When cross-references are made,\nthe HTML root is prepended to the URL.\n" }, { "code": null, "e": 11020, "s": 11002, "text": "\n --infile=name\n" }, { "code": null, "e": 11110, "s": 11020, "text": "\n\nSpecify the pod file to convert. Input is taken from STDIN if no\ninfile is specified.\n" }, { "code": null, "e": 11129, "s": 11110, "text": "\n --outfile=name\n" }, { "code": null, "e": 11216, "s": 11129, "text": "\n\nSpecify the HTML file to create. Output goes to STDOUT if no outfile\nis specified.\n" }, { "code": null, "e": 11235, "s": 11216, "text": "\n --podroot=name\n" }, { "code": null, "e": 11291, "s": 11235, "text": "\n\nSpecify the base directory for finding library pods.\n" }, { "code": null, "e": 11319, "s": 11291, "text": "\n --podpath=name:...:name\n" }, { "code": null, "e": 11449, "s": 11319, "text": "\n\nSpecify which subdirectories of the podroot contain pod files whose\nHTML converted forms can be linked-to in cross-references.\n" }, { "code": null, "e": 11477, "s": 11449, "text": "\n --libpods=name:...:name\n" }, { "code": null, "e": 11545, "s": 11477, "text": "\n\nList of page names (eg, perlfunc) which contain linkable =items.\n" }, { "code": null, "e": 11560, "s": 11545, "text": "\n --netscape\n" }, { "code": null, "e": 11609, "s": 11560, "text": "\n\nUse Netscape HTML directives when applicable.\n" }, { "code": null, "e": 11626, "s": 11609, "text": "\n --nonetscape\n" }, { "code": null, "e": 11676, "s": 11626, "text": "\n\nDo not use Netscape HTML directives (default).\n" }, { "code": null, "e": 11688, "s": 11676, "text": "\n --index\n" }, { "code": null, "e": 11758, "s": 11688, "text": "\n\nGenerate an index at the top of the HTML file (default behaviour).\n" }, { "code": null, "e": 11772, "s": 11758, "text": "\n --noindex\n" }, { "code": null, "e": 11829, "s": 11772, "text": "\n\nDo not generate an index at the top of the HTML file.\n" }, { "code": null, "e": 11843, "s": 11829, "text": "\n --recurse\n" }, { "code": null, "e": 11916, "s": 11843, "text": "\n\nRecurse into subdirectories specified in podpath (default behaviour).\n" }, { "code": null, "e": 11932, "s": 11916, "text": "\n --norecurse\n" }, { "code": null, "e": 11992, "s": 11932, "text": "\n\nDo not recurse into subdirectories specified in podpath.\n" }, { "code": null, "e": 12010, "s": 11992, "text": "\n --title=title\n" }, { "code": null, "e": 12059, "s": 12010, "text": "\n\nSpecify the title of the resulting HTML file.\n" }, { "code": null, "e": 12073, "s": 12059, "text": "\n --verbose\n" }, { "code": null, "e": 12103, "s": 12073, "text": "\n\nDisplay progress messages.\n" }, { "code": null, "e": 12120, "s": 12103, "text": "\nAdvertisements\n" }, { "code": null, "e": 12155, "s": 12120, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 12183, "s": 12155, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 12217, "s": 12183, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12234, "s": 12217, "text": " Frahaan Hussain" }, { "code": null, "e": 12267, "s": 12234, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 12278, "s": 12267, "text": " Pradeep D" }, { "code": null, "e": 12313, "s": 12278, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 12329, "s": 12313, "text": " Musab Zayadneh" }, { "code": null, "e": 12362, "s": 12329, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 12374, "s": 12362, "text": " GUHARAJANM" }, { "code": null, "e": 12406, "s": 12374, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 12414, "s": 12406, "text": " Uplatz" }, { "code": null, "e": 12421, "s": 12414, "text": " Print" }, { "code": null, "e": 12432, "s": 12421, "text": " Add Notes" } ]
How to draw a polygon in OpenCV using Java?
A polygon with all the interior angles less than 180 is known as a convex polygon. The org.opencv.imgproc package of Java OpenCV library contains a class named Imgproc. To draw a polygon you need to invoke the fillConvexPoly() method of this class. This method accepts 3 parameters − A Mat object representing the image on which the polygon is to be drawn. A Mat object representing the image on which the polygon is to be drawn. A MatOfPoint object points between which the polygon is to be drawn. A MatOfPoint object points between which the polygon is to be drawn. A Scalar object representing the color of the polygon. A Scalar object representing the color of the polygon. import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.MatOfPoint; import org.opencv.core.Point; import org.opencv.core.Scalar; import org.opencv.highgui.HighGui; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class DrawingConvexPolygon { public static void main(String args[]) { //Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); //Reading the source image in to a Mat object Mat src = Imgcodecs.imread("D:\\images\\blank.jpg"); //Drawing an arrowed line MatOfPoint points = new MatOfPoint ( new Point(108, 71), new Point(232, 52), new Point(321, 161), new Point(269, 250), new Point(126, 232), new Point(108, 71) ); Scalar color = new Scalar(64, 64, 64); Imgproc.fillConvexPoly (src, points, color); //Saving and displaying the image Imgcodecs.imwrite("arrowed_line.jpg", src); HighGui.imshow("Drawing an polygon", src); HighGui.waitKey(); } } On executing, the above program generates the following window −
[ { "code": null, "e": 1346, "s": 1062, "text": "A polygon with all the interior angles less than 180 is known as a convex polygon. The org.opencv.imgproc package of Java OpenCV library contains a class named Imgproc. To draw a polygon you need to invoke the fillConvexPoly() method of this class. This method accepts 3 parameters −" }, { "code": null, "e": 1419, "s": 1346, "text": "A Mat object representing the image on which the polygon is to be drawn." }, { "code": null, "e": 1492, "s": 1419, "text": "A Mat object representing the image on which the polygon is to be drawn." }, { "code": null, "e": 1561, "s": 1492, "text": "A MatOfPoint object points between which the polygon is to be drawn." }, { "code": null, "e": 1630, "s": 1561, "text": "A MatOfPoint object points between which the polygon is to be drawn." }, { "code": null, "e": 1685, "s": 1630, "text": "A Scalar object representing the color of the polygon." }, { "code": null, "e": 1740, "s": 1685, "text": "A Scalar object representing the color of the polygon." }, { "code": null, "e": 2787, "s": 1740, "text": "import org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.core.MatOfPoint;\nimport org.opencv.core.Point;\nimport org.opencv.core.Scalar;\nimport org.opencv.highgui.HighGui;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\npublic class DrawingConvexPolygon {\n public static void main(String args[]) {\n //Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n //Reading the source image in to a Mat object\n Mat src = Imgcodecs.imread(\"D:\\\\images\\\\blank.jpg\");\n //Drawing an arrowed line\n MatOfPoint points = new MatOfPoint (\n new Point(108, 71), new Point(232, 52),\n new Point(321, 161), new Point(269, 250),\n new Point(126, 232), new Point(108, 71)\n );\n Scalar color = new Scalar(64, 64, 64);\n Imgproc.fillConvexPoly (src, points, color);\n //Saving and displaying the image\n Imgcodecs.imwrite(\"arrowed_line.jpg\", src);\n HighGui.imshow(\"Drawing an polygon\", src);\n HighGui.waitKey();\n }\n}" }, { "code": null, "e": 2852, "s": 2787, "text": "On executing, the above program generates the following window −" } ]
Reverse elements of a Parallel Stream in Java - GeeksforGeeks
11 Dec, 2018 Given a Parallel Stream in Java, the task is to reverse its elements. Examples: Input: Parallel Stream = {11, 22, 33, 44} Output: {44, 33, 22, 11} Input: Parallel Stream = {a, b, c, d} Output: {d, c, b, a} Below are the various ways to do so: Using Collectors class : Since Streams in Java don’t store any elements, therefore, an intermediate collection is used for creating a new stream with the help of Collectors Class.Algorithm:Get the parallel stream.Convert the stream to list using Collectors.toList() method.For this list, reverse its elements using Collections.reverse() method.Convert this reversed list to stream using List.stream() method.Return/Print this stream with elements reversed.Below is the implementation of the above approach:Program:// Java program to reverse elements// of a parallel Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to reverse // the elements of the parallel stream public static <T> Collector<T, ?, Stream<T> > reverseStream() { return Collectors .collectingAndThen(Collectors.toList(), list -> { Collections.reverse(list); return list.stream(); }); } // Driver code public static void main(String[] args) { // Get the parallel stream List<Integer> lists = Arrays.asList(11, 22, 33, 44); Stream<Integer> stream = lists.parallelStream(); // Reverse and print the elements stream.collect(reverseStream()) .forEach(System.out::println); }}Output:44 33 22 11 Using LinkedList class : LinkedList class implements List interface and has a feature called Stack. So LinkedList supports insertion at the front. Taking advantage of this, a LinkedList can be created from elements of the specified stream and return descending iterator to it. This would reverse the elements of the parallel stream.Algorithm:Get the parallel stream.Convert the stream to LinkedList using Collectors.toCollection() method.For this LinkedList, return the descending iterator using descendingIterator() method.Return/Print this iterator with elements reversed.Below is the implementation of the above approach:Program:// Java program to reverse elements// of a parallel Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to reverse // the elements of the parallel stream public static <T> Iterator<T> reverseStream(Stream<T> stream) { return stream .collect(Collectors .toCollection(LinkedList::new)) .descendingIterator(); } // Driver code public static void main(String[] args) { // Get the parallel stream List<Integer> lists = Arrays.asList(11, 22, 33, 44); Stream<Integer> stream = lists.parallelStream(); // Reverse and print the elements Iterator<Integer> reverse = reverseStream(stream); reverse.forEachRemaining(System.out::println); }}Output:44 33 22 11 Collector.of() : The idea is to create a collector that accumulates elements of the specified Stream into an ArrayDeque or ArrayList in reverse orderAlgorithm:Get the parallel stream.Convert the stream to Collection using Collectors.of() method.In this collection, add the elements in reverse orderConvert this reversed collection to stream using Collection.stream() method.Return/Print this stream with elements reversed.Below is the implementation of the above approach:Program:// Java program to reverse elements// of a parallel Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to reverse // the elements of the parallel stream public static <T> Stream<T> reverseStream(Stream<T> stream) { return stream .collect( Collector.of( () -> new ArrayDeque<T>(), ArrayDeque::addFirst, (a, b) -> { b.addAll(a); return b; })) .stream(); } // Driver code public static void main(String[] args) { // Get the parallel stream List<Integer> lists = Arrays.asList(11, 22, 33, 44); Stream<Integer> stream = lists.parallelStream(); // Reverse and print the elements reverseStream(stream) .forEach(System.out::println); }}Output:44 33 22 11 Using Collectors class : Since Streams in Java don’t store any elements, therefore, an intermediate collection is used for creating a new stream with the help of Collectors Class.Algorithm:Get the parallel stream.Convert the stream to list using Collectors.toList() method.For this list, reverse its elements using Collections.reverse() method.Convert this reversed list to stream using List.stream() method.Return/Print this stream with elements reversed.Below is the implementation of the above approach:Program:// Java program to reverse elements// of a parallel Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to reverse // the elements of the parallel stream public static <T> Collector<T, ?, Stream<T> > reverseStream() { return Collectors .collectingAndThen(Collectors.toList(), list -> { Collections.reverse(list); return list.stream(); }); } // Driver code public static void main(String[] args) { // Get the parallel stream List<Integer> lists = Arrays.asList(11, 22, 33, 44); Stream<Integer> stream = lists.parallelStream(); // Reverse and print the elements stream.collect(reverseStream()) .forEach(System.out::println); }}Output:44 33 22 11 Get the parallel stream.Convert the stream to list using Collectors.toList() method.For this list, reverse its elements using Collections.reverse() method.Convert this reversed list to stream using List.stream() method.Return/Print this stream with elements reversed. Get the parallel stream. Convert the stream to list using Collectors.toList() method. For this list, reverse its elements using Collections.reverse() method. Convert this reversed list to stream using List.stream() method. Return/Print this stream with elements reversed. Below is the implementation of the above approach: Program: // Java program to reverse elements// of a parallel Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to reverse // the elements of the parallel stream public static <T> Collector<T, ?, Stream<T> > reverseStream() { return Collectors .collectingAndThen(Collectors.toList(), list -> { Collections.reverse(list); return list.stream(); }); } // Driver code public static void main(String[] args) { // Get the parallel stream List<Integer> lists = Arrays.asList(11, 22, 33, 44); Stream<Integer> stream = lists.parallelStream(); // Reverse and print the elements stream.collect(reverseStream()) .forEach(System.out::println); }} 44 33 22 11 Using LinkedList class : LinkedList class implements List interface and has a feature called Stack. So LinkedList supports insertion at the front. Taking advantage of this, a LinkedList can be created from elements of the specified stream and return descending iterator to it. This would reverse the elements of the parallel stream.Algorithm:Get the parallel stream.Convert the stream to LinkedList using Collectors.toCollection() method.For this LinkedList, return the descending iterator using descendingIterator() method.Return/Print this iterator with elements reversed.Below is the implementation of the above approach:Program:// Java program to reverse elements// of a parallel Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to reverse // the elements of the parallel stream public static <T> Iterator<T> reverseStream(Stream<T> stream) { return stream .collect(Collectors .toCollection(LinkedList::new)) .descendingIterator(); } // Driver code public static void main(String[] args) { // Get the parallel stream List<Integer> lists = Arrays.asList(11, 22, 33, 44); Stream<Integer> stream = lists.parallelStream(); // Reverse and print the elements Iterator<Integer> reverse = reverseStream(stream); reverse.forEachRemaining(System.out::println); }}Output:44 33 22 11 Algorithm: Get the parallel stream.Convert the stream to LinkedList using Collectors.toCollection() method.For this LinkedList, return the descending iterator using descendingIterator() method.Return/Print this iterator with elements reversed. Get the parallel stream. Convert the stream to LinkedList using Collectors.toCollection() method. For this LinkedList, return the descending iterator using descendingIterator() method. Return/Print this iterator with elements reversed. Below is the implementation of the above approach: Program: // Java program to reverse elements// of a parallel Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to reverse // the elements of the parallel stream public static <T> Iterator<T> reverseStream(Stream<T> stream) { return stream .collect(Collectors .toCollection(LinkedList::new)) .descendingIterator(); } // Driver code public static void main(String[] args) { // Get the parallel stream List<Integer> lists = Arrays.asList(11, 22, 33, 44); Stream<Integer> stream = lists.parallelStream(); // Reverse and print the elements Iterator<Integer> reverse = reverseStream(stream); reverse.forEachRemaining(System.out::println); }} 44 33 22 11 Collector.of() : The idea is to create a collector that accumulates elements of the specified Stream into an ArrayDeque or ArrayList in reverse orderAlgorithm:Get the parallel stream.Convert the stream to Collection using Collectors.of() method.In this collection, add the elements in reverse orderConvert this reversed collection to stream using Collection.stream() method.Return/Print this stream with elements reversed.Below is the implementation of the above approach:Program:// Java program to reverse elements// of a parallel Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to reverse // the elements of the parallel stream public static <T> Stream<T> reverseStream(Stream<T> stream) { return stream .collect( Collector.of( () -> new ArrayDeque<T>(), ArrayDeque::addFirst, (a, b) -> { b.addAll(a); return b; })) .stream(); } // Driver code public static void main(String[] args) { // Get the parallel stream List<Integer> lists = Arrays.asList(11, 22, 33, 44); Stream<Integer> stream = lists.parallelStream(); // Reverse and print the elements reverseStream(stream) .forEach(System.out::println); }}Output:44 33 22 11 Algorithm: Get the parallel stream.Convert the stream to Collection using Collectors.of() method.In this collection, add the elements in reverse orderConvert this reversed collection to stream using Collection.stream() method.Return/Print this stream with elements reversed. Get the parallel stream. Convert the stream to Collection using Collectors.of() method. In this collection, add the elements in reverse order Convert this reversed collection to stream using Collection.stream() method. Return/Print this stream with elements reversed. Below is the implementation of the above approach: Program: // Java program to reverse elements// of a parallel Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to reverse // the elements of the parallel stream public static <T> Stream<T> reverseStream(Stream<T> stream) { return stream .collect( Collector.of( () -> new ArrayDeque<T>(), ArrayDeque::addFirst, (a, b) -> { b.addAll(a); return b; })) .stream(); } // Driver code public static void main(String[] args) { // Get the parallel stream List<Integer> lists = Arrays.asList(11, 22, 33, 44); Stream<Integer> stream = lists.parallelStream(); // Reverse and print the elements reverseStream(stream) .forEach(System.out::println); }} 44 33 22 11 Java - util package Java-Collections Java-Stream-Collectors Java-Stream-programs Picked Technical Scripter 2018 Java Technical Scripter Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Generics in Java Comparator Interface in Java with Examples Strings in Java How to remove an element from ArrayList in Java? Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23583, "s": 23555, "text": "\n11 Dec, 2018" }, { "code": null, "e": 23653, "s": 23583, "text": "Given a Parallel Stream in Java, the task is to reverse its elements." }, { "code": null, "e": 23663, "s": 23653, "text": "Examples:" }, { "code": null, "e": 23791, "s": 23663, "text": "Input: Parallel Stream = {11, 22, 33, 44}\nOutput: {44, 33, 22, 11}\n\nInput: Parallel Stream = {a, b, c, d}\nOutput: {d, c, b, a}\n" }, { "code": null, "e": 23828, "s": 23791, "text": "Below are the various ways to do so:" }, { "code": null, "e": 28065, "s": 23828, "text": "Using Collectors class : Since Streams in Java don’t store any elements, therefore, an intermediate collection is used for creating a new stream with the help of Collectors Class.Algorithm:Get the parallel stream.Convert the stream to list using Collectors.toList() method.For this list, reverse its elements using Collections.reverse() method.Convert this reversed list to stream using List.stream() method.Return/Print this stream with elements reversed.Below is the implementation of the above approach:Program:// Java program to reverse elements// of a parallel Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to reverse // the elements of the parallel stream public static <T> Collector<T, ?, Stream<T> > reverseStream() { return Collectors .collectingAndThen(Collectors.toList(), list -> { Collections.reverse(list); return list.stream(); }); } // Driver code public static void main(String[] args) { // Get the parallel stream List<Integer> lists = Arrays.asList(11, 22, 33, 44); Stream<Integer> stream = lists.parallelStream(); // Reverse and print the elements stream.collect(reverseStream()) .forEach(System.out::println); }}Output:44\n33\n22\n11\nUsing LinkedList class : LinkedList class implements List interface and has a feature called Stack. So LinkedList supports insertion at the front. Taking advantage of this, a LinkedList can be created from elements of the specified stream and return descending iterator to it. This would reverse the elements of the parallel stream.Algorithm:Get the parallel stream.Convert the stream to LinkedList using Collectors.toCollection() method.For this LinkedList, return the descending iterator using descendingIterator() method.Return/Print this iterator with elements reversed.Below is the implementation of the above approach:Program:// Java program to reverse elements// of a parallel Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to reverse // the elements of the parallel stream public static <T> Iterator<T> reverseStream(Stream<T> stream) { return stream .collect(Collectors .toCollection(LinkedList::new)) .descendingIterator(); } // Driver code public static void main(String[] args) { // Get the parallel stream List<Integer> lists = Arrays.asList(11, 22, 33, 44); Stream<Integer> stream = lists.parallelStream(); // Reverse and print the elements Iterator<Integer> reverse = reverseStream(stream); reverse.forEachRemaining(System.out::println); }}Output:44\n33\n22\n11\nCollector.of() : The idea is to create a collector that accumulates elements of the specified Stream into an ArrayDeque or ArrayList in reverse orderAlgorithm:Get the parallel stream.Convert the stream to Collection using Collectors.of() method.In this collection, add the elements in reverse orderConvert this reversed collection to stream using Collection.stream() method.Return/Print this stream with elements reversed.Below is the implementation of the above approach:Program:// Java program to reverse elements// of a parallel Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to reverse // the elements of the parallel stream public static <T> Stream<T> reverseStream(Stream<T> stream) { return stream .collect( Collector.of( () -> new ArrayDeque<T>(), ArrayDeque::addFirst, (a, b) -> { b.addAll(a); return b; })) .stream(); } // Driver code public static void main(String[] args) { // Get the parallel stream List<Integer> lists = Arrays.asList(11, 22, 33, 44); Stream<Integer> stream = lists.parallelStream(); // Reverse and print the elements reverseStream(stream) .forEach(System.out::println); }}Output:44\n33\n22\n11\n" }, { "code": null, "e": 29486, "s": 28065, "text": "Using Collectors class : Since Streams in Java don’t store any elements, therefore, an intermediate collection is used for creating a new stream with the help of Collectors Class.Algorithm:Get the parallel stream.Convert the stream to list using Collectors.toList() method.For this list, reverse its elements using Collections.reverse() method.Convert this reversed list to stream using List.stream() method.Return/Print this stream with elements reversed.Below is the implementation of the above approach:Program:// Java program to reverse elements// of a parallel Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to reverse // the elements of the parallel stream public static <T> Collector<T, ?, Stream<T> > reverseStream() { return Collectors .collectingAndThen(Collectors.toList(), list -> { Collections.reverse(list); return list.stream(); }); } // Driver code public static void main(String[] args) { // Get the parallel stream List<Integer> lists = Arrays.asList(11, 22, 33, 44); Stream<Integer> stream = lists.parallelStream(); // Reverse and print the elements stream.collect(reverseStream()) .forEach(System.out::println); }}Output:44\n33\n22\n11\n" }, { "code": null, "e": 29754, "s": 29486, "text": "Get the parallel stream.Convert the stream to list using Collectors.toList() method.For this list, reverse its elements using Collections.reverse() method.Convert this reversed list to stream using List.stream() method.Return/Print this stream with elements reversed." }, { "code": null, "e": 29779, "s": 29754, "text": "Get the parallel stream." }, { "code": null, "e": 29840, "s": 29779, "text": "Convert the stream to list using Collectors.toList() method." }, { "code": null, "e": 29912, "s": 29840, "text": "For this list, reverse its elements using Collections.reverse() method." }, { "code": null, "e": 29977, "s": 29912, "text": "Convert this reversed list to stream using List.stream() method." }, { "code": null, "e": 30026, "s": 29977, "text": "Return/Print this stream with elements reversed." }, { "code": null, "e": 30077, "s": 30026, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 30086, "s": 30077, "text": "Program:" }, { "code": "// Java program to reverse elements// of a parallel Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to reverse // the elements of the parallel stream public static <T> Collector<T, ?, Stream<T> > reverseStream() { return Collectors .collectingAndThen(Collectors.toList(), list -> { Collections.reverse(list); return list.stream(); }); } // Driver code public static void main(String[] args) { // Get the parallel stream List<Integer> lists = Arrays.asList(11, 22, 33, 44); Stream<Integer> stream = lists.parallelStream(); // Reverse and print the elements stream.collect(reverseStream()) .forEach(System.out::println); }}", "e": 30974, "s": 30086, "text": null }, { "code": null, "e": 30987, "s": 30974, "text": "44\n33\n22\n11\n" }, { "code": null, "e": 32432, "s": 30987, "text": "Using LinkedList class : LinkedList class implements List interface and has a feature called Stack. So LinkedList supports insertion at the front. Taking advantage of this, a LinkedList can be created from elements of the specified stream and return descending iterator to it. This would reverse the elements of the parallel stream.Algorithm:Get the parallel stream.Convert the stream to LinkedList using Collectors.toCollection() method.For this LinkedList, return the descending iterator using descendingIterator() method.Return/Print this iterator with elements reversed.Below is the implementation of the above approach:Program:// Java program to reverse elements// of a parallel Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to reverse // the elements of the parallel stream public static <T> Iterator<T> reverseStream(Stream<T> stream) { return stream .collect(Collectors .toCollection(LinkedList::new)) .descendingIterator(); } // Driver code public static void main(String[] args) { // Get the parallel stream List<Integer> lists = Arrays.asList(11, 22, 33, 44); Stream<Integer> stream = lists.parallelStream(); // Reverse and print the elements Iterator<Integer> reverse = reverseStream(stream); reverse.forEachRemaining(System.out::println); }}Output:44\n33\n22\n11\n" }, { "code": null, "e": 32443, "s": 32432, "text": "Algorithm:" }, { "code": null, "e": 32676, "s": 32443, "text": "Get the parallel stream.Convert the stream to LinkedList using Collectors.toCollection() method.For this LinkedList, return the descending iterator using descendingIterator() method.Return/Print this iterator with elements reversed." }, { "code": null, "e": 32701, "s": 32676, "text": "Get the parallel stream." }, { "code": null, "e": 32774, "s": 32701, "text": "Convert the stream to LinkedList using Collectors.toCollection() method." }, { "code": null, "e": 32861, "s": 32774, "text": "For this LinkedList, return the descending iterator using descendingIterator() method." }, { "code": null, "e": 32912, "s": 32861, "text": "Return/Print this iterator with elements reversed." }, { "code": null, "e": 32963, "s": 32912, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 32972, "s": 32963, "text": "Program:" }, { "code": "// Java program to reverse elements// of a parallel Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to reverse // the elements of the parallel stream public static <T> Iterator<T> reverseStream(Stream<T> stream) { return stream .collect(Collectors .toCollection(LinkedList::new)) .descendingIterator(); } // Driver code public static void main(String[] args) { // Get the parallel stream List<Integer> lists = Arrays.asList(11, 22, 33, 44); Stream<Integer> stream = lists.parallelStream(); // Reverse and print the elements Iterator<Integer> reverse = reverseStream(stream); reverse.forEachRemaining(System.out::println); }}", "e": 33766, "s": 32972, "text": null }, { "code": null, "e": 33779, "s": 33766, "text": "44\n33\n22\n11\n" }, { "code": null, "e": 35152, "s": 33779, "text": "Collector.of() : The idea is to create a collector that accumulates elements of the specified Stream into an ArrayDeque or ArrayList in reverse orderAlgorithm:Get the parallel stream.Convert the stream to Collection using Collectors.of() method.In this collection, add the elements in reverse orderConvert this reversed collection to stream using Collection.stream() method.Return/Print this stream with elements reversed.Below is the implementation of the above approach:Program:// Java program to reverse elements// of a parallel Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to reverse // the elements of the parallel stream public static <T> Stream<T> reverseStream(Stream<T> stream) { return stream .collect( Collector.of( () -> new ArrayDeque<T>(), ArrayDeque::addFirst, (a, b) -> { b.addAll(a); return b; })) .stream(); } // Driver code public static void main(String[] args) { // Get the parallel stream List<Integer> lists = Arrays.asList(11, 22, 33, 44); Stream<Integer> stream = lists.parallelStream(); // Reverse and print the elements reverseStream(stream) .forEach(System.out::println); }}Output:44\n33\n22\n11\n" }, { "code": null, "e": 35163, "s": 35152, "text": "Algorithm:" }, { "code": null, "e": 35427, "s": 35163, "text": "Get the parallel stream.Convert the stream to Collection using Collectors.of() method.In this collection, add the elements in reverse orderConvert this reversed collection to stream using Collection.stream() method.Return/Print this stream with elements reversed." }, { "code": null, "e": 35452, "s": 35427, "text": "Get the parallel stream." }, { "code": null, "e": 35515, "s": 35452, "text": "Convert the stream to Collection using Collectors.of() method." }, { "code": null, "e": 35569, "s": 35515, "text": "In this collection, add the elements in reverse order" }, { "code": null, "e": 35646, "s": 35569, "text": "Convert this reversed collection to stream using Collection.stream() method." }, { "code": null, "e": 35695, "s": 35646, "text": "Return/Print this stream with elements reversed." }, { "code": null, "e": 35746, "s": 35695, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 35755, "s": 35746, "text": "Program:" }, { "code": "// Java program to reverse elements// of a parallel Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to reverse // the elements of the parallel stream public static <T> Stream<T> reverseStream(Stream<T> stream) { return stream .collect( Collector.of( () -> new ArrayDeque<T>(), ArrayDeque::addFirst, (a, b) -> { b.addAll(a); return b; })) .stream(); } // Driver code public static void main(String[] args) { // Get the parallel stream List<Integer> lists = Arrays.asList(11, 22, 33, 44); Stream<Integer> stream = lists.parallelStream(); // Reverse and print the elements reverseStream(stream) .forEach(System.out::println); }}", "e": 36629, "s": 35755, "text": null }, { "code": null, "e": 36642, "s": 36629, "text": "44\n33\n22\n11\n" }, { "code": null, "e": 36662, "s": 36642, "text": "Java - util package" }, { "code": null, "e": 36679, "s": 36662, "text": "Java-Collections" }, { "code": null, "e": 36702, "s": 36679, "text": "Java-Stream-Collectors" }, { "code": null, "e": 36723, "s": 36702, "text": "Java-Stream-programs" }, { "code": null, "e": 36730, "s": 36723, "text": "Picked" }, { "code": null, "e": 36754, "s": 36730, "text": "Technical Scripter 2018" }, { "code": null, "e": 36759, "s": 36754, "text": "Java" }, { "code": null, "e": 36778, "s": 36759, "text": "Technical Scripter" }, { "code": null, "e": 36783, "s": 36778, "text": "Java" }, { "code": null, "e": 36800, "s": 36783, "text": "Java-Collections" }, { "code": null, "e": 36898, "s": 36800, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36907, "s": 36898, "text": "Comments" }, { "code": null, "e": 36920, "s": 36907, "text": "Old Comments" }, { "code": null, "e": 36950, "s": 36920, "text": "Functional Interfaces in Java" }, { "code": null, "e": 36965, "s": 36950, "text": "Stream In Java" }, { "code": null, "e": 36986, "s": 36965, "text": "Constructors in Java" }, { "code": null, "e": 37032, "s": 36986, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 37051, "s": 37032, "text": "Exceptions in Java" }, { "code": null, "e": 37068, "s": 37051, "text": "Generics in Java" }, { "code": null, "e": 37111, "s": 37068, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 37127, "s": 37111, "text": "Strings in Java" }, { "code": null, "e": 37176, "s": 37127, "text": "How to remove an element from ArrayList in Java?" } ]
Angular Highcharts - Donut Chart
Following is an example of a Donut Chart. We have already seen the configurations used to draw a chart in Highcharts Configuration Syntax chapter. An example of a Donut Chart is given below. Let us now see the additional configurations/steps taken. Configure the chart type to be 'pie' based. chart.type decides the series type for the chart. Here, the default value is "line". var series = { type: 'pie' }; app.component.ts import { Component } from '@angular/core'; import * as Highcharts from 'highcharts'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { highcharts = Highcharts; chartOptions = { chart : { plotBorderWidth: null, plotShadow: false }, title : { text: 'Browser market shares at a specific website, 2014' }, tooltip : { pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>' }, plotOptions : { pie: { shadow: false, center: ['50%', '50%'], size:'45%', innerSize: '20%' } }, series : [{ type: 'pie', name: 'Browser share', data: [ ['Firefox', 45.0], ['IE', 26.8], { name: 'Chrome', y: 12.8, sliced: true, selected: true }, ['Safari', 8.5], ['Opera', 6.2], ['Others', 0.7] ] }] }; } Verify the result. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2077, "s": 2035, "text": "Following is an example of a Donut Chart." }, { "code": null, "e": 2183, "s": 2077, "text": "We have already seen the configurations used to draw a chart in Highcharts Configuration Syntax chapter. " }, { "code": null, "e": 2227, "s": 2183, "text": "An example of a Donut Chart is given below." }, { "code": null, "e": 2286, "s": 2227, "text": "Let us now see the additional configurations/steps taken.\n" }, { "code": null, "e": 2415, "s": 2286, "text": "Configure the chart type to be 'pie' based. chart.type decides the series type for the chart. Here, the default value is \"line\"." }, { "code": null, "e": 2448, "s": 2415, "text": "var series = {\n type: 'pie'\n};" }, { "code": null, "e": 2465, "s": 2448, "text": "app.component.ts" }, { "code": null, "e": 3629, "s": 2465, "text": "import { Component } from '@angular/core';\nimport * as Highcharts from 'highcharts';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n highcharts = Highcharts;\n chartOptions = { \n chart : {\n plotBorderWidth: null,\n plotShadow: false\n },\n title : {\n text: 'Browser market shares at a specific website, 2014' \n },\n tooltip : {\n pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'\n },\n plotOptions : {\n pie: {\n shadow: false,\n center: ['50%', '50%'],\n size:'45%',\n innerSize: '20%' \n }\n },\n series : [{\n type: 'pie',\n name: 'Browser share',\n data: [\n ['Firefox', 45.0],\n ['IE', 26.8],\n {\n name: 'Chrome',\n y: 12.8,\n sliced: true,\n selected: true\n },\n ['Safari', 8.5],\n ['Opera', 6.2],\n ['Others', 0.7]\n ]\n }]\n };\n}" }, { "code": null, "e": 3648, "s": 3629, "text": "Verify the result." }, { "code": null, "e": 3683, "s": 3648, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3697, "s": 3683, "text": " Anadi Sharma" }, { "code": null, "e": 3732, "s": 3697, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3746, "s": 3732, "text": " Anadi Sharma" }, { "code": null, "e": 3781, "s": 3746, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 3801, "s": 3781, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 3836, "s": 3801, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3853, "s": 3836, "text": " Frahaan Hussain" }, { "code": null, "e": 3886, "s": 3853, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 3898, "s": 3886, "text": " Senol Atac" }, { "code": null, "e": 3933, "s": 3898, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3945, "s": 3933, "text": " Senol Atac" }, { "code": null, "e": 3952, "s": 3945, "text": " Print" }, { "code": null, "e": 3963, "s": 3952, "text": " Add Notes" } ]
Using Reduce in Python. How to use the reduce function in... | by Luay Matalka | Towards Data Science
Python is an object-oriented programming (OOP) language. However, it provides some tools that provide a functional programming style. Some of these tools include the map(), filter(), and reduce() functions. In this tutorial, we will explore the reduce() function and unravel the versatility and usefulness that it provides. The map() and filter() functions are covered in detail here: towardsdatascience.com The best way to introduce the reduce() function is to start with a problem and attempt to solve it the old-fashioned way, using a for loop. Then we can attempt the same task using the reduce function. Let’s say that we have a list of numbers and we want to return their product. In other words, we want to multiply all the numbers in the list together and return that single value. We can accomplish this using a for loop: We have our list of numbers, num_list. We want to multiply the numbers in this list together and get their product. We create the variable product and set it equal to 1. We then loop through num_list using a for loop, and we multiply each number by the result of the previous iteration. After looping through num_list, the product, or the accumulator, will equal 120, which is the product of all the numbers in the list. It turns out that we can accomplish the above task using the reduce function instead of a for loop. The reduce function can take in three arguments, two of which are required. The two required arguments are: a function (that itself takes in two arguments), and an iterable (such as a list). The third argument, which is an initializer, is optional and thus we will discuss it later on. reduce(function, iterable[, initializer]) The reduce function is in the module functools, which contains higher-order functions. Higher-order functions are functions that act on or return other functions. Therefore, in order to use the reduce function, we either need to import the entire functools module, or we can import only the reduce function from functools: import functoolsfrom functools import reduce Note: if we import functools, we would need to access the reduce function like so: functools.reduce(arguments). If we import the reduce function only from the functools module, we can access the reduce function by just typing reduce(arguments). As previously noted, the reduce function takes in two required arguments: a function and an iterable. In order to avoid confusion between the reduce function and the function it takes in as an argument, I will refer to the reduce function as just reduce. The first argument that reduce takes in, the function, must itself take in two arguments. Reduce will then apply this function cumulatively to the elements of the iterable (from left to right), and reduces it to a single value. Let’s look at an example: Let’s say the iterable we use is a list, such as num_list from the above example: num_list = [1,2,3,4,5] And the function we use as the first argument for reduce is the following: def prod(x, y): return x * y This prod function takes in two arguments: x and y. It then returns their product, or x * y. Let’s pass in the prod function and num_list as our function and iterable, respectively, to reduce: from functools import reduceproduct = reduce(prod, num_list) Our iterable object is num_list, which is the list: [1,2,3,4,5]. Our function, prod, takes in two arguments, x and y. Reduce will start by taking the first two elements of num_list, 1 and 2, and passes them in to our prod function as the x and y arguments. The prod function returns their product, or 1 * 2, which equals 2. Reduce will then use this accumulated value of 2 as the new or updated x value, and uses the next element in num_list, which is 3, as our new or updated y value. It then sends these two values (2 and 3) as x and y to our prod function, which then returns their product, 2 * 3, or 6. This 6 will then be used as our new or updated x value, and the next element in num_list will be used as our new or updated y value, which is 4. It then sends 6 and 4 as our x and y values to the prod function, which returns 24. Thus, our new x value is 24, and our new y value is the next element from num_list, or 5. These two values are passed to the prod function as our x and y values, and prod returns their product, 24 * 5, which equals 120. Thus, reduce took an iterable object, in this case num_list, and reduced it down to a single value, 120. This value is then assigned to the variable product. In other words, the x argument gets updated with the accumulated value, and the y argument gets updated from the iterable. towardsdatascience.com Remember how we said that reduce can take in an optional third argument, the initializer? The default value for it is None. If we pass in an initializer, it will be used as the first x value by reduce (instead of x being the first element of the iterable). So if we passed in the number 2 in the above example as the initializer: product = reduce(prod, num_list, 2)print(product) #240 Then the first two values or arguments for x and y will be 2 and 1, respectively. All subsequent steps will be the same. In other words, the initializer is placed before the elements of our iterable in the calculation. Instead of passing in prod as the function in the above example, we can instead use a lambda expression (or anonymous function) to significantly shorten our code: product = reduce(lambda x,y: x*y, num_list) Note how the lambda expression takes in two arguments: x and y, and then returns their product, x*y. Here is a full tutorial on how to use lambda expressions: towardsdatascience.com There are so many other scenarios of when we can use reduce. For example, we can find the sum of the numbers in a list: num_list = [1,2,3,4,5]sum = reduce(lambda x,y: x + y, num_list)print(sum) #15 Or we can find the maximum number in a list: num_list = [1,2,3,4,5]max_num = reduce(lambda x,y: x if x > y else y, num_list)print(max_num) #5 Or the minimum number in a list: num_list = [1,2,3,4,5]min_num = reduce(lambda x,y: x if x < y else y, num_list)print(min_num) #1 And so many other applications! Note: Python does have built-in functions such as max(), min(), and sum() that would have been easier to use for these three examples. However, the goal was to show how reduce() can be used to accomplish many different tasks. In this tutorial, we learned how to import and use the reduce function in python. We then saw how lambda expressions can be passed in as an argument to reduce. Lastly, we saw some examples of how reduce can be used.
[ { "code": null, "e": 496, "s": 172, "text": "Python is an object-oriented programming (OOP) language. However, it provides some tools that provide a functional programming style. Some of these tools include the map(), filter(), and reduce() functions. In this tutorial, we will explore the reduce() function and unravel the versatility and usefulness that it provides." }, { "code": null, "e": 557, "s": 496, "text": "The map() and filter() functions are covered in detail here:" }, { "code": null, "e": 580, "s": 557, "text": "towardsdatascience.com" }, { "code": null, "e": 781, "s": 580, "text": "The best way to introduce the reduce() function is to start with a problem and attempt to solve it the old-fashioned way, using a for loop. Then we can attempt the same task using the reduce function." }, { "code": null, "e": 1003, "s": 781, "text": "Let’s say that we have a list of numbers and we want to return their product. In other words, we want to multiply all the numbers in the list together and return that single value. We can accomplish this using a for loop:" }, { "code": null, "e": 1424, "s": 1003, "text": "We have our list of numbers, num_list. We want to multiply the numbers in this list together and get their product. We create the variable product and set it equal to 1. We then loop through num_list using a for loop, and we multiply each number by the result of the previous iteration. After looping through num_list, the product, or the accumulator, will equal 120, which is the product of all the numbers in the list." }, { "code": null, "e": 1810, "s": 1424, "text": "It turns out that we can accomplish the above task using the reduce function instead of a for loop. The reduce function can take in three arguments, two of which are required. The two required arguments are: a function (that itself takes in two arguments), and an iterable (such as a list). The third argument, which is an initializer, is optional and thus we will discuss it later on." }, { "code": null, "e": 1852, "s": 1810, "text": "reduce(function, iterable[, initializer])" }, { "code": null, "e": 2175, "s": 1852, "text": "The reduce function is in the module functools, which contains higher-order functions. Higher-order functions are functions that act on or return other functions. Therefore, in order to use the reduce function, we either need to import the entire functools module, or we can import only the reduce function from functools:" }, { "code": null, "e": 2220, "s": 2175, "text": "import functoolsfrom functools import reduce" }, { "code": null, "e": 2465, "s": 2220, "text": "Note: if we import functools, we would need to access the reduce function like so: functools.reduce(arguments). If we import the reduce function only from the functools module, we can access the reduce function by just typing reduce(arguments)." }, { "code": null, "e": 2720, "s": 2465, "text": "As previously noted, the reduce function takes in two required arguments: a function and an iterable. In order to avoid confusion between the reduce function and the function it takes in as an argument, I will refer to the reduce function as just reduce." }, { "code": null, "e": 2948, "s": 2720, "text": "The first argument that reduce takes in, the function, must itself take in two arguments. Reduce will then apply this function cumulatively to the elements of the iterable (from left to right), and reduces it to a single value." }, { "code": null, "e": 2974, "s": 2948, "text": "Let’s look at an example:" }, { "code": null, "e": 3056, "s": 2974, "text": "Let’s say the iterable we use is a list, such as num_list from the above example:" }, { "code": null, "e": 3079, "s": 3056, "text": "num_list = [1,2,3,4,5]" }, { "code": null, "e": 3154, "s": 3079, "text": "And the function we use as the first argument for reduce is the following:" }, { "code": null, "e": 3186, "s": 3154, "text": "def prod(x, y): return x * y" }, { "code": null, "e": 3279, "s": 3186, "text": "This prod function takes in two arguments: x and y. It then returns their product, or x * y." }, { "code": null, "e": 3379, "s": 3279, "text": "Let’s pass in the prod function and num_list as our function and iterable, respectively, to reduce:" }, { "code": null, "e": 3440, "s": 3379, "text": "from functools import reduceproduct = reduce(prod, num_list)" }, { "code": null, "e": 4777, "s": 3440, "text": "Our iterable object is num_list, which is the list: [1,2,3,4,5]. Our function, prod, takes in two arguments, x and y. Reduce will start by taking the first two elements of num_list, 1 and 2, and passes them in to our prod function as the x and y arguments. The prod function returns their product, or 1 * 2, which equals 2. Reduce will then use this accumulated value of 2 as the new or updated x value, and uses the next element in num_list, which is 3, as our new or updated y value. It then sends these two values (2 and 3) as x and y to our prod function, which then returns their product, 2 * 3, or 6. This 6 will then be used as our new or updated x value, and the next element in num_list will be used as our new or updated y value, which is 4. It then sends 6 and 4 as our x and y values to the prod function, which returns 24. Thus, our new x value is 24, and our new y value is the next element from num_list, or 5. These two values are passed to the prod function as our x and y values, and prod returns their product, 24 * 5, which equals 120. Thus, reduce took an iterable object, in this case num_list, and reduced it down to a single value, 120. This value is then assigned to the variable product. In other words, the x argument gets updated with the accumulated value, and the y argument gets updated from the iterable." }, { "code": null, "e": 4800, "s": 4777, "text": "towardsdatascience.com" }, { "code": null, "e": 5130, "s": 4800, "text": "Remember how we said that reduce can take in an optional third argument, the initializer? The default value for it is None. If we pass in an initializer, it will be used as the first x value by reduce (instead of x being the first element of the iterable). So if we passed in the number 2 in the above example as the initializer:" }, { "code": null, "e": 5185, "s": 5130, "text": "product = reduce(prod, num_list, 2)print(product) #240" }, { "code": null, "e": 5404, "s": 5185, "text": "Then the first two values or arguments for x and y will be 2 and 1, respectively. All subsequent steps will be the same. In other words, the initializer is placed before the elements of our iterable in the calculation." }, { "code": null, "e": 5567, "s": 5404, "text": "Instead of passing in prod as the function in the above example, we can instead use a lambda expression (or anonymous function) to significantly shorten our code:" }, { "code": null, "e": 5611, "s": 5567, "text": "product = reduce(lambda x,y: x*y, num_list)" }, { "code": null, "e": 5712, "s": 5611, "text": "Note how the lambda expression takes in two arguments: x and y, and then returns their product, x*y." }, { "code": null, "e": 5770, "s": 5712, "text": "Here is a full tutorial on how to use lambda expressions:" }, { "code": null, "e": 5793, "s": 5770, "text": "towardsdatascience.com" }, { "code": null, "e": 5854, "s": 5793, "text": "There are so many other scenarios of when we can use reduce." }, { "code": null, "e": 5913, "s": 5854, "text": "For example, we can find the sum of the numbers in a list:" }, { "code": null, "e": 5991, "s": 5913, "text": "num_list = [1,2,3,4,5]sum = reduce(lambda x,y: x + y, num_list)print(sum) #15" }, { "code": null, "e": 6036, "s": 5991, "text": "Or we can find the maximum number in a list:" }, { "code": null, "e": 6133, "s": 6036, "text": "num_list = [1,2,3,4,5]max_num = reduce(lambda x,y: x if x > y else y, num_list)print(max_num) #5" }, { "code": null, "e": 6166, "s": 6133, "text": "Or the minimum number in a list:" }, { "code": null, "e": 6263, "s": 6166, "text": "num_list = [1,2,3,4,5]min_num = reduce(lambda x,y: x if x < y else y, num_list)print(min_num) #1" }, { "code": null, "e": 6295, "s": 6263, "text": "And so many other applications!" }, { "code": null, "e": 6521, "s": 6295, "text": "Note: Python does have built-in functions such as max(), min(), and sum() that would have been easier to use for these three examples. However, the goal was to show how reduce() can be used to accomplish many different tasks." } ]
numpy.char.center()
This function returns an array of the required width so that the input string is centered and padded on the left and right with fillchar. import numpy as np # np.char.center(arr, width,fillchar) print np.char.center('hello', 20,fillchar = '*') Here is its output − *******hello******** 63 Lectures 6 hours Abhilash Nelson 19 Lectures 8 hours DATAhill Solutions Srinivas Reddy 12 Lectures 3 hours DATAhill Solutions Srinivas Reddy 10 Lectures 2.5 hours Akbar Khan 20 Lectures 2 hours Pruthviraja L 63 Lectures 6 hours Anmol Print Add Notes Bookmark this page
[ { "code": null, "e": 2381, "s": 2243, "text": "This function returns an array of the required width so that the input string is centered and padded on the left and right with fillchar." }, { "code": null, "e": 2489, "s": 2381, "text": "import numpy as np \n# np.char.center(arr, width,fillchar) \nprint np.char.center('hello', 20,fillchar = '*')" }, { "code": null, "e": 2510, "s": 2489, "text": "Here is its output −" }, { "code": null, "e": 2532, "s": 2510, "text": "*******hello********\n" }, { "code": null, "e": 2565, "s": 2532, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 2582, "s": 2565, "text": " Abhilash Nelson" }, { "code": null, "e": 2615, "s": 2582, "text": "\n 19 Lectures \n 8 hours \n" }, { "code": null, "e": 2650, "s": 2615, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 2683, "s": 2650, "text": "\n 12 Lectures \n 3 hours \n" }, { "code": null, "e": 2718, "s": 2683, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 2753, "s": 2718, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2765, "s": 2753, "text": " Akbar Khan" }, { "code": null, "e": 2798, "s": 2765, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 2813, "s": 2798, "text": " Pruthviraja L" }, { "code": null, "e": 2846, "s": 2813, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 2853, "s": 2846, "text": " Anmol" }, { "code": null, "e": 2860, "s": 2853, "text": " Print" }, { "code": null, "e": 2871, "s": 2860, "text": " Add Notes" } ]
Java Examples - Execute multiple SQL statements
How to execute multiple SQL commands on a database simultaneously? Following example uses addBatch & executeBatch commands to execute multiple SQL commands simultaneously. import java.sql.*; public class jdbcConn { public static void main(String[] args) throws Exception { Class.forName("org.apache.derby.jdbc.ClientDriver"); Connection con = DriverManager.getConnection( "jdbc:derby://localhost:1527/testDb","name","pass"); Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); String insertEmp1 = "insert into emp values(10,'jay','trainee')"; String insertEmp2 = "insert into emp values(11,'jayes','trainee')"; String insertEmp3 = "insert into emp values(12,'shail','trainee')"; con.setAutoCommit(false); stmt.addBatch(insertEmp1); stmt.addBatch(insertEmp2); stmt.addBatch(insertEmp3); ResultSet rs = stmt.executeQuery("select * from emp"); rs.last(); System.out.println("rows before batch execution= "+ rs.getRow()); stmt.executeBatch(); con.commit(); System.out.println("Batch executed"); rs = stmt.executeQuery("select * from emp"); rs.last(); System.out.println("rows after batch execution = "+ rs.getRow()); } } The above code sample will produce the following result. The result may vary. rows before batch execution = 6 Batch executed rows after batch execution = = 9 Print Add Notes Bookmark this page
[ { "code": null, "e": 2135, "s": 2068, "text": "How to execute multiple SQL commands on a database simultaneously?" }, { "code": null, "e": 2240, "s": 2135, "text": "Following example uses addBatch & executeBatch commands to execute multiple SQL commands simultaneously." }, { "code": null, "e": 3408, "s": 2240, "text": "import java.sql.*;\n\npublic class jdbcConn {\n public static void main(String[] args) throws Exception {\n Class.forName(\"org.apache.derby.jdbc.ClientDriver\");\n Connection con = DriverManager.getConnection(\n \"jdbc:derby://localhost:1527/testDb\",\"name\",\"pass\");\n \n Statement stmt = con.createStatement(\n ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);\n \n String insertEmp1 = \"insert into emp values(10,'jay','trainee')\";\n String insertEmp2 = \"insert into emp values(11,'jayes','trainee')\";\n String insertEmp3 = \"insert into emp values(12,'shail','trainee')\";\n con.setAutoCommit(false);\n \n stmt.addBatch(insertEmp1);\n stmt.addBatch(insertEmp2);\n stmt.addBatch(insertEmp3);\n \n ResultSet rs = stmt.executeQuery(\"select * from emp\");\n rs.last();\n System.out.println(\"rows before batch execution= \"+ rs.getRow());\n stmt.executeBatch();\n con.commit();\n \n System.out.println(\"Batch executed\");\n rs = stmt.executeQuery(\"select * from emp\");\n rs.last();\n System.out.println(\"rows after batch execution = \"+ rs.getRow());\n }\n} " }, { "code": null, "e": 3486, "s": 3408, "text": "The above code sample will produce the following result. The result may vary." }, { "code": null, "e": 3568, "s": 3486, "text": "rows before batch execution = 6\nBatch executed\nrows after batch execution = = 9 \n" }, { "code": null, "e": 3575, "s": 3568, "text": " Print" }, { "code": null, "e": 3586, "s": 3575, "text": " Add Notes" } ]
Python String | strip() - GeeksforGeeks
21 Jan, 2021 The strip() method in-built function of Python is used to remove all the leading and trailing spaces from a string. Syntax :string.strip([chars]) Parameter: chars(optional): Character or a set of characters, that needs to be removed from the string. Returns: A copy of the string with both leading and trailing characters stripped. In case the character of the string to the left doesn’t match with the characters in the char parameter, the method stops removing the leading characters. In case the character of the string to the right doesn’t match with the characters in the char parameter, the method stops removing the trailing characters. Example #1: Python3 # Python code to illustrate the working of strip()string = ' Geeks for Geeks ' # Leading spaces are removedprint(string.strip()) # Geeks is removedprint(string.strip(' Geeks')) # Not removed since the spaces do not matchprint(string.strip('Geeks')) Output : Geeks for Geeks for Geeks for Geeks Example #2: Python3 # Python code to illustrate the working of strip()string = '@@@@Geeks for Geeks@@@@@' # Strip all '@' from beginning and endingprint(string.strip('@')) string = 'www.Geeksforgeeks.org' # '.grow' removes 'www' and 'org' and '.'print(string.strip('.grow')) Output: Geeks for Geeks Geeksforgeeks Example #3:The following code shows an application of strip() in python. Python3 # Python code to check for identifiersdef Count(string): print("Length before strip()") print(len(string)) # Using strip() to remove white spaces str = string.strip() print("Length after removing spaces") return str # Driver Codestring = " Geeks for Geeks "print(len(Count(string))) Output: Length before strip() 17 Length after removing spaces 15 nandishwar001 Akanksha_Rai RajuKumar19 Python-Built-in-functions python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Create a Pandas DataFrame from Lists Box Plot in Python using Matplotlib Python | Get dictionary keys as a list Enumerate() in Python Python Dictionary Bar Plot in Matplotlib Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method loops in python Python - Call function from another file
[ { "code": null, "e": 24026, "s": 23998, "text": "\n21 Jan, 2021" }, { "code": null, "e": 24142, "s": 24026, "text": "The strip() method in-built function of Python is used to remove all the leading and trailing spaces from a string." }, { "code": null, "e": 24172, "s": 24142, "text": "Syntax :string.strip([chars])" }, { "code": null, "e": 24183, "s": 24172, "text": "Parameter:" }, { "code": null, "e": 24276, "s": 24183, "text": "chars(optional): Character or a set of characters, that needs to be removed from the string." }, { "code": null, "e": 24358, "s": 24276, "text": "Returns: A copy of the string with both leading and trailing characters stripped." }, { "code": null, "e": 24513, "s": 24358, "text": "In case the character of the string to the left doesn’t match with the characters in the char parameter, the method stops removing the leading characters." }, { "code": null, "e": 24670, "s": 24513, "text": "In case the character of the string to the right doesn’t match with the characters in the char parameter, the method stops removing the trailing characters." }, { "code": null, "e": 24683, "s": 24670, "text": "Example #1: " }, { "code": null, "e": 24691, "s": 24683, "text": "Python3" }, { "code": "# Python code to illustrate the working of strip()string = ' Geeks for Geeks ' # Leading spaces are removedprint(string.strip()) # Geeks is removedprint(string.strip(' Geeks')) # Not removed since the spaces do not matchprint(string.strip('Geeks'))", "e": 24946, "s": 24691, "text": null }, { "code": null, "e": 24956, "s": 24946, "text": "Output : " }, { "code": null, "e": 24998, "s": 24956, "text": "Geeks for Geeks\nfor\n Geeks for Geeks " }, { "code": null, "e": 25011, "s": 24998, "text": "Example #2: " }, { "code": null, "e": 25019, "s": 25011, "text": "Python3" }, { "code": "# Python code to illustrate the working of strip()string = '@@@@Geeks for Geeks@@@@@' # Strip all '@' from beginning and endingprint(string.strip('@')) string = 'www.Geeksforgeeks.org' # '.grow' removes 'www' and 'org' and '.'print(string.strip('.grow'))", "e": 25274, "s": 25019, "text": null }, { "code": null, "e": 25283, "s": 25274, "text": "Output: " }, { "code": null, "e": 25313, "s": 25283, "text": "Geeks for Geeks\nGeeksforgeeks" }, { "code": null, "e": 25387, "s": 25313, "text": "Example #3:The following code shows an application of strip() in python. " }, { "code": null, "e": 25395, "s": 25387, "text": "Python3" }, { "code": "# Python code to check for identifiersdef Count(string): print(\"Length before strip()\") print(len(string)) # Using strip() to remove white spaces str = string.strip() print(\"Length after removing spaces\") return str # Driver Codestring = \" Geeks for Geeks \"print(len(Count(string)))", "e": 25702, "s": 25395, "text": null }, { "code": null, "e": 25710, "s": 25702, "text": "Output:" }, { "code": null, "e": 25767, "s": 25710, "text": "Length before strip()\n17\nLength after removing spaces\n15" }, { "code": null, "e": 25781, "s": 25767, "text": "nandishwar001" }, { "code": null, "e": 25794, "s": 25781, "text": "Akanksha_Rai" }, { "code": null, "e": 25806, "s": 25794, "text": "RajuKumar19" }, { "code": null, "e": 25832, "s": 25806, "text": "Python-Built-in-functions" }, { "code": null, "e": 25846, "s": 25832, "text": "python-string" }, { "code": null, "e": 25853, "s": 25846, "text": "Python" }, { "code": null, "e": 25951, "s": 25853, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25960, "s": 25951, "text": "Comments" }, { "code": null, "e": 25973, "s": 25960, "text": "Old Comments" }, { "code": null, "e": 26010, "s": 25973, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26046, "s": 26010, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 26085, "s": 26046, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26107, "s": 26085, "text": "Enumerate() in Python" }, { "code": null, "e": 26125, "s": 26107, "text": "Python Dictionary" }, { "code": null, "e": 26148, "s": 26125, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 26199, "s": 26148, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 26231, "s": 26199, "text": "Python Dictionary keys() method" }, { "code": null, "e": 26247, "s": 26231, "text": "loops in python" } ]
Highest and lowest in an array JavaScript
We are required to write a function that takes in an array of numbers and returns the difference between its highest and lowest number. At first, create an array − const arr = [23,54,65,76,87,87,431,-6,22,4,-454]; Now, find maximum and minimum values with Math.max() and Math.min() methods, respectively − const arrayDifference = (arr) => { let min, max; arr.forEach((num, index) => { if(index === 0){ min = num; max = num; }else{ min = Math.min(num, min); max = Math.max(num, max); }; }); The complete code is as follows − const arr = [23,54,65,76,87,87,431,-6,22,4,-454]; const arrayDifference = (arr) => { let min, max; arr.forEach((num, index) => { if(index === 0){ min = num; max = num; }else{ min = Math.min(num, min); max = Math.max(num, max); }; }); return max - min; }; console.log(arrayDifference(arr)); The output in the console will be − 885
[ { "code": null, "e": 1198, "s": 1062, "text": "We are required to write a function that takes in an array of numbers and returns the difference between its highest and lowest number." }, { "code": null, "e": 1226, "s": 1198, "text": "At first, create an array −" }, { "code": null, "e": 1276, "s": 1226, "text": "const arr = [23,54,65,76,87,87,431,-6,22,4,-454];" }, { "code": null, "e": 1368, "s": 1276, "text": "Now, find maximum and minimum values with Math.max() and Math.min() methods, respectively −" }, { "code": null, "e": 1609, "s": 1368, "text": "const arrayDifference = (arr) => {\n let min, max;\n arr.forEach((num, index) => {\n if(index === 0){\n min = num;\n max = num;\n }else{\n min = Math.min(num, min);\n max = Math.max(num, max);\n };\n});" }, { "code": null, "e": 1643, "s": 1609, "text": "The complete code is as follows −" }, { "code": null, "e": 1999, "s": 1643, "text": "const arr = [23,54,65,76,87,87,431,-6,22,4,-454];\nconst arrayDifference = (arr) => {\n let min, max;\n arr.forEach((num, index) => {\n if(index === 0){\n min = num;\n max = num;\n }else{\n min = Math.min(num, min);\n max = Math.max(num, max);\n };\n });\n return max - min;\n};\nconsole.log(arrayDifference(arr));" }, { "code": null, "e": 2035, "s": 1999, "text": "The output in the console will be −" }, { "code": null, "e": 2039, "s": 2035, "text": "885" } ]
How can I display text over columns in a bar chart in Matplotlib?
To display text over columns in a bar chart, we can use text() method so that we could place text at a specific location (x and y) of the bars column. Create lists for x, y and percentage. Create lists for x, y and percentage. Make a bar plot using bar() method. Make a bar plot using bar() method. Iterate zipped x, y and percentage to place text for the bars column. Iterate zipped x, y and percentage to place text for the bars column. To display the figure, use show() method. To display the figure, use show() method. import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True x = ['A', 'B', 'C', 'D', 'E'] y = [1, 3, 2, 0, 4] percentage = [10, 30, 20, 0, 40] ax = plt.bar(x, y) for x, y, p in zip(x, y, percentage): plt.text(x, y, p) plt.show()
[ { "code": null, "e": 1213, "s": 1062, "text": "To display text over columns in a bar chart, we can use text() method so that we could place text at a specific location (x and y) of the bars column." }, { "code": null, "e": 1251, "s": 1213, "text": "Create lists for x, y and percentage." }, { "code": null, "e": 1289, "s": 1251, "text": "Create lists for x, y and percentage." }, { "code": null, "e": 1325, "s": 1289, "text": "Make a bar plot using bar() method." }, { "code": null, "e": 1361, "s": 1325, "text": "Make a bar plot using bar() method." }, { "code": null, "e": 1431, "s": 1361, "text": "Iterate zipped x, y and percentage to place text for the bars column." }, { "code": null, "e": 1501, "s": 1431, "text": "Iterate zipped x, y and percentage to place text for the bars column." }, { "code": null, "e": 1543, "s": 1501, "text": "To display the figure, use show() method." }, { "code": null, "e": 1585, "s": 1543, "text": "To display the figure, use show() method." }, { "code": null, "e": 1876, "s": 1585, "text": "import matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = ['A', 'B', 'C', 'D', 'E']\ny = [1, 3, 2, 0, 4]\npercentage = [10, 30, 20, 0, 40]\nax = plt.bar(x, y)\nfor x, y, p in zip(x, y, percentage):\n plt.text(x, y, p)\nplt.show()" } ]
WebDriver executeAsyncScript vs executeScript in Selenium
There are differences between executeAsyncScript and executeScript methods. For an executeScript method, JavaScript Executor runs the JavaScript with the reference to the present selected window or frame. The script within the method shall run as the body of the unnamed function. Inside the script, the documents are used to point to the present document. Also, the local variables will not be present as the script has completed execution. However, the global variables shall be present. If the script consists of a return statement, then the below rules are followed − A webelement is returned for an HTML element. A webelement is returned for an HTML element. A double is returned for a decimal number. A double is returned for a decimal number. A long is returned for a non-decimal number. A long is returned for a non-decimal number. A Boolean is returned for a Boolean number. A Boolean is returned for a Boolean number. A string is returned for all the other cases. A string is returned for all the other cases. A list of objects is returned following the above rules for an array. A list of objects is returned following the above rules for an array. If the value is null or there is nothing to return, a null is returned. If the value is null or there is nothing to return, a null is returned. The arguments of the executeScript method can be Boolean, string, webelement, list or a number. An exception is raised, if the arguments are not of these types. The arguments shall be available using the arguments keyword. JavascriptExecutor j = (JavascriptExecutor) driver; String str = (String) j.executeScript("return document.readyState"); import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.JavascriptExecutor; public class ExecuteScriptMethod{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://www.tutorialspoint.com/index.htm"); // Javascript executor JavascriptExecutor j = (JavascriptExecutor) driver; //executeScript method String str = (String) j.executeScript("return document.readyState"); System.out.println(str); driver.quit(); } } For an executeAsyncScript method, JavaScript Executor runs an asynchronous part of JavaScript with the reference to the present selected window or frame. In comparison to executeScript, the scripts run with this method should clearly point that they are completed by invoking the given callback. The callback is always added as the last argument within the executed function. The first argument passed is used to get the script result. The values returned are handled in the similar way as the synchronous method. We can perform the below tasks with the executeAsyncScript method − To set the browser timeout. To set the browser timeout. To synchronize a test with an AJAX application. To synchronize a test with an AJAX application. To inject an XMLHttpRequest and wait for the result. To inject an XMLHttpRequest and wait for the result. The arguments of executeAsyncScript method can be Boolean, string, webelement, list or a number. An exception is raised, if the arguments are not of these types. The arguments shall be available using the arguments keyword. JavascriptExecutor j = (JavascriptExecutor) driver; j.executeAsyncScript ("window.setTimeout(arguments[arguments.length − 1], 800);"); import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; public class ExecuteAsyncScriptMethod{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://www.tutorialspoint.com/index.htm"); //get current system time long s = System.currentTimeMillis(); // Javascript executor JavascriptExecutor j = (JavascriptExecutor) driver; //executeAsyncScript method to set timeout j.executeAsyncScript ("window.setTimeout(arguments[arguments.length − 1], 800);"); System.out.println( "Time Elapsed is: " + (System.currentTimeMillis() − s)); driver.quit(); } }
[ { "code": null, "e": 1343, "s": 1062, "text": "There are differences between executeAsyncScript and executeScript methods. For an executeScript method, JavaScript Executor runs the JavaScript with the reference to the present selected window or frame. The script within the method shall run as the body of the unnamed function." }, { "code": null, "e": 1552, "s": 1343, "text": "Inside the script, the documents are used to point to the present document. Also, the local variables will not be present as the script has completed execution. However, the global variables shall be present." }, { "code": null, "e": 1634, "s": 1552, "text": "If the script consists of a return statement, then the below rules are followed −" }, { "code": null, "e": 1680, "s": 1634, "text": "A webelement is returned for an HTML element." }, { "code": null, "e": 1726, "s": 1680, "text": "A webelement is returned for an HTML element." }, { "code": null, "e": 1769, "s": 1726, "text": "A double is returned for a decimal number." }, { "code": null, "e": 1812, "s": 1769, "text": "A double is returned for a decimal number." }, { "code": null, "e": 1857, "s": 1812, "text": "A long is returned for a non-decimal number." }, { "code": null, "e": 1902, "s": 1857, "text": "A long is returned for a non-decimal number." }, { "code": null, "e": 1946, "s": 1902, "text": "A Boolean is returned for a Boolean number." }, { "code": null, "e": 1990, "s": 1946, "text": "A Boolean is returned for a Boolean number." }, { "code": null, "e": 2036, "s": 1990, "text": "A string is returned for all the other cases." }, { "code": null, "e": 2082, "s": 2036, "text": "A string is returned for all the other cases." }, { "code": null, "e": 2152, "s": 2082, "text": "A list of objects is returned following the above rules for an array." }, { "code": null, "e": 2222, "s": 2152, "text": "A list of objects is returned following the above rules for an array." }, { "code": null, "e": 2294, "s": 2222, "text": "If the value is null or there is nothing to return, a null is returned." }, { "code": null, "e": 2366, "s": 2294, "text": "If the value is null or there is nothing to return, a null is returned." }, { "code": null, "e": 2589, "s": 2366, "text": "The arguments of the executeScript method can be Boolean, string, webelement, list or a number. An exception is raised, if the arguments are not of these types. The arguments shall be available using the arguments keyword." }, { "code": null, "e": 2710, "s": 2589, "text": "JavascriptExecutor j = (JavascriptExecutor) driver;\nString str = (String) j.executeScript(\"return document.readyState\");" }, { "code": null, "e": 3431, "s": 2710, "text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.JavascriptExecutor;\npublic class ExecuteScriptMethod{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n // Javascript executor\n JavascriptExecutor j = (JavascriptExecutor) driver;\n //executeScript method\n String str = (String) j.executeScript(\"return document.readyState\");\n System.out.println(str);\n driver.quit();\n }\n}" }, { "code": null, "e": 3727, "s": 3431, "text": "For an executeAsyncScript method, JavaScript Executor runs an asynchronous part of JavaScript with the reference to the present selected window or frame. In comparison to executeScript, the scripts run with this method should clearly point that they are completed by invoking the given callback." }, { "code": null, "e": 3945, "s": 3727, "text": "The callback is always added as the last argument within the executed function. The first argument passed is used to get the script result. The values returned are handled in the similar way as the synchronous method." }, { "code": null, "e": 4013, "s": 3945, "text": "We can perform the below tasks with the executeAsyncScript method −" }, { "code": null, "e": 4041, "s": 4013, "text": "To set the browser timeout." }, { "code": null, "e": 4069, "s": 4041, "text": "To set the browser timeout." }, { "code": null, "e": 4117, "s": 4069, "text": "To synchronize a test with an AJAX application." }, { "code": null, "e": 4165, "s": 4117, "text": "To synchronize a test with an AJAX application." }, { "code": null, "e": 4218, "s": 4165, "text": "To inject an XMLHttpRequest and wait for the result." }, { "code": null, "e": 4271, "s": 4218, "text": "To inject an XMLHttpRequest and wait for the result." }, { "code": null, "e": 4495, "s": 4271, "text": "The arguments of executeAsyncScript method can be Boolean, string, webelement, list or a number. An exception is raised, if the arguments are not of these types. The arguments shall be available using the arguments keyword." }, { "code": null, "e": 4630, "s": 4495, "text": "JavascriptExecutor j = (JavascriptExecutor) driver;\nj.executeAsyncScript\n(\"window.setTimeout(arguments[arguments.length − 1], 800);\");" }, { "code": null, "e": 5567, "s": 4630, "text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.JavascriptExecutor;\npublic class ExecuteAsyncScriptMethod{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n //get current system time\n long s = System.currentTimeMillis();\n // Javascript executor\n JavascriptExecutor j = (JavascriptExecutor) driver;\n //executeAsyncScript method to set timeout\n j.executeAsyncScript\n (\"window.setTimeout(arguments[arguments.length − 1], 800);\");\n System.out.println(\n \"Time Elapsed is: \" + (System.currentTimeMillis() − s));\n driver.quit();\n }\n}" } ]
Pandas GroupBy – Count the occurrences of each combination
To groupby columns and count the occurrences of each combination in Pandas, we use the DataFrame.groupby() with size(). The groupby() method separates the DataFrame into groups. At first, let us import the pandas library with an alias pd − import pandas as pd Initialize the data of lists − # initializing the data mylist = {'Car': ['BMW', 'Mercedes', 'Lamborgini', 'Audi', 'Mercedes', 'Porche', 'RollsRoyce', 'BMW'], 'Place': ['Delhi', 'Hyderabad', 'Chandigarh', 'Bangalore', 'Hyderabad', 'Mumbai', 'Mumbai','Delhi'], 'Sold': [95, 80, 80, 75, 90, 90, 95, 50 ]} Next, we will create a DataFrame − # DataFrame dataFrame = pd.DataFrame(mylist, columns=['Car', 'Place', 'Sold']) Now, use the groupby() to count the occurrence with the size() − print("Counting the occurrences...") res = dataFrame.groupby(['Car', 'Place']).size() Following is the code to count the occurrences of each combination − # importing library import pandas as pd # initializing the data mylist = {'Car': ['BMW', 'Mercedes', 'Lamborgini', 'Audi', 'Mercedes', 'Porsche', 'RollsRoyce', 'BMW'], 'Place': ['Delhi', 'Hyderabad', 'Chandigarh', 'Bangalore', 'Hyderabad', 'Mumbai', 'Mumbai','Delhi'], 'Sold': [95, 80, 80, 75, 90, 90, 95, 50 ]} # DataFrame dataFrame = pd.DataFrame(mylist, columns=['Car', 'Place', 'Sold']) print(dataFrame) print("Counting the occurrences...") res = dataFrame.groupby(['Car', 'Place']).size() # Displaying the occurrences print(res) This will produce the following output − Car Place Sold 0 BMW Delhi 95 1 Mercedes Hyderabad 80 2 Lamborgini Chandigarh 80 3 Audi Bangalore 75 4 Mercedes Hyderabad 90 5 Porsche Mumbai 90 6 RollsRoyce Mumbai 95 7 BMW Delhi 50 Counting the occurrences... Car Place Audi Bangalore 1 BMW Delhi 2 Lamborgini Chandigarh 1 Mercedes Hyderabad 2 Porsche Mumbai 1 RollsRoyce Mumbai 1 dtype: int64
[ { "code": null, "e": 1240, "s": 1062, "text": "To groupby columns and count the occurrences of each combination in Pandas, we use the DataFrame.groupby() with size(). The groupby() method separates the DataFrame into groups." }, { "code": null, "e": 1302, "s": 1240, "text": "At first, let us import the pandas library with an alias pd −" }, { "code": null, "e": 1322, "s": 1302, "text": "import pandas as pd" }, { "code": null, "e": 1353, "s": 1322, "text": "Initialize the data of lists −" }, { "code": null, "e": 1624, "s": 1353, "text": "# initializing the data\nmylist = {'Car': ['BMW', 'Mercedes', 'Lamborgini', 'Audi', 'Mercedes', 'Porche', 'RollsRoyce', 'BMW'], 'Place': ['Delhi', 'Hyderabad', 'Chandigarh', 'Bangalore', 'Hyderabad', 'Mumbai', 'Mumbai','Delhi'],\n'Sold': [95, 80, 80, 75, 90, 90, 95, 50 ]}" }, { "code": null, "e": 1659, "s": 1624, "text": "Next, we will create a DataFrame −" }, { "code": null, "e": 1738, "s": 1659, "text": "# DataFrame\ndataFrame = pd.DataFrame(mylist, columns=['Car', 'Place', 'Sold'])" }, { "code": null, "e": 1803, "s": 1738, "text": "Now, use the groupby() to count the occurrence with the size() −" }, { "code": null, "e": 1889, "s": 1803, "text": "print(\"Counting the occurrences...\")\nres = dataFrame.groupby(['Car', 'Place']).size()" }, { "code": null, "e": 1958, "s": 1889, "text": "Following is the code to count the occurrences of each combination −" }, { "code": null, "e": 2497, "s": 1958, "text": "# importing library\nimport pandas as pd\n\n# initializing the data\nmylist = {'Car': ['BMW', 'Mercedes', 'Lamborgini', 'Audi', 'Mercedes', 'Porsche', 'RollsRoyce', 'BMW'],\n'Place': ['Delhi', 'Hyderabad', 'Chandigarh', 'Bangalore', 'Hyderabad', 'Mumbai', 'Mumbai','Delhi'],\n'Sold': [95, 80, 80, 75, 90, 90, 95, 50 ]}\n\n# DataFrame\ndataFrame = pd.DataFrame(mylist, columns=['Car', 'Place', 'Sold'])\n\nprint(dataFrame)\n\nprint(\"Counting the occurrences...\")\nres = dataFrame.groupby(['Car', 'Place']).size()\n\n# Displaying the occurrences\nprint(res)" }, { "code": null, "e": 2538, "s": 2497, "text": "This will produce the following output −" }, { "code": null, "e": 3134, "s": 2538, "text": " Car Place Sold\n0 BMW Delhi 95\n1 Mercedes Hyderabad 80\n2 Lamborgini Chandigarh 80\n3 Audi Bangalore 75\n4 Mercedes Hyderabad 90\n5 Porsche Mumbai 90\n6 RollsRoyce Mumbai 95\n7 BMW Delhi 50\nCounting the occurrences...\nCar Place\nAudi Bangalore 1\nBMW Delhi 2\nLamborgini Chandigarh 1\nMercedes Hyderabad 2\nPorsche Mumbai 1\nRollsRoyce Mumbai 1\ndtype: int64" } ]
Shadowing of static functions in Java - GeeksforGeeks
19 Feb, 2021 In Java, if the name of a derived class static function is the same as a base class static function then the base class static function shadows (or conceals) the derived class static function. For example, the following Java code prints “A.fun()” Note: Static method is a class property, so if a static method is called from a class name or object having a class container then the method of that class is called not the object’s method. Java // file name: Main.java // Parent classclass A { static void fun() { System.out.println("A.fun()"); }} // B is inheriting A// Child classclass B extends A { static void fun() { System.out.println("B.fun()"); }} // Driver Methodpublic class Main { public static void main(String args[]) { A a = new B(); a.fun(); // prints A.fun(); // B a = new B(); // a.fun(); // prints B.fun() // the variable type decides the method // being invoked, not the assigned object type }} A.fun() Note: If we make both A.fun() and B.fun() as non-static then the above program would print “B.fun()”. While both methods are static types, the variable type decides the method being invoked, not the assigned object typePlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. NikhilJaiswal Shreevardhan indranilsharma Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Initialize an ArrayList in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java LinkedList in Java Collections in Java
[ { "code": null, "e": 23919, "s": 23891, "text": "\n19 Feb, 2021" }, { "code": null, "e": 24359, "s": 23919, "text": "In Java, if the name of a derived class static function is the same as a base class static function then the base class static function shadows (or conceals) the derived class static function. For example, the following Java code prints “A.fun()” Note: Static method is a class property, so if a static method is called from a class name or object having a class container then the method of that class is called not the object’s method. " }, { "code": null, "e": 24364, "s": 24359, "text": "Java" }, { "code": "// file name: Main.java // Parent classclass A { static void fun() { System.out.println(\"A.fun()\"); }} // B is inheriting A// Child classclass B extends A { static void fun() { System.out.println(\"B.fun()\"); }} // Driver Methodpublic class Main { public static void main(String args[]) { A a = new B(); a.fun(); // prints A.fun(); // B a = new B(); // a.fun(); // prints B.fun() // the variable type decides the method // being invoked, not the assigned object type }}", "e": 24892, "s": 24364, "text": null }, { "code": null, "e": 24901, "s": 24892, "text": "A.fun()\n" }, { "code": null, "e": 25246, "s": 24901, "text": "Note: If we make both A.fun() and B.fun() as non-static then the above program would print “B.fun()”. While both methods are static types, the variable type decides the method being invoked, not the assigned object typePlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 25260, "s": 25246, "text": "NikhilJaiswal" }, { "code": null, "e": 25273, "s": 25260, "text": "Shreevardhan" }, { "code": null, "e": 25288, "s": 25273, "text": "indranilsharma" }, { "code": null, "e": 25293, "s": 25288, "text": "Java" }, { "code": null, "e": 25298, "s": 25293, "text": "Java" }, { "code": null, "e": 25396, "s": 25298, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25405, "s": 25396, "text": "Comments" }, { "code": null, "e": 25418, "s": 25405, "text": "Old Comments" }, { "code": null, "e": 25469, "s": 25418, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 25499, "s": 25469, "text": "HashMap in Java with Examples" }, { "code": null, "e": 25530, "s": 25499, "text": "How to iterate any Map in Java" }, { "code": null, "e": 25562, "s": 25530, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 25580, "s": 25562, "text": "ArrayList in Java" }, { "code": null, "e": 25612, "s": 25580, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 25632, "s": 25612, "text": "Stack Class in Java" }, { "code": null, "e": 25656, "s": 25632, "text": "Singleton Class in Java" }, { "code": null, "e": 25675, "s": 25656, "text": "LinkedList in Java" } ]
Python SQLite - Cursor Object
The sqlite3.Cursor class is an instance using which you can invoke methods that execute SQLite statements, fetch data from the result sets of the queries. You can create Cursor object using the cursor() method of the Connection object/class. import sqlite3 #Connecting to sqlite conn = sqlite3.connect('example.db') #Creating a cursor object using the cursor() method cursor = conn.cursor() Following are the various methods provided by the Cursor class/object. execute() This routine executes an SQL statement. The SQL statement may be parameterized (i.e., placeholders instead of SQL literals). The psycopg2 module supports placeholder using %s sign For example:cursor.execute("insert into people values (%s, %s)", (who, age)) executemany() This routine executes an SQL command against all parameter sequences or mappings found in the sequence sql. fetchone() This method fetches the next row of a query result set, returning a single sequence, or None when no more data is available. fetchmany() This routine fetches the next set of rows of a query result, returning a list. An empty list is returned when no more rows are available. The method tries to fetch as many rows as indicated by the size parameter. fetchall() This routine fetches all (remaining) rows of a query result, returning a list. An empty list is returned when no rows are available. Following are the properties of the Cursor class − arraySize This is a read/write property you can set the number of rows returned by the fetchmany() method. description This is a read only property which returns the list containing the description of columns in a result-set. lastrowid This is a read only property, if there are any auto-incremented columns in the table, this returns the value generated for that column in the last INSERT or, UPDATE operation. rowcount This returns the number of rows returned/updated in case of SELECT and UPDATE operations. connection This read-only attribute provides the SQLite database Connection used by the Cursor object. 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": 3447, "s": 3205, "text": "The sqlite3.Cursor class is an instance using which you can invoke methods that execute SQLite statements, fetch data from the result sets of the queries. You can create Cursor object using the cursor() method of the Connection object/class." }, { "code": null, "e": 3598, "s": 3447, "text": "import sqlite3\n\n#Connecting to sqlite\nconn = sqlite3.connect('example.db')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()" }, { "code": null, "e": 3669, "s": 3598, "text": "Following are the various methods provided by the Cursor class/object." }, { "code": null, "e": 3679, "s": 3669, "text": "execute()" }, { "code": null, "e": 3859, "s": 3679, "text": "This routine executes an SQL statement. The SQL statement may be parameterized (i.e., placeholders instead of SQL literals). The psycopg2 module supports placeholder using %s sign" }, { "code": null, "e": 3936, "s": 3859, "text": "For example:cursor.execute(\"insert into people values (%s, %s)\", (who, age))" }, { "code": null, "e": 3950, "s": 3936, "text": "executemany()" }, { "code": null, "e": 4058, "s": 3950, "text": "This routine executes an SQL command against all parameter sequences or mappings found in the sequence sql." }, { "code": null, "e": 4069, "s": 4058, "text": "fetchone()" }, { "code": null, "e": 4194, "s": 4069, "text": "This method fetches the next row of a query result set, returning a single sequence, or None when no more data is available." }, { "code": null, "e": 4206, "s": 4194, "text": "fetchmany()" }, { "code": null, "e": 4419, "s": 4206, "text": "This routine fetches the next set of rows of a query result, returning a list. An empty list is returned when no more rows are available. The method tries to fetch as many rows as indicated by the size parameter." }, { "code": null, "e": 4430, "s": 4419, "text": "fetchall()" }, { "code": null, "e": 4563, "s": 4430, "text": "This routine fetches all (remaining) rows of a query result, returning a list. An empty list is returned when no rows are available." }, { "code": null, "e": 4614, "s": 4563, "text": "Following are the properties of the Cursor class −" }, { "code": null, "e": 4624, "s": 4614, "text": "arraySize" }, { "code": null, "e": 4721, "s": 4624, "text": "This is a read/write property you can set the number of rows returned by the fetchmany() method." }, { "code": null, "e": 4733, "s": 4721, "text": "description" }, { "code": null, "e": 4840, "s": 4733, "text": "This is a read only property which returns the list containing the description of columns in a result-set." }, { "code": null, "e": 4850, "s": 4840, "text": "lastrowid" }, { "code": null, "e": 5026, "s": 4850, "text": "This is a read only property, if there are any auto-incremented columns in the table, this returns the value generated for that column in the last INSERT or, UPDATE operation." }, { "code": null, "e": 5035, "s": 5026, "text": "rowcount" }, { "code": null, "e": 5125, "s": 5035, "text": "This returns the number of rows returned/updated in case of SELECT and UPDATE operations." }, { "code": null, "e": 5136, "s": 5125, "text": "connection" }, { "code": null, "e": 5228, "s": 5136, "text": "This read-only attribute provides the SQLite database Connection used by the Cursor object." }, { "code": null, "e": 5265, "s": 5228, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5281, "s": 5265, "text": " Malhar Lathkar" }, { "code": null, "e": 5314, "s": 5281, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 5333, "s": 5314, "text": " Arnab Chakraborty" }, { "code": null, "e": 5368, "s": 5333, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 5390, "s": 5368, "text": " In28Minutes Official" }, { "code": null, "e": 5424, "s": 5390, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 5452, "s": 5424, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5487, "s": 5452, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 5501, "s": 5487, "text": " Lets Kode It" }, { "code": null, "e": 5534, "s": 5501, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 5551, "s": 5534, "text": " Abhilash Nelson" }, { "code": null, "e": 5558, "s": 5551, "text": " Print" }, { "code": null, "e": 5569, "s": 5558, "text": " Add Notes" } ]
Interpreting Coefficients in Linear and Logistic Regression | by Jonathan Benton | Towards Data Science
Though I briefly summarize linear regression and logistic regression below, this post focuses more on the models’ coefficients. For more information about linear and logistic regression models in general, click here and here. When I used to work at a restaurant, the beginning of every shift was marked by the same conversation amongst the staff: how busy we were going to be and why. Is it a holiday weekend? How’s the weather? What big sports events are scheduled? Though we spoke with the authority of behavioral economists, our predictions were based more on anecdotal evidence and gut feeling than on data. But we were on to something. Certainly there was a relationship between any number of factors (e.g. weather) and how busy we were going to be. We were, in our own way, conducting a little folk regression analysis. Regression analysis seeks to define the relationship between a dependent variable (y) and any number of independent variables (X). In linear regression the y variable is continuous (i.e. has an infinite set of possibilities). In logistic regression the y variable is categorical (and usually binary), but use of the logit function allows the y variable to be treated as continuous (learn more about that here). In either linear or logistic regression, each X variable’s effect on the y variable is expressed in the X variable’s coefficient. Though both models’ coefficients look similar, they need to be interpreted in very different ways, and the rest of this post will explain how to interpret them. (I will be using sklearn’s built-in “load_boston” housing dataset for both models. For linear regression, the target variable is the median value (in $10,000) of owner-occupied homes in a given neighborhood; for logistic regression, I split up the y variable into two categories, with median values over $21k labelled “1” and median values under $21k labelled “0.”) First, let’s look at the more straightforward coefficients: linear regression. After instantiating and fitting the model, use the .coef_ attribute to view the coefficients. linreg = LinearRegression()linreg.fit(X, y)linreg.coef_ I like to create a pandas dataframe that clearly shows each independent variable along side its coefficient: pd.DataFrame(linreg.coef_, X.columns, columns=['coef'])\ .sort_values(by='coef', ascending=False) As I said, interpreting linear regression coefficients is fairly straightforward, and you would verbally describe the coefficients like this: “For every one-unit increase in [X variable], the [y variable] increases by [coefficient] when all other variables are held constant.” So for variable RM (average number of rooms per house), this means as the average number of rooms increases by one unit (think “5” to “6”), the median value of homes in that neighborhood increases by ~$6,960 when all else is static. On the other hand, as concentration of nitric oxide increases by one unit (measured in parts per 10 million), the median value of homes decreases by ~$10,510. Logistic regression models are instantiated and fit the same way, and the .coef_ attribute is also used to view the model’s coefficients. (Note: you will need to use .coef_[0] for logistic regression to put it into a dataframe.) logreg = LogisticRegression()logreg.fit(X, y)log_odds = logreg.coef_[0]pd.DataFrame(log_odds, X.columns, columns=['coef'])\ .sort_values(by='coef', ascending=False) However, logistic regression coefficients aren’t as easily interpreted. This is because logistic regression uses the logit link function to “bend” our line of best fit and convert our classification problem into a regression problem. (Again, learn more here.) Because of the logit function, logistic regression coefficients represent the log odds that an observation is in the target class (“1”) given the values of its X variables. Thus, these log odd coefficients need to be converted to regular odds in order to make sense of them. Happily, this is done by simply exponentiating the log odds coefficients, which you can do with np.exp(): odds = np.exp(logreg.coef_[0])pd.DataFrame(odds, X.columns, columns=['coef'])\ .sort_values(by='coef', ascending=False) Now these coefficients are beginning to make more sense, and you would verbally describe the odds coefficients like this: “For every one-unit increase in [X variable], the odds that the observation is in (y class) are [coefficient] times as large as the odds that the observation is not in (y class) when all other variables are held constant.” So, as variable RM (again, average number of rooms) increases by one unit, the odds that the houses represented in the observation are in the target class (“1”) are over 6x as large as the odds that they won’t be in the target class. On the other hand, as concentration of nitric oxide increases by one unit, the odds that the houses are in the target class are only ~0.15. For odds less than 1 (our negative coefficients), we can take 1/odds to make even better sense of them. So as nitric oxide increases by 1, the odds that the house is NOT in the target class are 1/0.15 or 6.66x (ominous!) as likely as the odds that it IS in the target class. Simple enough! But as I was first learning how to model data using linear and logistic regression, this difference in the models’ coefficients was not clear to me, and I wasn’t quite sure how to verbally explain coefficients from a logistic regression model. I hope this helps students who are new to these concepts understand how to interpret coefficients in linear and logistic regression.
[ { "code": null, "e": 398, "s": 172, "text": "Though I briefly summarize linear regression and logistic regression below, this post focuses more on the models’ coefficients. For more information about linear and logistic regression models in general, click here and here." }, { "code": null, "e": 639, "s": 398, "text": "When I used to work at a restaurant, the beginning of every shift was marked by the same conversation amongst the staff: how busy we were going to be and why. Is it a holiday weekend? How’s the weather? What big sports events are scheduled?" }, { "code": null, "e": 998, "s": 639, "text": "Though we spoke with the authority of behavioral economists, our predictions were based more on anecdotal evidence and gut feeling than on data. But we were on to something. Certainly there was a relationship between any number of factors (e.g. weather) and how busy we were going to be. We were, in our own way, conducting a little folk regression analysis." }, { "code": null, "e": 1129, "s": 998, "text": "Regression analysis seeks to define the relationship between a dependent variable (y) and any number of independent variables (X)." }, { "code": null, "e": 1409, "s": 1129, "text": "In linear regression the y variable is continuous (i.e. has an infinite set of possibilities). In logistic regression the y variable is categorical (and usually binary), but use of the logit function allows the y variable to be treated as continuous (learn more about that here)." }, { "code": null, "e": 1700, "s": 1409, "text": "In either linear or logistic regression, each X variable’s effect on the y variable is expressed in the X variable’s coefficient. Though both models’ coefficients look similar, they need to be interpreted in very different ways, and the rest of this post will explain how to interpret them." }, { "code": null, "e": 2066, "s": 1700, "text": "(I will be using sklearn’s built-in “load_boston” housing dataset for both models. For linear regression, the target variable is the median value (in $10,000) of owner-occupied homes in a given neighborhood; for logistic regression, I split up the y variable into two categories, with median values over $21k labelled “1” and median values under $21k labelled “0.”)" }, { "code": null, "e": 2239, "s": 2066, "text": "First, let’s look at the more straightforward coefficients: linear regression. After instantiating and fitting the model, use the .coef_ attribute to view the coefficients." }, { "code": null, "e": 2295, "s": 2239, "text": "linreg = LinearRegression()linreg.fit(X, y)linreg.coef_" }, { "code": null, "e": 2404, "s": 2295, "text": "I like to create a pandas dataframe that clearly shows each independent variable along side its coefficient:" }, { "code": null, "e": 2539, "s": 2404, "text": "pd.DataFrame(linreg.coef_, X.columns, columns=['coef'])\\ .sort_values(by='coef', ascending=False)" }, { "code": null, "e": 2681, "s": 2539, "text": "As I said, interpreting linear regression coefficients is fairly straightforward, and you would verbally describe the coefficients like this:" }, { "code": null, "e": 2816, "s": 2681, "text": "“For every one-unit increase in [X variable], the [y variable] increases by [coefficient] when all other variables are held constant.”" }, { "code": null, "e": 3208, "s": 2816, "text": "So for variable RM (average number of rooms per house), this means as the average number of rooms increases by one unit (think “5” to “6”), the median value of homes in that neighborhood increases by ~$6,960 when all else is static. On the other hand, as concentration of nitric oxide increases by one unit (measured in parts per 10 million), the median value of homes decreases by ~$10,510." }, { "code": null, "e": 3437, "s": 3208, "text": "Logistic regression models are instantiated and fit the same way, and the .coef_ attribute is also used to view the model’s coefficients. (Note: you will need to use .coef_[0] for logistic regression to put it into a dataframe.)" }, { "code": null, "e": 3639, "s": 3437, "text": "logreg = LogisticRegression()logreg.fit(X, y)log_odds = logreg.coef_[0]pd.DataFrame(log_odds, X.columns, columns=['coef'])\\ .sort_values(by='coef', ascending=False)" }, { "code": null, "e": 3899, "s": 3639, "text": "However, logistic regression coefficients aren’t as easily interpreted. This is because logistic regression uses the logit link function to “bend” our line of best fit and convert our classification problem into a regression problem. (Again, learn more here.)" }, { "code": null, "e": 4280, "s": 3899, "text": "Because of the logit function, logistic regression coefficients represent the log odds that an observation is in the target class (“1”) given the values of its X variables. Thus, these log odd coefficients need to be converted to regular odds in order to make sense of them. Happily, this is done by simply exponentiating the log odds coefficients, which you can do with np.exp():" }, { "code": null, "e": 4437, "s": 4280, "text": "odds = np.exp(logreg.coef_[0])pd.DataFrame(odds, X.columns, columns=['coef'])\\ .sort_values(by='coef', ascending=False)" }, { "code": null, "e": 4559, "s": 4437, "text": "Now these coefficients are beginning to make more sense, and you would verbally describe the odds coefficients like this:" }, { "code": null, "e": 4782, "s": 4559, "text": "“For every one-unit increase in [X variable], the odds that the observation is in (y class) are [coefficient] times as large as the odds that the observation is not in (y class) when all other variables are held constant.”" }, { "code": null, "e": 5431, "s": 4782, "text": "So, as variable RM (again, average number of rooms) increases by one unit, the odds that the houses represented in the observation are in the target class (“1”) are over 6x as large as the odds that they won’t be in the target class. On the other hand, as concentration of nitric oxide increases by one unit, the odds that the houses are in the target class are only ~0.15. For odds less than 1 (our negative coefficients), we can take 1/odds to make even better sense of them. So as nitric oxide increases by 1, the odds that the house is NOT in the target class are 1/0.15 or 6.66x (ominous!) as likely as the odds that it IS in the target class." } ]
How to Left Join Multiple Tables in SQL - GeeksforGeeks
06 Apr, 2021 Left Join is one of the Keywords used while writing queries in SQL. In SQL we normally use Join for the purpose of forming a new table by taking out common data like rows or records or tuples from both the tables which are having matching records in general. Here when it comes to Left Join in SQL it only returns all the records or tuples or rows from left table and only those records matching from the right table. Syntax For Left Join: SELECT column names FROM table1 LEFT JOIN table2 ON table1.matching_column = table2.matching_column; Note: For example, if you have a left table with 10 rows, you are guaranteed to have at least 10 rows after applying join operation on two tables. Consider two tables: 1. Employee (Left Table) : 2. Projects (Right Table) : To Join these two tables and to obtain common information we need to use the following query SELECT E.Emp_id, E.First_Name, E.Last_Name, E.Gender, E.age, E.Date_of_join, P.date AS Project_Assigned_date, P.No_of_hours_worked AS hours_worked FROM Employee E LEFT JOIN Projects P ON E.Emp_id = P.Emp_id GROUP BY E.Emp_id; After execution of query the obtained table will be like: Once after obtaining the table as you can see that the Emp_id who is not assigned for a project who’s Project_Assigned_date has became NULL and No_of_hours_worked also became NULL cause the Employee has not assigned anything to do. Here Left Join mean in the sense based on above tables it took data from both the table rows which are matching and it also returned the values for the rows who’s data is not present in Table 2 as NULL cause we need to consider all the data of Left table. Multiple LEFT JOIN’s in One Query:Sometimes you need to LEFT JOIN more than two tables to get the data required for specific analyses. Fortunately, the LEFT JOIN keyword can be used with MULTIPLE TABLES in SQL. Consider a table called Salary: Here we combine the data from these tables Employee, Projects and Salary. To do this the query need to be written in the below format: SELECT E.Emp_id, E.First_Name, E.Last_Name, E.Gender, E.age, E.Date_of_join, P.No_of_hours_worked AS hours_worked, S.Salary_inc AS Salary_Increment FROM Employee E LEFT JOIN Projects P ON E.Emp_id = P.Emp_id LEFT JOIN Salary S ON E.Emp_id = S.Emp_id; And the resulting table looks like after multiple Left Join: Hence you can see that we have combined the data from three tables into one single table using Left Join multiple times. Consider one more Table called Experience: Here we combine the data from these tables Employee, Projects and Experience. To do this the query need to be written in the below format: SELECT E.Emp_id, E.First_Name, E.Last_Name, P.date AS Project_Assigned_date, E1.Experience AS EXP FROM Employee E LEFT JOIN Projects P ON E.Emp_id = P.Emp_id LEFT JOIN Experience E1 ON E.Emp_id = E1.id; And the resulting table looks like after multiple Left Join: As you can see, the LEFT JOIN in SQL can be used with multiple tables. DBMS-SQL Picked SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Update Multiple Columns in Single Update Statement in SQL? How to Alter Multiple Columns at Once in SQL Server? What is Temporary Table in SQL? SQL using Python SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query for Matching Multiple Values in the Same Column SQL Query to Insert Multiple Rows SQL Query to Convert VARCHAR to INT SQL | Subquery SQL - SELECT from Multiple Tables with MS SQL Server
[ { "code": null, "e": 24214, "s": 24186, "text": "\n06 Apr, 2021" }, { "code": null, "e": 24474, "s": 24214, "text": "Left Join is one of the Keywords used while writing queries in SQL. In SQL we normally use Join for the purpose of forming a new table by taking out common data like rows or records or tuples from both the tables which are having matching records in general. " }, { "code": null, "e": 24633, "s": 24474, "text": "Here when it comes to Left Join in SQL it only returns all the records or tuples or rows from left table and only those records matching from the right table." }, { "code": null, "e": 24655, "s": 24633, "text": "Syntax For Left Join:" }, { "code": null, "e": 24756, "s": 24655, "text": "SELECT column names\nFROM table1\nLEFT JOIN table2\nON table1.matching_column = table2.matching_column;" }, { "code": null, "e": 24904, "s": 24756, "text": " Note: For example, if you have a left table with 10 rows, you are guaranteed to have at least 10 rows after applying join operation on two tables." }, { "code": null, "e": 24926, "s": 24904, "text": "Consider two tables: " }, { "code": null, "e": 24953, "s": 24926, "text": "1. Employee (Left Table) :" }, { "code": null, "e": 24982, "s": 24953, "text": " 2. Projects (Right Table) :" }, { "code": null, "e": 25075, "s": 24982, "text": "To Join these two tables and to obtain common information we need to use the following query" }, { "code": null, "e": 25312, "s": 25075, "text": "SELECT E.Emp_id, E.First_Name, E.Last_Name, E.Gender, E.age, E.Date_of_join, \n P.date AS Project_Assigned_date, P.No_of_hours_worked AS hours_worked\nFROM Employee E\nLEFT JOIN Projects P\nON E.Emp_id = P.Emp_id\nGROUP BY E.Emp_id;" }, { "code": null, "e": 25370, "s": 25312, "text": "After execution of query the obtained table will be like:" }, { "code": null, "e": 25603, "s": 25370, "text": "Once after obtaining the table as you can see that the Emp_id who is not assigned for a project who’s Project_Assigned_date has became NULL and No_of_hours_worked also became NULL cause the Employee has not assigned anything to do." }, { "code": null, "e": 25859, "s": 25603, "text": "Here Left Join mean in the sense based on above tables it took data from both the table rows which are matching and it also returned the values for the rows who’s data is not present in Table 2 as NULL cause we need to consider all the data of Left table." }, { "code": null, "e": 26070, "s": 25859, "text": "Multiple LEFT JOIN’s in One Query:Sometimes you need to LEFT JOIN more than two tables to get the data required for specific analyses. Fortunately, the LEFT JOIN keyword can be used with MULTIPLE TABLES in SQL." }, { "code": null, "e": 26102, "s": 26070, "text": "Consider a table called Salary:" }, { "code": null, "e": 26176, "s": 26102, "text": "Here we combine the data from these tables Employee, Projects and Salary." }, { "code": null, "e": 26237, "s": 26176, "text": "To do this the query need to be written in the below format:" }, { "code": null, "e": 26493, "s": 26237, "text": "SELECT E.Emp_id, E.First_Name, E.Last_Name, E.Gender, E.age, E.Date_of_join, \n P.No_of_hours_worked AS hours_worked, S.Salary_inc AS Salary_Increment\nFROM Employee E\nLEFT JOIN Projects P\nON E.Emp_id = P.Emp_id\nLEFT JOIN Salary S\nON E.Emp_id = S.Emp_id;" }, { "code": null, "e": 26554, "s": 26493, "text": "And the resulting table looks like after multiple Left Join:" }, { "code": null, "e": 26675, "s": 26554, "text": "Hence you can see that we have combined the data from three tables into one single table using Left Join multiple times." }, { "code": null, "e": 26718, "s": 26675, "text": "Consider one more Table called Experience:" }, { "code": null, "e": 26796, "s": 26718, "text": "Here we combine the data from these tables Employee, Projects and Experience." }, { "code": null, "e": 26857, "s": 26796, "text": "To do this the query need to be written in the below format:" }, { "code": null, "e": 27062, "s": 26857, "text": "SELECT E.Emp_id, E.First_Name, E.Last_Name, P.date AS Project_Assigned_date, \nE1.Experience AS EXP\nFROM Employee E\nLEFT JOIN Projects\n P\nON E.Emp_id = P.Emp_id\nLEFT JOIN Experience E1\nON E.Emp_id = E1.id;" }, { "code": null, "e": 27123, "s": 27062, "text": "And the resulting table looks like after multiple Left Join:" }, { "code": null, "e": 27195, "s": 27123, "text": "As you can see, the LEFT JOIN in SQL can be used with multiple tables. " }, { "code": null, "e": 27204, "s": 27195, "text": "DBMS-SQL" }, { "code": null, "e": 27211, "s": 27204, "text": "Picked" }, { "code": null, "e": 27215, "s": 27211, "text": "SQL" }, { "code": null, "e": 27219, "s": 27215, "text": "SQL" }, { "code": null, "e": 27317, "s": 27219, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27326, "s": 27317, "text": "Comments" }, { "code": null, "e": 27339, "s": 27326, "text": "Old Comments" }, { "code": null, "e": 27405, "s": 27339, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 27458, "s": 27405, "text": "How to Alter Multiple Columns at Once in SQL Server?" }, { "code": null, "e": 27490, "s": 27458, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27507, "s": 27490, "text": "SQL using Python" }, { "code": null, "e": 27585, "s": 27507, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 27643, "s": 27585, "text": "SQL Query for Matching Multiple Values in the Same Column" }, { "code": null, "e": 27677, "s": 27643, "text": "SQL Query to Insert Multiple Rows" }, { "code": null, "e": 27713, "s": 27677, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 27728, "s": 27713, "text": "SQL | Subquery" } ]
Create Multiple Pie Charts using ggplot2 in R - GeeksforGeeks
08 Mar, 2021 Pie Chart, also known as circle chart, is the graphical representation of the relative size or frequency of the data in a circular format. Basically, it helps in visualizing the relative size or frequency of a particular group of data as a part of the whole. This article discusses how multiple pie charts can be created into one frame for consecutive comparison. Function used: pie() function as the name suggests is used for visualizing a pie chart. Syntax: pie(x, labels, radius, main, col, clockwise) Parameters: x: This parameter is the vector containing the value of the pie chart. labels: This parameter is the vector containing the labels of all the slices in Pie Chart. radius: This parameter is the value of the radius of the pie chart. This value is between -1 to 1. main: This parameter is the title of the chart. col: This parameter is the color used in the pie chart. clockwise: This parameter is the logical value which is used to draw the slices in clockwise or anti-clockwise direction. coord_polar() function is used to create a polar coordinate system, which helps in drawing a pie chart. Syntax: coord_polar(theta = “x”, start = 0, direction = 1, clip = “on”) Parameter: theta represents the angle start used for setting offset direction clip decides whether drawing should be clipped or not facet_grid() creates a matrix to display rows and columns faceting variables Syntax: facet_grid(facets, margins=FALSE, scales=”fixed”, space=”fixed”, shrink=TRUE, labeller=”label_value”, as.table=TRUE, drop=TRUE) Let us first create a regular pie chart Program 1 : Regular Pie Chart R x <- c(3,3,2,1,1) labels <- c('ADA','CN','PDS','CPDP','PE') pie(x, labels, main="Credits of subjects", col=rainbow(length(x))) Output: For building a Pie Chart in R, we can use ggplot2 package, but it does not have a direct method to do so. Instead, we plot a bar graph and then convert it into Pie Chart using coord_polar() function. Approach: Import library Create data Create dataframe Plot a bar graph Convert bar graph into Pie chart Remove numerical values and grid Program 2: Pie Chart using ggplot2 R library(ggplot2) df = data.frame(x <- c(3,3,2,1,1), labels <- c('ADA','CN','PDS','CPDP','PE')) ggplot(df, aes(x="", y=x, fill=labels)) +geom_bar(width = 1, stat = "identity") + coord_polar("y", start=0) +theme_void() Output: To plot multiple pie charts in R using ggplot2, we have to use an additional method named facet_grid(). This method forms a matrix defined by row and column faceting variables. When we have two different variables and need a matrix with all combinations of these two variables, we use this method. Approach: Import library Create dataframe Convert variables into categorical variables Plot Bar graph Convert into Pie Chart Add facet_grid() Program 3: Multiple Pie Chart R library(ggplot2)df = data.frame(subject <- c('ADA','ADA','ADA','CN','CN','CN','PDS','PDS','PDS','CPDP', 'CPDP','CPDP'), credit <- c('Midsem','Viva','Attendance','Midsem','Viva','Attendance', 'Midsem','Viva','Attendance','Midsem','Viva','Attendance'), value <- c(50,30,20,40,40,20,50,35,15,50,40,10)) df$subject <- factor(df$subject)df$credit <- factor(df$credit) ggplot(data=df, aes(x=" ", y=value, group=credit, colour=credit, fill=credit)) + geom_bar(width = 1, stat = "identity") + coord_polar("y", start=0) + facet_grid(.~ subject) +theme_void() Output: We can also plot multiple pie charts in the form of a donut chart using ggplot2 in R. Approach: Import library Create dataframe Convert variables into categorical variables Plot Bar graph using geom_col() Add an empty element before the subjects using scale_x_discrete() Convert into Pie Chart using coord_polar() Program 4: Multiple Pie Chart/ Donut Chart R library(ggplot2)df = data.frame(subject <- c('ADA','ADA','ADA','CN','CN','CN','PDS','PDS','PDS'), credit <- c('Midsem','Viva','Attendance','Midsem','Viva','Attendance', 'Midsem','Viva','Attendance'), value <- c(50,30,20,40,40,20,50,35,15)) df$subject <- factor(df$subject) # converts to a categorical variabledf$credit <- factor(df$credit) # converts to a categorical variable ggplot(df, aes(x = subject, y = value, fill = credit)) + geom_col() +scale_x_discrete(limits = c(" ", "ADA","CN","PDS")) +coord_polar("y") Output: Picked R-ggplot Technical Scripter 2020 R Language Technical Scripter 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? Logistic Regression in R Programming How to import an Excel File into R ? How to filter R DataFrame by values in a column? How to change the order of bars in bar chart in R ? R - if statement Replace Specific Characters in String in R
[ { "code": null, "e": 25266, "s": 25238, "text": "\n08 Mar, 2021" }, { "code": null, "e": 25630, "s": 25266, "text": "Pie Chart, also known as circle chart, is the graphical representation of the relative size or frequency of the data in a circular format. Basically, it helps in visualizing the relative size or frequency of a particular group of data as a part of the whole. This article discusses how multiple pie charts can be created into one frame for consecutive comparison." }, { "code": null, "e": 25645, "s": 25630, "text": "Function used:" }, { "code": null, "e": 25718, "s": 25645, "text": "pie() function as the name suggests is used for visualizing a pie chart." }, { "code": null, "e": 25771, "s": 25718, "text": "Syntax: pie(x, labels, radius, main, col, clockwise)" }, { "code": null, "e": 25783, "s": 25771, "text": "Parameters:" }, { "code": null, "e": 25854, "s": 25783, "text": "x: This parameter is the vector containing the value of the pie chart." }, { "code": null, "e": 25945, "s": 25854, "text": "labels: This parameter is the vector containing the labels of all the slices in Pie Chart." }, { "code": null, "e": 26044, "s": 25945, "text": "radius: This parameter is the value of the radius of the pie chart. This value is between -1 to 1." }, { "code": null, "e": 26092, "s": 26044, "text": "main: This parameter is the title of the chart." }, { "code": null, "e": 26148, "s": 26092, "text": "col: This parameter is the color used in the pie chart." }, { "code": null, "e": 26270, "s": 26148, "text": "clockwise: This parameter is the logical value which is used to draw the slices in clockwise or anti-clockwise direction." }, { "code": null, "e": 26374, "s": 26270, "text": "coord_polar() function is used to create a polar coordinate system, which helps in drawing a pie chart." }, { "code": null, "e": 26382, "s": 26374, "text": "Syntax:" }, { "code": null, "e": 26446, "s": 26382, "text": "coord_polar(theta = “x”, start = 0, direction = 1, clip = “on”)" }, { "code": null, "e": 26457, "s": 26446, "text": "Parameter:" }, { "code": null, "e": 26484, "s": 26457, "text": "theta represents the angle" }, { "code": null, "e": 26514, "s": 26484, "text": "start used for setting offset" }, { "code": null, "e": 26525, "s": 26514, "text": "direction " }, { "code": null, "e": 26579, "s": 26525, "text": "clip decides whether drawing should be clipped or not" }, { "code": null, "e": 26656, "s": 26579, "text": "facet_grid() creates a matrix to display rows and columns faceting variables" }, { "code": null, "e": 26664, "s": 26656, "text": "Syntax:" }, { "code": null, "e": 26792, "s": 26664, "text": "facet_grid(facets, margins=FALSE, scales=”fixed”, space=”fixed”, shrink=TRUE, labeller=”label_value”, as.table=TRUE, drop=TRUE)" }, { "code": null, "e": 26832, "s": 26792, "text": "Let us first create a regular pie chart" }, { "code": null, "e": 26862, "s": 26832, "text": "Program 1 : Regular Pie Chart" }, { "code": null, "e": 26864, "s": 26862, "text": "R" }, { "code": "x <- c(3,3,2,1,1) labels <- c('ADA','CN','PDS','CPDP','PE') pie(x, labels, main=\"Credits of subjects\", col=rainbow(length(x)))", "e": 26993, "s": 26864, "text": null }, { "code": null, "e": 27001, "s": 26993, "text": "Output:" }, { "code": null, "e": 27202, "s": 27001, "text": "For building a Pie Chart in R, we can use ggplot2 package, but it does not have a direct method to do so. Instead, we plot a bar graph and then convert it into Pie Chart using coord_polar() function. " }, { "code": null, "e": 27212, "s": 27202, "text": "Approach:" }, { "code": null, "e": 27227, "s": 27212, "text": "Import library" }, { "code": null, "e": 27239, "s": 27227, "text": "Create data" }, { "code": null, "e": 27256, "s": 27239, "text": "Create dataframe" }, { "code": null, "e": 27273, "s": 27256, "text": "Plot a bar graph" }, { "code": null, "e": 27306, "s": 27273, "text": "Convert bar graph into Pie chart" }, { "code": null, "e": 27339, "s": 27306, "text": "Remove numerical values and grid" }, { "code": null, "e": 27374, "s": 27339, "text": "Program 2: Pie Chart using ggplot2" }, { "code": null, "e": 27376, "s": 27374, "text": "R" }, { "code": "library(ggplot2) df = data.frame(x <- c(3,3,2,1,1), labels <- c('ADA','CN','PDS','CPDP','PE')) ggplot(df, aes(x=\"\", y=x, fill=labels)) +geom_bar(width = 1, stat = \"identity\") + coord_polar(\"y\", start=0) +theme_void()", "e": 27611, "s": 27376, "text": null }, { "code": null, "e": 27619, "s": 27611, "text": "Output:" }, { "code": null, "e": 27917, "s": 27619, "text": "To plot multiple pie charts in R using ggplot2, we have to use an additional method named facet_grid(). This method forms a matrix defined by row and column faceting variables. When we have two different variables and need a matrix with all combinations of these two variables, we use this method." }, { "code": null, "e": 27927, "s": 27917, "text": "Approach:" }, { "code": null, "e": 27942, "s": 27927, "text": "Import library" }, { "code": null, "e": 27959, "s": 27942, "text": "Create dataframe" }, { "code": null, "e": 28004, "s": 27959, "text": "Convert variables into categorical variables" }, { "code": null, "e": 28019, "s": 28004, "text": "Plot Bar graph" }, { "code": null, "e": 28042, "s": 28019, "text": "Convert into Pie Chart" }, { "code": null, "e": 28059, "s": 28042, "text": "Add facet_grid()" }, { "code": null, "e": 28090, "s": 28059, "text": "Program 3: Multiple Pie Chart " }, { "code": null, "e": 28092, "s": 28090, "text": "R" }, { "code": "library(ggplot2)df = data.frame(subject <- c('ADA','ADA','ADA','CN','CN','CN','PDS','PDS','PDS','CPDP', 'CPDP','CPDP'), credit <- c('Midsem','Viva','Attendance','Midsem','Viva','Attendance', 'Midsem','Viva','Attendance','Midsem','Viva','Attendance'), value <- c(50,30,20,40,40,20,50,35,15,50,40,10)) df$subject <- factor(df$subject)df$credit <- factor(df$credit) ggplot(data=df, aes(x=\" \", y=value, group=credit, colour=credit, fill=credit)) + geom_bar(width = 1, stat = \"identity\") + coord_polar(\"y\", start=0) + facet_grid(.~ subject) +theme_void()", "e": 28751, "s": 28092, "text": null }, { "code": null, "e": 28759, "s": 28751, "text": "Output:" }, { "code": null, "e": 28846, "s": 28759, "text": "We can also plot multiple pie charts in the form of a donut chart using ggplot2 in R. " }, { "code": null, "e": 28856, "s": 28846, "text": "Approach:" }, { "code": null, "e": 28871, "s": 28856, "text": "Import library" }, { "code": null, "e": 28888, "s": 28871, "text": "Create dataframe" }, { "code": null, "e": 28933, "s": 28888, "text": "Convert variables into categorical variables" }, { "code": null, "e": 28965, "s": 28933, "text": "Plot Bar graph using geom_col()" }, { "code": null, "e": 29031, "s": 28965, "text": "Add an empty element before the subjects using scale_x_discrete()" }, { "code": null, "e": 29074, "s": 29031, "text": "Convert into Pie Chart using coord_polar()" }, { "code": null, "e": 29118, "s": 29074, "text": "Program 4: Multiple Pie Chart/ Donut Chart " }, { "code": null, "e": 29120, "s": 29118, "text": "R" }, { "code": "library(ggplot2)df = data.frame(subject <- c('ADA','ADA','ADA','CN','CN','CN','PDS','PDS','PDS'), credit <- c('Midsem','Viva','Attendance','Midsem','Viva','Attendance', 'Midsem','Viva','Attendance'), value <- c(50,30,20,40,40,20,50,35,15)) df$subject <- factor(df$subject) # converts to a categorical variabledf$credit <- factor(df$credit) # converts to a categorical variable ggplot(df, aes(x = subject, y = value, fill = credit)) + geom_col() +scale_x_discrete(limits = c(\" \", \"ADA\",\"CN\",\"PDS\")) +coord_polar(\"y\")", "e": 29698, "s": 29120, "text": null }, { "code": null, "e": 29706, "s": 29698, "text": "Output:" }, { "code": null, "e": 29713, "s": 29706, "text": "Picked" }, { "code": null, "e": 29722, "s": 29713, "text": "R-ggplot" }, { "code": null, "e": 29746, "s": 29722, "text": "Technical Scripter 2020" }, { "code": null, "e": 29757, "s": 29746, "text": "R Language" }, { "code": null, "e": 29776, "s": 29757, "text": "Technical Scripter" }, { "code": null, "e": 29874, "s": 29776, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29883, "s": 29874, "text": "Comments" }, { "code": null, "e": 29896, "s": 29883, "text": "Old Comments" }, { "code": null, "e": 29948, "s": 29896, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29986, "s": 29948, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 30021, "s": 29986, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 30079, "s": 30021, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30116, "s": 30079, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 30153, "s": 30116, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 30202, "s": 30153, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30254, "s": 30202, "text": "How to change the order of bars in bar chart in R ?" }, { "code": null, "e": 30271, "s": 30254, "text": "R - if statement" } ]
How to customize how a JTabbedPane looks in Java?
To customize how a JTabbedPane looks, change its font style, font face, font size and the background and foreground colors. Let’s say the following is the JTabbedPane − JTabbedPane tabbedPane = new JTabbedPane(); Now, let us customize the above created JTabbedPane − tabbedPane.setBackground(Color.orange); tabbedPane.setForeground(Color.white); Font font = new Font("Verdana", Font.CENTER_BASELINE, 18); tabbedPane.setFont(font); The following is an example to customize JTabbedPane − package my; import javax.swing.*; import java.awt.*; public class SwingDemo { public static void main(String args[]) { JFrame frame = new JFrame("Technologies"); JTabbedPane tabbedPane = new JTabbedPane(); JPanel panel1, panel2, panel3, panel4, panel5; panel1 = new JPanel(); panel2 = new JPanel(); panel3 = new JPanel(); panel4 = new JPanel(); panel5 = new JPanel(); tabbedPane.addTab("Data Science", panel1); tabbedPane.addTab("Blockchain ", panel2); tabbedPane.addTab("PHP", panel3); tabbedPane.addTab("Matlab ", panel4); tabbedPane.addTab("Servlet", panel5); tabbedPane.setBackground(Color.orange); tabbedPane.setForeground(Color.white); Font font = new Font("Verdana", Font.CENTER_BASELINE, 18); tabbedPane.setFont(font); frame.add(tabbedPane); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(660,350); frame.setVisible(true); } }
[ { "code": null, "e": 1186, "s": 1062, "text": "To customize how a JTabbedPane looks, change its font style, font face, font size and the background and foreground colors." }, { "code": null, "e": 1231, "s": 1186, "text": "Let’s say the following is the JTabbedPane −" }, { "code": null, "e": 1275, "s": 1231, "text": "JTabbedPane tabbedPane = new JTabbedPane();" }, { "code": null, "e": 1329, "s": 1275, "text": "Now, let us customize the above created JTabbedPane −" }, { "code": null, "e": 1493, "s": 1329, "text": "tabbedPane.setBackground(Color.orange);\ntabbedPane.setForeground(Color.white);\nFont font = new Font(\"Verdana\", Font.CENTER_BASELINE, 18);\ntabbedPane.setFont(font);" }, { "code": null, "e": 1548, "s": 1493, "text": "The following is an example to customize JTabbedPane −" }, { "code": null, "e": 2536, "s": 1548, "text": "package my;\nimport javax.swing.*;\nimport java.awt.*;\npublic class SwingDemo {\n public static void main(String args[]) {\n JFrame frame = new JFrame(\"Technologies\");\n JTabbedPane tabbedPane = new JTabbedPane();\n JPanel panel1, panel2, panel3, panel4, panel5;\n panel1 = new JPanel();\n panel2 = new JPanel();\n panel3 = new JPanel();\n panel4 = new JPanel();\n panel5 = new JPanel();\n tabbedPane.addTab(\"Data Science\", panel1);\n tabbedPane.addTab(\"Blockchain \", panel2);\n tabbedPane.addTab(\"PHP\", panel3);\n tabbedPane.addTab(\"Matlab \", panel4);\n tabbedPane.addTab(\"Servlet\", panel5);\n tabbedPane.setBackground(Color.orange);\n tabbedPane.setForeground(Color.white);\n Font font = new Font(\"Verdana\", Font.CENTER_BASELINE, 18);\n tabbedPane.setFont(font);\n frame.add(tabbedPane);\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setSize(660,350);\n frame.setVisible(true);\n }\n}" } ]
Pointer to C++ Classes
A pointer to a C++ class is done exactly the same way as a pointer to a structure and to access members of a pointer to a class you use the member access operator -> operator, just as you do with pointers to structures. Also as with all pointers, you must initialize the pointer before using it. Let us try the following example to understand the concept of pointer to a class − #include <iostream> using namespace std; class Box { public: // Constructor definition Box(double l = 2.0, double b = 2.0, double h = 2.0) { cout <<"Constructor called." << endl; length = l; breadth = b; height = h; } double Volume() { return length * breadth * height; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; int main(void) { Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 Box *ptrBox; // Declare pointer to a class. // Save the address of first object ptrBox = &Box1; // Now try to access a member using member access operator cout << "Volume of Box1: " << ptrBox->Volume() << endl; // Save the address of second object ptrBox = &Box2; // Now try to access a member using member access operator cout << "Volume of Box2: " << ptrBox->Volume() << endl; return 0; } When the above code is compiled and executed, it produces the following result − Constructor called. Constructor called. Volume of Box1: 5.94 Volume of Box2: 102 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2614, "s": 2318, "text": "A pointer to a C++ class is done exactly the same way as a pointer to a structure and to access members of a pointer to a class you use the member access operator -> operator, just as you do with pointers to structures. Also as with all pointers, you must initialize the pointer before using it." }, { "code": null, "e": 2697, "s": 2614, "text": "Let us try the following example to understand the concept of pointer to a class −" }, { "code": null, "e": 3760, "s": 2697, "text": "#include <iostream>\n \nusing namespace std;\n\nclass Box {\n public:\n // Constructor definition\n Box(double l = 2.0, double b = 2.0, double h = 2.0) {\n cout <<\"Constructor called.\" << endl;\n length = l;\n breadth = b;\n height = h;\n }\n double Volume() {\n return length * breadth * height;\n }\n \n private:\n double length; // Length of a box\n double breadth; // Breadth of a box\n double height; // Height of a box\n};\n\nint main(void) {\n Box Box1(3.3, 1.2, 1.5); // Declare box1\n Box Box2(8.5, 6.0, 2.0); // Declare box2\n Box *ptrBox; // Declare pointer to a class.\n\n // Save the address of first object\n ptrBox = &Box1;\n\n // Now try to access a member using member access operator\n cout << \"Volume of Box1: \" << ptrBox->Volume() << endl;\n\n // Save the address of second object\n ptrBox = &Box2;\n\n // Now try to access a member using member access operator\n cout << \"Volume of Box2: \" << ptrBox->Volume() << endl;\n \n return 0;\n}" }, { "code": null, "e": 3841, "s": 3760, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3923, "s": 3841, "text": "Constructor called.\nConstructor called.\nVolume of Box1: 5.94\nVolume of Box2: 102\n" }, { "code": null, "e": 3960, "s": 3923, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 3979, "s": 3960, "text": " Arnab Chakraborty" }, { "code": null, "e": 4011, "s": 3979, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 4034, "s": 4011, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 4070, "s": 4034, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 4087, "s": 4070, "text": " Frahaan Hussain" }, { "code": null, "e": 4122, "s": 4087, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4139, "s": 4122, "text": " Frahaan Hussain" }, { "code": null, "e": 4174, "s": 4139, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4191, "s": 4174, "text": " Frahaan Hussain" }, { "code": null, "e": 4226, "s": 4191, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4243, "s": 4226, "text": " Frahaan Hussain" }, { "code": null, "e": 4250, "s": 4243, "text": " Print" }, { "code": null, "e": 4261, "s": 4250, "text": " Add Notes" } ]
Convert string to char array in C++
This is a C++ program to Convert string to char array in C++. This can be done in many ways: Begin Assign value to string m. For i = 0 to sizeof(m) Print the char array. End Live Demo #include<iostream> #include<string.h> using namespace std; int main() { char m[] = "Tutorialspoint"; string str; int i; for(i=0;i<sizeof(m);i++) { str[i] = m[i]; cout<<str[i]; } return 0; } We can simply call strcpy() function to copy the string to char array. Begin Assign value to string s. Copying the contents of the string to char array using strcpy(). End Live Demo #include <iostream> #include <string> #include <cstring> using namespace std; int main() { string str = "Tutorialspoint"; char c[str.size() + 1]; strcpy(c, str.c_str()); cout << c << '\n'; return 0; } Tutorialspoint We can avoid using strcpy() which is basically used in c by std::string::copy instead. Begin Assign value to string s. copying the contents of the string to char array using copy(). End Live Demo #include <iostream> #include <string> using namespace std; int main() { string str = "Tutorialspoint"; char c[str.size() + 1]; str.copy(c, str.size() + 1); c[str.size()] = '\0'; cout << c << '\n'; return 0; } Tutorialspoint
[ { "code": null, "e": 1155, "s": 1062, "text": "This is a C++ program to Convert string to char array in C++. This can be done in many ways:" }, { "code": null, "e": 1248, "s": 1155, "text": "Begin\n Assign value to string m.\n For i = 0 to sizeof(m)\n Print the char array.\nEnd" }, { "code": null, "e": 1259, "s": 1248, "text": " Live Demo" }, { "code": null, "e": 1479, "s": 1259, "text": "#include<iostream>\n#include<string.h>\nusing namespace std;\nint main() {\n char m[] = \"Tutorialspoint\";\n string str;\n int i;\n for(i=0;i<sizeof(m);i++) {\n str[i] = m[i];\n cout<<str[i];\n }\n return 0;\n}" }, { "code": null, "e": 1550, "s": 1479, "text": "We can simply call strcpy() function to copy the string to char array." }, { "code": null, "e": 1657, "s": 1550, "text": "Begin\n Assign value to string s.\n Copying the contents of the string to char array using strcpy().\nEnd" }, { "code": null, "e": 1668, "s": 1657, "text": " Live Demo" }, { "code": null, "e": 1884, "s": 1668, "text": "#include <iostream>\n#include <string>\n#include <cstring>\nusing namespace std;\nint main() {\n string str = \"Tutorialspoint\";\n char c[str.size() + 1];\n strcpy(c, str.c_str());\n cout << c << '\\n';\n return 0;\n}" }, { "code": null, "e": 1899, "s": 1884, "text": "Tutorialspoint" }, { "code": null, "e": 1959, "s": 1899, "text": "We can avoid using strcpy() which is basically used in c by" }, { "code": null, "e": 1986, "s": 1959, "text": "std::string::copy instead." }, { "code": null, "e": 2091, "s": 1986, "text": "Begin\n Assign value to string s.\n copying the contents of the string to char array using copy().\nEnd" }, { "code": null, "e": 2102, "s": 2091, "text": " Live Demo" }, { "code": null, "e": 2329, "s": 2102, "text": "#include <iostream>\n#include <string>\nusing namespace std;\nint main() {\n string str = \"Tutorialspoint\";\n char c[str.size() + 1];\n str.copy(c, str.size() + 1);\n c[str.size()] = '\\0';\n cout << c << '\\n';\n return 0;\n}" }, { "code": null, "e": 2344, "s": 2329, "text": "Tutorialspoint" } ]
For Loop- primeCheck | Practice | GeeksforGeeks
What do you do when you need to execute certain statements more than once? You put them in a loop. Loops are very powerful. Majority of coding questions need loops to work. You can't even input testcases without loops! Here, we will use for loop and check if the given number n is prime or not. Note: A number is prime if it's divisible by itself and 1. Also, 1 is not prime. Example 1: Input: n = 1 Output: No Example 2: Input: n = 2 Output: Yes User Task: Your task is to complete the provided function isPrime() which should return a string "Yes" if n is prime and "No" if not. Constraints: 1 ≤ n ≤ 1000 Video: YouTubeGeeksforGeeks500K subscribersC++ Programming Language Tutorial | Loops in C++ - Part 1 (Entry Controlled Loop) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.Full screen is unavailable. Learn MoreMore videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:09•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=MbEVFhucVa0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> 0 vikaschandra8051101 week ago //perfect soln string isPrime(int n) { if(n==1){ return "No"; } if(n==2 || n==3){ return "Yes"; } for (int i = 2; i <= sqrt(n); i++) { // Write your logic here if(n%i ==0){ return "No"; } // Return "Yes" if n is prime, else return "No" /*n is prime only if it is not divisible by any i. We will not reach till n and 1 is already discarded*/ } return "Yes";} +1 anshumanatrey3 weeks ago C++ ANSWER : string isPrime(int n) { int c=0; for (int i = 2; i <= n; i++) { if(n%i==0){ c++; } } if(c>1 || n==1){ cout<<"No"; } else { cout<<"Yes"; } } 0 anshumanatrey This comment was deleted. 0 imluckybanthia4 weeks ago string isPrime(int n) { int c=0; for (int i = 2; i <= n; i++) { if(n%i==0){ ++c; } } if(c>=2 || n==0||n==1){ cout<<"No";} else{ cout<<"Yes"; } 0 sumitd12991 month ago string isPrime(int n) { if(n==1){ return "No"; } for (int i = 2; i <= sqrt(n); i++) { if(n%i==0){ return "No"; } } return "Yes";} 0 akash119027401 month ago string isPrime(int n) { if(n==1)return "No"; if(n==2 || n==3) return "Yes"; if(n%2==0 || n%3==0) return "No"; for(int i = 5; i*i<=n;i+=6){ if(n%i==0 || n%(i+2)==0) return "No"; } return "Yes";} 0 srilakshmimounika01 month ago #include<bits/stdc++.h> using namespace std; int main() string isprime(int n) { for(int i=2;i,=sqrt(n);i++) { if(n%i==0) return “no”; } if(n==1) return “no”; else return “yes”; } return 0; } +1 saikumar0272071 month ago 1 0 mdshahid132 months ago string isPrime(int n) { for (int i = 2; i <= sqrt(n); i++) { if(n%i==0) return "No"; } if(n==1) return "No"; else return "Yes";} 0 nagaajayk2 months ago if(n==1) { return "No"; } for (int i = 2; i <= sqrt(n); i++) { if(n%i==0) { return "No"; } } return "Yes"; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 497, "s": 278, "text": "What do you do when you need to execute certain statements more than once? You put them in a loop. Loops are very powerful. Majority of coding questions need loops to work. You can't even input testcases without loops!" }, { "code": null, "e": 654, "s": 497, "text": "Here, we will use for loop and check if the given number n is prime or not.\nNote: A number is prime if it's divisible by itself and 1. Also, 1 is not prime." }, { "code": null, "e": 665, "s": 654, "text": "Example 1:" }, { "code": null, "e": 690, "s": 665, "text": "Input:\nn = 1\nOutput:\nNo\n" }, { "code": null, "e": 701, "s": 690, "text": "Example 2:" }, { "code": null, "e": 726, "s": 701, "text": "Input:\nn = 2\nOutput:\nYes" }, { "code": null, "e": 861, "s": 726, "text": "User Task: \nYour task is to complete the provided function isPrime() which should return a string \"Yes\" if n is prime and \"No\" if not." }, { "code": null, "e": 887, "s": 861, "text": "Constraints:\n1 ≤ n ≤ 1000" }, { "code": null, "e": 894, "s": 887, "text": "Video:" }, { "code": null, "e": 1812, "s": 894, "text": "YouTubeGeeksforGeeks500K subscribersC++ Programming Language Tutorial | Loops in C++ - Part 1 (Entry Controlled Loop) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.Full screen is unavailable. Learn MoreMore videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:09•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=MbEVFhucVa0\" 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": 1814, "s": 1812, "text": "0" }, { "code": null, "e": 1843, "s": 1814, "text": "vikaschandra8051101 week ago" }, { "code": null, "e": 1858, "s": 1843, "text": "//perfect soln" }, { "code": null, "e": 2284, "s": 1858, "text": "string isPrime(int n) { if(n==1){ return \"No\"; } if(n==2 || n==3){ return \"Yes\"; } for (int i = 2; i <= sqrt(n); i++) { // Write your logic here if(n%i ==0){ return \"No\"; } // Return \"Yes\" if n is prime, else return \"No\" /*n is prime only if it is not divisible by any i. We will not reach till n and 1 is already discarded*/ } return \"Yes\";} " }, { "code": null, "e": 2287, "s": 2284, "text": "+1" }, { "code": null, "e": 2312, "s": 2287, "text": "anshumanatrey3 weeks ago" }, { "code": null, "e": 2325, "s": 2312, "text": "C++ ANSWER :" }, { "code": null, "e": 2537, "s": 2325, "text": "string isPrime(int n) {\n int c=0;\n for (int i = 2; i <= n; i++) {\n if(n%i==0){\n c++;\n }\n }\n if(c>1 || n==1){\n cout<<\"No\";\n }\n else {\n cout<<\"Yes\";\n }\n}" }, { "code": null, "e": 2539, "s": 2537, "text": "0" }, { "code": null, "e": 2553, "s": 2539, "text": "anshumanatrey" }, { "code": null, "e": 2579, "s": 2553, "text": "This comment was deleted." }, { "code": null, "e": 2581, "s": 2579, "text": "0" }, { "code": null, "e": 2607, "s": 2581, "text": "imluckybanthia4 weeks ago" }, { "code": null, "e": 2819, "s": 2607, "text": "string isPrime(int n) { int c=0; for (int i = 2; i <= n; i++) { if(n%i==0){ ++c; } } if(c>=2 || n==0||n==1){ cout<<\"No\";} else{ cout<<\"Yes\"; } " }, { "code": null, "e": 2821, "s": 2819, "text": "0" }, { "code": null, "e": 2843, "s": 2821, "text": "sumitd12991 month ago" }, { "code": null, "e": 3011, "s": 2843, "text": "string isPrime(int n) { if(n==1){ return \"No\"; } for (int i = 2; i <= sqrt(n); i++) { if(n%i==0){ return \"No\"; } } return \"Yes\";}" }, { "code": null, "e": 3013, "s": 3011, "text": "0" }, { "code": null, "e": 3038, "s": 3013, "text": "akash119027401 month ago" }, { "code": null, "e": 3250, "s": 3038, "text": "string isPrime(int n) { if(n==1)return \"No\"; if(n==2 || n==3) return \"Yes\"; if(n%2==0 || n%3==0) return \"No\"; for(int i = 5; i*i<=n;i+=6){ if(n%i==0 || n%(i+2)==0) return \"No\"; } return \"Yes\";}" }, { "code": null, "e": 3252, "s": 3250, "text": "0" }, { "code": null, "e": 3282, "s": 3252, "text": "srilakshmimounika01 month ago" }, { "code": null, "e": 3306, "s": 3282, "text": "#include<bits/stdc++.h>" }, { "code": null, "e": 3327, "s": 3306, "text": "using namespace std;" }, { "code": null, "e": 3338, "s": 3327, "text": "int main()" }, { "code": null, "e": 3360, "s": 3338, "text": "string isprime(int n)" }, { "code": null, "e": 3362, "s": 3360, "text": "{" }, { "code": null, "e": 3390, "s": 3362, "text": "for(int i=2;i,=sqrt(n);i++)" }, { "code": null, "e": 3392, "s": 3390, "text": "{" }, { "code": null, "e": 3403, "s": 3392, "text": "if(n%i==0)" }, { "code": null, "e": 3416, "s": 3403, "text": "return “no”;" }, { "code": null, "e": 3418, "s": 3416, "text": "}" }, { "code": null, "e": 3427, "s": 3418, "text": "if(n==1)" }, { "code": null, "e": 3440, "s": 3427, "text": "return “no”;" }, { "code": null, "e": 3446, "s": 3440, "text": "else " }, { "code": null, "e": 3460, "s": 3446, "text": "return “yes”;" }, { "code": null, "e": 3462, "s": 3460, "text": "}" }, { "code": null, "e": 3472, "s": 3462, "text": "return 0;" }, { "code": null, "e": 3474, "s": 3472, "text": "}" }, { "code": null, "e": 3477, "s": 3474, "text": "+1" }, { "code": null, "e": 3503, "s": 3477, "text": "saikumar0272071 month ago" }, { "code": null, "e": 3505, "s": 3503, "text": "1" }, { "code": null, "e": 3507, "s": 3505, "text": "0" }, { "code": null, "e": 3530, "s": 3507, "text": "mdshahid132 months ago" }, { "code": null, "e": 3684, "s": 3530, "text": "string isPrime(int n) { for (int i = 2; i <= sqrt(n); i++) { if(n%i==0) return \"No\"; } if(n==1) return \"No\"; else return \"Yes\";}" }, { "code": null, "e": 3686, "s": 3684, "text": "0" }, { "code": null, "e": 3708, "s": 3686, "text": "nagaajayk2 months ago" }, { "code": null, "e": 3867, "s": 3708, "text": "if(n==1) {\n return \"No\";\n }\n for (int i = 2; i <= sqrt(n); i++) {\n if(n%i==0) {\n return \"No\";\n }\n }\n return \"Yes\";" }, { "code": null, "e": 4013, "s": 3867, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 4049, "s": 4013, "text": " Login to access your submissions. " }, { "code": null, "e": 4059, "s": 4049, "text": "\nProblem\n" }, { "code": null, "e": 4069, "s": 4059, "text": "\nContest\n" }, { "code": null, "e": 4132, "s": 4069, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4280, "s": 4132, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 4488, "s": 4280, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 4594, "s": 4488, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Logstash - Filters
Logstash uses filters in the middle of the pipeline between input and output. The filters of Logstash measures manipulate and create events like Apache-Access. Many filter plugins used to manage the events in Logstash. Here, in an example of the Logstash Aggregate Filter, we are filtering the duration every SQL transaction in a database and computing the total time. Installing the Aggregate Filter Plugin using the Logstash-plugin utility. The Logstash-plugin is a batch file for windows in bin folder in Logstash. >logstash-plugin install logstash-filter-aggregate In this configuration, you can see three ‘if’ statements for Initializing, Incrementing, and generating the total duration of transaction, i.e., the sql_duration. The aggregate plugin is used to add the sql_duration, present in every event of the input log. input { file { path => "C:/tpwork/logstash/bin/log/input.log" } } filter { grok { match => [ "message", "%{LOGLEVEL:loglevel} - %{NOTSPACE:taskid} - %{NOTSPACE:logger} - %{WORD:label}( - %{INT:duration:int})?" ] } if [logger] == "TRANSACTION_START" { aggregate { task_id => "%{taskid}" code => "map['sql_duration'] = 0" map_action => "create" } } if [logger] == "SQL" { aggregate { task_id => "%{taskid}" code => "map['sql_duration'] ||= 0 ; map['sql_duration'] += event.get('duration')" } } if [logger] == "TRANSACTION_END" { aggregate { task_id => "%{taskid}" code => "event.set('sql_duration', map['sql_duration'])" end_of_task => true timeout => 120 } } } output { file { path => "C:/tpwork/logstash/bin/log/output.log" } } We can run Logstash by using the following command. >logstash –f logstash.conf The following code block shows the input log data. INFO - 48566 - TRANSACTION_START - start INFO - 48566 - SQL - transaction1 - 320 INFO - 48566 - SQL - transaction1 - 200 INFO - 48566 - TRANSACTION_END - end As specified in the configuration file, the last ‘if’ statement where the logger is – TRANSACTION_END, which prints the total transaction time or sql_duration. This has been highlighted in yellow color in the output.log. { "path":"C:/tpwork/logstash/bin/log/input.log","@timestamp": "2016-12-22T19:04:37.214Z", "loglevel":"INFO","logger":"TRANSACTION_START","@version": "1","host":"wcnlab-PC", "message":"8566 - TRANSACTION_START - start\r","tags":[] } { "duration":320,"path":"C:/tpwork/logstash/bin/log/input.log", "@timestamp":"2016-12-22T19:04:38.366Z","loglevel":"INFO","logger":"SQL", "@version":"1","host":"wcnlab-PC","label":"transaction1", "message":" INFO - 48566 - SQL - transaction1 - 320\r","taskid":"48566","tags":[] } { "duration":200,"path":"C:/tpwork/logstash/bin/log/input.log", "@timestamp":"2016-12-22T19:04:38.373Z","loglevel":"INFO","logger":"SQL", "@version":"1","host":"wcnlab-PC","label":"transaction1", "message":" INFO - 48566 - SQL - transaction1 - 200\r","taskid":"48566","tags":[] } { "sql_duration":520,"path":"C:/tpwork/logstash/bin/log/input.log", "@timestamp":"2016-12-22T19:04:38.380Z","loglevel":"INFO","logger":"TRANSACTION_END", "@version":"1","host":"wcnlab-PC","label":"end", "message":" INFO - 48566 - TRANSACTION_END - end\r","taskid":"48566","tags":[] } Print Add Notes Bookmark this page
[ { "code": null, "e": 2424, "s": 2055, "text": "Logstash uses filters in the middle of the pipeline between input and output. The filters of Logstash measures manipulate and create events like Apache-Access. Many filter plugins used to manage the events in Logstash. Here, in an example of the Logstash Aggregate Filter, we are filtering the duration every SQL transaction in a database and computing the total time." }, { "code": null, "e": 2573, "s": 2424, "text": "Installing the Aggregate Filter Plugin using the Logstash-plugin utility. The Logstash-plugin is a batch file for windows in bin folder in Logstash." }, { "code": null, "e": 2625, "s": 2573, "text": ">logstash-plugin install logstash-filter-aggregate\n" }, { "code": null, "e": 2883, "s": 2625, "text": "In this configuration, you can see three ‘if’ statements for Initializing, Incrementing, and generating the total duration of transaction, i.e., the sql_duration. The aggregate plugin is used to add the sql_duration, present in every event of the input log." }, { "code": null, "e": 3841, "s": 2883, "text": "input {\n file {\n path => \"C:/tpwork/logstash/bin/log/input.log\"\n }\n} \nfilter {\n grok {\n match => [\n \"message\", \"%{LOGLEVEL:loglevel} - \n %{NOTSPACE:taskid} - %{NOTSPACE:logger} - \n %{WORD:label}( - %{INT:duration:int})?\" \n ]\n }\n if [logger] == \"TRANSACTION_START\" {\n aggregate {\n task_id => \"%{taskid}\"\n code => \"map['sql_duration'] = 0\"\n map_action => \"create\"\n }\n }\n if [logger] == \"SQL\" {\n aggregate {\n task_id => \"%{taskid}\"\n code => \"map['sql_duration'] ||= 0 ;\n map['sql_duration'] += event.get('duration')\"\n }\n }\n if [logger] == \"TRANSACTION_END\" {\n aggregate {\n task_id => \"%{taskid}\"\n code => \"event.set('sql_duration', map['sql_duration'])\"\n end_of_task => true\n timeout => 120\n }\n }\n}\noutput {\n file {\n path => \"C:/tpwork/logstash/bin/log/output.log\" \n }\n}" }, { "code": null, "e": 3893, "s": 3841, "text": "We can run Logstash by using the following command." }, { "code": null, "e": 3922, "s": 3893, "text": ">logstash –f logstash.conf \n" }, { "code": null, "e": 3973, "s": 3922, "text": "The following code block shows the input log data." }, { "code": null, "e": 4132, "s": 3973, "text": "INFO - 48566 - TRANSACTION_START - start\nINFO - 48566 - SQL - transaction1 - 320\nINFO - 48566 - SQL - transaction1 - 200\nINFO - 48566 - TRANSACTION_END - end\n" }, { "code": null, "e": 4353, "s": 4132, "text": "As specified in the configuration file, the last ‘if’ statement where the logger is – TRANSACTION_END, which prints the total transaction time or sql_duration. This has been highlighted in yellow color in the output.log." }, { "code": null, "e": 5474, "s": 4353, "text": "{\n \"path\":\"C:/tpwork/logstash/bin/log/input.log\",\"@timestamp\": \"2016-12-22T19:04:37.214Z\",\n \"loglevel\":\"INFO\",\"logger\":\"TRANSACTION_START\",\"@version\": \"1\",\"host\":\"wcnlab-PC\",\n \"message\":\"8566 - TRANSACTION_START - start\\r\",\"tags\":[]\n}\n{\n \"duration\":320,\"path\":\"C:/tpwork/logstash/bin/log/input.log\",\n \"@timestamp\":\"2016-12-22T19:04:38.366Z\",\"loglevel\":\"INFO\",\"logger\":\"SQL\",\n \"@version\":\"1\",\"host\":\"wcnlab-PC\",\"label\":\"transaction1\",\n \"message\":\" INFO - 48566 - SQL - transaction1 - 320\\r\",\"taskid\":\"48566\",\"tags\":[]\n}\n{\n \"duration\":200,\"path\":\"C:/tpwork/logstash/bin/log/input.log\",\n \"@timestamp\":\"2016-12-22T19:04:38.373Z\",\"loglevel\":\"INFO\",\"logger\":\"SQL\",\n \"@version\":\"1\",\"host\":\"wcnlab-PC\",\"label\":\"transaction1\",\n \"message\":\" INFO - 48566 - SQL - transaction1 - 200\\r\",\"taskid\":\"48566\",\"tags\":[]\n}\n{\n \"sql_duration\":520,\"path\":\"C:/tpwork/logstash/bin/log/input.log\",\n \"@timestamp\":\"2016-12-22T19:04:38.380Z\",\"loglevel\":\"INFO\",\"logger\":\"TRANSACTION_END\",\n \"@version\":\"1\",\"host\":\"wcnlab-PC\",\"label\":\"end\",\n \"message\":\" INFO - 48566 - TRANSACTION_END - end\\r\",\"taskid\":\"48566\",\"tags\":[]\n}" }, { "code": null, "e": 5481, "s": 5474, "text": " Print" }, { "code": null, "e": 5492, "s": 5481, "text": " Add Notes" } ]
Stock Buy Sell to Maximize Profit - GeeksforGeeks
21 Mar, 2022 The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days. For example, if the given array is {100, 180, 260, 310, 40, 535, 695}, the maximum profit can earn by buying on day 0, selling on day 3. Again, buy on day 4 and sell on day 6. If the given array of prices is sorted in decreasing order, then profit cannot be earned at all. Naive approach: A simple approach is to try buying the stocks and selling them on every single day when profitable and keep updating the maximum profit so far. Below is the implementation of the above approach: C++ C Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum profit// that can be made after buying and// selling the given stocksint maxProfit(int price[], int start, int end){ // If the stocks can't be bought if (end <= start) return 0; // Initialise the profit int profit = 0; // The day at which the stock // must be bought for (int i = start; i < end; i++) { // The day at which the // stock must be sold for (int j = i + 1; j <= end; j++) { // If buying the stock at ith day and // selling it at jth day is profitable if (price[j] > price[i]) { // Update the current profit int curr_profit = price[j] - price[i] + maxProfit(price, start, i - 1) + maxProfit(price, j + 1, end); // Update the maximum profit so far profit = max(profit, curr_profit); } } } return profit;} // Driver codeint main(){ int price[] = { 100, 180, 260, 310, 40, 535, 695 }; int n = sizeof(price) / sizeof(price[0]); cout << maxProfit(price, 0, n - 1); return 0;} // Importing the required header files#include <stdio.h> // Creating MACRO for finding the maximum number#define max(x, y)(((x) > (y)) ? (x) : (y)) // Creating MACRO for finding the minimum number#define min(x, y)(((x) < (y)) ? (x) : (y)) // Function to return the maximum profit// that can be made after buying and// selling the given stocksint maxProfit(int price[], int start, int end){ // If the stocks can't be bought if (end <= start) return 0; // Initialise the profit int profit = 0; // The day at which the stock // must be bought for (int i = start; i < end; i++) { // The day at which the // stock must be sold for (int j = i + 1; j <= end; j++) { // If buying the stock at ith day and // selling it at jth day is profitable if (price[j] > price[i]) { // Update the current profit int curr_profit = price[j] - price[i] + maxProfit(price, start, i - 1) + maxProfit(price, j + 1, end); // Update the maximum profit so far profit = max(profit, curr_profit); } } } return profit;} // Driver Codeint main(){ int price[] = { 100, 180, 260, 310, 40, 535, 695 }; int n = sizeof(price) / sizeof(price[0]); printf("%d", maxProfit(price, 0, n - 1)); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Function to return the maximum profit// that can be made after buying and// selling the given stocksstatic int maxProfit(int price[], int start, int end){ // If the stocks can't be bought if (end <= start) return 0; // Initialise the profit int profit = 0; // The day at which the stock // must be bought for (int i = start; i < end; i++) { // The day at which the // stock must be sold for (int j = i + 1; j <= end; j++) { // If buying the stock at ith day and // selling it at jth day is profitable if (price[j] > price[i]) { // Update the current profit int curr_profit = price[j] - price[i] + maxProfit(price, start, i - 1) + maxProfit(price, j + 1, end); // Update the maximum profit so far profit = Math.max(profit, curr_profit); } } } return profit;} // Driver codepublic static void main(String[] args){ int price[] = { 100, 180, 260, 310, 40, 535, 695 }; int n = price.length; System.out.print(maxProfit(price, 0, n - 1));}} // This code is contributed by PrinciRaj1992 # Python3 implementation of the approach # Function to return the maximum profit# that can be made after buying and# selling the given stocksdef maxProfit(price, start, end): # If the stocks can't be bought if (end <= start): return 0; # Initialise the profit profit = 0; # The day at which the stock # must be bought for i in range(start, end, 1): # The day at which the # stock must be sold for j in range(i+1, end+1): # If buying the stock at ith day and # selling it at jth day is profitable if (price[j] > price[i]): # Update the current profit curr_profit = price[j] - price[i] +\ maxProfit(price, start, i - 1)+ \ maxProfit(price, j + 1, end); # Update the maximum profit so far profit = max(profit, curr_profit); return profit; # Driver codeif __name__ == '__main__': price = [100, 180, 260, 310, 40, 535, 695]; n = len(price); print(maxProfit(price, 0, n - 1)); # This code is contributed by Rajput-Ji // C# implementation of the approachusing System; class GFG{ // Function to return the maximum profit// that can be made after buying and// selling the given stocksstatic int maxProfit(int []price, int start, int end){ // If the stocks can't be bought if (end <= start) return 0; // Initialise the profit int profit = 0; // The day at which the stock // must be bought for (int i = start; i < end; i++) { // The day at which the // stock must be sold for (int j = i + 1; j <= end; j++) { // If buying the stock at ith day and // selling it at jth day is profitable if (price[j] > price[i]) { // Update the current profit int curr_profit = price[j] - price[i] + maxProfit(price, start, i - 1) + maxProfit(price, j + 1, end); // Update the maximum profit so far profit = Math.Max(profit, curr_profit); } } } return profit;} // Driver codepublic static void Main(String[] args){ int []price = { 100, 180, 260, 310, 40, 535, 695 }; int n = price.Length; Console.Write(maxProfit(price, 0, n - 1));}} // This code is contributed by PrinciRaj1992 <script> // Javascript implementation of the approach // Function to return the maximum profit// that can be made after buying and// selling the given stocksfunction maxProfit( price, start, end){ // If the stocks can't be bought if (end <= start) return 0; // Initialise the profit let profit = 0; // The day at which the stock // must be bought for (let i = start; i < end; i++) { // The day at which the // stock must be sold for (let j = i + 1; j <= end; j++) { // If buying the stock at ith day and // selling it at jth day is profitable if (price[j] > price[i]) { // Update the current profit let curr_profit = price[j] - price[i] + maxProfit(price, start, i - 1) + maxProfit(price, j + 1, end); // Update the maximum profit so far profit = Math.max(profit, curr_profit); } } } return profit;} // Driver program let price = [ 100, 180, 260, 310, 40, 535, 695 ]; let n = price.length; document.write(maxProfit(price, 0, n - 1)); </script> 865 Efficient approach: If we are allowed to buy and sell only once, then we can use the following algorithm. Maximum difference between two elements. Here we are allowed to buy and sell multiple times. Following is the algorithm for this problem. Find the local minima and store it as starting index. If not exists, return.Find the local maxima. And store it as an ending index. If we reach the end, set the end as the ending index.Update the solution (Increment count of buy-sell pairs)Repeat the above steps if the end is not reached. Find the local minima and store it as starting index. If not exists, return. Find the local maxima. And store it as an ending index. If we reach the end, set the end as the ending index. Update the solution (Increment count of buy-sell pairs) Repeat the above steps if the end is not reached. C++ C Java Python3 C# Javascript // C++ Program to find best buying and selling days#include <bits/stdc++.h>using namespace std; // This function finds the buy sell// schedule for maximum profitvoid stockBuySell(int price[], int n){ // Prices must be given for at least two days if (n == 1) return; // Traverse through given price array int i = 0; while (i < n - 1) { // Find Local Minima // Note that the limit is (n-2) as we are // comparing present element to the next element while ((i < n - 1) && (price[i + 1] <= price[i])) i++; // If we reached the end, break // as no further solution possible if (i == n - 1) break; // Store the index of minima int buy = i++; // Find Local Maxima // Note that the limit is (n-1) as we are // comparing to previous element while ((i < n) && (price[i] >= price[i - 1])) i++; // Store the index of maxima int sell = i - 1; cout << "Buy on day: " << buy << "\t Sell on day: " << sell << endl; }} // Driver codeint main(){ // Stock prices on consecutive days int price[] = { 100, 180, 260, 310, 40, 535, 695 }; int n = sizeof(price) / sizeof(price[0]); // Function call stockBuySell(price, n); return 0;} // This is code is contributed by rathbhupendra // Program to find best buying and selling days#include <stdio.h> // solution structurestruct Interval { int buy; int sell;}; // This function finds the buy sell schedule for maximum profitvoid stockBuySell(int price[], int n){ // Prices must be given for at least two days if (n == 1) return; int count = 0; // count of solution pairs // solution vector Interval sol[n / 2 + 1]; // Traverse through given price array int i = 0; while (i < n - 1) { // Find Local Minima. Note that the limit is (n-2) as we are // comparing present element to the next element. while ((i < n - 1) && (price[i + 1] <= price[i])) i++; // If we reached the end, break as no further solution possible if (i == n - 1) break; // Store the index of minima sol[count].buy = i++; // Find Local Maxima. Note that the limit is (n-1) as we are // comparing to previous element while ((i < n) && (price[i] >= price[i - 1])) i++; // Store the index of maxima sol[count].sell = i - 1; // Increment count of buy/sell pairs count++; } // print solution if (count == 0) printf("There is no day when buying the stock will make profitn"); else { for (int i = 0; i < count; i++) printf("Buy on day: %dt Sell on day: %dn", sol[i].buy, sol[i].sell); } return;} // Driver program to test above functionsint main(){ // stock prices on consecutive days int price[] = { 100, 180, 260, 310, 40, 535, 695 }; int n = sizeof(price) / sizeof(price[0]); // function call stockBuySell(price, n); return 0;} // Program to find best buying and selling daysimport java.util.ArrayList; // Solution structureclass Interval { int buy, sell;} class StockBuySell { // This function finds the buy sell schedule for maximum profit void stockBuySell(int price[], int n) { // Prices must be given for at least two days if (n == 1) return; int count = 0; // solution array ArrayList<Interval> sol = new ArrayList<Interval>(); // Traverse through given price array int i = 0; while (i < n - 1) { // Find Local Minima. Note that the limit is (n-2) as we are // comparing present element to the next element. while ((i < n - 1) && (price[i + 1] <= price[i])) i++; // If we reached the end, break as no further solution possible if (i == n - 1) break; Interval e = new Interval(); e.buy = i++; // Store the index of minima // Find Local Maxima. Note that the limit is (n-1) as we are // comparing to previous element while ((i < n) && (price[i] >= price[i - 1])) i++; // Store the index of maxima e.sell = i - 1; sol.add(e); // Increment number of buy/sell count++; } // print solution if (count == 0) System.out.println("There is no day when buying the stock " + "will make profit"); else for (int j = 0; j < count; j++) System.out.println("Buy on day: " + sol.get(j).buy + " " + "Sell on day : " + sol.get(j).sell); return; } public static void main(String args[]) { StockBuySell stock = new StockBuySell(); // stock prices on consecutive days int price[] = { 100, 180, 260, 310, 40, 535, 695 }; int n = price.length; // function call stock.stockBuySell(price, n); }} // This code has been contributed by Mayank Jaiswal # Python3 Program to find# best buying and selling days # This function finds the buy sell# schedule for maximum profitdef stockBuySell(price, n): # Prices must be given for at least two days if (n == 1): return # Traverse through given price array i = 0 while (i < (n - 1)): # Find Local Minima # Note that the limit is (n-2) as we are # comparing present element to the next element while ((i < (n - 1)) and (price[i + 1] <= price[i])): i += 1 # If we reached the end, break # as no further solution possible if (i == n - 1): break # Store the index of minima buy = i i += 1 # Find Local Maxima # Note that the limit is (n-1) as we are # comparing to previous element while ((i < n) and (price[i] >= price[i - 1])): i += 1 # Store the index of maxima sell = i - 1 print("Buy on day: ",buy,"\t", "Sell on day: ",sell) # Driver code # Stock prices on consecutive daysprice = [100, 180, 260, 310, 40, 535, 695]n = len(price) # Function callstockBuySell(price, n) # This is code contributed by SHUBHAMSINGH10 // C# program to find best buying and selling daysusing System;using System.Collections.Generic; // Solution structureclass Interval{ public int buy, sell;} public class StockBuySell{ // This function finds the buy sell // schedule for maximum profit void stockBuySell(int []price, int n) { // Prices must be given for at least two days if (n == 1) return; int count = 0; // solution array List<Interval> sol = new List<Interval>(); // Traverse through given price array int i = 0; while (i < n - 1) { // Find Local Minima. Note that // the limit is (n-2) as we are // comparing present element // to the next element. while ((i < n - 1) && (price[i + 1] <= price[i])) i++; // If we reached the end, break // as no further solution possible if (i == n - 1) break; Interval e = new Interval(); e.buy = i++; // Store the index of minima // Find Local Maxima. Note that // the limit is (n-1) as we are // comparing to previous element while ((i < n) && (price[i] >= price[i - 1])) i++; // Store the index of maxima e.sell = i - 1; sol.Add(e); // Increment number of buy/sell count++; } // print solution if (count == 0) Console.WriteLine("There is no day when buying the stock " + "will make profit"); else for (int j = 0; j < count; j++) Console.WriteLine("Buy on day: " + sol[j].buy + " " + "Sell on day : " + sol[j].sell); return; } // Driver code public static void Main(String []args) { StockBuySell stock = new StockBuySell(); // stock prices on consecutive days int []price = { 100, 180, 260, 310, 40, 535, 695 }; int n = price.Length; // function call stock.stockBuySell(price, n); }} // This code is contributed by PrinciRaj1992 <script> // JavaScript program for the above approach // This function finds the buy sell // schedule for maximum profit function stockBuySell(price, n) { // Prices must be given for at least two days if (n == 1) return; // Traverse through given price array let i = 0; while (i < n - 1) { // Find Local Minima // Note that the limit is (n-2) as we are // comparing present element to the next element while ((i < n - 1) && (price[i + 1] <= price[i])) i++; // If we reached the end, break // as no further solution possible if (i == n - 1) break; // Store the index of minima let buy = i++; // Find Local Maxima // Note that the limit is (n-1) as we are // comparing to previous element while ((i < n) && (price[i] >= price[i - 1])) i++; // Store the index of maxima let sell = i - 1; document.write(`Buy on day: ${buy} Sell on day: ${sell}<br>`); } } // Driver code // Stock prices on consecutive days let price = [100, 180, 260, 310, 40, 535, 695]; let n = price.length; // Function call stockBuySell(price, n); // This code is contributed by Potta Lokesh </script> Buy on day: 0 Sell on day: 3 Buy on day: 4 Sell on day: 6 Time Complexity: The outer loop runs till I become n-1. The inner two loops increment the value of I in every iteration. So overall time complexity is O(n) Valley Peak Approach: In this approach, we just need to find the next greater element and subtract it from the current element so that the difference keeps increasing until we reach a minimum. If the sequence is a decreasing sequence, so the maximum profit possible is 0. C++ C Java Python3 C# Javascript #include <iostream>using namespace std; // Preprocessing helps the code run faster#define fl(i, a, b) for (int i = a; i < b; i++) // Function that returnint maxProfit(int* prices, int size){ // maxProfit adds up the difference between // adjacent elements if they are in increasing order int maxProfit = 0; // The loop starts from 1 // as its comparing with the previous fl(i, 1, size) if (prices[i] > prices[i - 1]) maxProfit += prices[i] - prices[i - 1]; return maxProfit;} // Driver Functionint main(){ int prices[] = { 100, 180, 260, 310, 40, 535, 695 }; int N = sizeof(prices) / sizeof(prices[0]); cout << maxProfit(prices, N) << endl; return 0;}// This code is contributed by Kingshuk Deb // Importing the required header files#include <stdio.h> // Creating MACRO for finding the maximum number#define max(x, y)(((x) > (y)) ? (x) : (y)) // Creating MACRO for finding the minimum number#define min(x, y)(((x) < (y)) ? (x) : (y)) // Function that returnint maxProfit(int prices[], int size){ // maxProfit adds up the difference between // adjacent elements if they are in increasing order int ans = 0; // The loop starts from 1 // as its comparing with the previous for (int i = 1; i < size; i++) { // If the current element is greater than the previous // then the difference is added to the answer if (prices[i] > prices[i - 1]) ans += prices[i] - prices[i - 1]; } return ans;} // Driver Codeint main(){ int price[] = { 100, 180, 260, 310, 40, 535, 695 }; int n = sizeof(price) / sizeof(price[0]); printf("%d", maxProfit(price, n)); return 0;} // Java program for the above approachimport java.io.*; class GFG{ static int maxProfit(int prices[], int size) { // maxProfit adds up the difference between // adjacent elements if they are in increasing order int maxProfit = 0; // The loop starts from 1 // as its comparing with the previous for (int i = 1; i < size; i++) if (prices[i] > prices[i - 1]) maxProfit += prices[i] - prices[i - 1]; return maxProfit; } // Driver code public static void main(String[] args) { // stock prices on consecutive days int price[] = { 100, 180, 260, 310, 40, 535, 695 }; int n = price.length; // function call System.out.println(maxProfit(price, n)); }} // This code is contributed by rajsanghavi9. # Python3 program for the above approachdef max_profit(prices: list, days: int) -> int: profit = 0 for i in range(1, days): # checks if elements are adjacent and in increasing order if prices[i] > prices[i-1]: # difference added to 'profit' profit += prices[i] - prices[i-1] return profit # Driver Codeif __name__ == '__main__': # stock prices on consecutive days prices = [100, 180, 260, 310, 40, 535, 695] # function call profit = max_profit(prices, len(prices)) print(profit) # This code is contributed by vishvofficial. // C# program for the above approachusing System; class GFG{ static int maxProfit(int[] prices, int size){ // maxProfit adds up the difference // between adjacent elements if they // are in increasing order int maxProfit = 0; // The loop starts from 1 as its // comparing with the previous for(int i = 1; i < size; i++) if (prices[i] > prices[i - 1]) maxProfit += prices[i] - prices[i - 1]; return maxProfit;} // Driver codepublic static void Main(string[] args){ // Stock prices on consecutive days int[] price = { 100, 180, 260, 310, 40, 535, 695 }; int n = price.Length; // Function call Console.WriteLine(maxProfit(price, n));}} // This code is contributed by ukasp <script>// javascript program for the above approach function maxProfit(prices , size) { // maxProfit adds up the difference between // adjacent elements if they are in increasing order var maxProfit = 0; // The loop starts from 1 // as its comparing with the previous for (i = 1; i < size; i++) if (prices[i] > prices[i - 1]) maxProfit += prices[i] - prices[i - 1]; return maxProfit; } // Driver code // stock prices on consecutive days var price = [ 100, 180, 260, 310, 40, 535, 695 ]; var n = price.length; // function call document.write(maxProfit(price, n)); // This code is contributed by umadevi9616</script> 865 Time Complexity: O(n)Auxiliary Space: O(1) This article is compiled by Ashish Anand and reviewed by the GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. rathbhupendra princiraj1992 SHUBHAMSINGH10 Rajput-Ji ashwanisng avanitrachhadiya2155 shivanisinghss2110 divyeshrabadiya07 ayusharora jana_sayantan surbhityagi15 arorakashish0911 lokeshpotta20 itskingshuk anikaseth98 pankajsharmagfg rajsanghavi9 vishvofficial kalrap615 ukasp umadevi9616 amnindersingh1414 Accolite Amazon Directi Flipkart Goldman Sachs Hike MakeMyTrip Microsoft Morgan Stanley Ola Cabs Oracle Paytm Pubmatic Quikr Samsung SAP Labs Sapient Swiggy Walmart Arrays Paytm Flipkart Morgan Stanley Accolite Amazon Microsoft Samsung Hike MakeMyTrip Ola Cabs Oracle Walmart Goldman Sachs Directi SAP Labs Quikr Pubmatic Sapient Swiggy Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction to Arrays Multidimensional Arrays in Java Linked List vs Array Python | Using 2D arrays/lists the right way Given an array of size n and a number k, find all elements that appear more than n/k times Queue | Set 1 (Introduction and Array Implementation) Subset Sum Problem | DP-25 K'th Smallest/Largest Element in Unsorted Array | Set 1 Find the Missing Number Array of Strings in C++ (5 Different Ways to Create)
[ { "code": null, "e": 24741, "s": 24713, "text": "\n21 Mar, 2022" }, { "code": null, "e": 25143, "s": 24741, "text": "The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days. For example, if the given array is {100, 180, 260, 310, 40, 535, 695}, the maximum profit can earn by buying on day 0, selling on day 3. Again, buy on day 4 and sell on day 6. If the given array of prices is sorted in decreasing order, then profit cannot be earned at all." }, { "code": null, "e": 25303, "s": 25143, "text": "Naive approach: A simple approach is to try buying the stocks and selling them on every single day when profitable and keep updating the maximum profit so far." }, { "code": null, "e": 25354, "s": 25303, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25358, "s": 25354, "text": "C++" }, { "code": null, "e": 25360, "s": 25358, "text": "C" }, { "code": null, "e": 25365, "s": 25360, "text": "Java" }, { "code": null, "e": 25373, "s": 25365, "text": "Python3" }, { "code": null, "e": 25376, "s": 25373, "text": "C#" }, { "code": null, "e": 25387, "s": 25376, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum profit// that can be made after buying and// selling the given stocksint maxProfit(int price[], int start, int end){ // If the stocks can't be bought if (end <= start) return 0; // Initialise the profit int profit = 0; // The day at which the stock // must be bought for (int i = start; i < end; i++) { // The day at which the // stock must be sold for (int j = i + 1; j <= end; j++) { // If buying the stock at ith day and // selling it at jth day is profitable if (price[j] > price[i]) { // Update the current profit int curr_profit = price[j] - price[i] + maxProfit(price, start, i - 1) + maxProfit(price, j + 1, end); // Update the maximum profit so far profit = max(profit, curr_profit); } } } return profit;} // Driver codeint main(){ int price[] = { 100, 180, 260, 310, 40, 535, 695 }; int n = sizeof(price) / sizeof(price[0]); cout << maxProfit(price, 0, n - 1); return 0;}", "e": 26657, "s": 25387, "text": null }, { "code": "// Importing the required header files#include <stdio.h> // Creating MACRO for finding the maximum number#define max(x, y)(((x) > (y)) ? (x) : (y)) // Creating MACRO for finding the minimum number#define min(x, y)(((x) < (y)) ? (x) : (y)) // Function to return the maximum profit// that can be made after buying and// selling the given stocksint maxProfit(int price[], int start, int end){ // If the stocks can't be bought if (end <= start) return 0; // Initialise the profit int profit = 0; // The day at which the stock // must be bought for (int i = start; i < end; i++) { // The day at which the // stock must be sold for (int j = i + 1; j <= end; j++) { // If buying the stock at ith day and // selling it at jth day is profitable if (price[j] > price[i]) { // Update the current profit int curr_profit = price[j] - price[i] + maxProfit(price, start, i - 1) + maxProfit(price, j + 1, end); // Update the maximum profit so far profit = max(profit, curr_profit); } } } return profit;} // Driver Codeint main(){ int price[] = { 100, 180, 260, 310, 40, 535, 695 }; int n = sizeof(price) / sizeof(price[0]); printf(\"%d\", maxProfit(price, 0, n - 1)); return 0;}", "e": 28089, "s": 26657, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the maximum profit// that can be made after buying and// selling the given stocksstatic int maxProfit(int price[], int start, int end){ // If the stocks can't be bought if (end <= start) return 0; // Initialise the profit int profit = 0; // The day at which the stock // must be bought for (int i = start; i < end; i++) { // The day at which the // stock must be sold for (int j = i + 1; j <= end; j++) { // If buying the stock at ith day and // selling it at jth day is profitable if (price[j] > price[i]) { // Update the current profit int curr_profit = price[j] - price[i] + maxProfit(price, start, i - 1) + maxProfit(price, j + 1, end); // Update the maximum profit so far profit = Math.max(profit, curr_profit); } } } return profit;} // Driver codepublic static void main(String[] args){ int price[] = { 100, 180, 260, 310, 40, 535, 695 }; int n = price.length; System.out.print(maxProfit(price, 0, n - 1));}} // This code is contributed by PrinciRaj1992", "e": 29425, "s": 28089, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the maximum profit# that can be made after buying and# selling the given stocksdef maxProfit(price, start, end): # If the stocks can't be bought if (end <= start): return 0; # Initialise the profit profit = 0; # The day at which the stock # must be bought for i in range(start, end, 1): # The day at which the # stock must be sold for j in range(i+1, end+1): # If buying the stock at ith day and # selling it at jth day is profitable if (price[j] > price[i]): # Update the current profit curr_profit = price[j] - price[i] +\\ maxProfit(price, start, i - 1)+ \\ maxProfit(price, j + 1, end); # Update the maximum profit so far profit = max(profit, curr_profit); return profit; # Driver codeif __name__ == '__main__': price = [100, 180, 260, 310, 40, 535, 695]; n = len(price); print(maxProfit(price, 0, n - 1)); # This code is contributed by Rajput-Ji", "e": 30569, "s": 29425, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the maximum profit// that can be made after buying and// selling the given stocksstatic int maxProfit(int []price, int start, int end){ // If the stocks can't be bought if (end <= start) return 0; // Initialise the profit int profit = 0; // The day at which the stock // must be bought for (int i = start; i < end; i++) { // The day at which the // stock must be sold for (int j = i + 1; j <= end; j++) { // If buying the stock at ith day and // selling it at jth day is profitable if (price[j] > price[i]) { // Update the current profit int curr_profit = price[j] - price[i] + maxProfit(price, start, i - 1) + maxProfit(price, j + 1, end); // Update the maximum profit so far profit = Math.Max(profit, curr_profit); } } } return profit;} // Driver codepublic static void Main(String[] args){ int []price = { 100, 180, 260, 310, 40, 535, 695 }; int n = price.Length; Console.Write(maxProfit(price, 0, n - 1));}} // This code is contributed by PrinciRaj1992", "e": 31894, "s": 30569, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the maximum profit// that can be made after buying and// selling the given stocksfunction maxProfit( price, start, end){ // If the stocks can't be bought if (end <= start) return 0; // Initialise the profit let profit = 0; // The day at which the stock // must be bought for (let i = start; i < end; i++) { // The day at which the // stock must be sold for (let j = i + 1; j <= end; j++) { // If buying the stock at ith day and // selling it at jth day is profitable if (price[j] > price[i]) { // Update the current profit let curr_profit = price[j] - price[i] + maxProfit(price, start, i - 1) + maxProfit(price, j + 1, end); // Update the maximum profit so far profit = Math.max(profit, curr_profit); } } } return profit;} // Driver program let price = [ 100, 180, 260, 310, 40, 535, 695 ]; let n = price.length; document.write(maxProfit(price, 0, n - 1)); </script>", "e": 33119, "s": 31894, "text": null }, { "code": null, "e": 33123, "s": 33119, "text": "865" }, { "code": null, "e": 33369, "s": 33123, "text": "Efficient approach: If we are allowed to buy and sell only once, then we can use the following algorithm. Maximum difference between two elements. Here we are allowed to buy and sell multiple times. Following is the algorithm for this problem. " }, { "code": null, "e": 33659, "s": 33369, "text": "Find the local minima and store it as starting index. If not exists, return.Find the local maxima. And store it as an ending index. If we reach the end, set the end as the ending index.Update the solution (Increment count of buy-sell pairs)Repeat the above steps if the end is not reached." }, { "code": null, "e": 33736, "s": 33659, "text": "Find the local minima and store it as starting index. If not exists, return." }, { "code": null, "e": 33846, "s": 33736, "text": "Find the local maxima. And store it as an ending index. If we reach the end, set the end as the ending index." }, { "code": null, "e": 33902, "s": 33846, "text": "Update the solution (Increment count of buy-sell pairs)" }, { "code": null, "e": 33952, "s": 33902, "text": "Repeat the above steps if the end is not reached." }, { "code": null, "e": 33956, "s": 33952, "text": "C++" }, { "code": null, "e": 33958, "s": 33956, "text": "C" }, { "code": null, "e": 33963, "s": 33958, "text": "Java" }, { "code": null, "e": 33971, "s": 33963, "text": "Python3" }, { "code": null, "e": 33974, "s": 33971, "text": "C#" }, { "code": null, "e": 33985, "s": 33974, "text": "Javascript" }, { "code": "// C++ Program to find best buying and selling days#include <bits/stdc++.h>using namespace std; // This function finds the buy sell// schedule for maximum profitvoid stockBuySell(int price[], int n){ // Prices must be given for at least two days if (n == 1) return; // Traverse through given price array int i = 0; while (i < n - 1) { // Find Local Minima // Note that the limit is (n-2) as we are // comparing present element to the next element while ((i < n - 1) && (price[i + 1] <= price[i])) i++; // If we reached the end, break // as no further solution possible if (i == n - 1) break; // Store the index of minima int buy = i++; // Find Local Maxima // Note that the limit is (n-1) as we are // comparing to previous element while ((i < n) && (price[i] >= price[i - 1])) i++; // Store the index of maxima int sell = i - 1; cout << \"Buy on day: \" << buy << \"\\t Sell on day: \" << sell << endl; }} // Driver codeint main(){ // Stock prices on consecutive days int price[] = { 100, 180, 260, 310, 40, 535, 695 }; int n = sizeof(price) / sizeof(price[0]); // Function call stockBuySell(price, n); return 0;} // This is code is contributed by rathbhupendra", "e": 35352, "s": 33985, "text": null }, { "code": "// Program to find best buying and selling days#include <stdio.h> // solution structurestruct Interval { int buy; int sell;}; // This function finds the buy sell schedule for maximum profitvoid stockBuySell(int price[], int n){ // Prices must be given for at least two days if (n == 1) return; int count = 0; // count of solution pairs // solution vector Interval sol[n / 2 + 1]; // Traverse through given price array int i = 0; while (i < n - 1) { // Find Local Minima. Note that the limit is (n-2) as we are // comparing present element to the next element. while ((i < n - 1) && (price[i + 1] <= price[i])) i++; // If we reached the end, break as no further solution possible if (i == n - 1) break; // Store the index of minima sol[count].buy = i++; // Find Local Maxima. Note that the limit is (n-1) as we are // comparing to previous element while ((i < n) && (price[i] >= price[i - 1])) i++; // Store the index of maxima sol[count].sell = i - 1; // Increment count of buy/sell pairs count++; } // print solution if (count == 0) printf(\"There is no day when buying the stock will make profitn\"); else { for (int i = 0; i < count; i++) printf(\"Buy on day: %dt Sell on day: %dn\", sol[i].buy, sol[i].sell); } return;} // Driver program to test above functionsint main(){ // stock prices on consecutive days int price[] = { 100, 180, 260, 310, 40, 535, 695 }; int n = sizeof(price) / sizeof(price[0]); // function call stockBuySell(price, n); return 0;}", "e": 37049, "s": 35352, "text": null }, { "code": "// Program to find best buying and selling daysimport java.util.ArrayList; // Solution structureclass Interval { int buy, sell;} class StockBuySell { // This function finds the buy sell schedule for maximum profit void stockBuySell(int price[], int n) { // Prices must be given for at least two days if (n == 1) return; int count = 0; // solution array ArrayList<Interval> sol = new ArrayList<Interval>(); // Traverse through given price array int i = 0; while (i < n - 1) { // Find Local Minima. Note that the limit is (n-2) as we are // comparing present element to the next element. while ((i < n - 1) && (price[i + 1] <= price[i])) i++; // If we reached the end, break as no further solution possible if (i == n - 1) break; Interval e = new Interval(); e.buy = i++; // Store the index of minima // Find Local Maxima. Note that the limit is (n-1) as we are // comparing to previous element while ((i < n) && (price[i] >= price[i - 1])) i++; // Store the index of maxima e.sell = i - 1; sol.add(e); // Increment number of buy/sell count++; } // print solution if (count == 0) System.out.println(\"There is no day when buying the stock \" + \"will make profit\"); else for (int j = 0; j < count; j++) System.out.println(\"Buy on day: \" + sol.get(j).buy + \" \" + \"Sell on day : \" + sol.get(j).sell); return; } public static void main(String args[]) { StockBuySell stock = new StockBuySell(); // stock prices on consecutive days int price[] = { 100, 180, 260, 310, 40, 535, 695 }; int n = price.length; // function call stock.stockBuySell(price, n); }} // This code has been contributed by Mayank Jaiswal", "e": 39192, "s": 37049, "text": null }, { "code": "# Python3 Program to find# best buying and selling days # This function finds the buy sell# schedule for maximum profitdef stockBuySell(price, n): # Prices must be given for at least two days if (n == 1): return # Traverse through given price array i = 0 while (i < (n - 1)): # Find Local Minima # Note that the limit is (n-2) as we are # comparing present element to the next element while ((i < (n - 1)) and (price[i + 1] <= price[i])): i += 1 # If we reached the end, break # as no further solution possible if (i == n - 1): break # Store the index of minima buy = i i += 1 # Find Local Maxima # Note that the limit is (n-1) as we are # comparing to previous element while ((i < n) and (price[i] >= price[i - 1])): i += 1 # Store the index of maxima sell = i - 1 print(\"Buy on day: \",buy,\"\\t\", \"Sell on day: \",sell) # Driver code # Stock prices on consecutive daysprice = [100, 180, 260, 310, 40, 535, 695]n = len(price) # Function callstockBuySell(price, n) # This is code contributed by SHUBHAMSINGH10", "e": 40479, "s": 39192, "text": null }, { "code": "// C# program to find best buying and selling daysusing System;using System.Collections.Generic; // Solution structureclass Interval{ public int buy, sell;} public class StockBuySell{ // This function finds the buy sell // schedule for maximum profit void stockBuySell(int []price, int n) { // Prices must be given for at least two days if (n == 1) return; int count = 0; // solution array List<Interval> sol = new List<Interval>(); // Traverse through given price array int i = 0; while (i < n - 1) { // Find Local Minima. Note that // the limit is (n-2) as we are // comparing present element // to the next element. while ((i < n - 1) && (price[i + 1] <= price[i])) i++; // If we reached the end, break // as no further solution possible if (i == n - 1) break; Interval e = new Interval(); e.buy = i++; // Store the index of minima // Find Local Maxima. Note that // the limit is (n-1) as we are // comparing to previous element while ((i < n) && (price[i] >= price[i - 1])) i++; // Store the index of maxima e.sell = i - 1; sol.Add(e); // Increment number of buy/sell count++; } // print solution if (count == 0) Console.WriteLine(\"There is no day when buying the stock \" + \"will make profit\"); else for (int j = 0; j < count; j++) Console.WriteLine(\"Buy on day: \" + sol[j].buy + \" \" + \"Sell on day : \" + sol[j].sell); return; } // Driver code public static void Main(String []args) { StockBuySell stock = new StockBuySell(); // stock prices on consecutive days int []price = { 100, 180, 260, 310, 40, 535, 695 }; int n = price.Length; // function call stock.stockBuySell(price, n); }} // This code is contributed by PrinciRaj1992", "e": 42703, "s": 40479, "text": null }, { "code": "<script> // JavaScript program for the above approach // This function finds the buy sell // schedule for maximum profit function stockBuySell(price, n) { // Prices must be given for at least two days if (n == 1) return; // Traverse through given price array let i = 0; while (i < n - 1) { // Find Local Minima // Note that the limit is (n-2) as we are // comparing present element to the next element while ((i < n - 1) && (price[i + 1] <= price[i])) i++; // If we reached the end, break // as no further solution possible if (i == n - 1) break; // Store the index of minima let buy = i++; // Find Local Maxima // Note that the limit is (n-1) as we are // comparing to previous element while ((i < n) && (price[i] >= price[i - 1])) i++; // Store the index of maxima let sell = i - 1; document.write(`Buy on day: ${buy} Sell on day: ${sell}<br>`); } } // Driver code // Stock prices on consecutive days let price = [100, 180, 260, 310, 40, 535, 695]; let n = price.length; // Function call stockBuySell(price, n); // This code is contributed by Potta Lokesh </script>", "e": 44220, "s": 42703, "text": null }, { "code": null, "e": 44286, "s": 44220, "text": "Buy on day: 0 Sell on day: 3\nBuy on day: 4 Sell on day: 6" }, { "code": null, "e": 44442, "s": 44286, "text": "Time Complexity: The outer loop runs till I become n-1. The inner two loops increment the value of I in every iteration. So overall time complexity is O(n)" }, { "code": null, "e": 44464, "s": 44442, "text": "Valley Peak Approach:" }, { "code": null, "e": 44714, "s": 44464, "text": "In this approach, we just need to find the next greater element and subtract it from the current element so that the difference keeps increasing until we reach a minimum. If the sequence is a decreasing sequence, so the maximum profit possible is 0." }, { "code": null, "e": 44718, "s": 44714, "text": "C++" }, { "code": null, "e": 44720, "s": 44718, "text": "C" }, { "code": null, "e": 44725, "s": 44720, "text": "Java" }, { "code": null, "e": 44733, "s": 44725, "text": "Python3" }, { "code": null, "e": 44736, "s": 44733, "text": "C#" }, { "code": null, "e": 44747, "s": 44736, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; // Preprocessing helps the code run faster#define fl(i, a, b) for (int i = a; i < b; i++) // Function that returnint maxProfit(int* prices, int size){ // maxProfit adds up the difference between // adjacent elements if they are in increasing order int maxProfit = 0; // The loop starts from 1 // as its comparing with the previous fl(i, 1, size) if (prices[i] > prices[i - 1]) maxProfit += prices[i] - prices[i - 1]; return maxProfit;} // Driver Functionint main(){ int prices[] = { 100, 180, 260, 310, 40, 535, 695 }; int N = sizeof(prices) / sizeof(prices[0]); cout << maxProfit(prices, N) << endl; return 0;}// This code is contributed by Kingshuk Deb", "e": 45482, "s": 44747, "text": null }, { "code": "// Importing the required header files#include <stdio.h> // Creating MACRO for finding the maximum number#define max(x, y)(((x) > (y)) ? (x) : (y)) // Creating MACRO for finding the minimum number#define min(x, y)(((x) < (y)) ? (x) : (y)) // Function that returnint maxProfit(int prices[], int size){ // maxProfit adds up the difference between // adjacent elements if they are in increasing order int ans = 0; // The loop starts from 1 // as its comparing with the previous for (int i = 1; i < size; i++) { // If the current element is greater than the previous // then the difference is added to the answer if (prices[i] > prices[i - 1]) ans += prices[i] - prices[i - 1]; } return ans;} // Driver Codeint main(){ int price[] = { 100, 180, 260, 310, 40, 535, 695 }; int n = sizeof(price) / sizeof(price[0]); printf(\"%d\", maxProfit(price, n)); return 0;}", "e": 46435, "s": 45482, "text": null }, { "code": "// Java program for the above approachimport java.io.*; class GFG{ static int maxProfit(int prices[], int size) { // maxProfit adds up the difference between // adjacent elements if they are in increasing order int maxProfit = 0; // The loop starts from 1 // as its comparing with the previous for (int i = 1; i < size; i++) if (prices[i] > prices[i - 1]) maxProfit += prices[i] - prices[i - 1]; return maxProfit; } // Driver code public static void main(String[] args) { // stock prices on consecutive days int price[] = { 100, 180, 260, 310, 40, 535, 695 }; int n = price.length; // function call System.out.println(maxProfit(price, n)); }} // This code is contributed by rajsanghavi9.", "e": 47268, "s": 46435, "text": null }, { "code": "# Python3 program for the above approachdef max_profit(prices: list, days: int) -> int: profit = 0 for i in range(1, days): # checks if elements are adjacent and in increasing order if prices[i] > prices[i-1]: # difference added to 'profit' profit += prices[i] - prices[i-1] return profit # Driver Codeif __name__ == '__main__': # stock prices on consecutive days prices = [100, 180, 260, 310, 40, 535, 695] # function call profit = max_profit(prices, len(prices)) print(profit) # This code is contributed by vishvofficial.", "e": 47863, "s": 47268, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ static int maxProfit(int[] prices, int size){ // maxProfit adds up the difference // between adjacent elements if they // are in increasing order int maxProfit = 0; // The loop starts from 1 as its // comparing with the previous for(int i = 1; i < size; i++) if (prices[i] > prices[i - 1]) maxProfit += prices[i] - prices[i - 1]; return maxProfit;} // Driver codepublic static void Main(string[] args){ // Stock prices on consecutive days int[] price = { 100, 180, 260, 310, 40, 535, 695 }; int n = price.Length; // Function call Console.WriteLine(maxProfit(price, n));}} // This code is contributed by ukasp", "e": 48615, "s": 47863, "text": null }, { "code": "<script>// javascript program for the above approach function maxProfit(prices , size) { // maxProfit adds up the difference between // adjacent elements if they are in increasing order var maxProfit = 0; // The loop starts from 1 // as its comparing with the previous for (i = 1; i < size; i++) if (prices[i] > prices[i - 1]) maxProfit += prices[i] - prices[i - 1]; return maxProfit; } // Driver code // stock prices on consecutive days var price = [ 100, 180, 260, 310, 40, 535, 695 ]; var n = price.length; // function call document.write(maxProfit(price, n)); // This code is contributed by umadevi9616</script>", "e": 49359, "s": 48615, "text": null }, { "code": null, "e": 49363, "s": 49359, "text": "865" }, { "code": null, "e": 49406, "s": 49363, "text": "Time Complexity: O(n)Auxiliary Space: O(1)" }, { "code": null, "e": 49612, "s": 49406, "text": "This article is compiled by Ashish Anand and reviewed by the GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 49737, "s": 49612, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 49751, "s": 49737, "text": "rathbhupendra" }, { "code": null, "e": 49765, "s": 49751, "text": "princiraj1992" }, { "code": null, "e": 49780, "s": 49765, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 49790, "s": 49780, "text": "Rajput-Ji" }, { "code": null, "e": 49801, "s": 49790, "text": "ashwanisng" }, { "code": null, "e": 49822, "s": 49801, "text": "avanitrachhadiya2155" }, { "code": null, "e": 49841, "s": 49822, "text": "shivanisinghss2110" }, { "code": null, "e": 49859, "s": 49841, "text": "divyeshrabadiya07" }, { "code": null, "e": 49870, "s": 49859, "text": "ayusharora" }, { "code": null, "e": 49884, "s": 49870, "text": "jana_sayantan" }, { "code": null, "e": 49898, "s": 49884, "text": "surbhityagi15" }, { "code": null, "e": 49915, "s": 49898, "text": "arorakashish0911" }, { "code": null, "e": 49929, "s": 49915, "text": "lokeshpotta20" }, { "code": null, "e": 49941, "s": 49929, "text": "itskingshuk" }, { "code": null, "e": 49953, "s": 49941, "text": "anikaseth98" }, { "code": null, "e": 49969, "s": 49953, "text": "pankajsharmagfg" }, { "code": null, "e": 49982, "s": 49969, "text": "rajsanghavi9" }, { "code": null, "e": 49996, "s": 49982, "text": "vishvofficial" }, { "code": null, "e": 50006, "s": 49996, "text": "kalrap615" }, { "code": null, "e": 50012, "s": 50006, "text": "ukasp" }, { "code": null, "e": 50024, "s": 50012, "text": "umadevi9616" }, { "code": null, "e": 50042, "s": 50024, "text": "amnindersingh1414" }, { "code": null, "e": 50051, "s": 50042, "text": "Accolite" }, { "code": null, "e": 50058, "s": 50051, "text": "Amazon" }, { "code": null, "e": 50066, "s": 50058, "text": "Directi" }, { "code": null, "e": 50075, "s": 50066, "text": "Flipkart" }, { "code": null, "e": 50089, "s": 50075, "text": "Goldman Sachs" }, { "code": null, "e": 50094, "s": 50089, "text": "Hike" }, { "code": null, "e": 50105, "s": 50094, "text": "MakeMyTrip" }, { "code": null, "e": 50115, "s": 50105, "text": "Microsoft" }, { "code": null, "e": 50130, "s": 50115, "text": "Morgan Stanley" }, { "code": null, "e": 50139, "s": 50130, "text": "Ola Cabs" }, { "code": null, "e": 50146, "s": 50139, "text": "Oracle" }, { "code": null, "e": 50152, "s": 50146, "text": "Paytm" }, { "code": null, "e": 50161, "s": 50152, "text": "Pubmatic" }, { "code": null, "e": 50167, "s": 50161, "text": "Quikr" }, { "code": null, "e": 50175, "s": 50167, "text": "Samsung" }, { "code": null, "e": 50184, "s": 50175, "text": "SAP Labs" }, { "code": null, "e": 50192, "s": 50184, "text": "Sapient" }, { "code": null, "e": 50199, "s": 50192, "text": "Swiggy" }, { "code": null, "e": 50207, "s": 50199, "text": "Walmart" }, { "code": null, "e": 50214, "s": 50207, "text": "Arrays" }, { "code": null, "e": 50220, "s": 50214, "text": "Paytm" }, { "code": null, "e": 50229, "s": 50220, "text": "Flipkart" }, { "code": null, "e": 50244, "s": 50229, "text": "Morgan Stanley" }, { "code": null, "e": 50253, "s": 50244, "text": "Accolite" }, { "code": null, "e": 50260, "s": 50253, "text": "Amazon" }, { "code": null, "e": 50270, "s": 50260, "text": "Microsoft" }, { "code": null, "e": 50278, "s": 50270, "text": "Samsung" }, { "code": null, "e": 50283, "s": 50278, "text": "Hike" }, { "code": null, "e": 50294, "s": 50283, "text": "MakeMyTrip" }, { "code": null, "e": 50303, "s": 50294, "text": "Ola Cabs" }, { "code": null, "e": 50310, "s": 50303, "text": "Oracle" }, { "code": null, "e": 50318, "s": 50310, "text": "Walmart" }, { "code": null, "e": 50332, "s": 50318, "text": "Goldman Sachs" }, { "code": null, "e": 50340, "s": 50332, "text": "Directi" }, { "code": null, "e": 50349, "s": 50340, "text": "SAP Labs" }, { "code": null, "e": 50355, "s": 50349, "text": "Quikr" }, { "code": null, "e": 50364, "s": 50355, "text": "Pubmatic" }, { "code": null, "e": 50372, "s": 50364, "text": "Sapient" }, { "code": null, "e": 50379, "s": 50372, "text": "Swiggy" }, { "code": null, "e": 50386, "s": 50379, "text": "Arrays" }, { "code": null, "e": 50484, "s": 50386, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 50493, "s": 50484, "text": "Comments" }, { "code": null, "e": 50506, "s": 50493, "text": "Old Comments" }, { "code": null, "e": 50529, "s": 50506, "text": "Introduction to Arrays" }, { "code": null, "e": 50561, "s": 50529, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 50582, "s": 50561, "text": "Linked List vs Array" }, { "code": null, "e": 50627, "s": 50582, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 50718, "s": 50627, "text": "Given an array of size n and a number k, find all elements that appear more than n/k times" }, { "code": null, "e": 50772, "s": 50718, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 50799, "s": 50772, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 50855, "s": 50799, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 50879, "s": 50855, "text": "Find the Missing Number" } ]
What is Fat Tail? | Towards Data Science
Hi, this is Roh (ρ) The series “Journey to Tempered Stable Distribution” is designed to help people understand one of the fat-tail distributions: tempered stable distribution. The purpose of this document is, therefore, to introduce and explain concepts and tools that are required to understanding the level of exploiting the tempered stable distribution for their own purpose. I will not get into the nitty-gritty of each type of fat-tail distribution, rather I try to explain the related statistical and mathematical concepts/issues in an intuitive way with some application in finance. I hope there is a useful takeaway for all the readers from different backgrounds. Feel free to ask any question through the email at the very end of this document. Part0 : Why Tempered Stable (TS) Distribution? [Click] Part1 : What is fat-tailed distribution? Part2 : Infinitely Divisible Distribution? [Click] In part 1, we discuss what it means for a random variable to have a “fat-tail” distribution. To understand the fat-tail, we need to answer the following two questions. 1. How far is far?2. How fat is fat? To talk about the tail, we need to determine how far is far to decide how far from the middle is far enough to say it a ‘tail’. In other words, where does the tail start? It depends! Unfortunately, there is no single answer. Consider the normal distribution. Note that there are two tails: right and left. If we want to describe the ‘right’ tail of the distribution from the one standard deviation from the mean, for example, then the shaded part refers to the right tail of the normal distribution. Formally, we can describe the tail as follows: right tail : P(X>x) left tail : P(X≤-x) for a large value of ‘x’. Now, we know the concept of the ‘tail’. [R codes for Tail]#For normal distribution with value 'x=a'a=11-pnorm(a) #right tailpnorm(-a) #left tail Think about the uniform distribution over [0,1]. Does it have a tail? In this blog, it says not every distribution has a tail. If you want “ the behavior of the tail” to describe the characteristics of the pdf when ‘x’ gets large, then bounded distributions do not have tails. Nevertheless, some features of tails can be quantified. In particular, by using limits and asymptotic behavior you can define the notion of heavy tails. SAS blog I will explain the (exponentially) bounded / not bounded distribution below. Please remind yourself of the uniform distribution when you get there! The tail part of distribution has been the main concern for risk management. For example, the two most heavily used risk measures for distribution of return or loss are Value at Risk (VaR) and Expected shortfall (ES) loss is literally minus (-) return Taking the limit to negative infinity is non-intuitive. So we take the negative of return values, i.e., turning the distribution over the y-axis. Just see how the quantity VaR and ES are related to ‘tail’. Do not need to understand the math or meaning behind them. “Be aware that the below graph is a distribution of Loss not Return!” Think about distribution of loss, L, equivalently (negative) return, on some asset over a given holding period. For the sake of understanding, we assume that the random variable of losses on tomorrow follows the normal distribution: Then, we can calculate the VaR in the following way: Through the second line, we can easily check that the VaR is just a quantity related to the fat tail. For more details about the VaR, check chapter two of the book “Quantitative Risk Management: Concepts, Techniques and Tools” and Eric Zivot’s lecture note on his website. [R codes for VaR]alpha = 0.95 #significant levelVaR.alpha = qnorm(alpha, mu, sigma)VaR.alpha = mu + sigma*qnorm(alpha, 0, 1) Similarly, we can see that expected shortfall is a quantity related to the tail part of the distribution: In the fourth line, it says “ES is the expected loss in the upper “tail” of the loss distribution. Similar to VaR, in the case of normal distribution, it is convenient to calculate the ES now that it is just a mean of truncated normal distribution. [R codes for ES]alpha = 0.95q.alpha.z = qnorm(alpha)ES.alpha = mu + sigma*(dnorm(q.alpha.z)/(1-alpha)) If anyone curious about why we divide by 1 — α , this is just a normalizing constant (or scaling factor) to make sure that the integration of the truncated loss distribution is one, which is a requirement for it to be a probability distribution. Back to the story of ‘tail’, I just wanted to emphasize that the tail distributions are widely used as risk management tool. Since we figured out what the ‘tail’ is in distribution and where it is used, now it is time to talk about the ‘fat’ part. We all know that normal distribution does not have a fat-tail. Instead, we were taught to use the student-t distribution and log normal distribution when modelling the financial return series to take into account the ‘fat-tail’ property. But we need to know the definition of fat tail. Unfortunately, there is no universal definition for the term fat. I will try to explain the fat-tail in the language of English, Graph, and Math. Hope you enjoy at least one of the three. A heavy tailed distribution has tails that are heavier than an exponential distribution (Bryson, 1974) Distribution is said to have a heavy tail when the tail part decays more slowly than the exponential distribution. It is convenient to use the exponential distribution as a reference. The pdf of the exponential distribution approaches zero ‘exponentially’ fast. That is, tail of the pdf looks like (but behaves differently from) the exponential distribution. I will show you 4 different graphs that show what happens in the far right tails of a set of different distributions as below: Exponential distribution (exp) Power-law distribution (PL) Normal distribution (N) Log-Normal distribution (LN) Student-t distribution Cauchy distribution Levy distribution Weibull distribution I will not explain each of these distributions. Instead, let’s just enjoy the graph of these distributions to feel what is going on in the tail part. The first graph shows the part of the whole graph whose ‘x’ lies in [0,5] With the figure 5 above, we cannot tell how the tail behaves. But, here are a few things that are worth mentioning Normal, student-t and Cauchy distributions are two-tailed distributions. All others are one tailed distributions For PL(2.5) and PL(3.5), there is a crossing over point near x=1.7, which indicates that PL(2.5) has a thicker tail. Let’s look at how it looks when ‘x’ lies in [5,8]. Be aware that the values in y-axis get much smaller. A: The most upper line would have the thickest tail! (But not quite!!!) And you will see why! Beforehand, let’s examine the important facts of figure 6 above. Normal and exp(2) distributions are crawling near 0 when x=5. Especially for normal distribution, its pdf value of 5 standard deviation is 0.000001486 (=pnorm(5)). This is around 8000 times smaller than that of Cauchy distribution. In other words, 5 sigma events are 8000 times more likely to happen under Cauchy distribution than Normal distribution. In figure 6, keep in mind that exp(0.2) distribution locates way above log normal distribution and power law distributions. Please check how it gets reversed in the following graphs after extending the range of ‘x’ values. Let’s see how it looks when ‘x’ lies in [8,100]. Again, be aware that the values in y-axis get much much smaller. Note that the blue line exp(0.2) decays fast while crossing the other two that are PL(2.5) and Cauchy. This is what it means by “decays slower than exponential distribution” It is surprising to see what happens near ‘x’ equals 100. Its pdf value of PL(1.5) is 0.0005. No wonder that first and second moment (mean and variance) are infinite for PL(1.5). Detail information about this will be covered in the next document. Stay tuned! Surprisingly, the blue line exp(0.2) decreases by crossing the PL(3.5) and LN(0,1). Also, we can see that LN(0,1) decays faster than PL(3.5) now that it crosses the PL(3.5) and goes under it. PL(1.5), PL(2.5) and Levy distributions are not even displayed in this graph. Fat tail distribution is a subclass of the heavy-tailed distribution. It means although every fat-tailed distribution is heavy-tailed, the reverse is not true (e.g., Weibull). According to Jay Taylor’s lecture notes, he differentiated the heavy and fat in the following way. Distribution is said to have a right heavy-tail if tails are “not” exponentially bounded We can interpret it as when ‘x’ gets large, the speed of exponentially increasing is faster than the speed of decreasing probability on heavy right tail. Take time to think about it! See how it connects to the English definition. Probability distribution function that decays slower than an exponential are called right heavy-tail. If the heavy right tail is not heavy enough, i.e., it decays super fast as ‘x’ goes to infinity, then equation 1 converges to zero. The obvious example is uniform distribution over [0,1] as we discussed above. Once ‘x’ exceeds the one, the probability of X greater than one becomes zero so that it is exponentially bounded. Another popular example is the normal distribution. Let X be a standard normal. Draw a series of graphs for the different lambda values to get We can see that it converges to zero so that tails of the normal distribution are exponentially bounded. [R codes for Figure. 3]f_exp = function(x, lambda){return (exp(lambda*x))cdf_normal = function(x) pnorm(x)ccdf_normal = function(x) {1-cdf_normal(x)}xs = seq(1,10,length=10000)plot(xs, f_exp(xs,0.1)*ccdf_normal(xs), type='l', xlab='',ylab='', col='blue', lwd=2)abline(v=1, lty = 'dashed')lines(xs,f_exp(xs,0.5)*ccdf_normal(xs), col='purple', lwd=2)lines(xs,f_exp(xs,1)*ccdf_normal(xs), col='red', lwd=2)lines(xs,f_exp(xs,1.5)*ccdf_normal(xs), col='orange', lwd=2)lines(xs,f_exp(xs,2)*ccdf_normal(xs), col='darkred', lwd=2)lines(xs,f_exp(xs,3)*ccdf_normal(xs), col='darkblue', lwd=2)grid()legend(8, 0.15, legend=c("0.1", "0.5","1","1.5","2","3"), title = "lambda", col=c("blue",'purple', "red",'orange','darkred','darkblue'), lwd=2, cex=1) Distribution is said to have a right fat-tail if there is a positive exponent (alpha) called the tail index such that The ‘~’ means same up to constant. Or the tail part is proportional to the power law. Precisely, it means the following. Feel free to skip if math is ‘heavy/fat’ for you. Therefore, the tail part of fat-tailed distributions follows a power law (which is ‘x’ to the power of minus alpha). For those who are not familiar with a power law, do not worry now. Think of the graph when alpha equals two. Remind yourself that tail part looks similar to power-law as we have seen in figures 5–8 above. I will explain power law in more detail from [Part 2] of this series. We went over the concept ‘fat-tail’ in this document intuitively, graphically, and mathematically. To understand the ‘tempered stable distribution’, it is necessary to have a fundamental understanding of the fat-tail. Hope this document was helpful to improve your understanding. Please comment below if you have any question. I hope you are curious about what is to come next. Next time, I will be back with “ Journey to Tempered Stable Distribution[Part. 2: Infinitely Divisible Distribution]” [R Codes of Figure. 5]f_exp = function(x, lambda, xmin) {lambda*exp(-lambda*(x-xmin))}f_power = function (x, k, x_min) { C = (k-1)*x_min^(k-1) return (C*x^(-k)) }f_cauchy = function(x) dcauchy(x)f_levy = function(x) dlevy(x) # required package: 'rmulti'f_weibul = function(x) dweibull(x,shape=1)f_norm = function(x) dnorm(x)f_lnorm = function(x) dlnorm(x)f_t = function(x) dt(x,5)xs = seq(0.1,100,length=1000)plot(xs, f_exp(xs,0.5,0.1),type='l',xlab='',ylab='', col='blue', lwd=2, main='Distributions on [0,5]', cex.main=1, xlim=c(0,5), ylim=c(0,2.5))lines(xs,f_exp(xs,1,0.1), col='purple', lwd=2)lines(xs,f_exp(xs,2,0.1), col='bisque3', lwd=2)lines(xs,f_power(xs,1.5, 1), col='red', lwd=2)lines(xs,f_power(xs,2.5, 1), col='orange', lwd=2)lines(xs,f_power(xs,3.5, 1), col='darkred', lwd=2)lines(xs,f_norm(xs),col='black', lwd=2)lines(xs,f_lnorm(xs), col='darkgreen', lwd=2)lines(xs,f_t(xs), col='deeppink', lwd=2)lines(xs, f_cauchy(xs), col='darkblue', lwd=2)lines(xs, f_levy(xs), col='azure4', lwd=2)lines(xs, f_weibul(xs), col='springgreen', lwd=2)abline(v=2, lty = 'dashed')abline(v=3, lty = 'dashed')grid()legend(3.5, 2.5, legend=c("exp(0.2)", "exp(1)", 'exp(2)', "PL(1.5)", 'PL(2.5)', 'PL(3.5)', 'N(0,1)','LN(0,1)','student-t(5)','Cauchy','Levy','Weibull'), col=c("blue",'purple', 'bisque3',"red",'orange','darkred', 'black','darkgreen','deeppink','darkblue', 'azure4','springgreen'), lwd=2, cex=0.8) [1] Jay Taylor, Heavy-tailed distribution (2013), Lecture notes, [2] Eric Zivot, Risk Measures (2013), Lecture notes [3] Aaron Clauset, Inference, Models and Simulation for Complex Systems (2011), Lecture notes [4] https://blogs.sas.com/content/iml/2014/10/13/fat-tailed-and-long-tailed-distributions.html I also added hyperlinks for the all references above. Please check the references for the detail information. I will update the reference later if there is anything that I missed. Thank you for reading this document. Do not forget to share this document with your friend if you find it useful.
[ { "code": null, "e": 192, "s": 172, "text": "Hi, this is Roh (ρ)" }, { "code": null, "e": 926, "s": 192, "text": "The series “Journey to Tempered Stable Distribution” is designed to help people understand one of the fat-tail distributions: tempered stable distribution. The purpose of this document is, therefore, to introduce and explain concepts and tools that are required to understanding the level of exploiting the tempered stable distribution for their own purpose. I will not get into the nitty-gritty of each type of fat-tail distribution, rather I try to explain the related statistical and mathematical concepts/issues in an intuitive way with some application in finance. I hope there is a useful takeaway for all the readers from different backgrounds. Feel free to ask any question through the email at the very end of this document." }, { "code": null, "e": 981, "s": 926, "text": "Part0 : Why Tempered Stable (TS) Distribution? [Click]" }, { "code": null, "e": 1022, "s": 981, "text": "Part1 : What is fat-tailed distribution?" }, { "code": null, "e": 1073, "s": 1022, "text": "Part2 : Infinitely Divisible Distribution? [Click]" }, { "code": null, "e": 1166, "s": 1073, "text": "In part 1, we discuss what it means for a random variable to have a “fat-tail” distribution." }, { "code": null, "e": 1241, "s": 1166, "text": "To understand the fat-tail, we need to answer the following two questions." }, { "code": null, "e": 1278, "s": 1241, "text": "1. How far is far?2. How fat is fat?" }, { "code": null, "e": 1503, "s": 1278, "text": "To talk about the tail, we need to determine how far is far to decide how far from the middle is far enough to say it a ‘tail’. In other words, where does the tail start? It depends! Unfortunately, there is no single answer." }, { "code": null, "e": 1778, "s": 1503, "text": "Consider the normal distribution. Note that there are two tails: right and left. If we want to describe the ‘right’ tail of the distribution from the one standard deviation from the mean, for example, then the shaded part refers to the right tail of the normal distribution." }, { "code": null, "e": 1825, "s": 1778, "text": "Formally, we can describe the tail as follows:" }, { "code": null, "e": 1845, "s": 1825, "text": "right tail : P(X>x)" }, { "code": null, "e": 1865, "s": 1845, "text": "left tail : P(X≤-x)" }, { "code": null, "e": 1931, "s": 1865, "text": "for a large value of ‘x’. Now, we know the concept of the ‘tail’." }, { "code": null, "e": 2037, "s": 1931, "text": "[R codes for Tail]#For normal distribution with value 'x=a'a=11-pnorm(a) #right tailpnorm(-a) #left tail" }, { "code": null, "e": 2164, "s": 2037, "text": "Think about the uniform distribution over [0,1]. Does it have a tail? In this blog, it says not every distribution has a tail." }, { "code": null, "e": 2476, "s": 2164, "text": "If you want “ the behavior of the tail” to describe the characteristics of the pdf when ‘x’ gets large, then bounded distributions do not have tails. Nevertheless, some features of tails can be quantified. In particular, by using limits and asymptotic behavior you can define the notion of heavy tails. SAS blog" }, { "code": null, "e": 2624, "s": 2476, "text": "I will explain the (exponentially) bounded / not bounded distribution below. Please remind yourself of the uniform distribution when you get there!" }, { "code": null, "e": 2841, "s": 2624, "text": "The tail part of distribution has been the main concern for risk management. For example, the two most heavily used risk measures for distribution of return or loss are Value at Risk (VaR) and Expected shortfall (ES)" }, { "code": null, "e": 2876, "s": 2841, "text": "loss is literally minus (-) return" }, { "code": null, "e": 3022, "s": 2876, "text": "Taking the limit to negative infinity is non-intuitive. So we take the negative of return values, i.e., turning the distribution over the y-axis." }, { "code": null, "e": 3141, "s": 3022, "text": "Just see how the quantity VaR and ES are related to ‘tail’. Do not need to understand the math or meaning behind them." }, { "code": null, "e": 3211, "s": 3141, "text": "“Be aware that the below graph is a distribution of Loss not Return!”" }, { "code": null, "e": 3444, "s": 3211, "text": "Think about distribution of loss, L, equivalently (negative) return, on some asset over a given holding period. For the sake of understanding, we assume that the random variable of losses on tomorrow follows the normal distribution:" }, { "code": null, "e": 3497, "s": 3444, "text": "Then, we can calculate the VaR in the following way:" }, { "code": null, "e": 3770, "s": 3497, "text": "Through the second line, we can easily check that the VaR is just a quantity related to the fat tail. For more details about the VaR, check chapter two of the book “Quantitative Risk Management: Concepts, Techniques and Tools” and Eric Zivot’s lecture note on his website." }, { "code": null, "e": 3895, "s": 3770, "text": "[R codes for VaR]alpha = 0.95 #significant levelVaR.alpha = qnorm(alpha, mu, sigma)VaR.alpha = mu + sigma*qnorm(alpha, 0, 1)" }, { "code": null, "e": 4001, "s": 3895, "text": "Similarly, we can see that expected shortfall is a quantity related to the tail part of the distribution:" }, { "code": null, "e": 4250, "s": 4001, "text": "In the fourth line, it says “ES is the expected loss in the upper “tail” of the loss distribution. Similar to VaR, in the case of normal distribution, it is convenient to calculate the ES now that it is just a mean of truncated normal distribution." }, { "code": null, "e": 4353, "s": 4250, "text": "[R codes for ES]alpha = 0.95q.alpha.z = qnorm(alpha)ES.alpha = mu + sigma*(dnorm(q.alpha.z)/(1-alpha))" }, { "code": null, "e": 4599, "s": 4353, "text": "If anyone curious about why we divide by 1 — α , this is just a normalizing constant (or scaling factor) to make sure that the integration of the truncated loss distribution is one, which is a requirement for it to be a probability distribution." }, { "code": null, "e": 4724, "s": 4599, "text": "Back to the story of ‘tail’, I just wanted to emphasize that the tail distributions are widely used as risk management tool." }, { "code": null, "e": 5199, "s": 4724, "text": "Since we figured out what the ‘tail’ is in distribution and where it is used, now it is time to talk about the ‘fat’ part. We all know that normal distribution does not have a fat-tail. Instead, we were taught to use the student-t distribution and log normal distribution when modelling the financial return series to take into account the ‘fat-tail’ property. But we need to know the definition of fat tail. Unfortunately, there is no universal definition for the term fat." }, { "code": null, "e": 5321, "s": 5199, "text": "I will try to explain the fat-tail in the language of English, Graph, and Math. Hope you enjoy at least one of the three." }, { "code": null, "e": 5424, "s": 5321, "text": "A heavy tailed distribution has tails that are heavier than an exponential distribution (Bryson, 1974)" }, { "code": null, "e": 5539, "s": 5424, "text": "Distribution is said to have a heavy tail when the tail part decays more slowly than the exponential distribution." }, { "code": null, "e": 5783, "s": 5539, "text": "It is convenient to use the exponential distribution as a reference. The pdf of the exponential distribution approaches zero ‘exponentially’ fast. That is, tail of the pdf looks like (but behaves differently from) the exponential distribution." }, { "code": null, "e": 5910, "s": 5783, "text": "I will show you 4 different graphs that show what happens in the far right tails of a set of different distributions as below:" }, { "code": null, "e": 5941, "s": 5910, "text": "Exponential distribution (exp)" }, { "code": null, "e": 5969, "s": 5941, "text": "Power-law distribution (PL)" }, { "code": null, "e": 5993, "s": 5969, "text": "Normal distribution (N)" }, { "code": null, "e": 6022, "s": 5993, "text": "Log-Normal distribution (LN)" }, { "code": null, "e": 6045, "s": 6022, "text": "Student-t distribution" }, { "code": null, "e": 6065, "s": 6045, "text": "Cauchy distribution" }, { "code": null, "e": 6083, "s": 6065, "text": "Levy distribution" }, { "code": null, "e": 6104, "s": 6083, "text": "Weibull distribution" }, { "code": null, "e": 6328, "s": 6104, "text": "I will not explain each of these distributions. Instead, let’s just enjoy the graph of these distributions to feel what is going on in the tail part. The first graph shows the part of the whole graph whose ‘x’ lies in [0,5]" }, { "code": null, "e": 6443, "s": 6328, "text": "With the figure 5 above, we cannot tell how the tail behaves. But, here are a few things that are worth mentioning" }, { "code": null, "e": 6556, "s": 6443, "text": "Normal, student-t and Cauchy distributions are two-tailed distributions. All others are one tailed distributions" }, { "code": null, "e": 6673, "s": 6556, "text": "For PL(2.5) and PL(3.5), there is a crossing over point near x=1.7, which indicates that PL(2.5) has a thicker tail." }, { "code": null, "e": 6777, "s": 6673, "text": "Let’s look at how it looks when ‘x’ lies in [5,8]. Be aware that the values in y-axis get much smaller." }, { "code": null, "e": 6871, "s": 6777, "text": "A: The most upper line would have the thickest tail! (But not quite!!!) And you will see why!" }, { "code": null, "e": 6936, "s": 6871, "text": "Beforehand, let’s examine the important facts of figure 6 above." }, { "code": null, "e": 7288, "s": 6936, "text": "Normal and exp(2) distributions are crawling near 0 when x=5. Especially for normal distribution, its pdf value of 5 standard deviation is 0.000001486 (=pnorm(5)). This is around 8000 times smaller than that of Cauchy distribution. In other words, 5 sigma events are 8000 times more likely to happen under Cauchy distribution than Normal distribution." }, { "code": null, "e": 7511, "s": 7288, "text": "In figure 6, keep in mind that exp(0.2) distribution locates way above log normal distribution and power law distributions. Please check how it gets reversed in the following graphs after extending the range of ‘x’ values." }, { "code": null, "e": 7625, "s": 7511, "text": "Let’s see how it looks when ‘x’ lies in [8,100]. Again, be aware that the values in y-axis get much much smaller." }, { "code": null, "e": 7799, "s": 7625, "text": "Note that the blue line exp(0.2) decays fast while crossing the other two that are PL(2.5) and Cauchy. This is what it means by “decays slower than exponential distribution”" }, { "code": null, "e": 8058, "s": 7799, "text": "It is surprising to see what happens near ‘x’ equals 100. Its pdf value of PL(1.5) is 0.0005. No wonder that first and second moment (mean and variance) are infinite for PL(1.5). Detail information about this will be covered in the next document. Stay tuned!" }, { "code": null, "e": 8250, "s": 8058, "text": "Surprisingly, the blue line exp(0.2) decreases by crossing the PL(3.5) and LN(0,1). Also, we can see that LN(0,1) decays faster than PL(3.5) now that it crosses the PL(3.5) and goes under it." }, { "code": null, "e": 8328, "s": 8250, "text": "PL(1.5), PL(2.5) and Levy distributions are not even displayed in this graph." }, { "code": null, "e": 8603, "s": 8328, "text": "Fat tail distribution is a subclass of the heavy-tailed distribution. It means although every fat-tailed distribution is heavy-tailed, the reverse is not true (e.g., Weibull). According to Jay Taylor’s lecture notes, he differentiated the heavy and fat in the following way." }, { "code": null, "e": 8692, "s": 8603, "text": "Distribution is said to have a right heavy-tail if tails are “not” exponentially bounded" }, { "code": null, "e": 8875, "s": 8692, "text": "We can interpret it as when ‘x’ gets large, the speed of exponentially increasing is faster than the speed of decreasing probability on heavy right tail. Take time to think about it!" }, { "code": null, "e": 8922, "s": 8875, "text": "See how it connects to the English definition." }, { "code": null, "e": 9024, "s": 8922, "text": "Probability distribution function that decays slower than an exponential are called right heavy-tail." }, { "code": null, "e": 9491, "s": 9024, "text": "If the heavy right tail is not heavy enough, i.e., it decays super fast as ‘x’ goes to infinity, then equation 1 converges to zero. The obvious example is uniform distribution over [0,1] as we discussed above. Once ‘x’ exceeds the one, the probability of X greater than one becomes zero so that it is exponentially bounded. Another popular example is the normal distribution. Let X be a standard normal. Draw a series of graphs for the different lambda values to get" }, { "code": null, "e": 9596, "s": 9491, "text": "We can see that it converges to zero so that tails of the normal distribution are exponentially bounded." }, { "code": null, "e": 10348, "s": 9596, "text": "[R codes for Figure. 3]f_exp = function(x, lambda){return (exp(lambda*x))cdf_normal = function(x) pnorm(x)ccdf_normal = function(x) {1-cdf_normal(x)}xs = seq(1,10,length=10000)plot(xs, f_exp(xs,0.1)*ccdf_normal(xs), type='l', xlab='',ylab='', col='blue', lwd=2)abline(v=1, lty = 'dashed')lines(xs,f_exp(xs,0.5)*ccdf_normal(xs), col='purple', lwd=2)lines(xs,f_exp(xs,1)*ccdf_normal(xs), col='red', lwd=2)lines(xs,f_exp(xs,1.5)*ccdf_normal(xs), col='orange', lwd=2)lines(xs,f_exp(xs,2)*ccdf_normal(xs), col='darkred', lwd=2)lines(xs,f_exp(xs,3)*ccdf_normal(xs), col='darkblue', lwd=2)grid()legend(8, 0.15, legend=c(\"0.1\", \"0.5\",\"1\",\"1.5\",\"2\",\"3\"), title = \"lambda\", col=c(\"blue\",'purple', \"red\",'orange','darkred','darkblue'), lwd=2, cex=1)" }, { "code": null, "e": 10466, "s": 10348, "text": "Distribution is said to have a right fat-tail if there is a positive exponent (alpha) called the tail index such that" }, { "code": null, "e": 10587, "s": 10466, "text": "The ‘~’ means same up to constant. Or the tail part is proportional to the power law. Precisely, it means the following." }, { "code": null, "e": 10637, "s": 10587, "text": "Feel free to skip if math is ‘heavy/fat’ for you." }, { "code": null, "e": 10863, "s": 10637, "text": "Therefore, the tail part of fat-tailed distributions follows a power law (which is ‘x’ to the power of minus alpha). For those who are not familiar with a power law, do not worry now. Think of the graph when alpha equals two." }, { "code": null, "e": 11029, "s": 10863, "text": "Remind yourself that tail part looks similar to power-law as we have seen in figures 5–8 above. I will explain power law in more detail from [Part 2] of this series." }, { "code": null, "e": 11525, "s": 11029, "text": "We went over the concept ‘fat-tail’ in this document intuitively, graphically, and mathematically. To understand the ‘tempered stable distribution’, it is necessary to have a fundamental understanding of the fat-tail. Hope this document was helpful to improve your understanding. Please comment below if you have any question. I hope you are curious about what is to come next. Next time, I will be back with “ Journey to Tempered Stable Distribution[Part. 2: Infinitely Divisible Distribution]”" }, { "code": null, "e": 12990, "s": 11525, "text": "[R Codes of Figure. 5]f_exp = function(x, lambda, xmin) {lambda*exp(-lambda*(x-xmin))}f_power = function (x, k, x_min) { C = (k-1)*x_min^(k-1) return (C*x^(-k)) }f_cauchy = function(x) dcauchy(x)f_levy = function(x) dlevy(x) # required package: 'rmulti'f_weibul = function(x) dweibull(x,shape=1)f_norm = function(x) dnorm(x)f_lnorm = function(x) dlnorm(x)f_t = function(x) dt(x,5)xs = seq(0.1,100,length=1000)plot(xs, f_exp(xs,0.5,0.1),type='l',xlab='',ylab='', col='blue', lwd=2, main='Distributions on [0,5]', cex.main=1, xlim=c(0,5), ylim=c(0,2.5))lines(xs,f_exp(xs,1,0.1), col='purple', lwd=2)lines(xs,f_exp(xs,2,0.1), col='bisque3', lwd=2)lines(xs,f_power(xs,1.5, 1), col='red', lwd=2)lines(xs,f_power(xs,2.5, 1), col='orange', lwd=2)lines(xs,f_power(xs,3.5, 1), col='darkred', lwd=2)lines(xs,f_norm(xs),col='black', lwd=2)lines(xs,f_lnorm(xs), col='darkgreen', lwd=2)lines(xs,f_t(xs), col='deeppink', lwd=2)lines(xs, f_cauchy(xs), col='darkblue', lwd=2)lines(xs, f_levy(xs), col='azure4', lwd=2)lines(xs, f_weibul(xs), col='springgreen', lwd=2)abline(v=2, lty = 'dashed')abline(v=3, lty = 'dashed')grid()legend(3.5, 2.5, legend=c(\"exp(0.2)\", \"exp(1)\", 'exp(2)', \"PL(1.5)\", 'PL(2.5)', 'PL(3.5)', 'N(0,1)','LN(0,1)','student-t(5)','Cauchy','Levy','Weibull'), col=c(\"blue\",'purple', 'bisque3',\"red\",'orange','darkred', 'black','darkgreen','deeppink','darkblue', 'azure4','springgreen'), lwd=2, cex=0.8)" }, { "code": null, "e": 13055, "s": 12990, "text": "[1] Jay Taylor, Heavy-tailed distribution (2013), Lecture notes," }, { "code": null, "e": 13107, "s": 13055, "text": "[2] Eric Zivot, Risk Measures (2013), Lecture notes" }, { "code": null, "e": 13201, "s": 13107, "text": "[3] Aaron Clauset, Inference, Models and Simulation for Complex Systems (2011), Lecture notes" }, { "code": null, "e": 13296, "s": 13201, "text": "[4] https://blogs.sas.com/content/iml/2014/10/13/fat-tailed-and-long-tailed-distributions.html" }, { "code": null, "e": 13476, "s": 13296, "text": "I also added hyperlinks for the all references above. Please check the references for the detail information. I will update the reference later if there is anything that I missed." } ]
How to use Global Variable in Postman Request?
We can use a Global variable in Postman Request. . We can set, get and clear a Global variable at runtime using the scripts. This is achieved by the pm.* function. The script to use a Global variable can be included either in the Tests or Pre-Request Script tab To set a Global variable, the script should be − pm.globals.set('<name of Global variable>', '<value of variable>') To get the value of a Global variable, the script should be − pm.globals.get('<name of Global variable>') To get the value of the Global variable in the Postman console, the script should be − console.log(pm.globals.get('<name of Global variable>') To delete a Global variable, the script is − pm.globals.unset('<name of Global variable>') Let us try to work with a Global variable g. Step1 − Add the below script to set the value value1 for the Global variable g. pm.globals.set('g', 'value1') Step2 − Add the below script to get the value of Global variable g and print it in console. console.log(pm.globals.get('g')) Step3 − Add the below script to delete the value of Global variable g and verify it. pm.globals.unset('g')) console.log(pm.globals.get('g')) Step4 − Click on Send to execute a request. Step5 − After the Response is received, open the Postman Console. It first displays value1 which is the value set for the Global variable g. Next, it displays undefined since the value of the Global variable g has been deleted in the Step3.
[ { "code": null, "e": 1324, "s": 1062, "text": "We can use a Global variable in Postman Request. . We can set, get and clear a Global variable at runtime using the scripts. This is achieved by the pm.* function. The script to use a Global variable can be included either in the Tests or Pre-Request Script tab" }, { "code": null, "e": 1373, "s": 1324, "text": "To set a Global variable, the script should be −" }, { "code": null, "e": 1440, "s": 1373, "text": "pm.globals.set('<name of Global variable>', '<value of variable>')" }, { "code": null, "e": 1502, "s": 1440, "text": "To get the value of a Global variable, the script should be −" }, { "code": null, "e": 1546, "s": 1502, "text": "pm.globals.get('<name of Global variable>')" }, { "code": null, "e": 1633, "s": 1546, "text": "To get the value of the Global variable in the Postman console, the script should be −" }, { "code": null, "e": 1689, "s": 1633, "text": "console.log(pm.globals.get('<name of Global variable>')" }, { "code": null, "e": 1734, "s": 1689, "text": "To delete a Global variable, the script is −" }, { "code": null, "e": 1780, "s": 1734, "text": "pm.globals.unset('<name of Global variable>')" }, { "code": null, "e": 1825, "s": 1780, "text": "Let us try to work with a Global variable g." }, { "code": null, "e": 1905, "s": 1825, "text": "Step1 − Add the below script to set the value value1 for the Global variable g." }, { "code": null, "e": 1935, "s": 1905, "text": "pm.globals.set('g', 'value1')" }, { "code": null, "e": 2027, "s": 1935, "text": "Step2 − Add the below script to get the value of Global variable g and print it in console." }, { "code": null, "e": 2060, "s": 2027, "text": "console.log(pm.globals.get('g'))" }, { "code": null, "e": 2145, "s": 2060, "text": "Step3 − Add the below script to delete the value of Global variable g and verify it." }, { "code": null, "e": 2201, "s": 2145, "text": "pm.globals.unset('g'))\nconsole.log(pm.globals.get('g'))" }, { "code": null, "e": 2245, "s": 2201, "text": "Step4 − Click on Send to execute a request." }, { "code": null, "e": 2486, "s": 2245, "text": "Step5 − After the Response is received, open the Postman Console. It first displays value1 which is the value set for the Global variable g. Next, it displays undefined since the value of the Global variable g has been deleted in the Step3." } ]
Redis - List Rpush Command
Redis RPUSH command inserts all the specified values at the tail of the list stored at the key. If the key does not exist, it is created as an empty list before performing the push operation. When the key holds a value that is not a list, an error is returned. Integer reply, the length of the list after the push operation. Following is the basic syntax of Redis RPUSH command. redis 127.0.0.1:6379> RPUSH KEY_NAME VALUE1..VALUEN redis 127.0.0.1:6379> RPUSH mylist "hello" (integer) 1 redis 127.0.0.1:6379> RPUSH mylist "foo" (integer) 2 redis 127.0.0.1:6379> RPUSH mylist "bar" (integer) 3 redis 127.0.0.1:6379> LRANGE mylist 0 -1 1) "hello" 2) "foo" 3) "bar" 22 Lectures 40 mins Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2306, "s": 2045, "text": "Redis RPUSH command inserts all the specified values at the tail of the list stored at the key. If the key does not exist, it is created as an empty list before performing the push operation. When the key holds a value that is not a list, an error is returned." }, { "code": null, "e": 2370, "s": 2306, "text": "Integer reply, the length of the list after the push operation." }, { "code": null, "e": 2424, "s": 2370, "text": "Following is the basic syntax of Redis RPUSH command." }, { "code": null, "e": 2478, "s": 2424, "text": "redis 127.0.0.1:6379> RPUSH KEY_NAME VALUE1..VALUEN \n" }, { "code": null, "e": 2718, "s": 2478, "text": "redis 127.0.0.1:6379> RPUSH mylist \"hello\" \n(integer) 1 \nredis 127.0.0.1:6379> RPUSH mylist \"foo\" \n(integer) 2 \nredis 127.0.0.1:6379> RPUSH mylist \"bar\" \n(integer) 3 \nredis 127.0.0.1:6379> LRANGE mylist 0 -1 \n1) \"hello\"\n2) \"foo\" \n3) \"bar\"\n" }, { "code": null, "e": 2750, "s": 2718, "text": "\n 22 Lectures \n 40 mins\n" }, { "code": null, "e": 2770, "s": 2750, "text": " Skillbakerystudios" }, { "code": null, "e": 2777, "s": 2770, "text": " Print" }, { "code": null, "e": 2788, "s": 2777, "text": " Add Notes" } ]
How to move the ResultSet cursor to the next row in JDBC?
Whenever we execute SQL statements using the executeQuery() method, it returns a ResultSet object which holds the tabular data returned by the SELECT queries(in general). The ResultSet object contains a cursor/pointer which points to the current row. Initially this cursor is positioned before first row (default position). You can move the cursor of the ResultSet object to the next row from the current position, using the next() method of the ResultSet interface. rs.next() This method returns a boolean value specifying whether the ResultSet object contains more rows. If there are no rows next to its current position this method returns false, else it returns true. Let us create a table with name tutorials_data in MySQL database using CREATE statement as shown below − CREATE TABLE tutorials_data( tutorial_id INT, tutorial_title VARCHAR(100), tutorial_author VARCHAR(40), submission_date date, PRIMARY KEY (tutorial_id) ); Now, we will insert 5 records in tutorials_data table using INSERT statements − insert into tutorials_data values(1, 'Java', 'Krishna Kasyap', DATE('2019-09-01')); insert into tutorials_data values(2, 'JFreeCharts', 'Satish Kumar', DATE('2019-05-01 ')); insert into tutorials_data values(3, 'JavaSprings', 'Amit Tiwari', DATE(' 2019-05-01')); insert into tutorials_data values(4, 'Android', 'Sai Ram', DATE('2019-03-01')); insert into tutorials_data values(5, 'Cassandra', 'Pruthvi Raj', DATE(' 2019-04-06')); In the following JDBC program we have established connection with the database and retrieved the contents of the table named tutorials_data into a ResultSet object, initially the cursor in this object will be at the default position (before first row), using the next() method we have moved the cursor from default position to first row, from first row to the second row and, displayed the contents of the both rows. import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class RSCursor_next { public static void main(String args[]) throws SQLException { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating the Statement Statement stmt = con.createStatement(); //Query to retrieve records String query = "Select * from tutorials_data"; //Executing the query ResultSet rs = stmt.executeQuery(query); //Moving the cursor from default position to 1st row. rs.next(); System.out.println("Contents of the first record: "); //Current record details. System.out.print("ID: "+rs.getInt("tutorial_id")+", "); System.out.print("Title: "+rs.getString("tutorial_title")+", "); System.out.print("Author: "+rs.getString("tutorial_author")+", "); System.out.print("Submission date: "+rs.getDate("submission_date")); System.out.println(); //Moving the cursor from default position to 2nd row. rs.next(); System.out.println("Contents of the second record: "); //Current record details. System.out.print("ID: "+rs.getInt("tutorial_id")+", "); System.out.print("Title: "+rs.getString("tutorial_title")+", "); System.out.print("Author: "+rs.getString("tutorial_author")+", "); System.out.print("Submission date: "+rs.getDate("submission_date")); System.out.println(); } } Connection established...... Contents of the first record: ID: 1, Title: Java, Author: Krishna Kasyap, Submission date: 2019-09-01 Contents of the second record: ID: 2, Title: JFreeCharts, Author: Satish kumar, Submission date: 2019-05-01
[ { "code": null, "e": 1233, "s": 1062, "text": "Whenever we execute SQL statements using the executeQuery() method, it returns a ResultSet object which holds the tabular data returned by the SELECT queries(in general)." }, { "code": null, "e": 1386, "s": 1233, "text": "The ResultSet object contains a cursor/pointer which points to the current row. Initially this cursor is positioned before first row (default position)." }, { "code": null, "e": 1529, "s": 1386, "text": "You can move the cursor of the ResultSet object to the next row from the current position, using the next() method of the ResultSet interface." }, { "code": null, "e": 1539, "s": 1529, "text": "rs.next()" }, { "code": null, "e": 1635, "s": 1539, "text": "This method returns a boolean value specifying whether the ResultSet object contains more rows." }, { "code": null, "e": 1734, "s": 1635, "text": "If there are no rows next to its current position this method returns false, else it returns true." }, { "code": null, "e": 1839, "s": 1734, "text": "Let us create a table with name tutorials_data in MySQL database using CREATE statement as shown below −" }, { "code": null, "e": 2009, "s": 1839, "text": "CREATE TABLE tutorials_data(\n tutorial_id INT,\n tutorial_title VARCHAR(100),\n tutorial_author VARCHAR(40),\n submission_date date,\n PRIMARY KEY (tutorial_id)\n);" }, { "code": null, "e": 2089, "s": 2009, "text": "Now, we will insert 5 records in tutorials_data table using INSERT statements −" }, { "code": null, "e": 2519, "s": 2089, "text": "insert into tutorials_data values(1, 'Java', 'Krishna Kasyap', DATE('2019-09-01'));\ninsert into tutorials_data values(2, 'JFreeCharts', 'Satish Kumar', DATE('2019-05-01 '));\ninsert into tutorials_data values(3, 'JavaSprings', 'Amit Tiwari', DATE(' 2019-05-01'));\ninsert into tutorials_data values(4, 'Android', 'Sai Ram', DATE('2019-03-01'));\ninsert into tutorials_data values(5, 'Cassandra', 'Pruthvi Raj', DATE(' 2019-04-06'));" }, { "code": null, "e": 2936, "s": 2519, "text": "In the following JDBC program we have established connection with the database and retrieved the contents of the table named tutorials_data into a ResultSet object, initially the cursor in this object will be at the default position (before first row), using the next() method we have moved the cursor from default position to first row, from first row to the second row and, displayed the contents of the both rows." }, { "code": null, "e": 4703, "s": 2936, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class RSCursor_next {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating the Statement\n Statement stmt = con.createStatement();\n //Query to retrieve records\n String query = \"Select * from tutorials_data\";\n //Executing the query\n ResultSet rs = stmt.executeQuery(query);\n //Moving the cursor from default position to 1st row.\n rs.next();\n System.out.println(\"Contents of the first record: \");\n //Current record details.\n System.out.print(\"ID: \"+rs.getInt(\"tutorial_id\")+\", \");\n System.out.print(\"Title: \"+rs.getString(\"tutorial_title\")+\", \");\n System.out.print(\"Author: \"+rs.getString(\"tutorial_author\")+\", \");\n System.out.print(\"Submission date: \"+rs.getDate(\"submission_date\"));\n System.out.println();\n //Moving the cursor from default position to 2nd row.\n rs.next();\n System.out.println(\"Contents of the second record: \");\n //Current record details.\n System.out.print(\"ID: \"+rs.getInt(\"tutorial_id\")+\", \");\n System.out.print(\"Title: \"+rs.getString(\"tutorial_title\")+\", \");\n System.out.print(\"Author: \"+rs.getString(\"tutorial_author\")+\", \");\n System.out.print(\"Submission date: \"+rs.getDate(\"submission_date\"));\n System.out.println();\n }\n}" }, { "code": null, "e": 4942, "s": 4703, "text": "Connection established......\nContents of the first record:\nID: 1, Title: Java, Author: Krishna Kasyap, Submission date: 2019-09-01\nContents of the second record:\nID: 2, Title: JFreeCharts, Author: Satish kumar, Submission date: 2019-05-01" } ]
Find Perimeter of a triangle in C++
In this problem, we will see the perimeter of a triangle, formula for the perimeter of different types of triangle and program to find them. Perimeter is defined as the total distance about the figure. Basically, it is the sum of all sides of the given figure. Perimeter of a triangle The perimeter of a triangle is the sum of all its three sides (triangle is a three sides figure). Formula, Perimeter = sum of all sides Perimeter = x + y + z Program to find the perimeter of a triangle, Live Demo #include <iostream> using namespace std; int calcPerimeter(int x, int y, int z ){ int perimeter = x + y + z; return perimeter; } int main(){ int x = 5, y = 7, z = 8; cout<<"The side of the triangle are \n"; cout<<"X = "<<x<<"\tY = "<<y<<"\tZ = "<<z<<endl; cout<<"The perimeter of the triangle is "<<calcPerimeter(x, y, z); return 0; } The side of the triangle are X = 5 Y = 7 Z = 8 The perimeter of the triangle is 20 Perimeter of different type of triangles, In mathematics, there are different types of triangle with some special properties. Though the basic formula of the perimeter remains the same, there are specific formulas of all types of triangle. Let’s see each of them. It is a special type of triangle in which all sides and angles are equal. Perimeter = 3*a Program to find the area of equilateral triangle, Live Demo #include <iostream> using namespace std; int calcPerimeter(int a){ int perimeter = 3*a; return perimeter; } int main(){ int a = 5; cout<<"The side of the equilateral triangle are \n"; cout<<"a = "<<a<<endl; cout<<"The perimeter of the triangle is "<<calcPerimeter(a); return 0; } The side of the equilateral triangle are a = 5 The perimeter of the triangle is 15 It is a special type of triangle in which two sides are equal and the third one has different length. Perimeter = 2*X + Y Program to find the perimeter of isosceles triangle, Live Demo #include <iostream> using namespace std; int calcPerimeter(int x, int y){ int perimeter = 2*x + y; return perimeter; } int main(){ int x = 5, y = 8; cout<<"The side of the Isosceles triangle are \n"; cout<<"X = "<<x<<"\tY = "<<y<<endl; cout<<"The perimeter of the triangle is "<<calcPerimeter(x, y); return 0; } The side of the Isosceles triangle are X = 5 Y = 8 The perimeter of the triangle is 18 It is a triangle whose all three sides are different. Perimeter = x + y + z
[ { "code": null, "e": 1203, "s": 1062, "text": "In this problem, we will see the perimeter of a triangle, formula for the\nperimeter of different types of triangle and program to find them." }, { "code": null, "e": 1323, "s": 1203, "text": "Perimeter is defined as the total distance about the figure. Basically, it is the sum of all sides of the given figure." }, { "code": null, "e": 1347, "s": 1323, "text": "Perimeter of a triangle" }, { "code": null, "e": 1445, "s": 1347, "text": "The perimeter of a triangle is the sum of all its three sides (triangle is a three\nsides figure)." }, { "code": null, "e": 1454, "s": 1445, "text": "Formula," }, { "code": null, "e": 1483, "s": 1454, "text": "Perimeter = sum of all sides" }, { "code": null, "e": 1505, "s": 1483, "text": "Perimeter = x + y + z" }, { "code": null, "e": 1550, "s": 1505, "text": "Program to find the perimeter of a triangle," }, { "code": null, "e": 1561, "s": 1550, "text": " Live Demo" }, { "code": null, "e": 1917, "s": 1561, "text": "#include <iostream>\nusing namespace std;\nint calcPerimeter(int x, int y, int z ){\n int perimeter = x + y + z;\n return perimeter;\n}\nint main(){\n int x = 5, y = 7, z = 8;\n cout<<\"The side of the triangle are \\n\";\n cout<<\"X = \"<<x<<\"\\tY = \"<<y<<\"\\tZ = \"<<z<<endl;\n cout<<\"The perimeter of the triangle is \"<<calcPerimeter(x, y, z);\n return 0;\n}" }, { "code": null, "e": 1946, "s": 1917, "text": "The side of the triangle are" }, { "code": null, "e": 2000, "s": 1946, "text": "X = 5 Y = 7 Z = 8\nThe perimeter of the triangle is 20" }, { "code": null, "e": 2042, "s": 2000, "text": "Perimeter of different type of triangles," }, { "code": null, "e": 2264, "s": 2042, "text": "In mathematics, there are different types of triangle with some special properties. Though the basic formula of the perimeter remains the same, there are specific formulas of all types of triangle. Let’s see each of them." }, { "code": null, "e": 2338, "s": 2264, "text": "It is a special type of triangle in which all sides and angles are equal." }, { "code": null, "e": 2354, "s": 2338, "text": "Perimeter = 3*a" }, { "code": null, "e": 2404, "s": 2354, "text": "Program to find the area of equilateral triangle," }, { "code": null, "e": 2415, "s": 2404, "text": " Live Demo" }, { "code": null, "e": 2716, "s": 2415, "text": "#include <iostream>\nusing namespace std;\nint calcPerimeter(int a){\n int perimeter = 3*a;\n return perimeter;\n}\nint main(){\n int a = 5;\n cout<<\"The side of the equilateral triangle are \\n\";\n cout<<\"a = \"<<a<<endl;\n cout<<\"The perimeter of the triangle is \"<<calcPerimeter(a);\n return 0;\n}" }, { "code": null, "e": 2757, "s": 2716, "text": "The side of the equilateral triangle are" }, { "code": null, "e": 2799, "s": 2757, "text": "a = 5\nThe perimeter of the triangle is 15" }, { "code": null, "e": 2901, "s": 2799, "text": "It is a special type of triangle in which two sides are equal and the third one\nhas different length." }, { "code": null, "e": 2921, "s": 2901, "text": "Perimeter = 2*X + Y" }, { "code": null, "e": 2974, "s": 2921, "text": "Program to find the perimeter of isosceles triangle," }, { "code": null, "e": 2985, "s": 2974, "text": " Live Demo" }, { "code": null, "e": 3318, "s": 2985, "text": "#include <iostream>\nusing namespace std;\nint calcPerimeter(int x, int y){\n int perimeter = 2*x + y;\n return perimeter;\n}\nint main(){\n int x = 5, y = 8;\n cout<<\"The side of the Isosceles triangle are \\n\";\n cout<<\"X = \"<<x<<\"\\tY = \"<<y<<endl;\n cout<<\"The perimeter of the triangle is \"<<calcPerimeter(x, y);\n return 0;\n}" }, { "code": null, "e": 3357, "s": 3318, "text": "The side of the Isosceles triangle are" }, { "code": null, "e": 3405, "s": 3357, "text": "X = 5 Y = 8\nThe perimeter of the triangle is 18" }, { "code": null, "e": 3459, "s": 3405, "text": "It is a triangle whose all three sides are different." }, { "code": null, "e": 3481, "s": 3459, "text": "Perimeter = x + y + z" } ]
Basics of image classification with Keras | by John Olafenwa | Towards Data Science
In my previous post, I delved into some of the theoretical concepts underlying artificial neural networks. In this post, I would be explaining some common operations that you would frequently need in keras. First, how to save models and use them for prediction later, displaying images from the dataset and loading images from our system and predicting their class. Fire up your IDE if you haven’t done so and read on. SAVING MODELS Training models is a very slow process, nobody want’s to do that every time, fortunately, we only need to train our model once, save it and then we can load it anytime and use it to predict new images. Keras saves models in the .h5 format, so in case you skipped installing h5py in the first tutorial I posted, pleas run pip3 install h5py We would also need matplotlib to visualize our image, hence, run pip3 install matplotlib Here is the code for the first tutorial import kerasfrom keras.datasets import mnistfrom keras.layers import Densefrom keras.models import Sequentialfrom keras.optimizers import SGD(train_x, train_y) , (test_x, test_y) = mnist.load_data()#train_x = train_x.astype('float32') / 255#test_x = test_x.astype('float32') / 255print(train_x.shape)print(train_y.shape)print(test_x.shape)print(test_y.shape)train_x = train_x.reshape(60000,784)test_x = test_x.reshape(10000,784)train_y = keras.utils.to_categorical(train_y,10)test_y = keras.utils.to_categorical(test_y,10)model = Sequential()model.add(Dense(units=128,activation="relu",input_shape=(784,)))model.add(Dense(units=128,activation="relu"))model.add(Dense(units=128,activation="relu"))model.add(Dense(units=10,activation="softmax"))model.compile(optimizer=SGD(0.001),loss="categorical_crossentropy",metrics=["accuracy"])model.fit(train_x,train_y,batch_size=32,epochs=10,verbose=1)accuracy = model.evaluate(x=test_x,y=test_y,batch_size=32)print("Accuracy: ",accuracy[1]) To save the model, simply add below after model.fit() model.save("mnist-model.h5") INFERENCE Inference refers to the process of predicting new images using our model. In your code, comment out the model.fit and instead replace with the following model.load_weights("mnistmodel.h5") Our code now looks like this import kerasfrom keras.datasets import mnistfrom keras.layers import Densefrom keras.models import Sequentialfrom keras.optimizers import SGD(train_x, train_y) , (test_x, test_y) = mnist.load_data()#train_x = train_x.astype('float32') / 255#test_x = test_x.astype('float32') / 255print(train_x.shape)print(train_y.shape)print(test_x.shape)print(test_y.shape)train_x = train_x.reshape(60000,784)test_x = test_x.reshape(10000,784)train_y = keras.utils.to_categorical(train_y,10)test_y = keras.utils.to_categorical(test_y,10)model = Sequential()model.add(Dense(units=128,activation="relu",input_shape=(784,)))model.add(Dense(units=128,activation="relu"))model.add(Dense(units=128,activation="relu"))model.add(Dense(units=10,activation="softmax"))model.compile(optimizer=SGD(0.001),loss="categorical_crossentropy",metrics=["accuracy"])model.load_weights("mnist-model.h5")#model.fit(train_x,train_y,batch_size=32,epochs=10,verbose=1)#model.save("mnistmodel.h5")accuracy = model.evaluate(x=test_x,y=test_y,batch_size=32)print("Accuracy: ",accuracy[1]) What we did here is to load the parameters of the model from the saved model file and the evaluate function runs predictions over the test dataset and returns the accuracy of our prediction. So far, I have demonstrated how to save models and use them later for prediction, however, this is all boring stuff, the real deal is being able to load a specific image and determine what class it belongs to. The first step is to add the code below to get the prediction for a specific image from the test img = test_x[130]test_img = img.reshape((1,784))img_class = model.predict_classes(test_img)prediction = img_class[0]classname = img_class[0]print("Class: ",classname) Here we just pick a random image, in this case at index 130 from the test set, we create a flatten copy that is reshaped to (1,784) and we feed this copy into our model, next we obtain the prediction and print it out. Comment out the model.evaluate in the code, add the above and run it. Your output should be this: Class: 6 Now that we have the prediction, we use matplotlib to display the image and its predicted class img = img.reshape((28,28))plt.imshow(img)plt.title(classname)plt.show() The reshape operation here is necessary to enable matplotlib display the image Your updated code should all be like this import kerasfrom keras.datasets import mnistfrom keras.layers import Densefrom keras.models import Sequentialfrom keras.optimizers import SGDimport matplotlib.pyplot as plt(train_x, train_y) , (test_x, test_y) = mnist.load_data()train_x = train_x.reshape(60000,784)test_x = test_x.reshape(10000,784)train_y = keras.utils.to_categorical(train_y,10)test_y = keras.utils.to_categorical(test_y,10)model = Sequential()model.add(Dense(units=128,activation="relu",input_shape=(784,)))model.add(Dense(units=128,activation="relu"))model.add(Dense(units=128,activation="relu"))model.add(Dense(units=10,activation="softmax"))model.compile(optimizer=SGD(0.001),loss="categorical_crossentropy",metrics=["accuracy"])model.load_weights("mnistmodel.h5")img = test_x[130]test_img = img.reshape((1,784))img_class = model.predict_classes(test_img)prediction = img_class[0]classname = img_class[0]print("Class: ",classname)img = img.reshape((28,28))plt.imshow(img)plt.title(classname)plt.show() Run this and your output should be this AND THAT’S IT! Absolutely simple, we have built a basic digit recognition system. I encourage you to try different indexes of the test images and see for yourself, what the result would be. But, what if we wanted to bring in an image not included in the test set, for this test, please save the image below to your system and copy it into the directory where your python file resides. Run the code below import kerasfrom keras.datasets import mnistfrom keras.layers import Densefrom keras.models import Sequentialfrom keras.optimizers import SGDimport matplotlib.pyplot as pltfrom keras.preprocessing import image(train_x, train_y) , (test_x, test_y) = mnist.load_data()train_x = train_x.reshape(60000,784)test_x = test_x.reshape(10000,784)train_y = keras.utils.to_categorical(train_y,10)test_y = keras.utils.to_categorical(test_y,10)model = Sequential()model.add(Dense(units=128,activation="relu",input_shape=(784,)))model.add(Dense(units=128,activation="relu"))model.add(Dense(units=128,activation="relu"))model.add(Dense(units=10,activation="softmax"))model.compile(optimizer=SGD(0.001),loss="categorical_crossentropy",metrics=["accuracy"])model.load_weights("mnistmodel.h5")img = image.load_img(path="testimage.png",grayscale=True,target_size=(28,28,1))img = image.img_to_array(img)test_img = img.reshape((1,784))img_class = model.predict_classes(test_img)prediction = img_class[0]classname = img_class[0]print("Class: ",classname)img = img.reshape((28,28))plt.imshow(img)plt.title(classname)plt.show() You might notice a few new things here, first we imported image from keras.preprocessing Next we added img = image.load_img(path="testimage.png",grayscale=True,target_size=(28,28,1))img = image.img_to_array(img) In the first line, we loaded the image from disk and specified that it should be resized to 28 x 28 x 1, remember that this is the dimension of the original mnist images, so its good we keep things constant. Next we converted the image into an array of pixels, that’s all. Run it and Check the result yourself, if the prediction would be 3 or not. Any questions or comments should be left in the comment box below, you can also reach me on twitter via @johnolafenwa If you love this tutorial, give some claps. The next post would be on using Convolutional Neural Networks, which would push our accuracy to over 99%!!! Just keep in touch.
[ { "code": null, "e": 538, "s": 172, "text": "In my previous post, I delved into some of the theoretical concepts underlying artificial neural networks. In this post, I would be explaining some common operations that you would frequently need in keras. First, how to save models and use them for prediction later, displaying images from the dataset and loading images from our system and predicting their class." }, { "code": null, "e": 591, "s": 538, "text": "Fire up your IDE if you haven’t done so and read on." }, { "code": null, "e": 605, "s": 591, "text": "SAVING MODELS" }, { "code": null, "e": 807, "s": 605, "text": "Training models is a very slow process, nobody want’s to do that every time, fortunately, we only need to train our model once, save it and then we can load it anytime and use it to predict new images." }, { "code": null, "e": 926, "s": 807, "text": "Keras saves models in the .h5 format, so in case you skipped installing h5py in the first tutorial I posted, pleas run" }, { "code": null, "e": 944, "s": 926, "text": "pip3 install h5py" }, { "code": null, "e": 1009, "s": 944, "text": "We would also need matplotlib to visualize our image, hence, run" }, { "code": null, "e": 1033, "s": 1009, "text": "pip3 install matplotlib" }, { "code": null, "e": 1073, "s": 1033, "text": "Here is the code for the first tutorial" }, { "code": null, "e": 2054, "s": 1073, "text": "import kerasfrom keras.datasets import mnistfrom keras.layers import Densefrom keras.models import Sequentialfrom keras.optimizers import SGD(train_x, train_y) , (test_x, test_y) = mnist.load_data()#train_x = train_x.astype('float32') / 255#test_x = test_x.astype('float32') / 255print(train_x.shape)print(train_y.shape)print(test_x.shape)print(test_y.shape)train_x = train_x.reshape(60000,784)test_x = test_x.reshape(10000,784)train_y = keras.utils.to_categorical(train_y,10)test_y = keras.utils.to_categorical(test_y,10)model = Sequential()model.add(Dense(units=128,activation=\"relu\",input_shape=(784,)))model.add(Dense(units=128,activation=\"relu\"))model.add(Dense(units=128,activation=\"relu\"))model.add(Dense(units=10,activation=\"softmax\"))model.compile(optimizer=SGD(0.001),loss=\"categorical_crossentropy\",metrics=[\"accuracy\"])model.fit(train_x,train_y,batch_size=32,epochs=10,verbose=1)accuracy = model.evaluate(x=test_x,y=test_y,batch_size=32)print(\"Accuracy: \",accuracy[1])" }, { "code": null, "e": 2108, "s": 2054, "text": "To save the model, simply add below after model.fit()" }, { "code": null, "e": 2137, "s": 2108, "text": "model.save(\"mnist-model.h5\")" }, { "code": null, "e": 2147, "s": 2137, "text": "INFERENCE" }, { "code": null, "e": 2221, "s": 2147, "text": "Inference refers to the process of predicting new images using our model." }, { "code": null, "e": 2251, "s": 2221, "text": "In your code, comment out the" }, { "code": null, "e": 2261, "s": 2251, "text": "model.fit" }, { "code": null, "e": 2300, "s": 2261, "text": "and instead replace with the following" }, { "code": null, "e": 2336, "s": 2300, "text": "model.load_weights(\"mnistmodel.h5\")" }, { "code": null, "e": 2365, "s": 2336, "text": "Our code now looks like this" }, { "code": null, "e": 3411, "s": 2365, "text": "import kerasfrom keras.datasets import mnistfrom keras.layers import Densefrom keras.models import Sequentialfrom keras.optimizers import SGD(train_x, train_y) , (test_x, test_y) = mnist.load_data()#train_x = train_x.astype('float32') / 255#test_x = test_x.astype('float32') / 255print(train_x.shape)print(train_y.shape)print(test_x.shape)print(test_y.shape)train_x = train_x.reshape(60000,784)test_x = test_x.reshape(10000,784)train_y = keras.utils.to_categorical(train_y,10)test_y = keras.utils.to_categorical(test_y,10)model = Sequential()model.add(Dense(units=128,activation=\"relu\",input_shape=(784,)))model.add(Dense(units=128,activation=\"relu\"))model.add(Dense(units=128,activation=\"relu\"))model.add(Dense(units=10,activation=\"softmax\"))model.compile(optimizer=SGD(0.001),loss=\"categorical_crossentropy\",metrics=[\"accuracy\"])model.load_weights(\"mnist-model.h5\")#model.fit(train_x,train_y,batch_size=32,epochs=10,verbose=1)#model.save(\"mnistmodel.h5\")accuracy = model.evaluate(x=test_x,y=test_y,batch_size=32)print(\"Accuracy: \",accuracy[1])" }, { "code": null, "e": 3602, "s": 3411, "text": "What we did here is to load the parameters of the model from the saved model file and the evaluate function runs predictions over the test dataset and returns the accuracy of our prediction." }, { "code": null, "e": 3812, "s": 3602, "text": "So far, I have demonstrated how to save models and use them later for prediction, however, this is all boring stuff, the real deal is being able to load a specific image and determine what class it belongs to." }, { "code": null, "e": 3909, "s": 3812, "text": "The first step is to add the code below to get the prediction for a specific image from the test" }, { "code": null, "e": 4076, "s": 3909, "text": "img = test_x[130]test_img = img.reshape((1,784))img_class = model.predict_classes(test_img)prediction = img_class[0]classname = img_class[0]print(\"Class: \",classname)" }, { "code": null, "e": 4200, "s": 4076, "text": "Here we just pick a random image, in this case at index 130 from the test set, we create a flatten copy that is reshaped to" }, { "code": null, "e": 4208, "s": 4200, "text": "(1,784)" }, { "code": null, "e": 4294, "s": 4208, "text": "and we feed this copy into our model, next we obtain the prediction and print it out." }, { "code": null, "e": 4364, "s": 4294, "text": "Comment out the model.evaluate in the code, add the above and run it." }, { "code": null, "e": 4392, "s": 4364, "text": "Your output should be this:" }, { "code": null, "e": 4401, "s": 4392, "text": "Class: 6" }, { "code": null, "e": 4497, "s": 4401, "text": "Now that we have the prediction, we use matplotlib to display the image and its predicted class" }, { "code": null, "e": 4569, "s": 4497, "text": "img = img.reshape((28,28))plt.imshow(img)plt.title(classname)plt.show()" }, { "code": null, "e": 4648, "s": 4569, "text": "The reshape operation here is necessary to enable matplotlib display the image" }, { "code": null, "e": 4690, "s": 4648, "text": "Your updated code should all be like this" }, { "code": null, "e": 5665, "s": 4690, "text": "import kerasfrom keras.datasets import mnistfrom keras.layers import Densefrom keras.models import Sequentialfrom keras.optimizers import SGDimport matplotlib.pyplot as plt(train_x, train_y) , (test_x, test_y) = mnist.load_data()train_x = train_x.reshape(60000,784)test_x = test_x.reshape(10000,784)train_y = keras.utils.to_categorical(train_y,10)test_y = keras.utils.to_categorical(test_y,10)model = Sequential()model.add(Dense(units=128,activation=\"relu\",input_shape=(784,)))model.add(Dense(units=128,activation=\"relu\"))model.add(Dense(units=128,activation=\"relu\"))model.add(Dense(units=10,activation=\"softmax\"))model.compile(optimizer=SGD(0.001),loss=\"categorical_crossentropy\",metrics=[\"accuracy\"])model.load_weights(\"mnistmodel.h5\")img = test_x[130]test_img = img.reshape((1,784))img_class = model.predict_classes(test_img)prediction = img_class[0]classname = img_class[0]print(\"Class: \",classname)img = img.reshape((28,28))plt.imshow(img)plt.title(classname)plt.show()" }, { "code": null, "e": 5705, "s": 5665, "text": "Run this and your output should be this" }, { "code": null, "e": 5787, "s": 5705, "text": "AND THAT’S IT! Absolutely simple, we have built a basic digit recognition system." }, { "code": null, "e": 5895, "s": 5787, "text": "I encourage you to try different indexes of the test images and see for yourself, what the result would be." }, { "code": null, "e": 6090, "s": 5895, "text": "But, what if we wanted to bring in an image not included in the test set, for this test, please save the image below to your system and copy it into the directory where your python file resides." }, { "code": null, "e": 6109, "s": 6090, "text": "Run the code below" }, { "code": null, "e": 7212, "s": 6109, "text": "import kerasfrom keras.datasets import mnistfrom keras.layers import Densefrom keras.models import Sequentialfrom keras.optimizers import SGDimport matplotlib.pyplot as pltfrom keras.preprocessing import image(train_x, train_y) , (test_x, test_y) = mnist.load_data()train_x = train_x.reshape(60000,784)test_x = test_x.reshape(10000,784)train_y = keras.utils.to_categorical(train_y,10)test_y = keras.utils.to_categorical(test_y,10)model = Sequential()model.add(Dense(units=128,activation=\"relu\",input_shape=(784,)))model.add(Dense(units=128,activation=\"relu\"))model.add(Dense(units=128,activation=\"relu\"))model.add(Dense(units=10,activation=\"softmax\"))model.compile(optimizer=SGD(0.001),loss=\"categorical_crossentropy\",metrics=[\"accuracy\"])model.load_weights(\"mnistmodel.h5\")img = image.load_img(path=\"testimage.png\",grayscale=True,target_size=(28,28,1))img = image.img_to_array(img)test_img = img.reshape((1,784))img_class = model.predict_classes(test_img)prediction = img_class[0]classname = img_class[0]print(\"Class: \",classname)img = img.reshape((28,28))plt.imshow(img)plt.title(classname)plt.show()" }, { "code": null, "e": 7301, "s": 7212, "text": "You might notice a few new things here, first we imported image from keras.preprocessing" }, { "code": null, "e": 7315, "s": 7301, "text": "Next we added" }, { "code": null, "e": 7424, "s": 7315, "text": "img = image.load_img(path=\"testimage.png\",grayscale=True,target_size=(28,28,1))img = image.img_to_array(img)" }, { "code": null, "e": 7632, "s": 7424, "text": "In the first line, we loaded the image from disk and specified that it should be resized to 28 x 28 x 1, remember that this is the dimension of the original mnist images, so its good we keep things constant." }, { "code": null, "e": 7697, "s": 7632, "text": "Next we converted the image into an array of pixels, that’s all." }, { "code": null, "e": 7772, "s": 7697, "text": "Run it and Check the result yourself, if the prediction would be 3 or not." }, { "code": null, "e": 7890, "s": 7772, "text": "Any questions or comments should be left in the comment box below, you can also reach me on twitter via @johnolafenwa" }, { "code": null, "e": 7934, "s": 7890, "text": "If you love this tutorial, give some claps." } ]
Standard Chartered Interview Experience - GeeksforGeeks
30 Oct, 2019 I attended an interview with Standard Chartered on 20th Oct 2019. I hold about 9 years of exp in java. There is only one round that was the written round. Find the exact pair of the numbers in an array whose sum of values is equal to targets. Assume that there is only such a pair. This implementation needs to be done in O(n).Find the prime factors of the given number and the output should be as 15-> 5, 3 and 9->3*3Given the array of numbers with positive and negative values. Arrange them so that all negative values appear first and positive next without changing the relative order.input: [-15, -17, -2, 19, -34, 5, 19, 0] output: [-15, -17, -2, -34, 19, 5, 19, 0] Find the exact pair of the numbers in an array whose sum of values is equal to targets. Assume that there is only such a pair. This implementation needs to be done in O(n). Find the prime factors of the given number and the output should be as 15-> 5, 3 and 9->3*3 Given the array of numbers with positive and negative values. Arrange them so that all negative values appear first and positive next without changing the relative order.input: [-15, -17, -2, 19, -34, 5, 19, 0] output: [-15, -17, -2, -34, 19, 5, 19, 0] input: [-15, -17, -2, 19, -34, 5, 19, 0] output: [-15, -17, -2, -34, 19, 5, 19, 0] Marketing Standard Chartered Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Amazon Interview Experience for SDE-1 (Off-Campus) 2022 Amazon Interview Experience Amazon Interview Experience for SDE-1 Amazon Interview Experience (Off-Campus) 2022 Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus) Amazon Interview Experience for SDE-1 (On-Campus) JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021 EPAM Interview Experience (Off-Campus)
[ { "code": null, "e": 26691, "s": 26663, "text": "\n30 Oct, 2019" }, { "code": null, "e": 26794, "s": 26691, "text": "I attended an interview with Standard Chartered on 20th Oct 2019. I hold about 9 years of exp in java." }, { "code": null, "e": 26846, "s": 26794, "text": "There is only one round that was the written round." }, { "code": null, "e": 27362, "s": 26846, "text": "Find the exact pair of the numbers in an array whose sum of values is equal to targets. Assume that there is only such a pair. This implementation needs to be done in O(n).Find the prime factors of the given number and the output should be as 15-> 5, 3 and 9->3*3Given the array of numbers with positive and negative values. Arrange them so that all negative values appear first and positive next without changing the relative order.input: [-15, -17, -2, 19, -34, 5, 19, 0]\noutput: [-15, -17, -2, -34, 19, 5, 19, 0]" }, { "code": null, "e": 27535, "s": 27362, "text": "Find the exact pair of the numbers in an array whose sum of values is equal to targets. Assume that there is only such a pair. This implementation needs to be done in O(n)." }, { "code": null, "e": 27627, "s": 27535, "text": "Find the prime factors of the given number and the output should be as 15-> 5, 3 and 9->3*3" }, { "code": null, "e": 27880, "s": 27627, "text": "Given the array of numbers with positive and negative values. Arrange them so that all negative values appear first and positive next without changing the relative order.input: [-15, -17, -2, 19, -34, 5, 19, 0]\noutput: [-15, -17, -2, -34, 19, 5, 19, 0]" }, { "code": null, "e": 27963, "s": 27880, "text": "input: [-15, -17, -2, 19, -34, 5, 19, 0]\noutput: [-15, -17, -2, -34, 19, 5, 19, 0]" }, { "code": null, "e": 27973, "s": 27963, "text": "Marketing" }, { "code": null, "e": 27992, "s": 27973, "text": "Standard Chartered" }, { "code": null, "e": 28014, "s": 27992, "text": "Interview Experiences" }, { "code": null, "e": 28112, "s": 28014, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28163, "s": 28112, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 28205, "s": 28163, "text": "Amazon AWS Interview Experience for SDE-1" }, { "code": null, "e": 28261, "s": 28205, "text": "Amazon Interview Experience for SDE-1 (Off-Campus) 2022" }, { "code": null, "e": 28289, "s": 28261, "text": "Amazon Interview Experience" }, { "code": null, "e": 28327, "s": 28289, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 28373, "s": 28327, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 28450, "s": 28373, "text": "Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)" }, { "code": null, "e": 28500, "s": 28450, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 28572, "s": 28500, "text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021" } ]
Count of distinct strings that can be obtained after performing exactly one swap - GeeksforGeeks
10 Jan, 2022 Given a string s containing lowercase English alphabet characters. The task is to calculate the number of distinct strings that can be obtained after performing exactly one swap. Input: s = “geek”Output: 6Explanation: Following are the strings formed by doing exactly one swapstrings = [“egek”,”eegk”,”geek”,”geke”,”gkee”, “keeg”]Therefore, there are 6 distinct possible strings. Input: s = “ab”Output: 1 Approach: This problem can be solved by using HashMaps. Follow the steps below to solve the given problem. Check for the number of unique elements in the string s. Store the frequencies of all the unique characters in a map. Declare a variable say ans = 0, to store the number of distinct possible strings. Iterate over the string and increment ans by no of elements apart from the current element which will be used to construct a new string. Iterate over the string again and check if the frequency of some characters is greater than 2. If so then increment answer by 1 as they will be forming only one extra unique string. Return ans as the final answer. Below is the implementation of the above approach C++ Java Python3 C# Javascript // C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to count number of distinct// string formed after one swaplong long countStrings(string S){ long long N = S.size(); // mp[] to store the frequency // of each character int mp[26] = { 0 }; // For storing frequencies for (auto i : S) { mp[i - 'a']++; } long long ans = 0; for (auto i : S) { ans += N - mp[i - 'a']; } ans /= 2; for (int i = 0; i < 26; i++) { if (mp[i] >= 2) { ans++; break; } } return ans;} // Driver Codeint main(){ string S = "geek"; // Function Call long long ans = countStrings(S); cout << ans << endl; return 0;} // Java code to implement the above approachimport java.util.*;public class GFG{ // Function to count number of distinct// string formed after one swapstatic long countStrings(String S){ long N = S.length(); // mp[] to store the frequency // of each character int mp[] = new int[26]; for(int i = 0; i < 26; i++) { mp[i] = 0; } // For storing frequencies for (int i = 0; i < S.length(); i++) { mp[S.charAt(i) - 'a']++; } long ans = 0; for (int i = 0; i < S.length(); i++) { ans += N - mp[S.charAt(i) - 'a']; } ans /= 2; for (int i = 0; i < 26; i++) { if (mp[i] >= 2) { ans++; break; } } return ans;} // Driver codepublic static void main(String args[]){ String S = "geek"; // Function Call long ans = countStrings(S); System.out.println(ans);}} // This code is contributed by Samim Hossain Mondal. # Python code to implement the above approach # Function to count number of distinct# string formed after one swapdef countStrings(S): N = len(S); # mp to store the frequency # of each character mp = [0 for i in range(26)]; for i in range(26): mp[i] = 0; # For storing frequencies for i in range(N): mp[ord(S[i]) - ord('a')] += 1; ans = 0; for i in range(N): ans += N - mp[ord(S[i]) - ord('a')]; ans //= 2; for i in range(26): if (mp[i] >= 2): ans += 1; break; return ans; # Driver codeif __name__ == '__main__': S = "geek"; # Function Call ans = countStrings(S); print(ans); # This code is contributed by 29AjayKumar // C# code to implement the above approachusing System;class GFG{ // Function to count number of distinct// string formed after one swapstatic long countStrings(string S){ long N = S.Length; // mp[] to store the frequency // of each character int []mp = new int[26]; for(int i = 0; i < 26; i++) { mp[i] = 0; } // For storing frequencies for (int i = 0; i < S.Length; i++) { mp[S[i] - 'a']++; } long ans = 0; for (int i = 0; i < S.Length; i++) { ans += N - mp[S[i] - 'a']; } ans /= 2; for (int i = 0; i < 26; i++) { if (mp[i] >= 2) { ans++; break; } } return ans;} // Driver codepublic static void Main(){ string S = "geek"; // Function Call long ans = countStrings(S); Console.Write(ans);}} // This code is contributed by Samim Hossain Mondal. <script> // JavaScript program for above approach // Function to count number of distinct// string formed after one swapfunction countStrings(S){ let N = S.length; // mp[] to store the frequency // of each character let mp = new Map(); // For storing frequencies for(let i = 0; i < S.length; i++) { if (!mp.has(S[i].charCodeAt(0) - 'a'.charCodeAt(0))) { mp.set(S[i].charCodeAt(0) - 'a'.charCodeAt(0), 1); } else { mp.set(S[i].charCodeAt(0) - 'a'.charCodeAt(0), mp.get(S[i].charCodeAt(0) - 'a'.charCodeAt(0)) + 1) } } let ans = 0; for(let i = 0; i < S.length; i++) { ans += N - mp.get(S[i].charCodeAt(0) - 'a'.charCodeAt(0)); } ans = Math.floor(ans / 2) for(let i = 0; i < 26; i++) { if (mp.get(i) >= 2) { ans++; break; } } return ans;} // Driver Codelet S = "geek"; // Function Calllet ans = countStrings(S);document.write(ans + '<br>') // This code is contributed by Potta Lokesh </script> 6 Time complexity: O(N)Auxiliary Space: O(1) lokeshpotta20 samim2000 29AjayKumar Algo-Geek 2021 Swap-Program Algo Geek Arrays Strings Arrays Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check if the given string is valid English word or not Sort strings on the basis of their numeric part Divide given number into two even parts Smallest set of vertices to visit all nodes of the given Graph Count of Palindrome Strings in given Array of strings Arrays in Java Arrays in C/C++ Maximum and minimum of an array using minimum number of comparisons Write a program to reverse an array or string Program for array rotation
[ { "code": null, "e": 27373, "s": 27345, "text": "\n10 Jan, 2022" }, { "code": null, "e": 27552, "s": 27373, "text": "Given a string s containing lowercase English alphabet characters. The task is to calculate the number of distinct strings that can be obtained after performing exactly one swap." }, { "code": null, "e": 27753, "s": 27552, "text": "Input: s = “geek”Output: 6Explanation: Following are the strings formed by doing exactly one swapstrings = [“egek”,”eegk”,”geek”,”geke”,”gkee”, “keeg”]Therefore, there are 6 distinct possible strings." }, { "code": null, "e": 27778, "s": 27753, "text": "Input: s = “ab”Output: 1" }, { "code": null, "e": 27885, "s": 27778, "text": "Approach: This problem can be solved by using HashMaps. Follow the steps below to solve the given problem." }, { "code": null, "e": 27942, "s": 27885, "text": "Check for the number of unique elements in the string s." }, { "code": null, "e": 28003, "s": 27942, "text": "Store the frequencies of all the unique characters in a map." }, { "code": null, "e": 28085, "s": 28003, "text": "Declare a variable say ans = 0, to store the number of distinct possible strings." }, { "code": null, "e": 28222, "s": 28085, "text": "Iterate over the string and increment ans by no of elements apart from the current element which will be used to construct a new string." }, { "code": null, "e": 28404, "s": 28222, "text": "Iterate over the string again and check if the frequency of some characters is greater than 2. If so then increment answer by 1 as they will be forming only one extra unique string." }, { "code": null, "e": 28436, "s": 28404, "text": "Return ans as the final answer." }, { "code": null, "e": 28486, "s": 28436, "text": "Below is the implementation of the above approach" }, { "code": null, "e": 28490, "s": 28486, "text": "C++" }, { "code": null, "e": 28495, "s": 28490, "text": "Java" }, { "code": null, "e": 28503, "s": 28495, "text": "Python3" }, { "code": null, "e": 28506, "s": 28503, "text": "C#" }, { "code": null, "e": 28517, "s": 28506, "text": "Javascript" }, { "code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to count number of distinct// string formed after one swaplong long countStrings(string S){ long long N = S.size(); // mp[] to store the frequency // of each character int mp[26] = { 0 }; // For storing frequencies for (auto i : S) { mp[i - 'a']++; } long long ans = 0; for (auto i : S) { ans += N - mp[i - 'a']; } ans /= 2; for (int i = 0; i < 26; i++) { if (mp[i] >= 2) { ans++; break; } } return ans;} // Driver Codeint main(){ string S = \"geek\"; // Function Call long long ans = countStrings(S); cout << ans << endl; return 0;}", "e": 29251, "s": 28517, "text": null }, { "code": "// Java code to implement the above approachimport java.util.*;public class GFG{ // Function to count number of distinct// string formed after one swapstatic long countStrings(String S){ long N = S.length(); // mp[] to store the frequency // of each character int mp[] = new int[26]; for(int i = 0; i < 26; i++) { mp[i] = 0; } // For storing frequencies for (int i = 0; i < S.length(); i++) { mp[S.charAt(i) - 'a']++; } long ans = 0; for (int i = 0; i < S.length(); i++) { ans += N - mp[S.charAt(i) - 'a']; } ans /= 2; for (int i = 0; i < 26; i++) { if (mp[i] >= 2) { ans++; break; } } return ans;} // Driver codepublic static void main(String args[]){ String S = \"geek\"; // Function Call long ans = countStrings(S); System.out.println(ans);}} // This code is contributed by Samim Hossain Mondal.", "e": 30171, "s": 29251, "text": null }, { "code": "# Python code to implement the above approach # Function to count number of distinct# string formed after one swapdef countStrings(S): N = len(S); # mp to store the frequency # of each character mp = [0 for i in range(26)]; for i in range(26): mp[i] = 0; # For storing frequencies for i in range(N): mp[ord(S[i]) - ord('a')] += 1; ans = 0; for i in range(N): ans += N - mp[ord(S[i]) - ord('a')]; ans //= 2; for i in range(26): if (mp[i] >= 2): ans += 1; break; return ans; # Driver codeif __name__ == '__main__': S = \"geek\"; # Function Call ans = countStrings(S); print(ans); # This code is contributed by 29AjayKumar", "e": 30894, "s": 30171, "text": null }, { "code": "// C# code to implement the above approachusing System;class GFG{ // Function to count number of distinct// string formed after one swapstatic long countStrings(string S){ long N = S.Length; // mp[] to store the frequency // of each character int []mp = new int[26]; for(int i = 0; i < 26; i++) { mp[i] = 0; } // For storing frequencies for (int i = 0; i < S.Length; i++) { mp[S[i] - 'a']++; } long ans = 0; for (int i = 0; i < S.Length; i++) { ans += N - mp[S[i] - 'a']; } ans /= 2; for (int i = 0; i < 26; i++) { if (mp[i] >= 2) { ans++; break; } } return ans;} // Driver codepublic static void Main(){ string S = \"geek\"; // Function Call long ans = countStrings(S); Console.Write(ans);}} // This code is contributed by Samim Hossain Mondal.", "e": 31761, "s": 30894, "text": null }, { "code": "<script> // JavaScript program for above approach // Function to count number of distinct// string formed after one swapfunction countStrings(S){ let N = S.length; // mp[] to store the frequency // of each character let mp = new Map(); // For storing frequencies for(let i = 0; i < S.length; i++) { if (!mp.has(S[i].charCodeAt(0) - 'a'.charCodeAt(0))) { mp.set(S[i].charCodeAt(0) - 'a'.charCodeAt(0), 1); } else { mp.set(S[i].charCodeAt(0) - 'a'.charCodeAt(0), mp.get(S[i].charCodeAt(0) - 'a'.charCodeAt(0)) + 1) } } let ans = 0; for(let i = 0; i < S.length; i++) { ans += N - mp.get(S[i].charCodeAt(0) - 'a'.charCodeAt(0)); } ans = Math.floor(ans / 2) for(let i = 0; i < 26; i++) { if (mp.get(i) >= 2) { ans++; break; } } return ans;} // Driver Codelet S = \"geek\"; // Function Calllet ans = countStrings(S);document.write(ans + '<br>') // This code is contributed by Potta Lokesh </script>", "e": 32909, "s": 31761, "text": null }, { "code": null, "e": 32911, "s": 32909, "text": "6" }, { "code": null, "e": 32954, "s": 32911, "text": "Time complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 32970, "s": 32956, "text": "lokeshpotta20" }, { "code": null, "e": 32980, "s": 32970, "text": "samim2000" }, { "code": null, "e": 32992, "s": 32980, "text": "29AjayKumar" }, { "code": null, "e": 33007, "s": 32992, "text": "Algo-Geek 2021" }, { "code": null, "e": 33020, "s": 33007, "text": "Swap-Program" }, { "code": null, "e": 33030, "s": 33020, "text": "Algo Geek" }, { "code": null, "e": 33037, "s": 33030, "text": "Arrays" }, { "code": null, "e": 33045, "s": 33037, "text": "Strings" }, { "code": null, "e": 33052, "s": 33045, "text": "Arrays" }, { "code": null, "e": 33060, "s": 33052, "text": "Strings" }, { "code": null, "e": 33158, "s": 33060, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33213, "s": 33158, "text": "Check if the given string is valid English word or not" }, { "code": null, "e": 33261, "s": 33213, "text": "Sort strings on the basis of their numeric part" }, { "code": null, "e": 33301, "s": 33261, "text": "Divide given number into two even parts" }, { "code": null, "e": 33364, "s": 33301, "text": "Smallest set of vertices to visit all nodes of the given Graph" }, { "code": null, "e": 33418, "s": 33364, "text": "Count of Palindrome Strings in given Array of strings" }, { "code": null, "e": 33433, "s": 33418, "text": "Arrays in Java" }, { "code": null, "e": 33449, "s": 33433, "text": "Arrays in C/C++" }, { "code": null, "e": 33517, "s": 33449, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 33563, "s": 33517, "text": "Write a program to reverse an array or string" } ]
Convert a Binary Tree to a Circular Doubly Link List - GeeksforGeeks
13 Oct, 2021 Given a Binary Tree, convert it to a Circular Doubly Linked List (In-Place). The left and right pointers in nodes are to be used as previous and next pointers respectively in converted Circular Linked List. The order of nodes in the List must be the same as in Inorder for the given Binary Tree. The first node of Inorder traversal must be the head node of the Circular List. Example: The idea can be described using the below steps. 1) Write a general-purpose function that concatenates two given circular doubly lists (This function is explained below). 2) Now traverse the given tree ....a) Recursively convert left subtree to a circular DLL. Let the converted list be leftList. ....a) Recursively convert right subtree to a circular DLL. Let the converted list be rightList. ....c) Make a circular linked list of root of the tree, make left and right of root to point to itself. ....d) Concatenate leftList with the list of the single root node. ....e) Concatenate the list produced in the step above (d) with rightList.Note that the above code traverses the tree in Postorder fashion. We can traverse in an inorder fashion also. We can first concatenate left subtree and root, then recur for the right subtree and concatenate the result with left-root concatenation. How to Concatenate two circular DLLs? Get the last node of the left list. Retrieving the last node is an O(1) operation since the prev pointer of the head points to the last node of the list. Connect it with the first node of the right list Get the last node of the second list Connect it with the head of the list. Below are implementations of the above idea. C++ Java Python3 C# Javascript // C++ Program to convert a Binary Tree// to a Circular Doubly Linked List#include<iostream>using namespace std; // To represents a node of a Binary Treestruct Node{ struct Node *left, *right; int data;}; // A function that appends rightList at the end// of leftList.Node *concatenate(Node *leftList, Node *rightList){ // If either of the list is empty // then return the other list if (leftList == NULL) return rightList; if (rightList == NULL) return leftList; // Store the last Node of left List Node *leftLast = leftList->left; // Store the last Node of right List Node *rightLast = rightList->left; // Connect the last node of Left List // with the first Node of the right List leftLast->right = rightList; rightList->left = leftLast; // Left of first node points to // the last node in the list leftList->left = rightLast; // Right of last node refers to the first // node of the List rightLast->right = leftList; return leftList;} // Function converts a tree to a circular Linked List// and then returns the head of the Linked ListNode *bTreeToCList(Node *root){ if (root == NULL) return NULL; // Recursively convert left and right subtrees Node *left = bTreeToCList(root->left); Node *right = bTreeToCList(root->right); // Make a circular linked list of single node // (or root). To do so, make the right and // left pointers of this node point to itself root->left = root->right = root; // Step 1 (concatenate the left list with the list // with single node, i.e., current node) // Step 2 (concatenate the returned list with the // right List) return concatenate(concatenate(left, root), right);} // Display Circular Link Listvoid displayCList(Node *head){ cout << "Circular Linked List is :\n"; Node *itr = head; do { cout << itr->data <<" "; itr = itr->right; } while (head!=itr); cout << "\n";} // Create a new Node and return its addressNode *newNode(int data){ Node *temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // Driver Program to test above functionint main(){ Node *root = newNode(10); root->left = newNode(12); root->right = newNode(15); root->left->left = newNode(25); root->left->right = newNode(30); root->right->left = newNode(36); Node *head = bTreeToCList(root); displayCList(head); return 0;} // Java Program to convert a Binary Tree to a// Circular Doubly Linked List // Node class represents a Node of a Treeclass Node{ int val; Node left,right; public Node(int val) { this.val = val; left = right = null; }} // A class to represent a treeclass Tree{ Node root; public Tree() { root = null; } // concatenate both the lists and returns the head // of the List public Node concatenate(Node leftList,Node rightList) { // If either of the list is empty, then // return the other list if (leftList == null) return rightList; if (rightList == null) return leftList; // Store the last Node of left List Node leftLast = leftList.left; // Store the last Node of right List Node rightLast = rightList.left; // Connect the last node of Left List // with the first Node of the right List leftLast.right = rightList; rightList.left = leftLast; // left of first node refers to // the last node in the list leftList.left = rightLast; // Right of last node refers to the first // node of the List rightLast.right = leftList; // Return the Head of the List return leftList; } // Method converts a tree to a circular // Link List and then returns the head // of the Link List public Node bTreeToCList(Node root) { if (root == null) return null; // Recursively convert left and right subtrees Node left = bTreeToCList(root.left); Node right = bTreeToCList(root.right); // Make a circular linked list of single node // (or root). To do so, make the right and // left pointers of this node point to itself root.left = root.right = root; // Step 1 (concatenate the left list with the list // with single node, i.e., current node) // Step 2 (concatenate the returned list with the // right List) return concatenate(concatenate(left, root), right); } // Display Circular Link List public void display(Node head) { System.out.println("Circular Linked List is :"); Node itr = head; do { System.out.print(itr.val+ " " ); itr = itr.right; } while (itr != head); System.out.println(); }} // Driver Codeclass Main{ public static void main(String args[]) { // Build the tree Tree tree = new Tree(); tree.root = new Node(10); tree.root.left = new Node(12); tree.root.right = new Node(15); tree.root.left.left = new Node(25); tree.root.left.right = new Node(30); tree.root.right.left = new Node(36); // head refers to the head of the Link List Node head = tree.bTreeToCList(tree.root); // Display the Circular LinkedList tree.display(head); }} # Python3 Program to convert a Binary # Tree to a Circular Doubly Linked List class newNode: def __init__(self, data): self.data = data self.left = self.right = None # A function that appends rightList # at the end of leftList. def concatenate(leftList, rightList): # If either of the list is empty # then return the other list if (leftList == None): return rightList if (rightList == None): return leftList # Store the last Node of left List leftLast = leftList.left # Store the last Node of right List rightLast = rightList.left # Connect the last node of Left List # with the first Node of the right List leftLast.right = rightList rightList.left = leftLast # Left of first node points to # the last node in the list leftList.left = rightLast # Right of last node refers to # the first node of the List rightLast.right = leftList return leftList # Function converts a tree to a circular # Linked List and then returns the head # of the Linked List def bTreeToCList(root): if (root == None): return None # Recursively convert left and # right subtrees left = bTreeToCList(root.left) right = bTreeToCList(root.right) # Make a circular linked list of single # node (or root). To do so, make the # right and left pointers of this node # point to itself root.left = root.right = root # Step 1 (concatenate the left list # with the list with single # node, i.e., current node) # Step 2 (concatenate the returned list # with the right List) return concatenate(concatenate(left, root), right) # Display Circular Link List def displayCList(head): print("Circular Linked List is :") itr = head first = 1 while (head != itr or first): print(itr.data, end = " ") itr = itr.right first = 0 print() # Driver Codeif __name__ == '__main__': root = newNode(10) root.left = newNode(12) root.right = newNode(15) root.left.left = newNode(25) root.left.right = newNode(30) root.right.left = newNode(36) head = bTreeToCList(root) displayCList(head) # This code is contributed by PranchalK // C# Program to convert a Binary Tree // to a Circular Doubly Linked List using System; // Node class represents a Node of a Tree public class Node{ public int val; public Node left, right; public Node(int val) { this.val = val; left = right = null; }} // A class to represent a tree public class Tree{ internal Node root; public Tree() { root = null; } // concatenate both the lists // and returns the head of the List public virtual Node concatenate(Node leftList, Node rightList) { // If either of the list is empty, // then return the other list if (leftList == null) { return rightList; } if (rightList == null) { return leftList; } // Store the last Node of left List Node leftLast = leftList.left; // Store the last Node of right List Node rightLast = rightList.left; // Connect the last node of Left List // with the first Node of the right List leftLast.right = rightList; rightList.left = leftLast; // left of first node refers to // the last node in the list leftList.left = rightLast; // Right of last node refers to // the first node of the List rightLast.right = leftList; // Return the Head of the List return leftList; } // Method converts a tree to a circular // Link List and then returns the head // of the Link List public virtual Node bTreeToCList(Node root) { if (root == null) { return null; } // Recursively convert left // and right subtrees Node left = bTreeToCList(root.left); Node right = bTreeToCList(root.right); // Make a circular linked list of single // node (or root). To do so, make the // right and left pointers of this node // point to itself root.left = root.right = root; // Step 1 (concatenate the left list with // the list with single node, // i.e., current node) // Step 2 (concatenate the returned list // with the right List) return concatenate(concatenate(left, root), right); } // Display Circular Link List public virtual void display(Node head) { Console.WriteLine("Circular Linked List is :"); Node itr = head; do { Console.Write(itr.val + " "); itr = itr.right; } while (itr != head); Console.WriteLine(); }} // Driver Code public class GFG{ public static void Main(string[] args) { // Build the tree Tree tree = new Tree(); tree.root = new Node(10); tree.root.left = new Node(12); tree.root.right = new Node(15); tree.root.left.left = new Node(25); tree.root.left.right = new Node(30); tree.root.right.left = new Node(36); // head refers to the head of the Link List Node head = tree.bTreeToCList(tree.root); // Display the Circular LinkedList tree.display(head); }} // This code is contributed by Shrikant13 <script>// javascript Program to convert a Binary Tree to a// Circular Doubly Linked List // Node class represents a Node of a Treeclass Node { constructor(val) { this.val = val; this.left = null; this.right = null; }} // A class to represent a var root = null; // concatenate both the lists and returns the head // of the List function concatenate(leftList, rightList) { // If either of the list is empty, then // return the other list if (leftList == null) return rightList; if (rightList == null) return leftList; // Store the last Node of left List var leftLast = leftList.left; // Store the last Node of right List var rightLast = rightList.left; // Connect the last node of Left List // with the first Node of the right List leftLast.right = rightList; rightList.left = leftLast; // left of first node refers to // the last node in the list leftList.left = rightLast; // Right of last node refers to the first // node of the List rightLast.right = leftList; // Return the Head of the List return leftList; } // Method converts a to a circular // Link List and then returns the head // of the Link List function bTreeToCList(root) { if (root == null) return null; // Recursively convert left and right subtrees var left = bTreeToCList(root.left); var right = bTreeToCList(root.right); // Make a circular linked list of single node // (or root). To do so, make the right and // left pointers of this node point to itself root.left = root.right = root; // Step 1 (concatenate the left list with the list // with single node, i.e., current node) // Step 2 (concatenate the returned list with the // right List) return concatenate(concatenate(left, root), right); } // Display Circular Link List function display(head) { document.write("Circular Linked List is :<br/>"); var itr = head; do { document.write(itr.val + " "); itr = itr.right; } while (itr != head); document.write(); } // Driver Code // Build the root = new Node(10); root.left = new Node(12); root.right = new Node(15); root.left.left = new Node(25); root.left.right = new Node(30); root.right.left = new Node(36); // head refers to the head of the Link List var head = bTreeToCList(root); // Display the Circular LinkedList display(head); // This code contributed by umadevi9616</script> Output: Circular Linked List is : 25 12 30 10 36 15 This article is contributed by Chirag 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. shrikanth13 PranchalKatiyar umadevi9616 simranarora5sos circular linked list doubly linked list SAP Labs Linked List Tree SAP Labs Linked List Tree circular linked list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Reverse a linked list Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node) Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) AVL Tree | Set 1 (Insertion) Level Order Binary Tree Traversal Binary Tree | Set 3 (Types of Binary Tree)
[ { "code": null, "e": 37091, "s": 37063, "text": "\n13 Oct, 2021" }, { "code": null, "e": 37170, "s": 37091, "text": "Given a Binary Tree, convert it to a Circular Doubly Linked List (In-Place). " }, { "code": null, "e": 37300, "s": 37170, "text": "The left and right pointers in nodes are to be used as previous and next pointers respectively in converted Circular Linked List." }, { "code": null, "e": 37389, "s": 37300, "text": "The order of nodes in the List must be the same as in Inorder for the given Binary Tree." }, { "code": null, "e": 37469, "s": 37389, "text": "The first node of Inorder traversal must be the head node of the Circular List." }, { "code": null, "e": 37478, "s": 37469, "text": "Example:" }, { "code": null, "e": 38365, "s": 37478, "text": "The idea can be described using the below steps. 1) Write a general-purpose function that concatenates two given circular doubly lists (This function is explained below). 2) Now traverse the given tree ....a) Recursively convert left subtree to a circular DLL. Let the converted list be leftList. ....a) Recursively convert right subtree to a circular DLL. Let the converted list be rightList. ....c) Make a circular linked list of root of the tree, make left and right of root to point to itself. ....d) Concatenate leftList with the list of the single root node. ....e) Concatenate the list produced in the step above (d) with rightList.Note that the above code traverses the tree in Postorder fashion. We can traverse in an inorder fashion also. We can first concatenate left subtree and root, then recur for the right subtree and concatenate the result with left-root concatenation." }, { "code": null, "e": 38404, "s": 38365, "text": "How to Concatenate two circular DLLs? " }, { "code": null, "e": 38558, "s": 38404, "text": "Get the last node of the left list. Retrieving the last node is an O(1) operation since the prev pointer of the head points to the last node of the list." }, { "code": null, "e": 38607, "s": 38558, "text": "Connect it with the first node of the right list" }, { "code": null, "e": 38644, "s": 38607, "text": "Get the last node of the second list" }, { "code": null, "e": 38682, "s": 38644, "text": "Connect it with the head of the list." }, { "code": null, "e": 38728, "s": 38682, "text": "Below are implementations of the above idea. " }, { "code": null, "e": 38732, "s": 38728, "text": "C++" }, { "code": null, "e": 38737, "s": 38732, "text": "Java" }, { "code": null, "e": 38745, "s": 38737, "text": "Python3" }, { "code": null, "e": 38748, "s": 38745, "text": "C#" }, { "code": null, "e": 38759, "s": 38748, "text": "Javascript" }, { "code": "// C++ Program to convert a Binary Tree// to a Circular Doubly Linked List#include<iostream>using namespace std; // To represents a node of a Binary Treestruct Node{ struct Node *left, *right; int data;}; // A function that appends rightList at the end// of leftList.Node *concatenate(Node *leftList, Node *rightList){ // If either of the list is empty // then return the other list if (leftList == NULL) return rightList; if (rightList == NULL) return leftList; // Store the last Node of left List Node *leftLast = leftList->left; // Store the last Node of right List Node *rightLast = rightList->left; // Connect the last node of Left List // with the first Node of the right List leftLast->right = rightList; rightList->left = leftLast; // Left of first node points to // the last node in the list leftList->left = rightLast; // Right of last node refers to the first // node of the List rightLast->right = leftList; return leftList;} // Function converts a tree to a circular Linked List// and then returns the head of the Linked ListNode *bTreeToCList(Node *root){ if (root == NULL) return NULL; // Recursively convert left and right subtrees Node *left = bTreeToCList(root->left); Node *right = bTreeToCList(root->right); // Make a circular linked list of single node // (or root). To do so, make the right and // left pointers of this node point to itself root->left = root->right = root; // Step 1 (concatenate the left list with the list // with single node, i.e., current node) // Step 2 (concatenate the returned list with the // right List) return concatenate(concatenate(left, root), right);} // Display Circular Link Listvoid displayCList(Node *head){ cout << \"Circular Linked List is :\\n\"; Node *itr = head; do { cout << itr->data <<\" \"; itr = itr->right; } while (head!=itr); cout << \"\\n\";} // Create a new Node and return its addressNode *newNode(int data){ Node *temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // Driver Program to test above functionint main(){ Node *root = newNode(10); root->left = newNode(12); root->right = newNode(15); root->left->left = newNode(25); root->left->right = newNode(30); root->right->left = newNode(36); Node *head = bTreeToCList(root); displayCList(head); return 0;}", "e": 41259, "s": 38759, "text": null }, { "code": "// Java Program to convert a Binary Tree to a// Circular Doubly Linked List // Node class represents a Node of a Treeclass Node{ int val; Node left,right; public Node(int val) { this.val = val; left = right = null; }} // A class to represent a treeclass Tree{ Node root; public Tree() { root = null; } // concatenate both the lists and returns the head // of the List public Node concatenate(Node leftList,Node rightList) { // If either of the list is empty, then // return the other list if (leftList == null) return rightList; if (rightList == null) return leftList; // Store the last Node of left List Node leftLast = leftList.left; // Store the last Node of right List Node rightLast = rightList.left; // Connect the last node of Left List // with the first Node of the right List leftLast.right = rightList; rightList.left = leftLast; // left of first node refers to // the last node in the list leftList.left = rightLast; // Right of last node refers to the first // node of the List rightLast.right = leftList; // Return the Head of the List return leftList; } // Method converts a tree to a circular // Link List and then returns the head // of the Link List public Node bTreeToCList(Node root) { if (root == null) return null; // Recursively convert left and right subtrees Node left = bTreeToCList(root.left); Node right = bTreeToCList(root.right); // Make a circular linked list of single node // (or root). To do so, make the right and // left pointers of this node point to itself root.left = root.right = root; // Step 1 (concatenate the left list with the list // with single node, i.e., current node) // Step 2 (concatenate the returned list with the // right List) return concatenate(concatenate(left, root), right); } // Display Circular Link List public void display(Node head) { System.out.println(\"Circular Linked List is :\"); Node itr = head; do { System.out.print(itr.val+ \" \" ); itr = itr.right; } while (itr != head); System.out.println(); }} // Driver Codeclass Main{ public static void main(String args[]) { // Build the tree Tree tree = new Tree(); tree.root = new Node(10); tree.root.left = new Node(12); tree.root.right = new Node(15); tree.root.left.left = new Node(25); tree.root.left.right = new Node(30); tree.root.right.left = new Node(36); // head refers to the head of the Link List Node head = tree.bTreeToCList(tree.root); // Display the Circular LinkedList tree.display(head); }}", "e": 44250, "s": 41259, "text": null }, { "code": "# Python3 Program to convert a Binary # Tree to a Circular Doubly Linked List class newNode: def __init__(self, data): self.data = data self.left = self.right = None # A function that appends rightList # at the end of leftList. def concatenate(leftList, rightList): # If either of the list is empty # then return the other list if (leftList == None): return rightList if (rightList == None): return leftList # Store the last Node of left List leftLast = leftList.left # Store the last Node of right List rightLast = rightList.left # Connect the last node of Left List # with the first Node of the right List leftLast.right = rightList rightList.left = leftLast # Left of first node points to # the last node in the list leftList.left = rightLast # Right of last node refers to # the first node of the List rightLast.right = leftList return leftList # Function converts a tree to a circular # Linked List and then returns the head # of the Linked List def bTreeToCList(root): if (root == None): return None # Recursively convert left and # right subtrees left = bTreeToCList(root.left) right = bTreeToCList(root.right) # Make a circular linked list of single # node (or root). To do so, make the # right and left pointers of this node # point to itself root.left = root.right = root # Step 1 (concatenate the left list # with the list with single # node, i.e., current node) # Step 2 (concatenate the returned list # with the right List) return concatenate(concatenate(left, root), right) # Display Circular Link List def displayCList(head): print(\"Circular Linked List is :\") itr = head first = 1 while (head != itr or first): print(itr.data, end = \" \") itr = itr.right first = 0 print() # Driver Codeif __name__ == '__main__': root = newNode(10) root.left = newNode(12) root.right = newNode(15) root.left.left = newNode(25) root.left.right = newNode(30) root.right.left = newNode(36) head = bTreeToCList(root) displayCList(head) # This code is contributed by PranchalK", "e": 46564, "s": 44250, "text": null }, { "code": "// C# Program to convert a Binary Tree // to a Circular Doubly Linked List using System; // Node class represents a Node of a Tree public class Node{ public int val; public Node left, right; public Node(int val) { this.val = val; left = right = null; }} // A class to represent a tree public class Tree{ internal Node root; public Tree() { root = null; } // concatenate both the lists // and returns the head of the List public virtual Node concatenate(Node leftList, Node rightList) { // If either of the list is empty, // then return the other list if (leftList == null) { return rightList; } if (rightList == null) { return leftList; } // Store the last Node of left List Node leftLast = leftList.left; // Store the last Node of right List Node rightLast = rightList.left; // Connect the last node of Left List // with the first Node of the right List leftLast.right = rightList; rightList.left = leftLast; // left of first node refers to // the last node in the list leftList.left = rightLast; // Right of last node refers to // the first node of the List rightLast.right = leftList; // Return the Head of the List return leftList; } // Method converts a tree to a circular // Link List and then returns the head // of the Link List public virtual Node bTreeToCList(Node root) { if (root == null) { return null; } // Recursively convert left // and right subtrees Node left = bTreeToCList(root.left); Node right = bTreeToCList(root.right); // Make a circular linked list of single // node (or root). To do so, make the // right and left pointers of this node // point to itself root.left = root.right = root; // Step 1 (concatenate the left list with // the list with single node, // i.e., current node) // Step 2 (concatenate the returned list // with the right List) return concatenate(concatenate(left, root), right); } // Display Circular Link List public virtual void display(Node head) { Console.WriteLine(\"Circular Linked List is :\"); Node itr = head; do { Console.Write(itr.val + \" \"); itr = itr.right; } while (itr != head); Console.WriteLine(); }} // Driver Code public class GFG{ public static void Main(string[] args) { // Build the tree Tree tree = new Tree(); tree.root = new Node(10); tree.root.left = new Node(12); tree.root.right = new Node(15); tree.root.left.left = new Node(25); tree.root.left.right = new Node(30); tree.root.right.left = new Node(36); // head refers to the head of the Link List Node head = tree.bTreeToCList(tree.root); // Display the Circular LinkedList tree.display(head); }} // This code is contributed by Shrikant13", "e": 49829, "s": 46564, "text": null }, { "code": "<script>// javascript Program to convert a Binary Tree to a// Circular Doubly Linked List // Node class represents a Node of a Treeclass Node { constructor(val) { this.val = val; this.left = null; this.right = null; }} // A class to represent a var root = null; // concatenate both the lists and returns the head // of the List function concatenate(leftList, rightList) { // If either of the list is empty, then // return the other list if (leftList == null) return rightList; if (rightList == null) return leftList; // Store the last Node of left List var leftLast = leftList.left; // Store the last Node of right List var rightLast = rightList.left; // Connect the last node of Left List // with the first Node of the right List leftLast.right = rightList; rightList.left = leftLast; // left of first node refers to // the last node in the list leftList.left = rightLast; // Right of last node refers to the first // node of the List rightLast.right = leftList; // Return the Head of the List return leftList; } // Method converts a to a circular // Link List and then returns the head // of the Link List function bTreeToCList(root) { if (root == null) return null; // Recursively convert left and right subtrees var left = bTreeToCList(root.left); var right = bTreeToCList(root.right); // Make a circular linked list of single node // (or root). To do so, make the right and // left pointers of this node point to itself root.left = root.right = root; // Step 1 (concatenate the left list with the list // with single node, i.e., current node) // Step 2 (concatenate the returned list with the // right List) return concatenate(concatenate(left, root), right); } // Display Circular Link List function display(head) { document.write(\"Circular Linked List is :<br/>\"); var itr = head; do { document.write(itr.val + \" \"); itr = itr.right; } while (itr != head); document.write(); } // Driver Code // Build the root = new Node(10); root.left = new Node(12); root.right = new Node(15); root.left.left = new Node(25); root.left.right = new Node(30); root.right.left = new Node(36); // head refers to the head of the Link List var head = bTreeToCList(root); // Display the Circular LinkedList display(head); // This code contributed by umadevi9616</script>", "e": 52612, "s": 49829, "text": null }, { "code": null, "e": 52622, "s": 52612, "text": "Output: " }, { "code": null, "e": 52666, "s": 52622, "text": "Circular Linked List is :\n25 12 30 10 36 15" }, { "code": null, "e": 53089, "s": 52666, "text": "This article is contributed by Chirag 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": 53101, "s": 53089, "text": "shrikanth13" }, { "code": null, "e": 53117, "s": 53101, "text": "PranchalKatiyar" }, { "code": null, "e": 53129, "s": 53117, "text": "umadevi9616" }, { "code": null, "e": 53145, "s": 53129, "text": "simranarora5sos" }, { "code": null, "e": 53166, "s": 53145, "text": "circular linked list" }, { "code": null, "e": 53185, "s": 53166, "text": "doubly linked list" }, { "code": null, "e": 53194, "s": 53185, "text": "SAP Labs" }, { "code": null, "e": 53206, "s": 53194, "text": "Linked List" }, { "code": null, "e": 53211, "s": 53206, "text": "Tree" }, { "code": null, "e": 53220, "s": 53211, "text": "SAP Labs" }, { "code": null, "e": 53232, "s": 53220, "text": "Linked List" }, { "code": null, "e": 53237, "s": 53232, "text": "Tree" }, { "code": null, "e": 53258, "s": 53237, "text": "circular linked list" }, { "code": null, "e": 53356, "s": 53258, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 53391, "s": 53356, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 53430, "s": 53391, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 53452, "s": 53430, "text": "Reverse a linked list" }, { "code": null, "e": 53500, "s": 53452, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 53538, "s": 53500, "text": "Linked List | Set 3 (Deleting a node)" }, { "code": null, "e": 53588, "s": 53538, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 53623, "s": 53588, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 53652, "s": 53623, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 53686, "s": 53652, "text": "Level Order Binary Tree Traversal" } ]
Tailwind CSS Border Color - GeeksforGeeks
23 Mar, 2022 This class accepts more than one value in tailwind CSS in which all the properties are covered in class form. It is the alternative to the CSS border-color property. This class is used to specify the border color of an element. Border Color classes: border-transparent: The border color will be transparent. border-current: The border will color depend on the parent element color. border-black: The border color will be black. border-white: The border color will be white. border-gray-50: The border color will be gray. border-red-50: The border color will be red. border-blue-50: The border color will be blue. border-indigo-50: The border color will be indigo. border-purple-50: The border color will be purple. border-green-50: The border color will be green. border-yellow-50: The border color will be yellow. border-pink-50: The border color will be pink. Note: The color’s values can be changeable according to your need from 50-900, the span should be 100, after the 100. Syntax: <element class="border-{color}">...</element> Example: HTML <!DOCTYPE html> <head> <link href= "https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center mx-4"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Border Color Class</b> <div class="mx-14 bg-green-200 grid grid-rows-4 grid-flow-col gap-2 text-justify p-2"> <p class="border-2 border-transparent p-2"> A Computer Science Portal for Geeks </p> <p class="border-2 border-current text-red-600 p-2"> A Computer Science Portal for Geeks </p> <p class="border-2 border-white p-2"> A Computer Science Portal for Geeks </p> <p class="border-2 border-black text-white p-2"> A Computer Science Portal for Geeks </p> <p class="border-2 border-gray-700 p-2"> A Computer Science Portal for Geeks </p> <p class="border-2 border-red-700 p-2"> A Computer Science Portal for Geeks </p> <p class="border-2 border-indigo-700 p-2"> A Computer Science Portal for Geeks </p> <p class="border-2 border-blue-700 p-2"> A Computer Science Portal for Geeks </p> <p class="border-2 border-green-700 p-2"> A Computer Science Portal for Geeks </p> <p class="border-2 border-yellow-700 p-2"> A Computer Science Portal for Geeks </p> <p class="border-2 border-pink-700 p-2"> A Computer Science Portal for Geeks </p> <p class="border-2 border-purple-700 p-2"> A Computer Science Portal for Geeks </p> </div> </body> </html> Output: Tailwind CSS Tailwind-Borders CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 37385, "s": 37357, "text": "\n23 Mar, 2022" }, { "code": null, "e": 37614, "s": 37385, "text": "This class accepts more than one value in tailwind CSS in which all the properties are covered in class form. It is the alternative to the CSS border-color property. This class is used to specify the border color of an element. " }, { "code": null, "e": 37636, "s": 37614, "text": "Border Color classes:" }, { "code": null, "e": 37694, "s": 37636, "text": "border-transparent: The border color will be transparent." }, { "code": null, "e": 37769, "s": 37694, "text": "border-current: The border will color depend on the parent element color." }, { "code": null, "e": 37815, "s": 37769, "text": "border-black: The border color will be black." }, { "code": null, "e": 37861, "s": 37815, "text": "border-white: The border color will be white." }, { "code": null, "e": 37908, "s": 37861, "text": "border-gray-50: The border color will be gray." }, { "code": null, "e": 37953, "s": 37908, "text": "border-red-50: The border color will be red." }, { "code": null, "e": 38000, "s": 37953, "text": "border-blue-50: The border color will be blue." }, { "code": null, "e": 38051, "s": 38000, "text": "border-indigo-50: The border color will be indigo." }, { "code": null, "e": 38102, "s": 38051, "text": "border-purple-50: The border color will be purple." }, { "code": null, "e": 38151, "s": 38102, "text": "border-green-50: The border color will be green." }, { "code": null, "e": 38202, "s": 38151, "text": "border-yellow-50: The border color will be yellow." }, { "code": null, "e": 38249, "s": 38202, "text": "border-pink-50: The border color will be pink." }, { "code": null, "e": 38367, "s": 38249, "text": "Note: The color’s values can be changeable according to your need from 50-900, the span should be 100, after the 100." }, { "code": null, "e": 38375, "s": 38367, "text": "Syntax:" }, { "code": null, "e": 38421, "s": 38375, "text": "<element class=\"border-{color}\">...</element>" }, { "code": null, "e": 38430, "s": 38421, "text": "Example:" }, { "code": null, "e": 38435, "s": 38430, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href= \"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center mx-4\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Border Color Class</b> <div class=\"mx-14 bg-green-200 grid grid-rows-4 grid-flow-col gap-2 text-justify p-2\"> <p class=\"border-2 border-transparent p-2\"> A Computer Science Portal for Geeks </p> <p class=\"border-2 border-current text-red-600 p-2\"> A Computer Science Portal for Geeks </p> <p class=\"border-2 border-white p-2\"> A Computer Science Portal for Geeks </p> <p class=\"border-2 border-black text-white p-2\"> A Computer Science Portal for Geeks </p> <p class=\"border-2 border-gray-700 p-2\"> A Computer Science Portal for Geeks </p> <p class=\"border-2 border-red-700 p-2\"> A Computer Science Portal for Geeks </p> <p class=\"border-2 border-indigo-700 p-2\"> A Computer Science Portal for Geeks </p> <p class=\"border-2 border-blue-700 p-2\"> A Computer Science Portal for Geeks </p> <p class=\"border-2 border-green-700 p-2\"> A Computer Science Portal for Geeks </p> <p class=\"border-2 border-yellow-700 p-2\"> A Computer Science Portal for Geeks </p> <p class=\"border-2 border-pink-700 p-2\"> A Computer Science Portal for Geeks </p> <p class=\"border-2 border-purple-700 p-2\"> A Computer Science Portal for Geeks </p> </div> </body> </html> ", "e": 40103, "s": 38435, "text": null }, { "code": null, "e": 40111, "s": 40103, "text": "Output:" }, { "code": null, "e": 40124, "s": 40111, "text": "Tailwind CSS" }, { "code": null, "e": 40141, "s": 40124, "text": "Tailwind-Borders" }, { "code": null, "e": 40145, "s": 40141, "text": "CSS" }, { "code": null, "e": 40162, "s": 40145, "text": "Web Technologies" }, { "code": null, "e": 40260, "s": 40162, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40310, "s": 40260, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 40372, "s": 40310, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 40420, "s": 40372, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 40478, "s": 40420, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 40533, "s": 40478, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 40573, "s": 40533, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 40606, "s": 40573, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 40651, "s": 40606, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40694, "s": 40651, "text": "How to fetch data from an API in ReactJS ?" } ]
Python | All Permutations of a string in lexicographical order without using recursion - GeeksforGeeks
26 Aug, 2019 Write a python program to print all the permutations of a string in lexicographical order. Examples: Input : python Output : hnopty hnopyt hnotpy hnotyp hnoypt ...... ytpnho ytpnoh ytpohn ytponh Input : xyz Output : xyz xzy yxz yzx zxy zyx Method 1:Using the default library itertools function permutations.permutations function will create all the permutations of a given string and then we sort the result to get our desired output. from itertools import permutations def lexicographical_permutation(str): perm = sorted(''.join(chars) for chars in permutations(str)) for x in perm: print(x) str ='abc'lexicographical_permutation(str) Output : abc acb bac bca cab cba Method 2: First we create a loop that will run n! ties where n is the length of the string as there will be n! permutations. Every iteration prints the string and finds its next larger lexicographical permutation to be printed in the next iteration. The next higher permutation is found as :- Let the string is called str, find the smallest index i such that all elements in str[i...end] are in descending order. If str[i...end] is the entire sequence, i.e. i == 0, then str is the highest permutation. So we simply reverse the entire string to get the smallest permutation which we consider as the next permutation. If i > 0, then we reverse str[i...end]. Then we look for the smallest element in str[i...end] that is greater than str[i – 1] and swap its position with str[i – 1]. This is then the next permutation.# import libraryfrom math import factorial def lexicographical_permutations(str): # there are going to be n ! permutations where n = len(seq) for p in range(factorial(len(str))): print(''.join(str)) i = len(str) - 1 # find i such that str[i:] is the largest sequence with # elements in descending lexicographic order while i > 0 and str[i-1] > str[i]: i -= 1 # reverse str[i:] str[i:] = reversed(str[i:]) if i > 0: q = i # find q such that str[q] is the smallest element # in str[p:] such that str[q] > str[i - 1] while str[i-1] > str[q]: q += 1 # swap str[i - 1] and str[q] temp = str[i-1] str[i-1]= str[q] str[q]= temp s = 'abcd's = list(s)s.sort()lexicographical_permutations(s)Output :abcd abdc acbd acdb adbc adcb bacd badc bcad bcda bdac bdca cabd cadb cbad cbda cdab cdba dabc dacb dbac dbca dcab dcbaMy Personal Notes arrow_drop_upSave # import libraryfrom math import factorial def lexicographical_permutations(str): # there are going to be n ! permutations where n = len(seq) for p in range(factorial(len(str))): print(''.join(str)) i = len(str) - 1 # find i such that str[i:] is the largest sequence with # elements in descending lexicographic order while i > 0 and str[i-1] > str[i]: i -= 1 # reverse str[i:] str[i:] = reversed(str[i:]) if i > 0: q = i # find q such that str[q] is the smallest element # in str[p:] such that str[q] > str[i - 1] while str[i-1] > str[q]: q += 1 # swap str[i - 1] and str[q] temp = str[i-1] str[i-1]= str[q] str[q]= temp s = 'abcd's = list(s)s.sort()lexicographical_permutations(s) Output : abcd abdc acbd acdb adbc adcb bacd badc bcad bcda bdac bdca cabd cadb cbad cbda cdab cdba dabc dacb dbac dbca dcab dcba Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Convert integer to string in Python
[ { "code": null, "e": 26269, "s": 26241, "text": "\n26 Aug, 2019" }, { "code": null, "e": 26360, "s": 26269, "text": "Write a python program to print all the permutations of a string in lexicographical order." }, { "code": null, "e": 26370, "s": 26360, "text": "Examples:" }, { "code": null, "e": 26514, "s": 26370, "text": "Input : python\nOutput : hnopty\nhnopyt\nhnotpy\nhnotyp\nhnoypt\n......\nytpnho\nytpnoh\nytpohn\nytponh\n\nInput : xyz\nOutput : xyz\nxzy\nyxz\nyzx\nzxy\nzyx\n\n" }, { "code": null, "e": 26709, "s": 26514, "text": "Method 1:Using the default library itertools function permutations.permutations function will create all the permutations of a given string and then we sort the result to get our desired output." }, { "code": "from itertools import permutations def lexicographical_permutation(str): perm = sorted(''.join(chars) for chars in permutations(str)) for x in perm: print(x) str ='abc'lexicographical_permutation(str)", "e": 26933, "s": 26709, "text": null }, { "code": null, "e": 26942, "s": 26933, "text": "Output :" }, { "code": null, "e": 26966, "s": 26942, "text": "abc\nacb\nbac\nbca\ncab\ncba" }, { "code": null, "e": 26976, "s": 26966, "text": "Method 2:" }, { "code": null, "e": 27091, "s": 26976, "text": "First we create a loop that will run n! ties where n is the length of the string as there will be n! permutations." }, { "code": null, "e": 27216, "s": 27091, "text": "Every iteration prints the string and finds its next larger lexicographical permutation to be printed in the next iteration." }, { "code": null, "e": 27259, "s": 27216, "text": "The next higher permutation is found as :-" }, { "code": null, "e": 27379, "s": 27259, "text": "Let the string is called str, find the smallest index i such that all elements in str[i...end] are in descending order." }, { "code": null, "e": 27583, "s": 27379, "text": "If str[i...end] is the entire sequence, i.e. i == 0, then str is the highest permutation. So we simply reverse the entire string to get the smallest permutation which we consider as the next permutation." }, { "code": null, "e": 27623, "s": 27583, "text": "If i > 0, then we reverse str[i...end]." }, { "code": null, "e": 27748, "s": 27623, "text": "Then we look for the smallest element in str[i...end] that is greater than str[i – 1] and swap its position with str[i – 1]." }, { "code": null, "e": 28917, "s": 27748, "text": "This is then the next permutation.# import libraryfrom math import factorial def lexicographical_permutations(str): # there are going to be n ! permutations where n = len(seq) for p in range(factorial(len(str))): print(''.join(str)) i = len(str) - 1 # find i such that str[i:] is the largest sequence with # elements in descending lexicographic order while i > 0 and str[i-1] > str[i]: i -= 1 # reverse str[i:] str[i:] = reversed(str[i:]) if i > 0: q = i # find q such that str[q] is the smallest element # in str[p:] such that str[q] > str[i - 1] while str[i-1] > str[q]: q += 1 # swap str[i - 1] and str[q] temp = str[i-1] str[i-1]= str[q] str[q]= temp s = 'abcd's = list(s)s.sort()lexicographical_permutations(s)Output :abcd\nabdc\nacbd\nacdb\nadbc\nadcb\nbacd\nbadc\nbcad\nbcda\nbdac\nbdca\ncabd\ncadb\ncbad\ncbda\ncdab\ncdba\ndabc\ndacb\ndbac\ndbca\ndcab\ndcbaMy Personal Notes\narrow_drop_upSave" }, { "code": "# import libraryfrom math import factorial def lexicographical_permutations(str): # there are going to be n ! permutations where n = len(seq) for p in range(factorial(len(str))): print(''.join(str)) i = len(str) - 1 # find i such that str[i:] is the largest sequence with # elements in descending lexicographic order while i > 0 and str[i-1] > str[i]: i -= 1 # reverse str[i:] str[i:] = reversed(str[i:]) if i > 0: q = i # find q such that str[q] is the smallest element # in str[p:] such that str[q] > str[i - 1] while str[i-1] > str[q]: q += 1 # swap str[i - 1] and str[q] temp = str[i-1] str[i-1]= str[q] str[q]= temp s = 'abcd's = list(s)s.sort()lexicographical_permutations(s)", "e": 29890, "s": 28917, "text": null }, { "code": null, "e": 29899, "s": 29890, "text": "Output :" }, { "code": null, "e": 30019, "s": 29899, "text": "abcd\nabdc\nacbd\nacdb\nadbc\nadcb\nbacd\nbadc\nbcad\nbcda\nbdac\nbdca\ncabd\ncadb\ncbad\ncbda\ncdab\ncdba\ndabc\ndacb\ndbac\ndbca\ndcab\ndcba" }, { "code": null, "e": 30026, "s": 30019, "text": "Python" }, { "code": null, "e": 30124, "s": 30026, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30142, "s": 30124, "text": "Python Dictionary" }, { "code": null, "e": 30177, "s": 30142, "text": "Read a file line by line in Python" }, { "code": null, "e": 30209, "s": 30177, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30231, "s": 30209, "text": "Enumerate() in Python" }, { "code": null, "e": 30273, "s": 30231, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30303, "s": 30273, "text": "Iterate over a list in Python" }, { "code": null, "e": 30329, "s": 30303, "text": "Python String | replace()" }, { "code": null, "e": 30373, "s": 30329, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 30402, "s": 30373, "text": "*args and **kwargs in Python" } ]
HTML | DOM IFrame contentDocument Property - GeeksforGeeks
30 Sep, 2019 The IFrame contentDocument property in HTML DOM is used to return the document object generated by a frame or iframe element. It can be used in the host window to access the document object that belongs to a frame or iframe element. Syntax: iframeObject.contentDocument Return Value: It returns the reference of the document object. If there is no object available then it returns null. Example: <!DOCTYPE html> <html> <head> <title> HTML DOM iframe contentDocument Property </title> </head> <body style="text-align:center;"> <h1>GeeksforGeeks</h1> <h2> HTML DOM iframe contentDocument Property </h2> <iframe src="https://ide.geeksforgeeks.org/index.php" id="GFG" height="200" width="400"> </iframe> <br><br> <button onclick="Geeks()"> Submit </button> <script> function Geeks() { var iframeID = document.getElementById("GFG"); var iframeCW = (iframeID.contentWindow || iframeID.contentDocument); if (iframeCW.document)iframeCW = iframeCW.document; iframeCW.body.style.border = "5px solid black"; } </script> </body> </html> Before Clicking on the Button: After Clicking on the Button: Supported Browsers: The browsers supported by HTML DOM IFrame contentDocument property are listed below: 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. HTML-DOM HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) How to Insert Form Data into Database using PHP ? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? HTML | <img> align Attribute 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": 26037, "s": 26009, "text": "\n30 Sep, 2019" }, { "code": null, "e": 26270, "s": 26037, "text": "The IFrame contentDocument property in HTML DOM is used to return the document object generated by a frame or iframe element. It can be used in the host window to access the document object that belongs to a frame or iframe element." }, { "code": null, "e": 26278, "s": 26270, "text": "Syntax:" }, { "code": null, "e": 26308, "s": 26278, "text": "iframeObject.contentDocument " }, { "code": null, "e": 26425, "s": 26308, "text": "Return Value: It returns the reference of the document object. If there is no object available then it returns null." }, { "code": null, "e": 26434, "s": 26425, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title> HTML DOM iframe contentDocument Property </title> </head> <body style=\"text-align:center;\"> <h1>GeeksforGeeks</h1> <h2> HTML DOM iframe contentDocument Property </h2> <iframe src=\"https://ide.geeksforgeeks.org/index.php\" id=\"GFG\" height=\"200\" width=\"400\"> </iframe> <br><br> <button onclick=\"Geeks()\"> Submit </button> <script> function Geeks() { var iframeID = document.getElementById(\"GFG\"); var iframeCW = (iframeID.contentWindow || iframeID.contentDocument); if (iframeCW.document)iframeCW = iframeCW.document; iframeCW.body.style.border = \"5px solid black\"; } </script> </body> </html>", "e": 27286, "s": 26434, "text": null }, { "code": null, "e": 27317, "s": 27286, "text": "Before Clicking on the Button:" }, { "code": null, "e": 27347, "s": 27317, "text": "After Clicking on the Button:" }, { "code": null, "e": 27452, "s": 27347, "text": "Supported Browsers: The browsers supported by HTML DOM IFrame contentDocument property are listed below:" }, { "code": null, "e": 27466, "s": 27452, "text": "Google Chrome" }, { "code": null, "e": 27484, "s": 27466, "text": "Internet Explorer" }, { "code": null, "e": 27492, "s": 27484, "text": "Firefox" }, { "code": null, "e": 27499, "s": 27492, "text": "Safari" }, { "code": null, "e": 27505, "s": 27499, "text": "Opera" }, { "code": null, "e": 27642, "s": 27505, "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": 27651, "s": 27642, "text": "HTML-DOM" }, { "code": null, "e": 27656, "s": 27651, "text": "HTML" }, { "code": null, "e": 27673, "s": 27656, "text": "Web Technologies" }, { "code": null, "e": 27678, "s": 27673, "text": "HTML" }, { "code": null, "e": 27776, "s": 27678, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27800, "s": 27776, "text": "REST API (Introduction)" }, { "code": null, "e": 27850, "s": 27800, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27887, "s": 27850, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27951, "s": 27887, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 27980, "s": 27951, "text": "HTML | <img> align Attribute" }, { "code": null, "e": 28020, "s": 27980, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28053, "s": 28020, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28098, "s": 28053, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28141, "s": 28098, "text": "How to fetch data from an API in ReactJS ?" } ]
Perl | rename() Function - GeeksforGeeks
25 Jun, 2019 rename() function in Perl renames the old name of a file to a new name as given by the user. Syntax: rename(old_file_path, new_file_path) Parameters:old_file_path: path of the old file along with its namenew_file_path: path of the new file along with its name Returns0 on failure and 1 on success Example: #!/usr/bin/perl -w # Calling the rename() function # with required parametersrename("D:/GeeksforGeeks/GFG File.txt", "D:/GeeksforGeeks/GFG File 2.txt") || die ( "Error in renaming" ); Output: Original File: Running the Command: Updated File: Steps to Run the above code:Step1: Create a file anywhere in your System and copy the File Path.Step 2: Provide the path of your File in the code above and save it as .pl extension.Step 3: Run the above code in Command line as perl Filename.pl.Step 4: Name of the File is now changed with the new name provided. Perl-File-Functions Perl-function Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl Tutorial - Learn Perl With Examples Perl | Basic Syntax of a Perl Program Perl | Inheritance in OOPs Perl | Opening and Reading a File Perl | Multidimensional Hashes Perl | Scope of Variables Perl | ne operator Perl | Hashes Perl | Data Types Perl | defined() Function
[ { "code": null, "e": 25315, "s": 25287, "text": "\n25 Jun, 2019" }, { "code": null, "e": 25408, "s": 25315, "text": "rename() function in Perl renames the old name of a file to a new name as given by the user." }, { "code": null, "e": 25453, "s": 25408, "text": "Syntax: rename(old_file_path, new_file_path)" }, { "code": null, "e": 25575, "s": 25453, "text": "Parameters:old_file_path: path of the old file along with its namenew_file_path: path of the new file along with its name" }, { "code": null, "e": 25612, "s": 25575, "text": "Returns0 on failure and 1 on success" }, { "code": null, "e": 25621, "s": 25612, "text": "Example:" }, { "code": "#!/usr/bin/perl -w # Calling the rename() function # with required parametersrename(\"D:/GeeksforGeeks/GFG File.txt\", \"D:/GeeksforGeeks/GFG File 2.txt\") || die ( \"Error in renaming\" );", "e": 25818, "s": 25621, "text": null }, { "code": null, "e": 25826, "s": 25818, "text": "Output:" }, { "code": null, "e": 25842, "s": 25826, "text": "Original File: " }, { "code": null, "e": 25864, "s": 25842, "text": "Running the Command: " }, { "code": null, "e": 26191, "s": 25864, "text": "Updated File: Steps to Run the above code:Step1: Create a file anywhere in your System and copy the File Path.Step 2: Provide the path of your File in the code above and save it as .pl extension.Step 3: Run the above code in Command line as perl Filename.pl.Step 4: Name of the File is now changed with the new name provided." }, { "code": null, "e": 26211, "s": 26191, "text": "Perl-File-Functions" }, { "code": null, "e": 26225, "s": 26211, "text": "Perl-function" }, { "code": null, "e": 26230, "s": 26225, "text": "Perl" }, { "code": null, "e": 26235, "s": 26230, "text": "Perl" }, { "code": null, "e": 26333, "s": 26235, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26374, "s": 26333, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 26412, "s": 26374, "text": "Perl | Basic Syntax of a Perl Program" }, { "code": null, "e": 26439, "s": 26412, "text": "Perl | Inheritance in OOPs" }, { "code": null, "e": 26473, "s": 26439, "text": "Perl | Opening and Reading a File" }, { "code": null, "e": 26504, "s": 26473, "text": "Perl | Multidimensional Hashes" }, { "code": null, "e": 26530, "s": 26504, "text": "Perl | Scope of Variables" }, { "code": null, "e": 26549, "s": 26530, "text": "Perl | ne operator" }, { "code": null, "e": 26563, "s": 26549, "text": "Perl | Hashes" }, { "code": null, "e": 26581, "s": 26563, "text": "Perl | Data Types" } ]
How to Crop an Image using the Numpy Module? - GeeksforGeeks
12 Nov, 2020 In this article, we are going to learn about the most naive and efficient approach to crop an image without using any additional module. The numpy module is a Python library used for working with arrays, and large data sets. Python does not have any native support for arrays, as opposed to other high-level languages such as C, C++, Java, etc. which provides an implementation for arrays natively. Python rather has Linked lists, which does solve the problem for static allocation (mostly) and allows for storage of heterogeneous data, but does not allow for contiguous storage of data. Numpy makes up for this drawback by introducing arrays in the language which are a homogeneous data structure and are stored in contiguous memory locations. Since the data inside an image (excluding the header info) is homogeneous, and are generally accessed sequentially or by direct access (via adding offsets), using arrays for storing image pixel data is allows for faster operations on the image. In this article, we will take a look at cropping an image using Numpy arrays (containing pixel information). There are various methods in many modules to crop an image, the most naive and efficient approach to crop an image is to use indexing of numpy arrays. Since Numpy doesn’t support the image cropping method natively (since it not being an image processing library), we can use the indexing methods to fulfill our purpose. For Demonstration, we would be using the following image:- The following image is has 4K (3840×2160) dimensions. We would be cropping the above image such that the logo in the middle occupies a large part of the image. Since cropping image is *generally a manual thing to do, we would have to get the coordinates to the Region of Interest beforehand. 4 coordinates (or a pair of size 2 tuples) are required for cropping. The first set of coordinates specify the Top left corner of the ROI (or Bbox) and the next two denote the bottom right corner coordinates of the ROI. For our case the coordinates for the ROI would be (1413, 653) and (2361, 1385) (assuming row-major indexing is used). For displaying and reading the image, we would be taking the help of Pillow library, which is an image processing library in python. Below is the program to crop a given image: Python3 # Import required modulesfrom PIL import Imageimport numpy as np # Load imageimage = Image.open('W3.jpg') # Convert image to arrayimage_arr = numpy.array(image) # Crop imageimage_arr = image_arr[700:1400, 1450:2361] # Convert array to imageimage = Image.fromarray(image_arr) # Display imageimage.show() Output: Explanation: Firstly we imported the Image module of the PIL (or pillow) library. Then we imported the Numpy library under the alias np (common convention). After which we created an Image object of our desired image (W3.jpg), and stored the object in the variable image. So, the image variable is of type PIL.JpegImagePlugin.JpegImageFile. To create Numpy array out of this object, we passed it through the np.array() method, which extracted all the Pixel data from the image and stored it in the variable image_arr. This resulted us in having a Numpy array of shape (2160, 3840, 3). Then we sliced the array from each dimension. In the statement image_arr[700:1400, 1450:2361] the 700 is denoting the starting row, and 1400 is denoting the ending row. Where, 1450 represents starting column, and 2316 represents the ending column. All these values depict the pixel at the location, therefore the crop with the top left coordinates of (1450, 700) and bottom left coordinates of (2361, 1400). Finally, we converted the Numpy array back to an image using Image.fromarray(). In the end we displayed the image using the show() 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 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": "\n12 Nov, 2020" }, { "code": null, "e": 25674, "s": 25537, "text": "In this article, we are going to learn about the most naive and efficient approach to crop an image without using any additional module." }, { "code": null, "e": 26282, "s": 25674, "text": "The numpy module is a Python library used for working with arrays, and large data sets. Python does not have any native support for arrays, as opposed to other high-level languages such as C, C++, Java, etc. which provides an implementation for arrays natively. Python rather has Linked lists, which does solve the problem for static allocation (mostly) and allows for storage of heterogeneous data, but does not allow for contiguous storage of data. Numpy makes up for this drawback by introducing arrays in the language which are a homogeneous data structure and are stored in contiguous memory locations." }, { "code": null, "e": 26637, "s": 26282, "text": "Since the data inside an image (excluding the header info) is homogeneous, and are generally accessed sequentially or by direct access (via adding offsets), using arrays for storing image pixel data is allows for faster operations on the image. In this article, we will take a look at cropping an image using Numpy arrays (containing pixel information). " }, { "code": null, "e": 26789, "s": 26637, "text": "There are various methods in many modules to crop an image, the most naive and efficient approach to crop an image is to use indexing of numpy arrays. " }, { "code": null, "e": 27017, "s": 26789, "text": "Since Numpy doesn’t support the image cropping method natively (since it not being an image processing library), we can use the indexing methods to fulfill our purpose. For Demonstration, we would be using the following image:-" }, { "code": null, "e": 27072, "s": 27017, "text": "The following image is has 4K (3840×2160) dimensions. " }, { "code": null, "e": 27179, "s": 27072, "text": "We would be cropping the above image such that the logo in the middle occupies a large part of the image. " }, { "code": null, "e": 27783, "s": 27179, "text": "Since cropping image is *generally a manual thing to do, we would have to get the coordinates to the Region of Interest beforehand. 4 coordinates (or a pair of size 2 tuples) are required for cropping. The first set of coordinates specify the Top left corner of the ROI (or Bbox) and the next two denote the bottom right corner coordinates of the ROI. For our case the coordinates for the ROI would be (1413, 653) and (2361, 1385) (assuming row-major indexing is used). For displaying and reading the image, we would be taking the help of Pillow library, which is an image processing library in python." }, { "code": null, "e": 27827, "s": 27783, "text": "Below is the program to crop a given image:" }, { "code": null, "e": 27835, "s": 27827, "text": "Python3" }, { "code": "# Import required modulesfrom PIL import Imageimport numpy as np # Load imageimage = Image.open('W3.jpg') # Convert image to arrayimage_arr = numpy.array(image) # Crop imageimage_arr = image_arr[700:1400, 1450:2361] # Convert array to imageimage = Image.fromarray(image_arr) # Display imageimage.show()", "e": 28143, "s": 27835, "text": null }, { "code": null, "e": 28151, "s": 28143, "text": "Output:" }, { "code": null, "e": 28164, "s": 28151, "text": "Explanation:" }, { "code": null, "e": 28493, "s": 28164, "text": "Firstly we imported the Image module of the PIL (or pillow) library. Then we imported the Numpy library under the alias np (common convention). After which we created an Image object of our desired image (W3.jpg), and stored the object in the variable image. So, the image variable is of type PIL.JpegImagePlugin.JpegImageFile. " }, { "code": null, "e": 28738, "s": 28493, "text": "To create Numpy array out of this object, we passed it through the np.array() method, which extracted all the Pixel data from the image and stored it in the variable image_arr. This resulted us in having a Numpy array of shape (2160, 3840, 3). " }, { "code": null, "e": 29147, "s": 28738, "text": "Then we sliced the array from each dimension. In the statement image_arr[700:1400, 1450:2361] the 700 is denoting the starting row, and 1400 is denoting the ending row. Where, 1450 represents starting column, and 2316 represents the ending column. All these values depict the pixel at the location, therefore the crop with the top left coordinates of (1450, 700) and bottom left coordinates of (2361, 1400). " }, { "code": null, "e": 29290, "s": 29147, "text": "Finally, we converted the Numpy array back to an image using Image.fromarray(). In the end we displayed the image using the show() function. " }, { "code": null, "e": 29303, "s": 29290, "text": "Python-numpy" }, { "code": null, "e": 29310, "s": 29303, "text": "Python" }, { "code": null, "e": 29408, "s": 29310, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29440, "s": 29408, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29482, "s": 29440, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29524, "s": 29482, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29551, "s": 29524, "text": "Python Classes and Objects" }, { "code": null, "e": 29607, "s": 29551, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29629, "s": 29607, "text": "Defaultdict in Python" }, { "code": null, "e": 29668, "s": 29629, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29699, "s": 29668, "text": "Python | os.path.join() method" }, { "code": null, "e": 29728, "s": 29699, "text": "Create a directory in Python" } ]