title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to sort element by numerical value of data attribute using JavaScript ?
02 Mar, 2020 The task is to sort numeric data attribute, there are many ways to sort the HTML elements by the numerical value of data-attributes with the help of JavaScript. In this article, we will explain popular and less time-consuming ones. Example 1: First, select the outer element(var outer). Get children of outer element by using .find() method and apply sort() method on children of outer. Return the difference between 2 elements by accessing their property by el.dataset.percentage property. Program:<!DOCTYPE HTML><html> <head> <title> Sort element by numerical value of data attribute with JavaScript </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> .outer { width: 200px; } .child { margin: 10px; } h1 { color: green; } #geeks { color: green; font-size: 16px; font-weight: bold; } </style></head> <body id="body"> <center> <h1> GeeksforGeeks </h1> <b> Click on button to perform operation </b> <br> <div class="outer"> <div class="child" data-percentage="34">34</div> <div class="child" data-percentage="61">61</div> <div class="child" data-percentage="17">17</div> <div class="child" data-percentage="49">49</div> </div> <br> <button onClick="GFG_Fun()"> click here </button> <p id="geeks"></p> <script> var down = document.getElementById('geeks'); // Main function function GFG_Fun() { var $wrap = $('.outer'); $wrap.find('.child').sort(function(a, b) { return +a.dataset.percentage - +b.dataset.percentage; }) .appendTo($wrap); down.innerHTML = "Elements sorted"; } </script> </center></body> </html> <!DOCTYPE HTML><html> <head> <title> Sort element by numerical value of data attribute with JavaScript </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> .outer { width: 200px; } .child { margin: 10px; } h1 { color: green; } #geeks { color: green; font-size: 16px; font-weight: bold; } </style></head> <body id="body"> <center> <h1> GeeksforGeeks </h1> <b> Click on button to perform operation </b> <br> <div class="outer"> <div class="child" data-percentage="34">34</div> <div class="child" data-percentage="61">61</div> <div class="child" data-percentage="17">17</div> <div class="child" data-percentage="49">49</div> </div> <br> <button onClick="GFG_Fun()"> click here </button> <p id="geeks"></p> <script> var down = document.getElementById('geeks'); // Main function function GFG_Fun() { var $wrap = $('.outer'); $wrap.find('.child').sort(function(a, b) { return +a.dataset.percentage - +b.dataset.percentage; }) .appendTo($wrap); down.innerHTML = "Elements sorted"; } </script> </center></body> </html> Output: Example 2: First, select the outer element(var outer). Get children of outer by .find() method and apply sort() method on children of outer. Return the difference between 2 elements by accessing their property by el.getAttribute(‘data-percentage’) . Program:<!DOCTYPE HTML><html> <head> <title> Sort element by numerical value of data attribute with JavaScript </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> .outer { width: 200px; } .child { margin: 10px; } h1 { color: green; } #geeks { color: green; font-size: 16px; font-weight: bold; } </style></head> <body id="body"> <center> <h1> GeeksforGeeks </h1> <b> Click on button to perform operation </b> <br> <div class="outer"> <div class="child" data-percentage="34">34</div> <div class="child" data-percentage="61">61</div> <div class="child" data-percentage="17">17</div> <div class="child" data-percentage="49">49</div> </div> <br> <button onClick="GFG_Fun()"> click here </button> <p id="geeks"></p> <script> var down = document.getElementById('geeks'); // Main function function GFG_Fun() { var $wrap = $('.outer'); $wrap.find('.child').sort(function(a, b) { return + a.getAttribute('data-percentage') - +b.getAttribute('data-percentage'); }) .appendTo($wrap); down.innerHTML = "Elements sorted"; } </script> </center></body> </html> <!DOCTYPE HTML><html> <head> <title> Sort element by numerical value of data attribute with JavaScript </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> .outer { width: 200px; } .child { margin: 10px; } h1 { color: green; } #geeks { color: green; font-size: 16px; font-weight: bold; } </style></head> <body id="body"> <center> <h1> GeeksforGeeks </h1> <b> Click on button to perform operation </b> <br> <div class="outer"> <div class="child" data-percentage="34">34</div> <div class="child" data-percentage="61">61</div> <div class="child" data-percentage="17">17</div> <div class="child" data-percentage="49">49</div> </div> <br> <button onClick="GFG_Fun()"> click here </button> <p id="geeks"></p> <script> var down = document.getElementById('geeks'); // Main function function GFG_Fun() { var $wrap = $('.outer'); $wrap.find('.child').sort(function(a, b) { return + a.getAttribute('data-percentage') - +b.getAttribute('data-percentage'); }) .appendTo($wrap); down.innerHTML = "Elements sorted"; } </script> </center></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Mar, 2020" }, { "code": null, "e": 260, "s": 28, "text": "The task is to sort numeric data attribute, there are many ways to sort the HTML elements by the numerical value of data-attributes with the help of JavaScript. In this article, we will explain popular and less time-consuming ones." }, { "code": null, "e": 519, "s": 260, "text": "Example 1: First, select the outer element(var outer). Get children of outer element by using .find() method and apply sort() method on children of outer. Return the difference between 2 elements by accessing their property by el.dataset.percentage property." }, { "code": null, "e": 2244, "s": 519, "text": "Program:<!DOCTYPE HTML><html> <head> <title> Sort element by numerical value of data attribute with JavaScript </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> .outer { width: 200px; } .child { margin: 10px; } h1 { color: green; } #geeks { color: green; font-size: 16px; font-weight: bold; } </style></head> <body id=\"body\"> <center> <h1> GeeksforGeeks </h1> <b> Click on button to perform operation </b> <br> <div class=\"outer\"> <div class=\"child\" data-percentage=\"34\">34</div> <div class=\"child\" data-percentage=\"61\">61</div> <div class=\"child\" data-percentage=\"17\">17</div> <div class=\"child\" data-percentage=\"49\">49</div> </div> <br> <button onClick=\"GFG_Fun()\"> click here </button> <p id=\"geeks\"></p> <script> var down = document.getElementById('geeks'); // Main function function GFG_Fun() { var $wrap = $('.outer'); $wrap.find('.child').sort(function(a, b) { return +a.dataset.percentage - +b.dataset.percentage; }) .appendTo($wrap); down.innerHTML = \"Elements sorted\"; } </script> </center></body> </html>" }, { "code": "<!DOCTYPE HTML><html> <head> <title> Sort element by numerical value of data attribute with JavaScript </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> .outer { width: 200px; } .child { margin: 10px; } h1 { color: green; } #geeks { color: green; font-size: 16px; font-weight: bold; } </style></head> <body id=\"body\"> <center> <h1> GeeksforGeeks </h1> <b> Click on button to perform operation </b> <br> <div class=\"outer\"> <div class=\"child\" data-percentage=\"34\">34</div> <div class=\"child\" data-percentage=\"61\">61</div> <div class=\"child\" data-percentage=\"17\">17</div> <div class=\"child\" data-percentage=\"49\">49</div> </div> <br> <button onClick=\"GFG_Fun()\"> click here </button> <p id=\"geeks\"></p> <script> var down = document.getElementById('geeks'); // Main function function GFG_Fun() { var $wrap = $('.outer'); $wrap.find('.child').sort(function(a, b) { return +a.dataset.percentage - +b.dataset.percentage; }) .appendTo($wrap); down.innerHTML = \"Elements sorted\"; } </script> </center></body> </html>", "e": 3961, "s": 2244, "text": null }, { "code": null, "e": 3969, "s": 3961, "text": "Output:" }, { "code": null, "e": 4219, "s": 3969, "text": "Example 2: First, select the outer element(var outer). Get children of outer by .find() method and apply sort() method on children of outer. Return the difference between 2 elements by accessing their property by el.getAttribute(‘data-percentage’) ." }, { "code": null, "e": 5948, "s": 4219, "text": "Program:<!DOCTYPE HTML><html> <head> <title> Sort element by numerical value of data attribute with JavaScript </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> .outer { width: 200px; } .child { margin: 10px; } h1 { color: green; } #geeks { color: green; font-size: 16px; font-weight: bold; } </style></head> <body id=\"body\"> <center> <h1> GeeksforGeeks </h1> <b> Click on button to perform operation </b> <br> <div class=\"outer\"> <div class=\"child\" data-percentage=\"34\">34</div> <div class=\"child\" data-percentage=\"61\">61</div> <div class=\"child\" data-percentage=\"17\">17</div> <div class=\"child\" data-percentage=\"49\">49</div> </div> <br> <button onClick=\"GFG_Fun()\"> click here </button> <p id=\"geeks\"></p> <script> var down = document.getElementById('geeks'); // Main function function GFG_Fun() { var $wrap = $('.outer'); $wrap.find('.child').sort(function(a, b) { return + a.getAttribute('data-percentage') - +b.getAttribute('data-percentage'); }) .appendTo($wrap); down.innerHTML = \"Elements sorted\"; } </script> </center></body> </html>" }, { "code": "<!DOCTYPE HTML><html> <head> <title> Sort element by numerical value of data attribute with JavaScript </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> .outer { width: 200px; } .child { margin: 10px; } h1 { color: green; } #geeks { color: green; font-size: 16px; font-weight: bold; } </style></head> <body id=\"body\"> <center> <h1> GeeksforGeeks </h1> <b> Click on button to perform operation </b> <br> <div class=\"outer\"> <div class=\"child\" data-percentage=\"34\">34</div> <div class=\"child\" data-percentage=\"61\">61</div> <div class=\"child\" data-percentage=\"17\">17</div> <div class=\"child\" data-percentage=\"49\">49</div> </div> <br> <button onClick=\"GFG_Fun()\"> click here </button> <p id=\"geeks\"></p> <script> var down = document.getElementById('geeks'); // Main function function GFG_Fun() { var $wrap = $('.outer'); $wrap.find('.child').sort(function(a, b) { return + a.getAttribute('data-percentage') - +b.getAttribute('data-percentage'); }) .appendTo($wrap); down.innerHTML = \"Elements sorted\"; } </script> </center></body> </html>", "e": 7669, "s": 5948, "text": null }, { "code": null, "e": 7677, "s": 7669, "text": "Output:" }, { "code": null, "e": 7686, "s": 7677, "text": "CSS-Misc" }, { "code": null, "e": 7696, "s": 7686, "text": "HTML-Misc" }, { "code": null, "e": 7712, "s": 7696, "text": "JavaScript-Misc" }, { "code": null, "e": 7716, "s": 7712, "text": "CSS" }, { "code": null, "e": 7721, "s": 7716, "text": "HTML" }, { "code": null, "e": 7732, "s": 7721, "text": "JavaScript" }, { "code": null, "e": 7749, "s": 7732, "text": "Web Technologies" }, { "code": null, "e": 7776, "s": 7749, "text": "Web technologies Questions" }, { "code": null, "e": 7781, "s": 7776, "text": "HTML" } ]
Java - sin() Method
The method returns the sine of the specified double value. double sin(double d) Here is the detail of parameters − d − A double data type. d − A double data type. This method returns the sine of the specified double value. This method returns the sine of the specified double value. public class Test { public static void main(String args[]) { double degrees = 45.0; double radians = Math.toRadians(degrees); System.out.format("The value of pi is %.4f%n", Math.PI); System.out.format("The sine of %.1f degrees is %.4f%n", degrees, Math.sin(radians)); } } This will produce the following result − The value of pi is 3.1416 The sine of 45.0 degrees is 0.7071
[ { "code": null, "e": 2570, "s": 2511, "text": "The method returns the sine of the specified double value." }, { "code": null, "e": 2592, "s": 2570, "text": "double sin(double d)\n" }, { "code": null, "e": 2627, "s": 2592, "text": "Here is the detail of parameters −" }, { "code": null, "e": 2651, "s": 2627, "text": "d − A double data type." }, { "code": null, "e": 2675, "s": 2651, "text": "d − A double data type." }, { "code": null, "e": 2735, "s": 2675, "text": "This method returns the sine of the specified double value." }, { "code": null, "e": 2795, "s": 2735, "text": "This method returns the sine of the specified double value." }, { "code": null, "e": 3099, "s": 2795, "text": "public class Test {\n\n public static void main(String args[]) {\n double degrees = 45.0;\n double radians = Math.toRadians(degrees);\n\n System.out.format(\"The value of pi is %.4f%n\", Math.PI);\n System.out.format(\"The sine of %.1f degrees is %.4f%n\", degrees, Math.sin(radians));\n }\n}" }, { "code": null, "e": 3140, "s": 3099, "text": "This will produce the following result −" } ]
Java Math round() method with Example
11 Apr, 2018 The java.lang.Math.round() is a built-in math function which returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result after adding 1/2, and casting the result to type long. If the argument is NaN, the result is 0. If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE. If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE. Syntax: public static int round(float val) Parameter: val - floating-point value to be rounded to an integer. Returns:The method returns the value of the argument rounded to the nearest int value. Example: To show working of java.lang.Math.round() function // Java program to demonstrate working// of java.lang.Math.round() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { // float numbers float x = 4567.9874f; // find the closest int for these floats System.out.println(Math.round(x)); float y = -3421.134f; // find the closest int for these floats System.out.println(Math.round(y)); double positiveInfinity = Double.POSITIVE_INFINITY; // returns the Integer.MAX_VALUE value when System.out.println(Math.round(positiveInfinity)); }} Output: 4568 -3421 9223372036854775807 Java-lang package java-math Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Stream In Java Collections in Java Singleton Class in Java Set in Java Initializing a List in Java Introduction to Java Multithreading in Java Constructors in Java Exceptions in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Apr, 2018" }, { "code": null, "e": 292, "s": 52, "text": "The java.lang.Math.round() is a built-in math function which returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result after adding 1/2, and casting the result to type long." }, { "code": null, "e": 333, "s": 292, "text": "If the argument is NaN, the result is 0." }, { "code": null, "e": 492, "s": 333, "text": "If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE." }, { "code": null, "e": 654, "s": 492, "text": "If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE." }, { "code": null, "e": 662, "s": 654, "text": "Syntax:" }, { "code": null, "e": 767, "s": 662, "text": "public static int round(float val)\nParameter: \nval - floating-point value to be rounded to an integer. \n" }, { "code": null, "e": 854, "s": 767, "text": "Returns:The method returns the value of the argument rounded to the nearest int value." }, { "code": null, "e": 914, "s": 854, "text": "Example: To show working of java.lang.Math.round() function" }, { "code": "// Java program to demonstrate working// of java.lang.Math.round() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { // float numbers float x = 4567.9874f; // find the closest int for these floats System.out.println(Math.round(x)); float y = -3421.134f; // find the closest int for these floats System.out.println(Math.round(y)); double positiveInfinity = Double.POSITIVE_INFINITY; // returns the Integer.MAX_VALUE value when System.out.println(Math.round(positiveInfinity)); }}", "e": 1546, "s": 914, "text": null }, { "code": null, "e": 1554, "s": 1546, "text": "Output:" }, { "code": null, "e": 1586, "s": 1554, "text": "4568\n-3421\n9223372036854775807\n" }, { "code": null, "e": 1604, "s": 1586, "text": "Java-lang package" }, { "code": null, "e": 1614, "s": 1604, "text": "java-math" }, { "code": null, "e": 1619, "s": 1614, "text": "Java" }, { "code": null, "e": 1624, "s": 1619, "text": "Java" }, { "code": null, "e": 1722, "s": 1624, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1741, "s": 1722, "text": "Interfaces in Java" }, { "code": null, "e": 1756, "s": 1741, "text": "Stream In Java" }, { "code": null, "e": 1776, "s": 1756, "text": "Collections in Java" }, { "code": null, "e": 1800, "s": 1776, "text": "Singleton Class in Java" }, { "code": null, "e": 1812, "s": 1800, "text": "Set in Java" }, { "code": null, "e": 1840, "s": 1812, "text": "Initializing a List in Java" }, { "code": null, "e": 1861, "s": 1840, "text": "Introduction to Java" }, { "code": null, "e": 1884, "s": 1861, "text": "Multithreading in Java" }, { "code": null, "e": 1905, "s": 1884, "text": "Constructors in Java" } ]
CSS
CSS is acronym of Cascading Style Sheets. It helps to define the presentation of HTML elements as a separate file known as CSS file having .css extension. CSS helps to change formatting of any HTML element by just making changes at one place. All changes made would be reflected automatically to all of the web pages of the website in which that element appeared. CSS Rules are the styles that we have to create in order to create style sheets. These rules define appearance of associated HTML element. The general form of CSS syntax is as follows: Selector {property: value;} Key Points Selector is HTML element to which CSS rule is applied. Selector is HTML element to which CSS rule is applied. Property specifies the attribute that you want to change corresponding to the selector. Property specifies the attribute that you want to change corresponding to the selector. Property can take specified value. Property can take specified value. Property and Value are separated by a colon (:). Property and Value are separated by a colon (:). Each declaration is separated by semi colon (;). Each declaration is separated by semi colon (;). Following are examples of CSS rules: P { color : red;} h1 (color : green; font-style : italic } body { color : cyan; font-family : Arial; font- style : 16pt} Following are the four methods to add CSS to HTML documents. Inline Style Sheets Embedded Style Sheets External Style Sheets Imported Style Sheets Inline Style Sheets Inline Style Sheets Embedded Style Sheets Embedded Style Sheets External Style Sheets External Style Sheets Imported Style Sheets Imported Style Sheets Inline Style Sheets are included with HTML element i.e. they are placed inline with the element. To add inline CSS, we have to declare style attribute which can contain any CSS property. Syntax: <Tagname STYLE = “ Declaration1 ; Declaration2 “> .... </Tagname> Let’s consider the following example using Inline Style Sheets: <p style="color: blue; text-align: left; font-size: 15pt"> Inline Style Sheets are included with HTML element i.e. they are placed inline with the element. To add inline CSS, we have to declare style attribute which can contain any CSS property. </p> Output − Embedded Style Sheets are used to apply same appearance to all occurrence of a specific element. These are defined in <head> element by using the <style> element. Syntax <head> <title> .... </title> <style type =”text/css”> .......CSS Rules/Styles.... </style> </head> Let’s consider the following example using Embedded Style Sheets: <style type="text/css"> p {color:green; text-align: left; font-size: 10pt} h1 { color: red; font-weight: bold} </style> External Style Sheets are the separate .css files that contain the CSS rules. These files can be linked to any HTML documents using <link> tag with rel attribute. Syntax: <head> <link rel= “stylesheet” type=”text/css” href= “url of css file”> </head> In order to create external css and link it to HTML document, follow the following steps: First of all create a CSS file and define all CSS rules for several HTML elements. Let’s name this file as external.css. First of all create a CSS file and define all CSS rules for several HTML elements. Let’s name this file as external.css. p{ Color: orange; text-align: left; font-size: 10pt; } h1{ Color: orange; font-weight: bold; } Now create HTML document and name it as externaldemo.html. Now create HTML document and name it as externaldemo.html. <html> <head> <title> External Style Sheets Demo </title> <link rel="stylesheet" type="text/css" href="external.css"> </head> <body> <h1> External Style Sheets</h1> <p>External Style Sheets are the separate .css files that contain the CSS rules.</p> </body> </html> Imported Style Sheets allow us to import style rules from other style sheets. To import CSS rules we have to use @import before all the rules in a style sheet. Syntax: <head><title> Title Information </title> <style type=”text/css”> @import URL (cssfilepath) ... CSS rules... </style> </head> Let’s consider the following example using Inline Style Sheets: <html> <head> <title> External Style Sheets Demo </title> <style> @import url(external.css); </style> </head> <body> <h1> External Style Sheets</h1> <p>External Style Sheets are the separate .css files that contain the CSS rules.</p>
[ { "code": null, "e": 2763, "s": 2607, "text": "CSS is acronym of Cascading Style Sheets. It helps to define the presentation of HTML elements as a separate file known as CSS file having .css extension. " }, { "code": null, "e": 2972, "s": 2763, "text": "CSS helps to change formatting of any HTML element by just making changes at one place. All changes made would be reflected automatically to all of the web pages of the website in which that element appeared." }, { "code": null, "e": 3157, "s": 2972, "text": "CSS Rules are the styles that we have to create in order to create style sheets. These rules define appearance of associated HTML element. The general form of CSS syntax is as follows:" }, { "code": null, "e": 3185, "s": 3157, "text": "Selector {property: value;}" }, { "code": null, "e": 3196, "s": 3185, "text": "Key Points" }, { "code": null, "e": 3251, "s": 3196, "text": "Selector is HTML element to which CSS rule is applied." }, { "code": null, "e": 3306, "s": 3251, "text": "Selector is HTML element to which CSS rule is applied." }, { "code": null, "e": 3394, "s": 3306, "text": "Property specifies the attribute that you want to change corresponding to the selector." }, { "code": null, "e": 3482, "s": 3394, "text": "Property specifies the attribute that you want to change corresponding to the selector." }, { "code": null, "e": 3517, "s": 3482, "text": "Property can take specified value." }, { "code": null, "e": 3552, "s": 3517, "text": "Property can take specified value." }, { "code": null, "e": 3601, "s": 3552, "text": "Property and Value are separated by a colon (:)." }, { "code": null, "e": 3650, "s": 3601, "text": "Property and Value are separated by a colon (:)." }, { "code": null, "e": 3699, "s": 3650, "text": "Each declaration is separated by semi colon (;)." }, { "code": null, "e": 3748, "s": 3699, "text": "Each declaration is separated by semi colon (;)." }, { "code": null, "e": 3785, "s": 3748, "text": "Following are examples of CSS rules:" }, { "code": null, "e": 3908, "s": 3785, "text": "P { color : red;}\n\nh1 (color : green; font-style : italic }\n\nbody { color : cyan; font-family : Arial; font- style : 16pt}" }, { "code": null, "e": 3969, "s": 3908, "text": "Following are the four methods to add CSS to HTML documents." }, { "code": null, "e": 4057, "s": 3969, "text": "\nInline Style Sheets\nEmbedded Style Sheets\nExternal Style Sheets\nImported Style Sheets\n" }, { "code": null, "e": 4077, "s": 4057, "text": "Inline Style Sheets" }, { "code": null, "e": 4097, "s": 4077, "text": "Inline Style Sheets" }, { "code": null, "e": 4119, "s": 4097, "text": "Embedded Style Sheets" }, { "code": null, "e": 4141, "s": 4119, "text": "Embedded Style Sheets" }, { "code": null, "e": 4163, "s": 4141, "text": "External Style Sheets" }, { "code": null, "e": 4185, "s": 4163, "text": "External Style Sheets" }, { "code": null, "e": 4207, "s": 4185, "text": "Imported Style Sheets" }, { "code": null, "e": 4229, "s": 4207, "text": "Imported Style Sheets" }, { "code": null, "e": 4417, "s": 4229, "text": "Inline Style Sheets are included with HTML element i.e. they are placed inline with the element. \nTo add inline CSS, we have to declare style attribute which can contain any CSS property." }, { "code": null, "e": 4425, "s": 4417, "text": "Syntax:" }, { "code": null, "e": 4492, "s": 4425, "text": "<Tagname STYLE = “ Declaration1 ; Declaration2 “> .... </Tagname>" }, { "code": null, "e": 4556, "s": 4492, "text": "Let’s consider the following example using Inline Style Sheets:" }, { "code": null, "e": 4807, "s": 4556, "text": "<p style=\"color: blue; text-align: left; font-size: 15pt\">\nInline Style Sheets are included with HTML element i.e. they are placed inline with the element.\nTo add inline CSS, we have to declare style attribute which can contain any CSS property.\n</p>" }, { "code": null, "e": 4816, "s": 4807, "text": "Output −" }, { "code": null, "e": 4980, "s": 4816, "text": "Embedded Style Sheets are used to apply same appearance to all occurrence of a specific element. These are defined in <head> element by using the <style> element." }, { "code": null, "e": 4987, "s": 4980, "text": "Syntax" }, { "code": null, "e": 5100, "s": 4987, "text": "<head> <title> .... </title>\n <style type =”text/css”>\n .......CSS Rules/Styles....\n </style>\t\t\n</head>" }, { "code": null, "e": 5166, "s": 5100, "text": "Let’s consider the following example using Embedded Style Sheets:" }, { "code": null, "e": 5292, "s": 5166, "text": "<style type=\"text/css\">\n p {color:green; text-align: left; font-size: 10pt}\n h1 { color: red; font-weight: bold}\n</style>" }, { "code": null, "e": 5456, "s": 5292, "text": "External Style Sheets are the separate .css files that contain the CSS rules. These files can be linked to any HTML documents using <link> tag with rel attribute.\n" }, { "code": null, "e": 5464, "s": 5456, "text": "Syntax:" }, { "code": null, "e": 5545, "s": 5464, "text": "<head> <link rel= “stylesheet” type=”text/css” href= “url of css file”>\n</head>" }, { "code": null, "e": 5635, "s": 5545, "text": "In order to create external css and link it to HTML document, follow the following steps:" }, { "code": null, "e": 5756, "s": 5635, "text": "First of all create a CSS file and define all CSS rules for several HTML elements. Let’s name this file as external.css." }, { "code": null, "e": 5877, "s": 5756, "text": "First of all create a CSS file and define all CSS rules for several HTML elements. Let’s name this file as external.css." }, { "code": null, "e": 5997, "s": 5877, "text": "p{ \n Color: orange; text-align: left; font-size: 10pt;\n}\nh1{ \n Color: orange; font-weight: bold;\n}" }, { "code": null, "e": 6056, "s": 5997, "text": "Now create HTML document and name it as externaldemo.html." }, { "code": null, "e": 6115, "s": 6056, "text": "Now create HTML document and name it as externaldemo.html." }, { "code": null, "e": 6418, "s": 6115, "text": "<html>\n <head>\n <title> External Style Sheets Demo </title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"external.css\">\n </head>\n <body>\n <h1> External Style Sheets</h1>\n <p>External Style Sheets are the separate .css files that contain the CSS rules.</p>\n </body>\n</html>" }, { "code": null, "e": 6578, "s": 6418, "text": "Imported Style Sheets allow us to import style rules from other style sheets. To import CSS rules we have to use @import before all the rules in a style sheet." }, { "code": null, "e": 6586, "s": 6578, "text": "Syntax:" }, { "code": null, "e": 6729, "s": 6586, "text": "<head><title> Title Information </title>\n <style type=”text/css”>\n @import URL (cssfilepath)\n ... CSS rules...\n </style>\n</head>" }, { "code": null, "e": 6793, "s": 6729, "text": "Let’s consider the following example using Inline Style Sheets:" } ]
ETL Testing - Quick Guide
The data in a Data Warehouse system is loaded with an ETL (Extract, Transform, Load) tool. As the name suggests, it performs the following three operations − Extracts the data from your transactional system which can be an Oracle, Microsoft, or any other relational database, Extracts the data from your transactional system which can be an Oracle, Microsoft, or any other relational database, Transforms the data by performing data cleansing operations, and then Transforms the data by performing data cleansing operations, and then Loads the data into the OLAP data Warehouse. Loads the data into the OLAP data Warehouse. You can also extract data from flat files like spreadsheets and CSV files using an ETL tool and load it into an OLAP data warehouse for data analysis and reporting. Let us take an example to understand it better. Let us assume there is a manufacturing company having multiple departments such as sales, HR, Material Management, EWM, etc. All these departments have separate databases which they use to maintain information w.r.t. their work and each database has a different technology, landscape, table names, columns, etc. Now, if the company wants to analyze historical data and generate reports, all the data from these data sources should be extracted and loaded into a Data Warehouse to save it for analytical work. An ETL tool extracts the data from all these heterogeneous data sources, transforms the data (like applying calculations, joining fields, keys, removing incorrect data fields, etc.), and loads it into a Data Warehouse. Later, you can use various Business Intelligence (BI) tools to generate meaningful reports, dashboards, and visualizations using this data. An ETL tool is used to extract data from different data sources, transform the data, and load it into a DW system; however a BI tool is used to generate interactive and ad-hoc reports for end-users, dashboard for senior management, data visualizations for monthly, quarterly, and annual board meetings. The most common ETL tools include − SAP BO Data Services (BODS), Informatica – Power Center, Microsoft – SSIS, Oracle Data Integrator ODI, Talend Open Studio, Clover ETL Open source, etc. Some popular BI tools include − SAP Business Objects, SAP Lumira, IBM Cognos, JasperSoft, Microsoft BI Platform, Tableau, Oracle Business Intelligence Enterprise Edition, etc. Let us now discuss in a little more detail the key steps involved in an ETL procedure − It involves extracting the data from different heterogeneous data sources. Data extraction from a transactional system varies as per the requirement and the ETL tool in use. It is normally done by running scheduled jobs in off-business hours like running jobs at night or over the weekend. It involves transforming the data into a suitable format that can be easily loaded into a DW system. Data transformation involves applying calculations, joins, and defining primary and foreign keys on the data. For example, if you want % of total revenue which is not in database, you will apply % formula in transformation and load the data. Similarly, if you have the first name and the last name of users in different columns, then you can apply a concatenate operation before loading the data. Some data doesn’t require any transformation; such data is known as direct move or pass through data. Data transformation also involves data correction and cleansing of data, removing incorrect data, incomplete data formation, and fixing data errors. It also includes data integrity and formatting incompatible data before loading it into a DW system. It involves loading the data into a DW system for analytical reporting and information. The target system can be a simple delimited flat file or a data warehouse. A typical ETL tool-based data warehouse uses staging area, data integration, and access layers to perform its functions. It’s normally a 3-layer architecture. Staging Layer − The staging layer or staging database is used to store the data extracted from different source data systems. Staging Layer − The staging layer or staging database is used to store the data extracted from different source data systems. Data Integration Layer − The integration layer transforms the data from the staging layer and moves the data to a database, where the data is arranged into hierarchical groups, often called dimensions, and into facts and aggregate facts. The combination of facts and dimensions tables in a DW system is called a schema. Data Integration Layer − The integration layer transforms the data from the staging layer and moves the data to a database, where the data is arranged into hierarchical groups, often called dimensions, and into facts and aggregate facts. The combination of facts and dimensions tables in a DW system is called a schema. Access Layer − The access layer is used by end-users to retrieve the data for analytical reporting and information. Access Layer − The access layer is used by end-users to retrieve the data for analytical reporting and information. The following illustration shows how the three layers interact with each other. ETL testing is done before data is moved into a production data warehouse system. It is sometimes also called as table balancing or production reconciliation. It is different from database testing in terms of its scope and the steps to be taken to complete this. The main objective of ETL testing is to identify and mitigate data defects and general errors that occur prior to processing of data for analytical reporting. Here is a list of the common tasks involved in ETL Testing − Understand the data to be used for reporting Review the Data Model Source to target mapping Data checks on source data Packages and schema validation Data verification in the target system Verification of data transformation calculations and aggregation rules Sample data comparison between the source and the target system Data integrity and quality checks in the target system Performance testing on data Both ETL testing and database testing involve data validation, but they are not the same. ETL testing is normally performed on data in a data warehouse system, whereas database testing is commonly performed on transactional systems where the data comes from different applications into the transactional database. Here, we have highlighted the major differences between ETL testing and Database testing. ETL testing involves the following operations − Validation of data movement from the source to the target system. Validation of data movement from the source to the target system. Verification of data count in the source and the target system. Verification of data count in the source and the target system. Verifying data extraction, transformation as per requirement and expectation. Verifying data extraction, transformation as per requirement and expectation. Verifying if table relations − joins and keys − are preserved during the transformation. Verifying if table relations − joins and keys − are preserved during the transformation. Common ETL testing tools include QuerySurge, Informatica, etc. Database testing stresses more on data accuracy, correctness of data and valid values. It involves the following operations − Verifying if primary and foreign keys are maintained. Verifying if primary and foreign keys are maintained. Verifying if the columns in a table have valid data values. Verifying if the columns in a table have valid data values. Verifying data accuracy in columns. Example − Number of months column shouldn’t have a value greater than 12. Verifying data accuracy in columns. Example − Number of months column shouldn’t have a value greater than 12. Verifying missing data in columns. Check if there are null columns which actually should have a valid value. Verifying missing data in columns. Check if there are null columns which actually should have a valid value. Common database testing tools include Selenium, QTP, etc. The following table captures the key features of Database and ETL testing and their comparison − ETL Testing categorization is done based on objectives of testing and reporting. Testing categories vary as per the organization standards and it also depends on the client requirements. Generally, ETL testing is categorized based on the following points − Source to Target Count Testing − It involves matching of count of records in the source and the target systems. Source to Target Count Testing − It involves matching of count of records in the source and the target systems. Source to Target Data Testing − It involves data validation between the source and the target systems. It also involves data integration and threshold value check and duplicate data check in the target system. Source to Target Data Testing − It involves data validation between the source and the target systems. It also involves data integration and threshold value check and duplicate data check in the target system. Data Mapping or Transformation Testing − It confirms the mapping of objects in the source and the target systems. It also involves checking the functionality of data in the target system. Data Mapping or Transformation Testing − It confirms the mapping of objects in the source and the target systems. It also involves checking the functionality of data in the target system. End-User Testing − It involves generating reports for end-users to verify if the data in the reports are as per expectation. It involves finding deviation in reports and cross-check the data in the target system for report validation. End-User Testing − It involves generating reports for end-users to verify if the data in the reports are as per expectation. It involves finding deviation in reports and cross-check the data in the target system for report validation. Retesting − It involves fixing the bugs and defects in data in the target system and running the reports again for data validation. Retesting − It involves fixing the bugs and defects in data in the target system and running the reports again for data validation. System Integration Testing − It involves testing all the individual systems, and later combine the results to find if there are any deviations. There are three approaches that can be used to perform this: top-down, bottom-up, and hybrid. System Integration Testing − It involves testing all the individual systems, and later combine the results to find if there are any deviations. There are three approaches that can be used to perform this: top-down, bottom-up, and hybrid. Based on the structure of a Data Warehouse system, ETL testing (irrespective of the tool that is used) can be divided into the following categories − In this type of testing, there is a new DW system built and verified. Data inputs are taken from customers/end-users and also from different data sources and a new data warehouse is created. Later, the data is verified in the new system with help of ETL tools. In migration testing, customers have an existing Data Warehouse and ETL, but they look for a new ETL tool to improve the efficiency. It involves migration of data from the existing system using a new ETL tool. In change testing, new data is added from different data sources to an existing system. Customers can also change the existing rules for ETL or a new rule can also be added. Report testing involves creating reports for data validation. Reports are the final output of any DW system. Reports are tested based on their layout, data in the report, and calculated values. ETL testing is different from database testing or any other conventional testing. One may have to face different types of challenges while performing ETL testing. Here we listed a few common challenges − Data loss during the ETL process. Data loss during the ETL process. Incorrect, incomplete or duplicate data. Incorrect, incomplete or duplicate data. DW system contains historical data, so the data volume is too large and extremely complex to perform ETL testing in the target system. DW system contains historical data, so the data volume is too large and extremely complex to perform ETL testing in the target system. ETL testers are normally not provided with access to see job schedules in the ETL tool. They hardly have access to BI Reporting tools to see the final layout of reports and data inside the reports. ETL testers are normally not provided with access to see job schedules in the ETL tool. They hardly have access to BI Reporting tools to see the final layout of reports and data inside the reports. Tough to generate and build test cases, as data volume is too high and complex. Tough to generate and build test cases, as data volume is too high and complex. ETL testers normally don’t have an idea of end-user report requirements and business flow of the information. ETL testers normally don’t have an idea of end-user report requirements and business flow of the information. ETL testing involves various complex SQL concepts for data validation in the target system. ETL testing involves various complex SQL concepts for data validation in the target system. Sometimes the testers are not provided with the source-to-target mapping information. Sometimes the testers are not provided with the source-to-target mapping information. Unstable testing environment delay the development and testing of a process. Unstable testing environment delay the development and testing of a process. An ETL tester is primarily responsible for validating the data sources, extraction of data, applying transformation logic, and loading the data in the target tables. The key responsibilities of an ETL tester are listed below. It involves the following operations − Count check Reconcile records with the source data Data type check Ensure no spam data loaded Remove duplicate data Check all the keys are in place Transformation logic is applied before loading the data. It involves the following operations − Data threshold validation check, for example, age value shouldn’t be more than 100. Data threshold validation check, for example, age value shouldn’t be more than 100. Record count check, before and after the transformation logic applied. Record count check, before and after the transformation logic applied. Data flow validation from the staging area to the intermediate tables. Data flow validation from the staging area to the intermediate tables. Surrogate key check. Surrogate key check. Data is loaded from the staging area to the target system. It involves the following operations − Record count check from the intermediate table to the target system. Record count check from the intermediate table to the target system. Ensure the key field data is not missing or Null. Ensure the key field data is not missing or Null. Check if the aggregate values and calculated measures are loaded in the fact tables. Check if the aggregate values and calculated measures are loaded in the fact tables. Check modeling views based on the target tables. Check modeling views based on the target tables. Check if CDC has been applied on the incremental load table. Check if CDC has been applied on the incremental load table. Data check in dimension table and history table check. Data check in dimension table and history table check. Check the BI reports based on the loaded fact and dimension table and as per the expected results. Check the BI reports based on the loaded fact and dimension table and as per the expected results. ETL testers are required to test the tools and the test-cases as well. It involves the following operations − Test the ETL tool and its functions Test the ETL Data Warehouse system Create, design, and execute the test plans and test cases. Test the flat file data transfers. It is important that you define the correct ETL Testing technique before starting the testing process. You should take an acceptance from all the stakeholders and ensure that a correct technique is selected to perform ETL testing. This technique should be well known to the testing team and they should be aware of the steps involved in the testing process. There are various types of testing techniques that can be used. In this chapter, we will discuss the testing techniques in brief. To perform Analytical Reporting and Analysis, the data in your production should be correct. This testing is done on the data that is moved to the production system. It involves data validation in the production system and comparing it the with the source data. This type of testing is done when the tester has less time to perform the testing operation. It involves checking the count of data in the source and the target systems. It doesn’t involve checking the values of data in the target system. It also doesn’t involve if the data is in ascending or descending order after mapping of data. In this type of testing, a tester validates data values from the source to the target system. It checks the data values in the source system and the corresponding values in the target system after transformation. This type of testing is time-consuming and is normally performed in financial and banking projects. In this type of testing, a tester validates the range of data. All the threshold values in the target system are checked if they are as per the expected result. It also involves integration of data in the target system from multiple source systems after transformation and loading. Example − Age attribute shouldn’t have a value greater than 100. In the date column DD/MM/YY, the month field shouldn’t have a value greater than 12. Application migration testing is normally performed automatically when you move from an old application to a new application system. This testing saves a lot of time. It checks if the data extracted from an old application is same as per the data in the new application system. It includes performing various checks such as data type check, data length check, and index check. Here a Test Engineer performs the following scenarios − Primary Key, Foreign Key, NOT NULL, NULL, and UNIQUE. This testing involves checking for duplicate data in the target system. When there is a huge amount of data in the target system, it is possible that there is duplicate data in the production system that may result in incorrect data in Analytical Reports. Duplicate values can be checked with SQL statement like − Select Cust_Id, Cust_NAME, Quantity, COUNT (*) FROM Customer GROUP BY Cust_Id, Cust_NAME, Quantity HAVING COUNT (*) >1; Duplicate data appears in the target system due to the following reasons − If no primary key is defined, then duplicate values may come. Due to incorrect mapping or environmental issues. Manual errors while transferring data from the source to the target system. Data transformation testing is not performed by running a single SQL statement. It is time-consuming and involves running multiple SQL queries for each row to verify the transformation rules. The tester needs to run SQL queries for each row and then compare the output with the target data. Data quality testing involves performing number check, date check, null check, precision check, etc. A tester performs Syntax Test to report invalid characters, incorrect upper/lower case order, etc. and Reference Tests to check if the data is according to the data model. Incremental testing is performed to verify if Insert and Update statements are executed as per the expected result. This testing is performed step-by-step with old and new data. When we make changes to data transformation and aggregation rules to add new functionality which also helps the tester to find new errors, it is called Regression Testing. The bugs in data that that comes in regression testing are called Regression. When you run the tests after fixing the codes, it is called retesting. System integration testing involves testing the components of a system individually and later integrating the modules. There are three ways a system integration can be done: top-down, bottom-up, and hybrid. Navigation testing is also known as testing the front-end of the system. It involves enduser point of view testing by checking all the aspects of the front-end report − includes data in various fields, calculation and aggregates, etc. ETL testing covers all the steps involved in an ETL lifecycle. It starts with understanding the business requirements till the generation of a summary report. The common steps under ETL Testing lifecycle are listed below − Understanding the business requirement. Understanding the business requirement. Validation of the business requirement. Validation of the business requirement. Test Estimation is used to provide the estimated time to run test-cases and to complete the summary report. Test Estimation is used to provide the estimated time to run test-cases and to complete the summary report. Test Planning involves finding the Testing technique based on the inputs as per business requirement. Test Planning involves finding the Testing technique based on the inputs as per business requirement. Creating test scenarios and test cases. Creating test scenarios and test cases. Once the test-cases are ready and approved, the next step is to perform pre-execution check. Once the test-cases are ready and approved, the next step is to perform pre-execution check. Execute all the test-cases. Execute all the test-cases. The last step is to generate a complete summary report and file a closure process. The last step is to generate a complete summary report and file a closure process. ETL Test Scenarios are used to validate an ETL Testing Process. The following table explains some of the most common scenarios and test-cases that are used by ETL testers. Structure Validation It involves validating the source and the target table structure as per the mapping document. Data type should be validated in the source and the target systems. The length of data types in the source and the target system should be same. Data field types and their format should be same in the source and the target system. Validating the column names in the target system. Validating Mapping document It involves validating the mapping document to ensure all the information has been provided. The mapping document should have change log, maintain data types, length, transformation rules, etc. Validate Constraints It involves validating the constraints and ensuring that they are applied on the expected tables. Data Consistency check It involves checking the misuse of integrity constraints like Foreign Key. The length and data type of an attribute may vary in different tables, though their definition remains same at the semantic layer. Data Completeness Validation It involves checking if all the data is loaded to the target system from the source system. Counting the number of records in the source and the target systems. Boundary value analysis. Validating the unique values of primary keys. Data Correctness Validation It involves validating the values of data in the target system. Misspelled or inaccurate data is found in table. Null, Not Unique data is stored when you disable integrity constraint at the time of import. Data Transform validation It involves creating a spreadsheet of scenarios for input values and expected results and then validating with end-users. Validating parent-child relationship in the data by creating scenarios. Using data profiling to compare the range of values in each field. Validating if the data types in the warehouse are same as mentioned in the data model. Data Quality Validation It involves performing number check, date check, precision check, data check, Null check, etc. Example − Date format should be same for all the values. Null Validation It involves checking the Null values where Not Null is mentioned for that field. Duplicate Validation It involves validating duplicate values in the target system when data is coming from multiple columns from the source system. Validating primary keys and other columns if there is any duplicate values as per the business requirement. Date Validation check Validating date field for various actions performed in ETL process. Common test-cases to perform Date validation − From_Date should not greater than To_Date From_Date should not greater than To_Date Format of date values should be proper. Format of date values should be proper. Date values should not have any junk values or null values Date values should not have any junk values or null values Full Data Validation Minus Query It involves validating full data set in the source and the target tables by using minus query. You need to perform both source minus target and target minus source. You need to perform both source minus target and target minus source. If the minus query returns a value, that should be considered as mismatching rows. If the minus query returns a value, that should be considered as mismatching rows. You need to match the rows in source and target using the Intersect statement. You need to match the rows in source and target using the Intersect statement. The count returned by Intersect should match with the individual counts of source and target tables. The count returned by Intersect should match with the individual counts of source and target tables. If the minus query returns no rows and the count intersect is less than the source count or the target table count, then the table holds duplicate rows. If the minus query returns no rows and the count intersect is less than the source count or the target table count, then the table holds duplicate rows. Other Test Scenarios Other Test scenarios can be to verify that the extraction process did not extract duplicate data from the source system. The testing team will maintain a list of SQL statements that are run to validate that no duplicate data have been extracted from the source systems. Data Cleaning Unwanted data should be removed before loading the data to the staging area. ETL performance tuning is used to ensure if an ETL system can handle an expected load of multiple users and transactions. Performance tuning typically involves server-side workload on the ETL system. It is used to test the server response in multiuser environment and to find bottlenecks. These can be found in source and target systems, mapping of systems, configuration like session management properties, etc. Follow the steps given below to perform ETL testing performance tuning − Step 1 − Find the load that is being transformed in production. Step 1 − Find the load that is being transformed in production. Step 2 − Create new data of that same load or move from Production data to your local performance server. Step 2 − Create new data of that same load or move from Production data to your local performance server. Step 3 − Disable the ETL until you generate the load required. Step 3 − Disable the ETL until you generate the load required. Step 4 − Take the count of the needed data from the tables of the database. Step 4 − Take the count of the needed data from the tables of the database. Step 5 − Note down the last run of ETL and enable the ETL, so that it will get enough stress to transform the entire load created. Run it Step 5 − Note down the last run of ETL and enable the ETL, so that it will get enough stress to transform the entire load created. Run it Step 6 − After the ETL completes its run, take the count of the data created. Step 6 − After the ETL completes its run, take the count of the data created. Find out the total time it took to transform the load. Find out whether performance time has improved or dropped. Check that the entire expected load got extracted and transferred. The goal of ETL testing is to achieve credible data. Data credibility can be attained by making the testing cycle more effective. A comprehensive test strategy is the setting up of an effective test cycle. The testing strategy should cover test planning for each stage of ETL process, every time the data moves and state the responsibilities of each stakeholder, e.g., business analysts, infrastructure team, QA team, DBA’s, Developers and Business Users. To ensure testing readiness from all aspects, the key areas a test strategy should focus on are − Scope of testing − Describe testing techniques and types to be used. Scope of testing − Describe testing techniques and types to be used. Setting up the test environment. Setting up the test environment. Test data availability − It is recommended to have production like data covering all/critical business requirement. Test data availability − It is recommended to have production like data covering all/critical business requirement. Data quality and performance acceptance criteria. Data quality and performance acceptance criteria. In ETL testing, data accuracy is used to ensure if data is accurately loaded to the target system as per the expectation. The key steps in performing data accuracy are as follows − Value comparison involves comparing the data in source and target system with minimum or no transformation. It can be done using various ETL Testing tools, for example, Source Qualifier Transformation in Informatica. Some expression transformations can also be performed in data accuracy testing. Various set operators can be used in SQL statements to check data accuracy in the source and the target systems. Common operators are Minus and Intersect operators. The results of these operators can be considered as deviation in value in the target and the source system. Critical data columns can be checked by comparing distinct values in the source and the target systems. Here is a sample query that can be used to check critical data columns − SELECT cust_name, Order_Id, city, count(*) FROM customer GROUP BY cust_name, Order_Id, city; Checking the metadata involves validating the source and the target table structure w.r.t. the mapping document. The mapping document has details of the source and target columns, data transformations rules and the data types, all the fields that define the structure of tables in the source and the target systems. The length of target column data type should be equal to or greater than the source column data type. Let us take an example. Suppose you have the first names and the last names in the source table and the data length for each is defined as 50 characters. Then, the target data length for full name column in the target system should be a minimum of 100 or more. Data type checking involves verifying the source and the target data type and ensuring that they are same. There is a possibility that the target data type is different from the source data after a transformation. Hence there is a need to check the transformation rules as well. Constraint checking involves verifying the index values and constraints as per the design specification document. All the columns that cannot have Null values should have Not Null constraint. Primary keys columns are indexed as per the design document. Performing data transformations is a bit complex, as it cannot be achieved by writing a single SQL query and then comparing the output with the target. For ETL Testing Data Transformation, you may have to write multiple SQL queries for each row to verify the transformation rules. To start with, make sure the source data is sufficient to test all the transformation rules. The key to perform a successful ETL testing for data transformations is to pick the correct and sufficient sample data from the source system to apply the transformation rules. The key steps for ETL Testing Data Transformation are listed below − The first step is to create a list of scenarios of input data and the expected results and validate these with the business customer. This is a good approach for requirements gathering during design and could also be used as a part of testing. The first step is to create a list of scenarios of input data and the expected results and validate these with the business customer. This is a good approach for requirements gathering during design and could also be used as a part of testing. The next step is to create the test data that contains all the scenarios. Utilize an ETL developer to automate the entire process of populating the datasets with the scenario spreadsheet to permit versatility and mobility for the reason that the scenarios are likely to change. The next step is to create the test data that contains all the scenarios. Utilize an ETL developer to automate the entire process of populating the datasets with the scenario spreadsheet to permit versatility and mobility for the reason that the scenarios are likely to change. Next, utilize data profiling results to compare the range and submission of values in each field between the target and source data. Next, utilize data profiling results to compare the range and submission of values in each field between the target and source data. Validate the accurate processing of ETL generated fields, e.g., surrogate keys. Validate the accurate processing of ETL generated fields, e.g., surrogate keys. Validating the data types within the warehouse are the same as was specified in the data model or design. Validating the data types within the warehouse are the same as was specified in the data model or design. Create data scenarios between tables that test referential integrity. Create data scenarios between tables that test referential integrity. Validate the parent-to-child relationships in the data. Validate the parent-to-child relationships in the data. The final step is to perform lookup transformation. Your lookup query should be straight without any aggregation and expected to return only one value per the source table. You can directly join the lookup table in the source qualifier as in the previous test. If this is not the case, write a query joining the lookup table with the main table in the source and compare the data in the corresponding columns in the target. The final step is to perform lookup transformation. Your lookup query should be straight without any aggregation and expected to return only one value per the source table. You can directly join the lookup table in the source qualifier as in the previous test. If this is not the case, write a query joining the lookup table with the main table in the source and compare the data in the corresponding columns in the target. Checking data quality during ETL testing involves performing quality checks on data that is loaded in the target system. It includes the following tests − The Number format should be same across the target system. For example, in the source system, the format of numbering the columns is x.30, but if the target is only 30, then it has to load not prefixing x. in target column number. The Date format should be consistent in both the source and the target systems. For example, it should be same across all the records. The Standard format is: yyyy-mm-dd. Precision value should display as expected in the target table. For example, in the source table, the value is 15.2323422, but in the target table, it should display as 15.23 or round of 15. It involves checking the data as per the business requirement. The records that don’t meet certain criteria should be filtered out. Example − Only those records whose date_id >=2015 and Account_Id != ‘001’ should load in the target table. Some columns should have Null as per the requirement and possible values for that field. Example − Termination Date column should display Null unless and until its Active status Column is “T” or “Deceased”. Common checks like From_Date should not greater than To_Date can be done. Checking Data Completeness is done to verify that the data in the target system is as per expectation after loading. The common tests that can be performed for this are as follows − Checking Aggregate functions (sum, max, min, count), Checking Aggregate functions (sum, max, min, count), Checking and validating the counts and the actual data between the source and the target for columns without transformations or with simple transformations. Checking and validating the counts and the actual data between the source and the target for columns without transformations or with simple transformations. Compare the count of number of records in the source and the target tables. It can be done by writing the following queries − SELECT count (1) FROM employee; SELECT count (1) FROM emp_dim; It involves checking the aggregate functions such as count, sum, and max in the source and target tables (fact or dimension). It involves comparing the distinct values and the count of rows for each distinct value. SELECT city, count(*) FROM employee GROUP BY city; SELECT city_id, count(*) FROM emp_dim GROUP BY city_id; It involves validating the primary key and the unique key in a column or in combination of columns that should be unique as per the business requirements. You can use the following query to perform duplicate data validation − SELECT first_name, last_name, date_of_joining, count (1) FROM employee GROUP BY first_name, last_name HAVING count(1)>1; Backup recovery for a system is planned to ensure that system is restored as soon as possible from a failure and operations are resumed as early as possible without losing any important data. ETL Backup recovery testing is used to ensure that the Data Warehouse system recovers successfully from hardware, software, or from a network failure with losing any data. A proper backup plan must be prepared to ensure maximum system availability. Backup systems should be able to restore with ease and should take over the failed system without any data loss. ETL Testing Backup recovery involves exposing the application or the DW system to extreme conditions for any hardware component, software crash, etc. The next step is to ensure that recovery process is initiated, system verification is done, and data recovery is achieved. ETL testing is mostly done using SQL scripts and gathering the data in spreadsheets. This approach to perform ETL testing is very slow and time-consuming, error-prone, and is performed on sample data. Your ETL test team writes SQL queries to test data in a warehouse system and they need to execute them manually using a SQL editor and then put the data into an Excel spreadsheet and compare them manually. This process is time-consuming, resourceintensive, and inefficient. There are various tools available in the market to automate this process. The most common ETL Testing tools are QuerySurge and Informatica Data Validation. QuerySurge is a data testing solution designed for testing Big Data, Data Warehouses, and the ETL process. It can automate the entire process for you and fit nicely into your DevOps strategy. The key features of QuerySurge are as follows − It has Query Wizards to create test QueryPairs fast and easily without the user having to write any SQL. It has Query Wizards to create test QueryPairs fast and easily without the user having to write any SQL. It has a Design Library with reusable Query Snippets. You can create custom QueryPairs as well. It has a Design Library with reusable Query Snippets. You can create custom QueryPairs as well. It can compare data from source files and data stores to the target Data Warehouse or Big Data store. It can compare data from source files and data stores to the target Data Warehouse or Big Data store. It can compare millions of rows and columns of data in minutes. It can compare millions of rows and columns of data in minutes. It allows the user to schedule tests to run (1) immediately, (2) any date/time, or (3) automatically after an event ends. It allows the user to schedule tests to run (1) immediately, (2) any date/time, or (3) automatically after an event ends. It can produce informative reports, view updates, and auto-email results to your team. It can produce informative reports, view updates, and auto-email results to your team. To automate the entire process, your ETL tool should start QuerySurge through command line API after the ETL software completes its load process. QuerySurge will run automatically and unattended, executing all tests and then emailing everyone on the team with results. Just like QuerySurge, Informatica Data Validation provides an ETL testing tool that helps you to accelerate and automate the ETL testing process in the development and production environment. It allows you to deliver complete, repeatable, and auditable test coverage in less time. It requires no programming skills! To test a data warehouse system or a BI application, one needs to have a data-centric approach. ETL Testing best practices help to minimize the cost and time to perform the testing. It improves the quality of data to be loaded to the target system which generates high quality dashboards and reports for end-users. We have listed here a few best practices that can be followed for ETL Testing − It is extremely important to analyze the data to understand requirements in order to set up a correct data model. Spending time to understand the requirements and having a correct data model for the target system can reduce the ETL challenges. It is also important to study the source systems, data quality, and build correct data validation rules for ETL modules. An ETL strategy should be formulated based on the data structure of the source and the target systems. End-users are normally aware of data issues, but they have no idea on how to fix them. It is important to find these errors and correct them before they reach the ETL system. A common way to resolve this is at the ETL execution time, but the best practice is to find the errors in the source system and take steps to rectify them at the source system level. One of the common ETL best practices is to select a tool that is most compatible with the source and the target systems. The ETL tool’s capability to generate SQL scripts for the source and the target systems can reduce the processing time and resources. It allows one to process transformation anywhere within the environment that is most appropriate. Another best practice during ETL implementation is scheduling, auditing, and monitoring of ETL jobs to ensure that the loads are performed as per expectation. Sometimes, data warehouse tables are larger in size and it is not possible to refresh them during every ETL cycle. Incremental loads ensure that only records changed since the last update are brought into the ETL process and it puts a huge impact on the scalability and the time taken to refresh the system. Normally the source systems don’t have timestamps or a primary key to identify the changes easily. Such problems can be very costly, if identified at the later stages of the project. One of the ETL best practices is to cover such aspects in the initial source system study. This knowledge helps the ETL team to identify changed data capture problems and determine the most appropriate strategy. It is best practice to make sure the offered ETL solution is scalable. At the time of implementation, one needs to ensure that ETL solution is scalable with the business requirement and its potential growth in future.
[ { "code": null, "e": 2437, "s": 2279, "text": "The data in a Data Warehouse system is loaded with an ETL (Extract, Transform, Load) tool. As the name suggests, it performs the following three operations −" }, { "code": null, "e": 2555, "s": 2437, "text": "Extracts the data from your transactional system which can be an Oracle, Microsoft, or any other relational database," }, { "code": null, "e": 2673, "s": 2555, "text": "Extracts the data from your transactional system which can be an Oracle, Microsoft, or any other relational database," }, { "code": null, "e": 2743, "s": 2673, "text": "Transforms the data by performing data cleansing operations, and then" }, { "code": null, "e": 2813, "s": 2743, "text": "Transforms the data by performing data cleansing operations, and then" }, { "code": null, "e": 2858, "s": 2813, "text": "Loads the data into the OLAP data Warehouse." }, { "code": null, "e": 2903, "s": 2858, "text": "Loads the data into the OLAP data Warehouse." }, { "code": null, "e": 3116, "s": 2903, "text": "You can also extract data from flat files like spreadsheets and CSV files using an ETL tool and load it into an OLAP data warehouse for data analysis and reporting. Let us take an example to understand it better." }, { "code": null, "e": 3625, "s": 3116, "text": "Let us assume there is a manufacturing company having multiple departments such as sales, HR, Material Management, EWM, etc. All these departments have separate databases which they use to maintain information w.r.t. their work and each database has a different technology, landscape, table names, columns, etc. Now, if the company wants to analyze historical data and generate reports, all the data from these data sources should be extracted and loaded into a Data Warehouse to save it for analytical work." }, { "code": null, "e": 3984, "s": 3625, "text": "An ETL tool extracts the data from all these heterogeneous data sources, transforms the data (like applying calculations, joining fields, keys, removing incorrect data fields, etc.), and loads it into a Data Warehouse. Later, you can use various Business Intelligence (BI) tools to generate meaningful reports, dashboards, and visualizations using this data." }, { "code": null, "e": 4287, "s": 3984, "text": "An ETL tool is used to extract data from different data sources, transform the data, and load it into a DW system; however a BI tool is used to generate interactive and ad-hoc reports for end-users, dashboard for senior management, data visualizations for monthly, quarterly, and annual board meetings." }, { "code": null, "e": 4475, "s": 4287, "text": "The most common ETL tools include − SAP BO Data Services (BODS), Informatica – Power Center, Microsoft – SSIS, Oracle Data Integrator ODI, Talend Open Studio, Clover ETL Open source, etc." }, { "code": null, "e": 4651, "s": 4475, "text": "Some popular BI tools include − SAP Business Objects, SAP Lumira, IBM Cognos, JasperSoft, Microsoft BI Platform, Tableau, Oracle Business Intelligence Enterprise Edition, etc." }, { "code": null, "e": 4739, "s": 4651, "text": "Let us now discuss in a little more detail the key steps involved in an ETL procedure −" }, { "code": null, "e": 5029, "s": 4739, "text": "It involves extracting the data from different heterogeneous data sources. Data extraction from a transactional system varies as per the requirement and the ETL tool in use. It is normally done by running scheduled jobs in off-business hours like running jobs at night or over the weekend." }, { "code": null, "e": 5629, "s": 5029, "text": "It involves transforming the data into a suitable format that can be easily loaded into a DW system. Data transformation involves applying calculations, joins, and defining primary and foreign keys on the data. For example, if you want % of total revenue which is not in database, you will apply % formula in transformation and load the data. Similarly, if you have the first name and the last name of users in different columns, then you can apply a concatenate operation before loading the data. Some data doesn’t require any transformation; such data is known as direct move or pass through data." }, { "code": null, "e": 5879, "s": 5629, "text": "Data transformation also involves data correction and cleansing of data, removing incorrect data, incomplete data formation, and fixing data errors. It also includes data integrity and formatting incompatible data before loading it into a DW system." }, { "code": null, "e": 6042, "s": 5879, "text": "It involves loading the data into a DW system for analytical reporting and information. The target system can be a simple delimited flat file or a data warehouse." }, { "code": null, "e": 6201, "s": 6042, "text": "A typical ETL tool-based data warehouse uses staging area, data integration, and access layers to perform its functions. It’s normally a 3-layer architecture." }, { "code": null, "e": 6327, "s": 6201, "text": "Staging Layer − The staging layer or staging database is used to store the data extracted from different source data systems." }, { "code": null, "e": 6453, "s": 6327, "text": "Staging Layer − The staging layer or staging database is used to store the data extracted from different source data systems." }, { "code": null, "e": 6773, "s": 6453, "text": "Data Integration Layer − The integration layer transforms the data from the staging layer and moves the data to a database, where the data is arranged into hierarchical groups, often called dimensions, and into facts and aggregate facts. The combination of facts and dimensions tables in a DW system is called a schema." }, { "code": null, "e": 7093, "s": 6773, "text": "Data Integration Layer − The integration layer transforms the data from the staging layer and moves the data to a database, where the data is arranged into hierarchical groups, often called dimensions, and into facts and aggregate facts. The combination of facts and dimensions tables in a DW system is called a schema." }, { "code": null, "e": 7209, "s": 7093, "text": "Access Layer − The access layer is used by end-users to retrieve the data for analytical reporting and information." }, { "code": null, "e": 7325, "s": 7209, "text": "Access Layer − The access layer is used by end-users to retrieve the data for analytical reporting and information." }, { "code": null, "e": 7405, "s": 7325, "text": "The following illustration shows how the three layers interact with each other." }, { "code": null, "e": 7668, "s": 7405, "text": "ETL testing is done before data is moved into a production data warehouse system. It is sometimes also called as table balancing or production reconciliation. It is different from database testing in terms of its scope and the steps to be taken to complete this." }, { "code": null, "e": 7827, "s": 7668, "text": "The main objective of ETL testing is to identify and mitigate data defects and general errors that occur prior to processing of data for analytical reporting." }, { "code": null, "e": 7888, "s": 7827, "text": "Here is a list of the common tasks involved in ETL Testing −" }, { "code": null, "e": 7933, "s": 7888, "text": "Understand the data to be used for reporting" }, { "code": null, "e": 7955, "s": 7933, "text": "Review the Data Model" }, { "code": null, "e": 7980, "s": 7955, "text": "Source to target mapping" }, { "code": null, "e": 8007, "s": 7980, "text": "Data checks on source data" }, { "code": null, "e": 8038, "s": 8007, "text": "Packages and schema validation" }, { "code": null, "e": 8077, "s": 8038, "text": "Data verification in the target system" }, { "code": null, "e": 8148, "s": 8077, "text": "Verification of data transformation calculations and aggregation rules" }, { "code": null, "e": 8212, "s": 8148, "text": "Sample data comparison between the source and the target system" }, { "code": null, "e": 8267, "s": 8212, "text": "Data integrity and quality checks in the target system" }, { "code": null, "e": 8295, "s": 8267, "text": "Performance testing on data" }, { "code": null, "e": 8609, "s": 8295, "text": "Both ETL testing and database testing involve data validation, but they are not the same. ETL testing is normally performed on data in a data warehouse system, whereas database testing is commonly performed on transactional systems where the data comes from different applications into the transactional database." }, { "code": null, "e": 8699, "s": 8609, "text": "Here, we have highlighted the major differences between ETL testing and Database testing." }, { "code": null, "e": 8747, "s": 8699, "text": "ETL testing involves the following operations −" }, { "code": null, "e": 8813, "s": 8747, "text": "Validation of data movement from the source to the target system." }, { "code": null, "e": 8879, "s": 8813, "text": "Validation of data movement from the source to the target system." }, { "code": null, "e": 8943, "s": 8879, "text": "Verification of data count in the source and the target system." }, { "code": null, "e": 9007, "s": 8943, "text": "Verification of data count in the source and the target system." }, { "code": null, "e": 9085, "s": 9007, "text": "Verifying data extraction, transformation as per requirement and expectation." }, { "code": null, "e": 9163, "s": 9085, "text": "Verifying data extraction, transformation as per requirement and expectation." }, { "code": null, "e": 9252, "s": 9163, "text": "Verifying if table relations − joins and keys − are preserved during the transformation." }, { "code": null, "e": 9341, "s": 9252, "text": "Verifying if table relations − joins and keys − are preserved during the transformation." }, { "code": null, "e": 9404, "s": 9341, "text": "Common ETL testing tools include QuerySurge, Informatica, etc." }, { "code": null, "e": 9530, "s": 9404, "text": "Database testing stresses more on data accuracy, correctness of data and valid values. It involves the following operations −" }, { "code": null, "e": 9584, "s": 9530, "text": "Verifying if primary and foreign keys are maintained." }, { "code": null, "e": 9638, "s": 9584, "text": "Verifying if primary and foreign keys are maintained." }, { "code": null, "e": 9698, "s": 9638, "text": "Verifying if the columns in a table have valid data values." }, { "code": null, "e": 9758, "s": 9698, "text": "Verifying if the columns in a table have valid data values." }, { "code": null, "e": 9868, "s": 9758, "text": "Verifying data accuracy in columns. Example − Number of months column shouldn’t have a value greater than 12." }, { "code": null, "e": 9978, "s": 9868, "text": "Verifying data accuracy in columns. Example − Number of months column shouldn’t have a value greater than 12." }, { "code": null, "e": 10087, "s": 9978, "text": "Verifying missing data in columns. Check if there are null columns which actually should have a valid value." }, { "code": null, "e": 10196, "s": 10087, "text": "Verifying missing data in columns. Check if there are null columns which actually should have a valid value." }, { "code": null, "e": 10254, "s": 10196, "text": "Common database testing tools include Selenium, QTP, etc." }, { "code": null, "e": 10351, "s": 10254, "text": "The following table captures the key features of Database and ETL testing and their comparison −" }, { "code": null, "e": 10608, "s": 10351, "text": "ETL Testing categorization is done based on objectives of testing and reporting. Testing categories vary as per the organization standards and it also depends on the client requirements. Generally, ETL testing is categorized based on the following points −" }, { "code": null, "e": 10720, "s": 10608, "text": "Source to Target Count Testing − It involves matching of count of records in the source and the target systems." }, { "code": null, "e": 10832, "s": 10720, "text": "Source to Target Count Testing − It involves matching of count of records in the source and the target systems." }, { "code": null, "e": 11042, "s": 10832, "text": "Source to Target Data Testing − It involves data validation between the source and the target systems. It also involves data integration and threshold value check and duplicate data check in the target system." }, { "code": null, "e": 11252, "s": 11042, "text": "Source to Target Data Testing − It involves data validation between the source and the target systems. It also involves data integration and threshold value check and duplicate data check in the target system." }, { "code": null, "e": 11440, "s": 11252, "text": "Data Mapping or Transformation Testing − It confirms the mapping of objects in the source and the target systems. It also involves checking the functionality of data in the target system." }, { "code": null, "e": 11628, "s": 11440, "text": "Data Mapping or Transformation Testing − It confirms the mapping of objects in the source and the target systems. It also involves checking the functionality of data in the target system." }, { "code": null, "e": 11863, "s": 11628, "text": "End-User Testing − It involves generating reports for end-users to verify if the data in the reports are as per expectation. It involves finding deviation in reports and cross-check the data in the target system for report validation." }, { "code": null, "e": 12098, "s": 11863, "text": "End-User Testing − It involves generating reports for end-users to verify if the data in the reports are as per expectation. It involves finding deviation in reports and cross-check the data in the target system for report validation." }, { "code": null, "e": 12230, "s": 12098, "text": "Retesting − It involves fixing the bugs and defects in data in the target system and running the reports again for data validation." }, { "code": null, "e": 12362, "s": 12230, "text": "Retesting − It involves fixing the bugs and defects in data in the target system and running the reports again for data validation." }, { "code": null, "e": 12600, "s": 12362, "text": "System Integration Testing − It involves testing all the individual systems, and later combine the results to find if there are any deviations. There are three approaches that can be used to perform this: top-down, bottom-up, and hybrid." }, { "code": null, "e": 12838, "s": 12600, "text": "System Integration Testing − It involves testing all the individual systems, and later combine the results to find if there are any deviations. There are three approaches that can be used to perform this: top-down, bottom-up, and hybrid." }, { "code": null, "e": 12988, "s": 12838, "text": "Based on the structure of a Data Warehouse system, ETL testing (irrespective of the tool that is used) can be divided into the following categories −" }, { "code": null, "e": 13249, "s": 12988, "text": "In this type of testing, there is a new DW system built and verified. Data inputs are taken from customers/end-users and also from different data sources and a new data warehouse is created. Later, the data is verified in the new system with help of ETL tools." }, { "code": null, "e": 13459, "s": 13249, "text": "In migration testing, customers have an existing Data Warehouse and ETL, but they look for a new ETL tool to improve the efficiency. It involves migration of data from the existing system using a new ETL tool." }, { "code": null, "e": 13633, "s": 13459, "text": "In change testing, new data is added from different data sources to an existing system. Customers can also change the existing rules for ETL or a new rule can also be added." }, { "code": null, "e": 13827, "s": 13633, "text": "Report testing involves creating reports for data validation. Reports are the final output of any DW system. Reports are tested based on their layout, data in the report, and calculated values." }, { "code": null, "e": 14031, "s": 13827, "text": "ETL testing is different from database testing or any other conventional testing. One may have to face different types of challenges while performing ETL testing. Here we listed a few common challenges −" }, { "code": null, "e": 14065, "s": 14031, "text": "Data loss during the ETL process." }, { "code": null, "e": 14099, "s": 14065, "text": "Data loss during the ETL process." }, { "code": null, "e": 14140, "s": 14099, "text": "Incorrect, incomplete or duplicate data." }, { "code": null, "e": 14181, "s": 14140, "text": "Incorrect, incomplete or duplicate data." }, { "code": null, "e": 14316, "s": 14181, "text": "DW system contains historical data, so the data volume is too large and extremely complex to perform ETL testing in the target system." }, { "code": null, "e": 14451, "s": 14316, "text": "DW system contains historical data, so the data volume is too large and extremely complex to perform ETL testing in the target system." }, { "code": null, "e": 14649, "s": 14451, "text": "ETL testers are normally not provided with access to see job schedules in the ETL tool. They hardly have access to BI Reporting tools to see the final layout of reports and data inside the reports." }, { "code": null, "e": 14847, "s": 14649, "text": "ETL testers are normally not provided with access to see job schedules in the ETL tool. They hardly have access to BI Reporting tools to see the final layout of reports and data inside the reports." }, { "code": null, "e": 14927, "s": 14847, "text": "Tough to generate and build test cases, as data volume is too high and complex." }, { "code": null, "e": 15007, "s": 14927, "text": "Tough to generate and build test cases, as data volume is too high and complex." }, { "code": null, "e": 15117, "s": 15007, "text": "ETL testers normally don’t have an idea of end-user report requirements and business flow of the information." }, { "code": null, "e": 15227, "s": 15117, "text": "ETL testers normally don’t have an idea of end-user report requirements and business flow of the information." }, { "code": null, "e": 15319, "s": 15227, "text": "ETL testing involves various complex SQL concepts for data validation in the target system." }, { "code": null, "e": 15411, "s": 15319, "text": "ETL testing involves various complex SQL concepts for data validation in the target system." }, { "code": null, "e": 15497, "s": 15411, "text": "Sometimes the testers are not provided with the source-to-target mapping information." }, { "code": null, "e": 15583, "s": 15497, "text": "Sometimes the testers are not provided with the source-to-target mapping information." }, { "code": null, "e": 15660, "s": 15583, "text": "Unstable testing environment delay the development and testing of a process." }, { "code": null, "e": 15737, "s": 15660, "text": "Unstable testing environment delay the development and testing of a process." }, { "code": null, "e": 15903, "s": 15737, "text": "An ETL tester is primarily responsible for validating the data sources, extraction of data, applying transformation logic, and loading the data in the target tables." }, { "code": null, "e": 15963, "s": 15903, "text": "The key responsibilities of an ETL tester are listed below." }, { "code": null, "e": 16002, "s": 15963, "text": "It involves the following operations −" }, { "code": null, "e": 16014, "s": 16002, "text": "Count check" }, { "code": null, "e": 16053, "s": 16014, "text": "Reconcile records with the source data" }, { "code": null, "e": 16069, "s": 16053, "text": "Data type check" }, { "code": null, "e": 16096, "s": 16069, "text": "Ensure no spam data loaded" }, { "code": null, "e": 16118, "s": 16096, "text": "Remove duplicate data" }, { "code": null, "e": 16150, "s": 16118, "text": "Check all the keys are in place" }, { "code": null, "e": 16246, "s": 16150, "text": "Transformation logic is applied before loading the data. It involves the following operations −" }, { "code": null, "e": 16330, "s": 16246, "text": "Data threshold validation check, for example, age value shouldn’t be more than 100." }, { "code": null, "e": 16414, "s": 16330, "text": "Data threshold validation check, for example, age value shouldn’t be more than 100." }, { "code": null, "e": 16485, "s": 16414, "text": "Record count check, before and after the transformation logic applied." }, { "code": null, "e": 16556, "s": 16485, "text": "Record count check, before and after the transformation logic applied." }, { "code": null, "e": 16627, "s": 16556, "text": "Data flow validation from the staging area to the intermediate tables." }, { "code": null, "e": 16698, "s": 16627, "text": "Data flow validation from the staging area to the intermediate tables." }, { "code": null, "e": 16719, "s": 16698, "text": "Surrogate key check." }, { "code": null, "e": 16740, "s": 16719, "text": "Surrogate key check." }, { "code": null, "e": 16838, "s": 16740, "text": "Data is loaded from the staging area to the target system. It involves the following operations −" }, { "code": null, "e": 16907, "s": 16838, "text": "Record count check from the intermediate table to the target system." }, { "code": null, "e": 16976, "s": 16907, "text": "Record count check from the intermediate table to the target system." }, { "code": null, "e": 17026, "s": 16976, "text": "Ensure the key field data is not missing or Null." }, { "code": null, "e": 17076, "s": 17026, "text": "Ensure the key field data is not missing or Null." }, { "code": null, "e": 17161, "s": 17076, "text": "Check if the aggregate values and calculated measures are loaded in the fact tables." }, { "code": null, "e": 17246, "s": 17161, "text": "Check if the aggregate values and calculated measures are loaded in the fact tables." }, { "code": null, "e": 17295, "s": 17246, "text": "Check modeling views based on the target tables." }, { "code": null, "e": 17344, "s": 17295, "text": "Check modeling views based on the target tables." }, { "code": null, "e": 17405, "s": 17344, "text": "Check if CDC has been applied on the incremental load table." }, { "code": null, "e": 17466, "s": 17405, "text": "Check if CDC has been applied on the incremental load table." }, { "code": null, "e": 17521, "s": 17466, "text": "Data check in dimension table and history table check." }, { "code": null, "e": 17576, "s": 17521, "text": "Data check in dimension table and history table check." }, { "code": null, "e": 17675, "s": 17576, "text": "Check the BI reports based on the loaded fact and dimension table and as per the expected results." }, { "code": null, "e": 17774, "s": 17675, "text": "Check the BI reports based on the loaded fact and dimension table and as per the expected results." }, { "code": null, "e": 17884, "s": 17774, "text": "ETL testers are required to test the tools and the test-cases as well. It involves the following operations −" }, { "code": null, "e": 17920, "s": 17884, "text": "Test the ETL tool and its functions" }, { "code": null, "e": 17955, "s": 17920, "text": "Test the ETL Data Warehouse system" }, { "code": null, "e": 18014, "s": 17955, "text": "Create, design, and execute the test plans and test cases." }, { "code": null, "e": 18049, "s": 18014, "text": "Test the flat file data transfers." }, { "code": null, "e": 18407, "s": 18049, "text": "It is important that you define the correct ETL Testing technique before starting the testing process. You should take an acceptance from all the stakeholders and ensure that a correct technique is selected to perform ETL testing. This technique should be well known to the testing team and they should be aware of the steps involved in the testing process." }, { "code": null, "e": 18537, "s": 18407, "text": "There are various types of testing techniques that can be used. In this chapter, we will discuss the testing techniques in brief." }, { "code": null, "e": 18799, "s": 18537, "text": "To perform Analytical Reporting and Analysis, the data in your production should be correct. This testing is done on the data that is moved to the production system. It involves data validation in the production system and comparing it the with the source data." }, { "code": null, "e": 19133, "s": 18799, "text": "This type of testing is done when the tester has less time to perform the testing operation. It involves checking the count of data in the source and the target systems. It doesn’t involve checking the values of data in the target system. It also doesn’t involve if the data is in ascending or descending order after mapping of data." }, { "code": null, "e": 19446, "s": 19133, "text": "In this type of testing, a tester validates data values from the source to the target system. It checks the data values in the source system and the corresponding values in the target system after transformation. This type of testing is time-consuming and is normally performed in financial and banking projects." }, { "code": null, "e": 19728, "s": 19446, "text": "In this type of testing, a tester validates the range of data. All the threshold values in the target system are checked if they are as per the expected result. It also involves integration of data in the target system from multiple source systems after transformation and loading." }, { "code": null, "e": 19878, "s": 19728, "text": "Example − Age attribute shouldn’t have a value greater than 100. In the date column DD/MM/YY, the month field shouldn’t have a value greater than 12." }, { "code": null, "e": 20156, "s": 19878, "text": "Application migration testing is normally performed automatically when you move from an old application to a new application system. This testing saves a lot of time. It checks if the data extracted from an old application is same as per the data in the new application system." }, { "code": null, "e": 20365, "s": 20156, "text": "It includes performing various checks such as data type check, data length check, and index check. Here a Test Engineer performs the following scenarios − Primary Key, Foreign Key, NOT NULL, NULL, and UNIQUE." }, { "code": null, "e": 20621, "s": 20365, "text": "This testing involves checking for duplicate data in the target system. When there is a huge amount of data in the target system, it is possible that there is duplicate data in the production system that may result in incorrect data in Analytical Reports." }, { "code": null, "e": 20679, "s": 20621, "text": "Duplicate values can be checked with SQL statement like −" }, { "code": null, "e": 20801, "s": 20679, "text": "Select Cust_Id, Cust_NAME, Quantity, COUNT (*) \nFROM Customer\nGROUP BY Cust_Id, Cust_NAME, Quantity HAVING COUNT (*) >1;\n" }, { "code": null, "e": 20876, "s": 20801, "text": "Duplicate data appears in the target system due to the following reasons −" }, { "code": null, "e": 20938, "s": 20876, "text": "If no primary key is defined, then duplicate values may come." }, { "code": null, "e": 20988, "s": 20938, "text": "Due to incorrect mapping or environmental issues." }, { "code": null, "e": 21064, "s": 20988, "text": "Manual errors while transferring data from the source to the target system." }, { "code": null, "e": 21355, "s": 21064, "text": "Data transformation testing is not performed by running a single SQL statement. It is time-consuming and involves running multiple SQL queries for each row to verify the transformation rules. The tester needs to run SQL queries for each row and then compare the output with the target data." }, { "code": null, "e": 21628, "s": 21355, "text": "Data quality testing involves performing number check, date check, null check, precision check, etc. A tester performs Syntax Test to report invalid characters, incorrect upper/lower case order, etc. and Reference Tests to check if the data is according to the data model." }, { "code": null, "e": 21806, "s": 21628, "text": "Incremental testing is performed to verify if Insert and Update statements are executed as per the expected result. This testing is performed step-by-step with old and new data." }, { "code": null, "e": 22056, "s": 21806, "text": "When we make changes to data transformation and aggregation rules to add new functionality which also helps the tester to find new errors, it is called Regression Testing. The bugs in data that that comes in regression testing are called Regression." }, { "code": null, "e": 22127, "s": 22056, "text": "When you run the tests after fixing the codes, it is called retesting." }, { "code": null, "e": 22334, "s": 22127, "text": "System integration testing involves testing the components of a system individually and later integrating the modules. There are three ways a system integration can be done: top-down, bottom-up, and hybrid." }, { "code": null, "e": 22571, "s": 22334, "text": "Navigation testing is also known as testing the front-end of the system. It involves enduser point of view testing by checking all the aspects of the front-end report − includes data in various fields, calculation and aggregates, etc." }, { "code": null, "e": 22730, "s": 22571, "text": "ETL testing covers all the steps involved in an ETL lifecycle. It starts with understanding the business requirements till the generation of a summary report." }, { "code": null, "e": 22794, "s": 22730, "text": "The common steps under ETL Testing lifecycle are listed below −" }, { "code": null, "e": 22834, "s": 22794, "text": "Understanding the business requirement." }, { "code": null, "e": 22874, "s": 22834, "text": "Understanding the business requirement." }, { "code": null, "e": 22914, "s": 22874, "text": "Validation of the business requirement." }, { "code": null, "e": 22954, "s": 22914, "text": "Validation of the business requirement." }, { "code": null, "e": 23062, "s": 22954, "text": "Test Estimation is used to provide the estimated time to run test-cases and to complete the summary report." }, { "code": null, "e": 23170, "s": 23062, "text": "Test Estimation is used to provide the estimated time to run test-cases and to complete the summary report." }, { "code": null, "e": 23272, "s": 23170, "text": "Test Planning involves finding the Testing technique based on the inputs as per business requirement." }, { "code": null, "e": 23374, "s": 23272, "text": "Test Planning involves finding the Testing technique based on the inputs as per business requirement." }, { "code": null, "e": 23414, "s": 23374, "text": "Creating test scenarios and test cases." }, { "code": null, "e": 23454, "s": 23414, "text": "Creating test scenarios and test cases." }, { "code": null, "e": 23547, "s": 23454, "text": "Once the test-cases are ready and approved, the next step is to perform pre-execution check." }, { "code": null, "e": 23640, "s": 23547, "text": "Once the test-cases are ready and approved, the next step is to perform pre-execution check." }, { "code": null, "e": 23668, "s": 23640, "text": "Execute all the test-cases." }, { "code": null, "e": 23696, "s": 23668, "text": "Execute all the test-cases." }, { "code": null, "e": 23779, "s": 23696, "text": "The last step is to generate a complete summary report and file a closure process." }, { "code": null, "e": 23862, "s": 23779, "text": "The last step is to generate a complete summary report and file a closure process." }, { "code": null, "e": 24034, "s": 23862, "text": "ETL Test Scenarios are used to validate an ETL Testing Process. The following table explains some of the most common scenarios and test-cases that are used by ETL testers." }, { "code": null, "e": 24055, "s": 24034, "text": "Structure Validation" }, { "code": null, "e": 24149, "s": 24055, "text": "It involves validating the source and the target table structure as per the mapping document." }, { "code": null, "e": 24217, "s": 24149, "text": "Data type should be validated in the source and the target systems." }, { "code": null, "e": 24294, "s": 24217, "text": "The length of data types in the source and the target system should be same." }, { "code": null, "e": 24380, "s": 24294, "text": "Data field types and their format should be same in the source and the target system." }, { "code": null, "e": 24430, "s": 24380, "text": "Validating the column names in the target system." }, { "code": null, "e": 24458, "s": 24430, "text": "Validating Mapping document" }, { "code": null, "e": 24652, "s": 24458, "text": "It involves validating the mapping document to ensure all the information has been provided. The mapping document should have change log, maintain data types, length, transformation rules, etc." }, { "code": null, "e": 24673, "s": 24652, "text": "Validate Constraints" }, { "code": null, "e": 24771, "s": 24673, "text": "It involves validating the constraints and ensuring that they are applied on the expected tables." }, { "code": null, "e": 24794, "s": 24771, "text": "Data Consistency check" }, { "code": null, "e": 24869, "s": 24794, "text": "It involves checking the misuse of integrity constraints like Foreign Key." }, { "code": null, "e": 25000, "s": 24869, "text": "The length and data type of an attribute may vary in different tables, though their definition remains same at the semantic layer." }, { "code": null, "e": 25029, "s": 25000, "text": "Data Completeness Validation" }, { "code": null, "e": 25121, "s": 25029, "text": "It involves checking if all the data is loaded to the target system from the source system." }, { "code": null, "e": 25190, "s": 25121, "text": "Counting the number of records in the source and the target systems." }, { "code": null, "e": 25215, "s": 25190, "text": "Boundary value analysis." }, { "code": null, "e": 25261, "s": 25215, "text": "Validating the unique values of primary keys." }, { "code": null, "e": 25289, "s": 25261, "text": "Data Correctness Validation" }, { "code": null, "e": 25353, "s": 25289, "text": "It involves validating the values of data in the target system." }, { "code": null, "e": 25402, "s": 25353, "text": "Misspelled or inaccurate data is found in table." }, { "code": null, "e": 25495, "s": 25402, "text": "Null, Not Unique data is stored when you disable integrity constraint at the time of import." }, { "code": null, "e": 25521, "s": 25495, "text": "Data Transform validation" }, { "code": null, "e": 25643, "s": 25521, "text": "It involves creating a spreadsheet of scenarios for input values and expected results and then validating with end-users." }, { "code": null, "e": 25715, "s": 25643, "text": "Validating parent-child relationship in the data by creating scenarios." }, { "code": null, "e": 25782, "s": 25715, "text": "Using data profiling to compare the range of values in each field." }, { "code": null, "e": 25869, "s": 25782, "text": "Validating if the data types in the warehouse are same as mentioned in the data model." }, { "code": null, "e": 25893, "s": 25869, "text": "Data Quality Validation" }, { "code": null, "e": 25988, "s": 25893, "text": "It involves performing number check, date check, precision check, data check, Null check, etc." }, { "code": null, "e": 26045, "s": 25988, "text": "Example − Date format should be same for all the values." }, { "code": null, "e": 26061, "s": 26045, "text": "Null Validation" }, { "code": null, "e": 26142, "s": 26061, "text": "It involves checking the Null values where Not Null is mentioned for that field." }, { "code": null, "e": 26163, "s": 26142, "text": "Duplicate Validation" }, { "code": null, "e": 26290, "s": 26163, "text": "It involves validating duplicate values in the target system when data is coming from multiple columns from the source system." }, { "code": null, "e": 26398, "s": 26290, "text": "Validating primary keys and other columns if there is any duplicate values as per the business requirement." }, { "code": null, "e": 26420, "s": 26398, "text": "Date Validation check" }, { "code": null, "e": 26488, "s": 26420, "text": "Validating date field for various actions performed in ETL process." }, { "code": null, "e": 26535, "s": 26488, "text": "Common test-cases to perform Date validation −" }, { "code": null, "e": 26577, "s": 26535, "text": "From_Date should not greater than To_Date" }, { "code": null, "e": 26619, "s": 26577, "text": "From_Date should not greater than To_Date" }, { "code": null, "e": 26659, "s": 26619, "text": "Format of date values should be proper." }, { "code": null, "e": 26699, "s": 26659, "text": "Format of date values should be proper." }, { "code": null, "e": 26758, "s": 26699, "text": "Date values should not have any junk values or null values" }, { "code": null, "e": 26817, "s": 26758, "text": "Date values should not have any junk values or null values" }, { "code": null, "e": 26850, "s": 26817, "text": "Full Data Validation Minus Query" }, { "code": null, "e": 26945, "s": 26850, "text": "It involves validating full data set in the source and the target tables by using minus query." }, { "code": null, "e": 27015, "s": 26945, "text": "You need to perform both source minus target and target minus source." }, { "code": null, "e": 27085, "s": 27015, "text": "You need to perform both source minus target and target minus source." }, { "code": null, "e": 27168, "s": 27085, "text": "If the minus query returns a value, that should be considered as mismatching rows." }, { "code": null, "e": 27251, "s": 27168, "text": "If the minus query returns a value, that should be considered as mismatching rows." }, { "code": null, "e": 27330, "s": 27251, "text": "You need to match the rows in source and target using the Intersect statement." }, { "code": null, "e": 27409, "s": 27330, "text": "You need to match the rows in source and target using the Intersect statement." }, { "code": null, "e": 27510, "s": 27409, "text": "The count returned by Intersect should match with the individual counts of source and target tables." }, { "code": null, "e": 27611, "s": 27510, "text": "The count returned by Intersect should match with the individual counts of source and target tables." }, { "code": null, "e": 27764, "s": 27611, "text": "If the minus query returns no rows and the count intersect is less than the source count or the target table count, then the table holds duplicate rows." }, { "code": null, "e": 27917, "s": 27764, "text": "If the minus query returns no rows and the count intersect is less than the source count or the target table count, then the table holds duplicate rows." }, { "code": null, "e": 27938, "s": 27917, "text": "Other Test Scenarios" }, { "code": null, "e": 28059, "s": 27938, "text": "Other Test scenarios can be to verify that the extraction process did not extract duplicate data from the source system." }, { "code": null, "e": 28208, "s": 28059, "text": "The testing team will maintain a list of SQL statements that are run to validate that no duplicate data have been extracted from the source systems." }, { "code": null, "e": 28222, "s": 28208, "text": "Data Cleaning" }, { "code": null, "e": 28299, "s": 28222, "text": "Unwanted data should be removed before loading the data to the staging area." }, { "code": null, "e": 28712, "s": 28299, "text": "ETL performance tuning is used to ensure if an ETL system can handle an expected load of multiple users and transactions. Performance tuning typically involves server-side workload on the ETL system. It is used to test the server response in multiuser environment and to find bottlenecks. These can be found in source and target systems, mapping of systems, configuration like session management properties, etc." }, { "code": null, "e": 28785, "s": 28712, "text": "Follow the steps given below to perform ETL testing performance tuning −" }, { "code": null, "e": 28849, "s": 28785, "text": "Step 1 − Find the load that is being transformed in production." }, { "code": null, "e": 28913, "s": 28849, "text": "Step 1 − Find the load that is being transformed in production." }, { "code": null, "e": 29019, "s": 28913, "text": "Step 2 − Create new data of that same load or move from Production data to your local performance server." }, { "code": null, "e": 29125, "s": 29019, "text": "Step 2 − Create new data of that same load or move from Production data to your local performance server." }, { "code": null, "e": 29188, "s": 29125, "text": "Step 3 − Disable the ETL until you generate the load required." }, { "code": null, "e": 29251, "s": 29188, "text": "Step 3 − Disable the ETL until you generate the load required." }, { "code": null, "e": 29327, "s": 29251, "text": "Step 4 − Take the count of the needed data from the tables of the database." }, { "code": null, "e": 29403, "s": 29327, "text": "Step 4 − Take the count of the needed data from the tables of the database." }, { "code": null, "e": 29541, "s": 29403, "text": "Step 5 − Note down the last run of ETL and enable the ETL, so that it will get enough stress to transform the entire load created. Run it" }, { "code": null, "e": 29679, "s": 29541, "text": "Step 5 − Note down the last run of ETL and enable the ETL, so that it will get enough stress to transform the entire load created. Run it" }, { "code": null, "e": 29757, "s": 29679, "text": "Step 6 − After the ETL completes its run, take the count of the data created." }, { "code": null, "e": 29835, "s": 29757, "text": "Step 6 − After the ETL completes its run, take the count of the data created." }, { "code": null, "e": 29890, "s": 29835, "text": "Find out the total time it took to transform the load." }, { "code": null, "e": 29949, "s": 29890, "text": "Find out whether performance time has improved or dropped." }, { "code": null, "e": 30016, "s": 29949, "text": "Check that the entire expected load got extracted and transferred." }, { "code": null, "e": 30146, "s": 30016, "text": "The goal of ETL testing is to achieve credible data. Data credibility can be attained by making the testing cycle more effective." }, { "code": null, "e": 30472, "s": 30146, "text": "A comprehensive test strategy is the setting up of an effective test cycle. The testing strategy should cover test planning for each stage of ETL process, every time the data moves and state the responsibilities of each stakeholder, e.g., business analysts, infrastructure team, QA team, DBA’s, Developers and Business Users." }, { "code": null, "e": 30570, "s": 30472, "text": "To ensure testing readiness from all aspects, the key areas a test strategy should focus on are −" }, { "code": null, "e": 30639, "s": 30570, "text": "Scope of testing − Describe testing techniques and types to be used." }, { "code": null, "e": 30708, "s": 30639, "text": "Scope of testing − Describe testing techniques and types to be used." }, { "code": null, "e": 30741, "s": 30708, "text": "Setting up the test environment." }, { "code": null, "e": 30774, "s": 30741, "text": "Setting up the test environment." }, { "code": null, "e": 30890, "s": 30774, "text": "Test data availability − It is recommended to have production like data covering all/critical business requirement." }, { "code": null, "e": 31006, "s": 30890, "text": "Test data availability − It is recommended to have production like data covering all/critical business requirement." }, { "code": null, "e": 31056, "s": 31006, "text": "Data quality and performance acceptance criteria." }, { "code": null, "e": 31106, "s": 31056, "text": "Data quality and performance acceptance criteria." }, { "code": null, "e": 31287, "s": 31106, "text": "In ETL testing, data accuracy is used to ensure if data is accurately loaded to the target system as per the expectation. The key steps in performing data accuracy are as follows −" }, { "code": null, "e": 31505, "s": 31287, "text": "Value comparison involves comparing the data in source and target system with minimum or no transformation. It can be done using various ETL Testing tools, for example, Source Qualifier Transformation in Informatica." }, { "code": null, "e": 31859, "s": 31505, "text": "Some expression transformations can also be performed in data accuracy testing. Various set operators can be used in SQL statements to check data accuracy in the source and the target systems. Common operators are Minus and Intersect operators. The results of these operators can be considered as deviation in value in the target and the source system." }, { "code": null, "e": 32036, "s": 31859, "text": "Critical data columns can be checked by comparing distinct values in the source and the target systems. Here is a sample query that can be used to check critical data columns −" }, { "code": null, "e": 32131, "s": 32036, "text": "SELECT cust_name, Order_Id, city, count(*) FROM customer \nGROUP BY cust_name, Order_Id, city;\n" }, { "code": null, "e": 32447, "s": 32131, "text": "Checking the metadata involves validating the source and the target table structure w.r.t. the mapping document. The mapping document has details of the source and target columns, data transformations rules and the data types, all the fields that define the structure of tables in the source and the target systems." }, { "code": null, "e": 32810, "s": 32447, "text": "The length of target column data type should be equal to or greater than the source column data type. Let us take an example. Suppose you have the first names and the last names in the source table and the data length for each is defined as 50 characters. Then, the target data length for full name column in the target system should be a minimum of 100 or more." }, { "code": null, "e": 33089, "s": 32810, "text": "Data type checking involves verifying the source and the target data type and ensuring that they are same. There is a possibility that the target data type is different from the source data after a transformation. Hence there is a need to check the transformation rules as well." }, { "code": null, "e": 33342, "s": 33089, "text": "Constraint checking involves verifying the index values and constraints as per the design specification document. All the columns that cannot have Null values should have Not Null constraint. Primary keys columns are indexed as per the design document." }, { "code": null, "e": 33623, "s": 33342, "text": "Performing data transformations is a bit complex, as it cannot be achieved by writing a single SQL query and then comparing the output with the target. For ETL Testing Data Transformation, you may have to write multiple SQL queries for each row to verify the transformation rules." }, { "code": null, "e": 33893, "s": 33623, "text": "To start with, make sure the source data is sufficient to test all the transformation rules. The key to perform a successful ETL testing for data transformations is to pick the correct and sufficient sample data from the source system to apply the transformation rules." }, { "code": null, "e": 33962, "s": 33893, "text": "The key steps for ETL Testing Data Transformation are listed below −" }, { "code": null, "e": 34206, "s": 33962, "text": "The first step is to create a list of scenarios of input data and the expected results and validate these with the business customer. This is a good approach for requirements gathering during design and could also be used as a part of testing." }, { "code": null, "e": 34450, "s": 34206, "text": "The first step is to create a list of scenarios of input data and the expected results and validate these with the business customer. This is a good approach for requirements gathering during design and could also be used as a part of testing." }, { "code": null, "e": 34728, "s": 34450, "text": "The next step is to create the test data that contains all the scenarios. Utilize an ETL developer to automate the entire process of populating the datasets with the scenario spreadsheet to permit versatility and mobility for the reason that the scenarios are likely to change." }, { "code": null, "e": 35006, "s": 34728, "text": "The next step is to create the test data that contains all the scenarios. Utilize an ETL developer to automate the entire process of populating the datasets with the scenario spreadsheet to permit versatility and mobility for the reason that the scenarios are likely to change." }, { "code": null, "e": 35139, "s": 35006, "text": "Next, utilize data profiling results to compare the range and submission of values in each field between the target and source data." }, { "code": null, "e": 35272, "s": 35139, "text": "Next, utilize data profiling results to compare the range and submission of values in each field between the target and source data." }, { "code": null, "e": 35352, "s": 35272, "text": "Validate the accurate processing of ETL generated fields, e.g., surrogate keys." }, { "code": null, "e": 35432, "s": 35352, "text": "Validate the accurate processing of ETL generated fields, e.g., surrogate keys." }, { "code": null, "e": 35538, "s": 35432, "text": "Validating the data types within the warehouse are the same as was specified in the data model or design." }, { "code": null, "e": 35644, "s": 35538, "text": "Validating the data types within the warehouse are the same as was specified in the data model or design." }, { "code": null, "e": 35714, "s": 35644, "text": "Create data scenarios between tables that test referential integrity." }, { "code": null, "e": 35784, "s": 35714, "text": "Create data scenarios between tables that test referential integrity." }, { "code": null, "e": 35840, "s": 35784, "text": "Validate the parent-to-child relationships in the data." }, { "code": null, "e": 35896, "s": 35840, "text": "Validate the parent-to-child relationships in the data." }, { "code": null, "e": 36320, "s": 35896, "text": "The final step is to perform lookup transformation. Your lookup query should be straight without any aggregation and expected to return only one value per the source table. You can directly join the lookup table in the source qualifier as in the previous test. If this is not the case, write a query joining the lookup table with the main table in the source and compare the data in the corresponding columns in the target." }, { "code": null, "e": 36744, "s": 36320, "text": "The final step is to perform lookup transformation. Your lookup query should be straight without any aggregation and expected to return only one value per the source table. You can directly join the lookup table in the source qualifier as in the previous test. If this is not the case, write a query joining the lookup table with the main table in the source and compare the data in the corresponding columns in the target." }, { "code": null, "e": 36899, "s": 36744, "text": "Checking data quality during ETL testing involves performing quality checks on data that is loaded in the target system. It includes the following tests −" }, { "code": null, "e": 37130, "s": 36899, "text": "The Number format should be same across the target system. For example, in the source system, the format of numbering the columns is x.30, but if the target is only 30, then it has to load not prefixing x. in target column number." }, { "code": null, "e": 37301, "s": 37130, "text": "The Date format should be consistent in both the source and the target systems. For example, it should be same across all the records. The Standard format is: yyyy-mm-dd." }, { "code": null, "e": 37492, "s": 37301, "text": "Precision value should display as expected in the target table. For example, in the source table, the value is 15.2323422, but in the target table, it should display as 15.23 or round of 15." }, { "code": null, "e": 37624, "s": 37492, "text": "It involves checking the data as per the business requirement. The records that don’t meet certain criteria should be filtered out." }, { "code": null, "e": 37731, "s": 37624, "text": "Example − Only those records whose date_id >=2015 and Account_Id != ‘001’ should load in the target table." }, { "code": null, "e": 37820, "s": 37731, "text": "Some columns should have Null as per the requirement and possible values for that field." }, { "code": null, "e": 37938, "s": 37820, "text": "Example − Termination Date column should display Null unless and until its Active status Column is “T” or “Deceased”." }, { "code": null, "e": 38012, "s": 37938, "text": "Common checks like From_Date should not greater than To_Date can be done." }, { "code": null, "e": 38129, "s": 38012, "text": "Checking Data Completeness is done to verify that the data in the target system is as per expectation after loading." }, { "code": null, "e": 38194, "s": 38129, "text": "The common tests that can be performed for this are as follows −" }, { "code": null, "e": 38247, "s": 38194, "text": "Checking Aggregate functions (sum, max, min, count)," }, { "code": null, "e": 38300, "s": 38247, "text": "Checking Aggregate functions (sum, max, min, count)," }, { "code": null, "e": 38457, "s": 38300, "text": "Checking and validating the counts and the actual data between the source and the target for columns without transformations or with simple transformations." }, { "code": null, "e": 38614, "s": 38457, "text": "Checking and validating the counts and the actual data between the source and the target for columns without transformations or with simple transformations." }, { "code": null, "e": 38740, "s": 38614, "text": "Compare the count of number of records in the source and the target tables. It can be done by writing the following queries −" }, { "code": null, "e": 38806, "s": 38740, "text": "SELECT count (1) FROM employee; \nSELECT count (1) FROM emp_dim; \n" }, { "code": null, "e": 38932, "s": 38806, "text": "It involves checking the aggregate functions such as count, sum, and max in the source and target tables (fact or dimension)." }, { "code": null, "e": 39021, "s": 38932, "text": "It involves comparing the distinct values and the count of rows for each distinct value." }, { "code": null, "e": 39130, "s": 39021, "text": "SELECT city, count(*) FROM employee GROUP BY city; \nSELECT city_id, count(*) FROM emp_dim GROUP BY city_id;\n" }, { "code": null, "e": 39356, "s": 39130, "text": "It involves validating the primary key and the unique key in a column or in combination of columns that should be unique as per the business requirements. You can use the following query to perform duplicate data validation −" }, { "code": null, "e": 39478, "s": 39356, "text": "SELECT first_name, last_name, date_of_joining, count (1) FROM employee\nGROUP BY first_name, last_name HAVING count(1)>1;\n" }, { "code": null, "e": 39670, "s": 39478, "text": "Backup recovery for a system is planned to ensure that system is restored as soon as possible from a failure and operations are resumed as early as possible without losing any important data." }, { "code": null, "e": 39842, "s": 39670, "text": "ETL Backup recovery testing is used to ensure that the Data Warehouse system recovers successfully from hardware, software, or from a network failure with losing any data." }, { "code": null, "e": 40032, "s": 39842, "text": "A proper backup plan must be prepared to ensure maximum system availability. Backup systems should be able to restore with ease and should take over the failed system without any data loss." }, { "code": null, "e": 40305, "s": 40032, "text": "ETL Testing Backup recovery involves exposing the application or the DW system to extreme conditions for any hardware component, software crash, etc. The next step is to ensure that recovery process is initiated, system verification is done, and data recovery is achieved." }, { "code": null, "e": 40506, "s": 40305, "text": "ETL testing is mostly done using SQL scripts and gathering the data in spreadsheets. This approach to perform ETL testing is very slow and time-consuming, error-prone, and is performed on sample data." }, { "code": null, "e": 40780, "s": 40506, "text": "Your ETL test team writes SQL queries to test data in a warehouse system and they need to execute them manually using a SQL editor and then put the data into an Excel spreadsheet and compare them manually. This process is time-consuming, resourceintensive, and inefficient." }, { "code": null, "e": 40936, "s": 40780, "text": "There are various tools available in the market to automate this process. The most common ETL Testing tools are QuerySurge and Informatica Data Validation." }, { "code": null, "e": 41128, "s": 40936, "text": "QuerySurge is a data testing solution designed for testing Big Data, Data Warehouses, and the ETL process. It can automate the entire process for you and fit nicely into your DevOps strategy." }, { "code": null, "e": 41176, "s": 41128, "text": "The key features of QuerySurge are as follows −" }, { "code": null, "e": 41281, "s": 41176, "text": "It has Query Wizards to create test QueryPairs fast and easily without the user having to write any SQL." }, { "code": null, "e": 41386, "s": 41281, "text": "It has Query Wizards to create test QueryPairs fast and easily without the user having to write any SQL." }, { "code": null, "e": 41482, "s": 41386, "text": "It has a Design Library with reusable Query Snippets. You can create custom QueryPairs as well." }, { "code": null, "e": 41578, "s": 41482, "text": "It has a Design Library with reusable Query Snippets. You can create custom QueryPairs as well." }, { "code": null, "e": 41680, "s": 41578, "text": "It can compare data from source files and data stores to the target Data Warehouse or Big Data store." }, { "code": null, "e": 41782, "s": 41680, "text": "It can compare data from source files and data stores to the target Data Warehouse or Big Data store." }, { "code": null, "e": 41846, "s": 41782, "text": "It can compare millions of rows and columns of data in minutes." }, { "code": null, "e": 41910, "s": 41846, "text": "It can compare millions of rows and columns of data in minutes." }, { "code": null, "e": 42032, "s": 41910, "text": "It allows the user to schedule tests to run (1) immediately, (2) any date/time, or (3) automatically after an event ends." }, { "code": null, "e": 42154, "s": 42032, "text": "It allows the user to schedule tests to run (1) immediately, (2) any date/time, or (3) automatically after an event ends." }, { "code": null, "e": 42241, "s": 42154, "text": "It can produce informative reports, view updates, and auto-email results to your team." }, { "code": null, "e": 42328, "s": 42241, "text": "It can produce informative reports, view updates, and auto-email results to your team." }, { "code": null, "e": 42474, "s": 42328, "text": "To automate the entire process, your ETL tool should start QuerySurge through command line API after the ETL software completes its load process." }, { "code": null, "e": 42597, "s": 42474, "text": "QuerySurge will run automatically and unattended, executing all tests and then emailing everyone on the team with results." }, { "code": null, "e": 42913, "s": 42597, "text": "Just like QuerySurge, Informatica Data Validation provides an ETL testing tool that helps you to accelerate and automate the ETL testing process in the development and production environment. It allows you to deliver complete, repeatable, and auditable test coverage in less time. It requires no programming skills!" }, { "code": null, "e": 43228, "s": 42913, "text": "To test a data warehouse system or a BI application, one needs to have a data-centric approach. ETL Testing best practices help to minimize the cost and time to perform the testing. It improves the quality of data to be loaded to the target system which generates high quality dashboards and reports for end-users." }, { "code": null, "e": 43308, "s": 43228, "text": "We have listed here a few best practices that can be followed for ETL Testing −" }, { "code": null, "e": 43776, "s": 43308, "text": "It is extremely important to analyze the data to understand requirements in order to set up a correct data model. Spending time to understand the requirements and having a correct data model for the target system can reduce the ETL challenges. It is also important to study the source systems, data quality, and build correct data validation rules for ETL modules. An ETL strategy should be formulated based on the data structure of the source and the target systems." }, { "code": null, "e": 44134, "s": 43776, "text": "End-users are normally aware of data issues, but they have no idea on how to fix them. It is important to find these errors and correct them before they reach the ETL system. A common way to resolve this is at the ETL execution time, but the best practice is to find the errors in the source system and take steps to rectify them at the source system level." }, { "code": null, "e": 44487, "s": 44134, "text": "One of the common ETL best practices is to select a tool that is most compatible with the source and the target systems. The ETL tool’s capability to generate SQL scripts for the source and the target systems can reduce the processing time and resources. It allows one to process transformation anywhere within the environment that is most appropriate." }, { "code": null, "e": 44646, "s": 44487, "text": "Another best practice during ETL implementation is scheduling, auditing, and monitoring of ETL jobs to ensure that the loads are performed as per expectation." }, { "code": null, "e": 44954, "s": 44646, "text": "Sometimes, data warehouse tables are larger in size and it is not possible to refresh them during every ETL cycle. Incremental loads ensure that only records changed since the last update are brought into the ETL process and it puts a huge impact on the scalability and the time taken to refresh the system." }, { "code": null, "e": 45349, "s": 44954, "text": "Normally the source systems don’t have timestamps or a primary key to identify the changes easily. Such problems can be very costly, if identified at the later stages of the project. One of the ETL best practices is to cover such aspects in the initial source system study. This knowledge helps the ETL team to identify changed data capture problems and determine the most appropriate strategy." } ]
Invoking an overloaded constructor using this keyword in C#
27 Aug, 2021 Prerequisite : Constructors in C#C# provides a powerful keyword known as this keyword and this keyword has many usages. Here we use this keyword to call an overloaded constructor from another constructor.Important Points: When you use this keyword to call a constructor, the constructor should belong to the same class. You can also pass parameter in this keyword. This keyword always pointing to the members of the same class in which it is used. When you use this keyword, it tells the compiler to invoke the default constructor. Or in other words, it means a constructor that does not contain arguments.Syntax: class X { public X: this() { // Code.. } } this keyword contains the same type and the same number of parameters that are present in the calling constructor.Syntax: class X { public X(int x): this(int) { // Code.. } } This concept removes the assignment of replication of properties in the same class. Below programs illustrate how to call the overloaded constructor using this keyword:Example 1: CSharp // C# program to illustrate how to invoke// overloaded constructor using this keywordusing System;class Geek { // Constructor without parameter public Geek() { Console.WriteLine("Hello! Constructor 1"); } // Constructor with parameter // Here this keyword is used // to call Geek constructor public Geek(int a) : this() { Console.WriteLine("Hello! Constructor 2"); }} // Driver Classpublic class GFG { // Main method static public void Main() { // Create object of Geek class Geek obj = new Geek(2); }} Output: Hello! Constructor 1 Hello! Constructor 2 Explanation: In the above example, Geek class contains two constructors, i.e, Geek() is without parameter and Geek(int a) is with parameter. Now we call Geek() constructor in Geek(int a) by using this() keyword. Here this() keyword does not contain any argument because the constructor does not contain any parameter. Example 2: CSharp // C# program to illustrate how to invoke// overloaded constructor using this keywordusing System;class Geek { // Constructor with parameters public Geek(int a, double b, string c) { Console.WriteLine(a); Console.WriteLine(b); Console.WriteLine(c); } // Constructor with parameters // Here this keyword is used // to call Geek constructor public Geek(int a, int b) : this(50, 2.9, "Hello") { Console.WriteLine(a); Console.WriteLine(b); }} // Driver Classpublic class GFG { // Main method static public void Main() { // Create object of Geek class Geek obj = new Geek(15, 30); }} Output: 50 2.9 Hello 15 30 Explanation: In the above example, Geek class contains two constructors, i.e, Geek(int a, double b, string c) and Geek(int a, int b) and both are parameterized constructors. Now we call Geek(int a, double b, string c) constructor in Geek(int a, int b) by using this(50, 2.9, “Hello”) keyword. Here this(50, 2.9, “Hello”) keyword contains the same number and type of argument that are present in the Geek(int a, double b, string c) constructor. singghakshay CSharp-OOP Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Multiple inheritance using interfaces Introduction to .NET Framework Differences Between .NET Core and .NET Framework C# | Delegates C# | Data Types C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method C# | Arrays Extension Method in C#
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Aug, 2021" }, { "code": null, "e": 275, "s": 52, "text": "Prerequisite : Constructors in C#C# provides a powerful keyword known as this keyword and this keyword has many usages. Here we use this keyword to call an overloaded constructor from another constructor.Important Points: " }, { "code": null, "e": 373, "s": 275, "text": "When you use this keyword to call a constructor, the constructor should belong to the same class." }, { "code": null, "e": 418, "s": 373, "text": "You can also pass parameter in this keyword." }, { "code": null, "e": 501, "s": 418, "text": "This keyword always pointing to the members of the same class in which it is used." }, { "code": null, "e": 668, "s": 501, "text": "When you use this keyword, it tells the compiler to invoke the default constructor. Or in other words, it means a constructor that does not contain arguments.Syntax: " }, { "code": null, "e": 730, "s": 668, "text": "class X \n{\n\n public X: this()\n {\n\n // Code..\n\n }\n}" }, { "code": null, "e": 853, "s": 730, "text": "this keyword contains the same type and the same number of parameters that are present in the calling constructor.Syntax: " }, { "code": null, "e": 923, "s": 853, "text": "class X\n{\n public X(int x): this(int)\n {\n\n // Code..\n }\n}" }, { "code": null, "e": 1007, "s": 923, "text": "This concept removes the assignment of replication of properties in the same class." }, { "code": null, "e": 1103, "s": 1007, "text": "Below programs illustrate how to call the overloaded constructor using this keyword:Example 1: " }, { "code": null, "e": 1110, "s": 1103, "text": "CSharp" }, { "code": "// C# program to illustrate how to invoke// overloaded constructor using this keywordusing System;class Geek { // Constructor without parameter public Geek() { Console.WriteLine(\"Hello! Constructor 1\"); } // Constructor with parameter // Here this keyword is used // to call Geek constructor public Geek(int a) : this() { Console.WriteLine(\"Hello! Constructor 2\"); }} // Driver Classpublic class GFG { // Main method static public void Main() { // Create object of Geek class Geek obj = new Geek(2); }}", "e": 1690, "s": 1110, "text": null }, { "code": null, "e": 1700, "s": 1690, "text": "Output: " }, { "code": null, "e": 1742, "s": 1700, "text": "Hello! Constructor 1\nHello! Constructor 2" }, { "code": null, "e": 2072, "s": 1742, "text": "Explanation: In the above example, Geek class contains two constructors, i.e, Geek() is without parameter and Geek(int a) is with parameter. Now we call Geek() constructor in Geek(int a) by using this() keyword. Here this() keyword does not contain any argument because the constructor does not contain any parameter. Example 2: " }, { "code": null, "e": 2079, "s": 2072, "text": "CSharp" }, { "code": "// C# program to illustrate how to invoke// overloaded constructor using this keywordusing System;class Geek { // Constructor with parameters public Geek(int a, double b, string c) { Console.WriteLine(a); Console.WriteLine(b); Console.WriteLine(c); } // Constructor with parameters // Here this keyword is used // to call Geek constructor public Geek(int a, int b) : this(50, 2.9, \"Hello\") { Console.WriteLine(a); Console.WriteLine(b); }} // Driver Classpublic class GFG { // Main method static public void Main() { // Create object of Geek class Geek obj = new Geek(15, 30); }}", "e": 2760, "s": 2079, "text": null }, { "code": null, "e": 2770, "s": 2760, "text": "Output: " }, { "code": null, "e": 2789, "s": 2770, "text": "50\n2.9\nHello\n15\n30" }, { "code": null, "e": 3234, "s": 2789, "text": "Explanation: In the above example, Geek class contains two constructors, i.e, Geek(int a, double b, string c) and Geek(int a, int b) and both are parameterized constructors. Now we call Geek(int a, double b, string c) constructor in Geek(int a, int b) by using this(50, 2.9, “Hello”) keyword. Here this(50, 2.9, “Hello”) keyword contains the same number and type of argument that are present in the Geek(int a, double b, string c) constructor. " }, { "code": null, "e": 3247, "s": 3234, "text": "singghakshay" }, { "code": null, "e": 3258, "s": 3247, "text": "CSharp-OOP" }, { "code": null, "e": 3265, "s": 3258, "text": "Picked" }, { "code": null, "e": 3268, "s": 3265, "text": "C#" }, { "code": null, "e": 3366, "s": 3268, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3394, "s": 3366, "text": "C# Dictionary with examples" }, { "code": null, "e": 3437, "s": 3394, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 3468, "s": 3437, "text": "Introduction to .NET Framework" }, { "code": null, "e": 3517, "s": 3468, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 3532, "s": 3517, "text": "C# | Delegates" }, { "code": null, "e": 3548, "s": 3532, "text": "C# | Data Types" }, { "code": null, "e": 3588, "s": 3548, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 3610, "s": 3588, "text": "C# | Replace() Method" }, { "code": null, "e": 3622, "s": 3610, "text": "C# | Arrays" } ]
Difference between std::swap and std::vector::swap
19 Jul, 2021 The std::swap is a general function used to exchange the given values whereas the std::vector::swap is a specialized function that can swap all the contents of two different vector containers.Below are some major key differences between std::swap and std::vector::swap, In practice, both the functions will swap the contents of vectors in O(1) time and give the same performance. For consistency, it may be better to use the std::swap. Program 1: To illustrate swapping of two vectors using std::swap(). CPP // CPP program to illustrate swapping// of two vectors using std::swap() #include <bits/stdc++.h>using namespace std; int main(){ vector<int> v1 = { 1, 2, 3 }; vector<int> v2 = { 4, 5, 6 }; // swapping the above two vectors // by traversing and swapping each element for (int i = 0; i < 3; i++) { swap(v1[i], v2[i]); } // print vector v1 cout << "Vector v1 = "; for (int i = 0; i < 3; i++) { cout << v1[i] << " "; } // print vector v2 cout << "\nVector v2 = "; for (int i = 0; i < 3; i++) { cout << v2[i] << " "; } return 0;} Vector v1 = 4 5 6 Vector v2 = 1 2 3 Program 2: To illustrate swapping of two vectors using std::vector::swap(). CPP // CPP program to illustrate swapping// of two vectors using std::vector::swap() #include <bits/stdc++.h>using namespace std; int main(){ vector<int> v1 = { 1, 2, 3 }; vector<int> v2 = { 4, 5, 6 }; // swapping the above two vectors // using std::vector::swap v1.swap(v2); // print vector v1 cout << "Vector v1 = "; for (int i = 0; i < 3; i++) { cout << v1[i] << " "; } // print vector v2 cout << "\nVector v2 = "; for (int i = 0; i < 3; i++) { cout << v2[i] << " "; } return 0;} Vector v1 = 4 5 6 Vector v2 = 1 2 3 bhagatea CPP-Functions cpp-vector STL C++ Difference Between STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Priority Queue in C++ Standard Template Library (STL) Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Substring in C++ Class method vs Static method in Python Difference between BFS and DFS Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Differences between JDK, JRE and JVM
[ { "code": null, "e": 53, "s": 25, "text": "\n19 Jul, 2021" }, { "code": null, "e": 325, "s": 53, "text": "The std::swap is a general function used to exchange the given values whereas the std::vector::swap is a specialized function that can swap all the contents of two different vector containers.Below are some major key differences between std::swap and std::vector::swap, " }, { "code": null, "e": 491, "s": 325, "text": "In practice, both the functions will swap the contents of vectors in O(1) time and give the same performance. For consistency, it may be better to use the std::swap." }, { "code": null, "e": 561, "s": 491, "text": "Program 1: To illustrate swapping of two vectors using std::swap(). " }, { "code": null, "e": 565, "s": 561, "text": "CPP" }, { "code": "// CPP program to illustrate swapping// of two vectors using std::swap() #include <bits/stdc++.h>using namespace std; int main(){ vector<int> v1 = { 1, 2, 3 }; vector<int> v2 = { 4, 5, 6 }; // swapping the above two vectors // by traversing and swapping each element for (int i = 0; i < 3; i++) { swap(v1[i], v2[i]); } // print vector v1 cout << \"Vector v1 = \"; for (int i = 0; i < 3; i++) { cout << v1[i] << \" \"; } // print vector v2 cout << \"\\nVector v2 = \"; for (int i = 0; i < 3; i++) { cout << v2[i] << \" \"; } return 0;}", "e": 1161, "s": 565, "text": null }, { "code": null, "e": 1198, "s": 1161, "text": "Vector v1 = 4 5 6 \nVector v2 = 1 2 3" }, { "code": null, "e": 1278, "s": 1200, "text": "Program 2: To illustrate swapping of two vectors using std::vector::swap(). " }, { "code": null, "e": 1282, "s": 1278, "text": "CPP" }, { "code": "// CPP program to illustrate swapping// of two vectors using std::vector::swap() #include <bits/stdc++.h>using namespace std; int main(){ vector<int> v1 = { 1, 2, 3 }; vector<int> v2 = { 4, 5, 6 }; // swapping the above two vectors // using std::vector::swap v1.swap(v2); // print vector v1 cout << \"Vector v1 = \"; for (int i = 0; i < 3; i++) { cout << v1[i] << \" \"; } // print vector v2 cout << \"\\nVector v2 = \"; for (int i = 0; i < 3; i++) { cout << v2[i] << \" \"; } return 0;}", "e": 1821, "s": 1282, "text": null }, { "code": null, "e": 1858, "s": 1821, "text": "Vector v1 = 4 5 6 \nVector v2 = 1 2 3" }, { "code": null, "e": 1869, "s": 1860, "text": "bhagatea" }, { "code": null, "e": 1883, "s": 1869, "text": "CPP-Functions" }, { "code": null, "e": 1894, "s": 1883, "text": "cpp-vector" }, { "code": null, "e": 1898, "s": 1894, "text": "STL" }, { "code": null, "e": 1902, "s": 1898, "text": "C++" }, { "code": null, "e": 1921, "s": 1902, "text": "Difference Between" }, { "code": null, "e": 1925, "s": 1921, "text": "STL" }, { "code": null, "e": 1929, "s": 1925, "text": "CPP" }, { "code": null, "e": 2027, "s": 1929, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2081, "s": 2027, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 2124, "s": 2081, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 2158, "s": 2124, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 2183, "s": 2158, "text": "unordered_map in C++ STL" }, { "code": null, "e": 2200, "s": 2183, "text": "Substring in C++" }, { "code": null, "e": 2240, "s": 2200, "text": "Class method vs Static method in Python" }, { "code": null, "e": 2271, "s": 2240, "text": "Difference between BFS and DFS" }, { "code": null, "e": 2332, "s": 2271, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2400, "s": 2332, "text": "Difference Between Method Overloading and Method Overriding in Java" } ]
Entropy and Information Gain in Decision Trees | by Jeremiah Lutes | Towards Data Science
What criteria should a decision tree algorithm use to split variables/columns? Before building a decision tree algorithm the first step is to answer this question. Let’s take a look at one of the ways to answer this question. To do so we will need to understand a use a few key concepts from information theory. Let’s examine this method by taking the following steps: Take a very brief look at what a Decision Tree is.Define and examine the formula for Entropy.Discuss what a Bit is in information theory.Define Information Gain and use entropy to calculate it.Write some basic Python functions using the above concepts. Take a very brief look at what a Decision Tree is. Define and examine the formula for Entropy. Discuss what a Bit is in information theory. Define Information Gain and use entropy to calculate it. Write some basic Python functions using the above concepts. In data science, the decision tree algorithm is a supervised learning algorithm for classification or regression problems. Our end goal is to use historical data to predict an outcome. Unlike linear regression, decision trees can pick up nonlinear interactions between variables in the data. Let’s look at a very simple decision tree. Below is a workflow that can be used to make a decision on whether or not to eat a peanut butter cookie. In this example, a decision tree can pick up on the fact that you should only eat the cookie if certain criteria are met. This is the ultimate goal of a decision tree. We want to keep making decisions(splits) until certain criteria are met. Once met we can use it to classify or make a prediction. This example is very basic using only two variables ( allergy, ruining dinner). But, if you have a dataset with thousands of variables/columns how do you decide which variables/columns are the most efficient to split on? A popular way to solve this problem, especially if using an ID3 algorithm, is to use entropy and information gain. Let’s say we have some data and we want to use it to make an online quiz that predicts something about the quiz taker. After looking at the relationships in the data we have decided to use a decision tree algorithm. If you have never been sucked into an online quiz, you can see hundreds of examples here. The goal of the quiz will be to guess if the quiz taker is from one of America’s midwest states. The questions in the quiz will revolve around if they like a certain type of food or not. Below has a small fictional dataset with fifteen entries. Each entry has answers to a series of questions. Most questions are about if they liked a certain type of food, in which the participant answered (1) for yes or (0) for now. The last column(“midwest?”) is our target column, meaning that once the decision tree is built, this is the classification we are trying to guess. To get us started we will use an information theory metric called entropy. In data science, entropy is used as a way to measure how “mixed” a column is. Specifically, entropy is used to measure disorder. Let’s start by finding the entropy of our target column, “midwest?”. There are ten people who live in the midwest and five people who don’t. If someone was going to ask you how mixed the column is, you could say it was sort of mixed, with a majority(2/3) of the people from the midwest. Entropy gives us a way to quantify the answer” sort of mixed”. The more mixed the (1)s and (0)s in the column are, the higher the entropy. If “midwest?” had equal amounts of (1)s and (0)s our entropy would be 1. If “midwest?” consisted only of (1)s the entropy would be 0. We can use the following formula to calculate entropy: Let’s go through each step of the formula and calculate the entropy for the “midwest?” column. We need to iterate through each unique value in a single column and assign it to i. For this example, we have 2 cases(c) in the “midwest?” column, either (0) or (1).We then compute the probability of that value occurring in the data. For the case of (1), the probability is 10/15. For the case of (0), the probability is 5/15.We take the probability of each case and multiply it by the logarithm base 2 of the probability. 2 is the most common base because entropy is measured in bits(more on that later). The full explanation of why 2 is used is out of the scope of this post, but a user on stack exchange offers a good explanation. For the case of(1), we get 10/15*log2(10/15). For the case of (0), we get 5/15*log2(5/15).Next, we take our product from each case above and sum it together. For this example, 10/15*log2(10/15) + 5/15*log2(5/15).Finally, we negate the total sum from above, — (10/15*log2(10/15) + 5/15*log2(5/15)). We need to iterate through each unique value in a single column and assign it to i. For this example, we have 2 cases(c) in the “midwest?” column, either (0) or (1). We then compute the probability of that value occurring in the data. For the case of (1), the probability is 10/15. For the case of (0), the probability is 5/15. We take the probability of each case and multiply it by the logarithm base 2 of the probability. 2 is the most common base because entropy is measured in bits(more on that later). The full explanation of why 2 is used is out of the scope of this post, but a user on stack exchange offers a good explanation. For the case of(1), we get 10/15*log2(10/15). For the case of (0), we get 5/15*log2(5/15). Next, we take our product from each case above and sum it together. For this example, 10/15*log2(10/15) + 5/15*log2(5/15). Finally, we negate the total sum from above, — (10/15*log2(10/15) + 5/15*log2(5/15)). Once we put the steps all together we get the below: Our final entropy is .918278. So, what does that really mean? Moving forward it will be important to understand the concept of bit. In information theory, a bit is thought of as a binary number representing 0 for no information and 1 for a full bit of information. We can represent a bit of information as a binary number because it either has the value (1) or (0). Suppose there’s an equal probability of it raining tomorrow (1) or not raining(0). If I tell you that it will rain tomorrow, I’ve given you one bit of information. We can also think of entropy as information. Suppose we have a loaded six-sided die which always lands on (3). Each time we roll the die, we know upfront that the result will be (3). We gain no new information by rolling the die, so entropy is 0. On the other hand, if the die is far and we roll a (3) there was a 1/6 chance in rolling the (3). Now we have gained information. Thus, rolling the die gives us one bit of information — which side the number landed on. For a deeper dive into the concept of a bit of information, you can read more here. We get less than one “bit” of information — only .918278 — because there are more (1)s in the “midwest?” column than (0)s. This means that if we were predicting a new value, we could guess that the answer is (1) and be right more often than wrong (because there’s a 2/3 probability of the answer being 1). Due to this prior knowledge, we gain less than a full “bit” of information when we observe a new value. Our goal is to find the best variable(s)/column(s) to split on when building a decision tree. Eventually, we want to keep splitting the variables/columns until our mixed target column is no longer mixed. For instance, let’s look at the entropy of the “midwest?” column after we have split our dataset on the “potato_salad?” column. Above, our dataset is split in two sections. On the left side, everyone who likes potato salad. On the right side everyone who doesn’t. We fill focus on the left side which now has seven people from the midwest and two people who aren’t. By using the formula for entropy on the left split midwest column the new entropy is .764204. This is great! Our goal is to lower the entropy and we went from .918278 to .764204. But, we can’t stop there, if we look at the right column our entropy went up as there are an equal amount of (1)s and (0)s. What we need is a way to see how the entropy changes on both sides of the split. The formula for information gain will do that. It gives us a number to quantify how many bits of information we have gained each time we split our data. Earlier we established we want splits that lower the entropy of our target column. When we split on “potato_salad?” we saw that entropy in the “midwest?” went down on the left side. Now we need to understand the total entropy lowered when we look at both sides of the split. Let’s take a look at information gain. Information gain will use the following formula: Let’s breakdown what is going here. We’ll go back to our “potato_salad?” example. The variables in the above formula will represent the following: T = Target, our “midwest?” column A = the variable(column) we are testing, “potato_salad?” v = each value in A, each value in the “potato_salad?” column First, we’ll calculate the orginal entropy for (T) before the split , .918278Then, for each unique value (v) in variable (A), we compute the number of rows in which (A) takes on the value (v), and divide it by the total number of rows. For the “potato_salad?” column we get 9/15 for the unique value of (1) and 6/15 for the unique value of (0).Next, we multiply the results by the entropy of the rows where (A) is (v). For the left split( split on 1 for “potato_salad?”) we get 9/15 * .764204. For the right side of the split ( split on 0 for “potato_salad?”) we get 6/15 * 1.We add all of these subset products together, 9/14*.764204 + 6/15 = .8585224. First, we’ll calculate the orginal entropy for (T) before the split , .918278 Then, for each unique value (v) in variable (A), we compute the number of rows in which (A) takes on the value (v), and divide it by the total number of rows. For the “potato_salad?” column we get 9/15 for the unique value of (1) and 6/15 for the unique value of (0). Next, we multiply the results by the entropy of the rows where (A) is (v). For the left split( split on 1 for “potato_salad?”) we get 9/15 * .764204. For the right side of the split ( split on 0 for “potato_salad?”) we get 6/15 * 1. We add all of these subset products together, 9/14*.764204 + 6/15 = .8585224. 5. We then subtract from the overall entropy to get information gain, .918278 -.8585224 = .059754 Our information gain is .059754. What does that tell us? Here’s an alternate explanation. We’re finding the entropy of each set post-split, weighting it by the number of items in each split, then subtracting from the current entropy. If the result is positive, we’ve lowered entropy with our split. The higher the result is, the more we’ve lowered entropy. We end up with .059754, which means that we gain .059754 bits of information by splitting our data set on the “potato_salad?” variable/column. Our information gain is low, but it’s still positive which is because we lowered the entropy on the left side of the split. Now we need to repeat this process for every column we are using. Instead of doing this by hand let’s write some Python code. Now that we understand information gain, we need a way to repeat this process to find the variable/column with the largest information gain. To do this, we can create a few simple functions in Python. Let’s turn our above table into a DataFrame using the Python pandas library. We will import pandas and use the read_csv() function to make a DataFrame named “midwest”. import pandas as pdmidwest = pd.read_csv('midwes.csv') For this function, we will need the NumPy library to use the bincount() function and the math module to use the log() function. import numpyimport math Next, we will define our function with one parameter. The argument given will be the series, list, or NumPy array in which we are trying to calculate the entropy. def calc_entropy(column): We will need to find the percentage of each case in the column. We can use the numpy.bincount() function for this. The return value is a NumPy array which will store the count of each unique value from the column that was passed as an argument. counts = numpy.bincount(column) We’ll store the probabilities of each unique value by dividing the “counts” array by the length of the column. probabilities = counts / len(column) We can then initialize a variable named “entropy” and set it to 0. entropy = 0 Next, we can use a “for loop” to loop through each probability in our probabilities array and multiply it by the logarithm base 2 of probability using the math.log() function. Then, add each case to our stored entropy variable. *be sure to check your probability is great than 0 otherwise log(0) will return undefined for prob in probabilities: if prob > 0: endtropy += prob * math.log(prob,2) Finally, we’ll return our negated entropy variable. return -entropy All together now: Great! Now we can build a function to calculate information gain. We’ll need to define a function that will have three parameters, one for the entire dataset, one for the name of the column we want to split on, and one for the name of our target column. def calc_information_gain(data, split_name, target_name): Next, we can use the entropy function from earlier to calculate the original entropy of our target column. orginal_entropy = calc_entropy(data[target_name]) Now we need to split our column. *For this example we will only use the variables/columns with two unique. If you want to split on a variable/column such as “age”, there are several ways to do this. One way is to split on every unique value. Another way is to simplify the calculation of information gain and make splits simpler by not splitting for each unique value. Instead, the median is found for the variable/coumn being split on. Any rows where the value of the variable is below the median will go to the left branch, and the rest of the rows will go to the right branch. To compute information gain, we’ll only have to compute entropies for two subsets. We won’t be walking through this method but once the split on the median is performed the rest of steps would be the same as outlined below. Since the columns we are working with only have two unique values we will make a left split and a right split. We’ll start by using the pandas.Series.unique() to give us an array of the unique values in the column values = data[split_name].unique() Next, we will create a left and right split using “values”. left_split = data[data[split_name] == values[0]]right_split = data[data[split_name] == values[1]] Now we can initiate a variable to subtract from our original entropy. to_subtract = 0 Then we’ll iterate through each subset created by our split, calculate the probability of the subset, and then add the product of the probability and the subsets target column’s entropy. for subset in [left_split, right_split]: prob = (subset.shape[0] / data.shape[0]) to_subtract += prob * calc_entropy(subset[target_name]) Finally, we can return the difference of to_subract being subtracted from the original entropy. return original_entropy - to_subtract The entire function is below. Our final function will be one that will return the variable/column name with the highest information gain. As mentioned earlier we are only using the columns with two unique values for this example. We’ll store those column names in a list to use in the function. To get to the point we’ll hard code this for this example but in a large dataset, it would be best to write code to build this list dynamically based on the criteria we use to choose the columns. columns = ['apple_pie?', 'potato_salad?', 'sushi?'] Let’s wrap the final step in a function so we can reuse it as needed. It will have one parameter, the list of columns we want to find the highest information gain for. def highest_info_gain(columns): We’ll intialize an empty dictionary to store our information gains. information_gains = {} And then we can iterate through the list of columns and store the result in our information_gains dictionary. for col in columns: information_gain = calc_information_gain(midwest, col, 'midwest?) information_gains[col] = information_gain Finally, we can return the key of the highest value in our dictionary. return max(information_gains, key=information_gains.get) All together now: Once we execute our final function print(highest_info_gain(midwest, columns, 'midwest?'))//sushi we see the variable/column with the highest information gain is ‘sushi?’. We can visualize a split on sushi below: Our left split has two people out of six from the midwest. The right split has eight out of the nine people from the midwest. This was an efficient split and lowered our entropy on both sides. If we were to continue we would use recursion to keep splitting each split with a goal to end each branch with an entropy of zero. Decision trees can be a useful machine learning algorithm to pick up nonlinear interactions between variables in the data. In this example, we looked at the beginning stages of a decision tree classification algorithm. We then looked at three information theory concepts, entropy, bit, and information gain. By using these concepts we were able to build a few functions in Python to decide which variables/columns were the most efficient to split on. With a firm grasp on these concepts, we can move forward to build a decision tree.
[ { "code": null, "e": 251, "s": 172, "text": "What criteria should a decision tree algorithm use to split variables/columns?" }, { "code": null, "e": 484, "s": 251, "text": "Before building a decision tree algorithm the first step is to answer this question. Let’s take a look at one of the ways to answer this question. To do so we will need to understand a use a few key concepts from information theory." }, { "code": null, "e": 541, "s": 484, "text": "Let’s examine this method by taking the following steps:" }, { "code": null, "e": 794, "s": 541, "text": "Take a very brief look at what a Decision Tree is.Define and examine the formula for Entropy.Discuss what a Bit is in information theory.Define Information Gain and use entropy to calculate it.Write some basic Python functions using the above concepts." }, { "code": null, "e": 845, "s": 794, "text": "Take a very brief look at what a Decision Tree is." }, { "code": null, "e": 889, "s": 845, "text": "Define and examine the formula for Entropy." }, { "code": null, "e": 934, "s": 889, "text": "Discuss what a Bit is in information theory." }, { "code": null, "e": 991, "s": 934, "text": "Define Information Gain and use entropy to calculate it." }, { "code": null, "e": 1051, "s": 991, "text": "Write some basic Python functions using the above concepts." }, { "code": null, "e": 1343, "s": 1051, "text": "In data science, the decision tree algorithm is a supervised learning algorithm for classification or regression problems. Our end goal is to use historical data to predict an outcome. Unlike linear regression, decision trees can pick up nonlinear interactions between variables in the data." }, { "code": null, "e": 1491, "s": 1343, "text": "Let’s look at a very simple decision tree. Below is a workflow that can be used to make a decision on whether or not to eat a peanut butter cookie." }, { "code": null, "e": 2125, "s": 1491, "text": "In this example, a decision tree can pick up on the fact that you should only eat the cookie if certain criteria are met. This is the ultimate goal of a decision tree. We want to keep making decisions(splits) until certain criteria are met. Once met we can use it to classify or make a prediction. This example is very basic using only two variables ( allergy, ruining dinner). But, if you have a dataset with thousands of variables/columns how do you decide which variables/columns are the most efficient to split on? A popular way to solve this problem, especially if using an ID3 algorithm, is to use entropy and information gain." }, { "code": null, "e": 2997, "s": 2125, "text": "Let’s say we have some data and we want to use it to make an online quiz that predicts something about the quiz taker. After looking at the relationships in the data we have decided to use a decision tree algorithm. If you have never been sucked into an online quiz, you can see hundreds of examples here. The goal of the quiz will be to guess if the quiz taker is from one of America’s midwest states. The questions in the quiz will revolve around if they like a certain type of food or not. Below has a small fictional dataset with fifteen entries. Each entry has answers to a series of questions. Most questions are about if they liked a certain type of food, in which the participant answered (1) for yes or (0) for now. The last column(“midwest?”) is our target column, meaning that once the decision tree is built, this is the classification we are trying to guess." }, { "code": null, "e": 3270, "s": 2997, "text": "To get us started we will use an information theory metric called entropy. In data science, entropy is used as a way to measure how “mixed” a column is. Specifically, entropy is used to measure disorder. Let’s start by finding the entropy of our target column, “midwest?”." }, { "code": null, "e": 3761, "s": 3270, "text": "There are ten people who live in the midwest and five people who don’t. If someone was going to ask you how mixed the column is, you could say it was sort of mixed, with a majority(2/3) of the people from the midwest. Entropy gives us a way to quantify the answer” sort of mixed”. The more mixed the (1)s and (0)s in the column are, the higher the entropy. If “midwest?” had equal amounts of (1)s and (0)s our entropy would be 1. If “midwest?” consisted only of (1)s the entropy would be 0." }, { "code": null, "e": 3816, "s": 3761, "text": "We can use the following formula to calculate entropy:" }, { "code": null, "e": 3911, "s": 3816, "text": "Let’s go through each step of the formula and calculate the entropy for the “midwest?” column." }, { "code": null, "e": 4843, "s": 3911, "text": "We need to iterate through each unique value in a single column and assign it to i. For this example, we have 2 cases(c) in the “midwest?” column, either (0) or (1).We then compute the probability of that value occurring in the data. For the case of (1), the probability is 10/15. For the case of (0), the probability is 5/15.We take the probability of each case and multiply it by the logarithm base 2 of the probability. 2 is the most common base because entropy is measured in bits(more on that later). The full explanation of why 2 is used is out of the scope of this post, but a user on stack exchange offers a good explanation. For the case of(1), we get 10/15*log2(10/15). For the case of (0), we get 5/15*log2(5/15).Next, we take our product from each case above and sum it together. For this example, 10/15*log2(10/15) + 5/15*log2(5/15).Finally, we negate the total sum from above, — (10/15*log2(10/15) + 5/15*log2(5/15))." }, { "code": null, "e": 5009, "s": 4843, "text": "We need to iterate through each unique value in a single column and assign it to i. For this example, we have 2 cases(c) in the “midwest?” column, either (0) or (1)." }, { "code": null, "e": 5171, "s": 5009, "text": "We then compute the probability of that value occurring in the data. For the case of (1), the probability is 10/15. For the case of (0), the probability is 5/15." }, { "code": null, "e": 5570, "s": 5171, "text": "We take the probability of each case and multiply it by the logarithm base 2 of the probability. 2 is the most common base because entropy is measured in bits(more on that later). The full explanation of why 2 is used is out of the scope of this post, but a user on stack exchange offers a good explanation. For the case of(1), we get 10/15*log2(10/15). For the case of (0), we get 5/15*log2(5/15)." }, { "code": null, "e": 5693, "s": 5570, "text": "Next, we take our product from each case above and sum it together. For this example, 10/15*log2(10/15) + 5/15*log2(5/15)." }, { "code": null, "e": 5779, "s": 5693, "text": "Finally, we negate the total sum from above, — (10/15*log2(10/15) + 5/15*log2(5/15))." }, { "code": null, "e": 5832, "s": 5779, "text": "Once we put the steps all together we get the below:" }, { "code": null, "e": 5894, "s": 5832, "text": "Our final entropy is .918278. So, what does that really mean?" }, { "code": null, "e": 6362, "s": 5894, "text": "Moving forward it will be important to understand the concept of bit. In information theory, a bit is thought of as a binary number representing 0 for no information and 1 for a full bit of information. We can represent a bit of information as a binary number because it either has the value (1) or (0). Suppose there’s an equal probability of it raining tomorrow (1) or not raining(0). If I tell you that it will rain tomorrow, I’ve given you one bit of information." }, { "code": null, "e": 6828, "s": 6362, "text": "We can also think of entropy as information. Suppose we have a loaded six-sided die which always lands on (3). Each time we roll the die, we know upfront that the result will be (3). We gain no new information by rolling the die, so entropy is 0. On the other hand, if the die is far and we roll a (3) there was a 1/6 chance in rolling the (3). Now we have gained information. Thus, rolling the die gives us one bit of information — which side the number landed on." }, { "code": null, "e": 6912, "s": 6828, "text": "For a deeper dive into the concept of a bit of information, you can read more here." }, { "code": null, "e": 7322, "s": 6912, "text": "We get less than one “bit” of information — only .918278 — because there are more (1)s in the “midwest?” column than (0)s. This means that if we were predicting a new value, we could guess that the answer is (1) and be right more often than wrong (because there’s a 2/3 probability of the answer being 1). Due to this prior knowledge, we gain less than a full “bit” of information when we observe a new value." }, { "code": null, "e": 7526, "s": 7322, "text": "Our goal is to find the best variable(s)/column(s) to split on when building a decision tree. Eventually, we want to keep splitting the variables/columns until our mixed target column is no longer mixed." }, { "code": null, "e": 7654, "s": 7526, "text": "For instance, let’s look at the entropy of the “midwest?” column after we have split our dataset on the “potato_salad?” column." }, { "code": null, "e": 8429, "s": 7654, "text": "Above, our dataset is split in two sections. On the left side, everyone who likes potato salad. On the right side everyone who doesn’t. We fill focus on the left side which now has seven people from the midwest and two people who aren’t. By using the formula for entropy on the left split midwest column the new entropy is .764204. This is great! Our goal is to lower the entropy and we went from .918278 to .764204. But, we can’t stop there, if we look at the right column our entropy went up as there are an equal amount of (1)s and (0)s. What we need is a way to see how the entropy changes on both sides of the split. The formula for information gain will do that. It gives us a number to quantify how many bits of information we have gained each time we split our data." }, { "code": null, "e": 8743, "s": 8429, "text": "Earlier we established we want splits that lower the entropy of our target column. When we split on “potato_salad?” we saw that entropy in the “midwest?” went down on the left side. Now we need to understand the total entropy lowered when we look at both sides of the split. Let’s take a look at information gain." }, { "code": null, "e": 8792, "s": 8743, "text": "Information gain will use the following formula:" }, { "code": null, "e": 8828, "s": 8792, "text": "Let’s breakdown what is going here." }, { "code": null, "e": 8939, "s": 8828, "text": "We’ll go back to our “potato_salad?” example. The variables in the above formula will represent the following:" }, { "code": null, "e": 8973, "s": 8939, "text": "T = Target, our “midwest?” column" }, { "code": null, "e": 9030, "s": 8973, "text": "A = the variable(column) we are testing, “potato_salad?”" }, { "code": null, "e": 9092, "s": 9030, "text": "v = each value in A, each value in the “potato_salad?” column" }, { "code": null, "e": 9746, "s": 9092, "text": "First, we’ll calculate the orginal entropy for (T) before the split , .918278Then, for each unique value (v) in variable (A), we compute the number of rows in which (A) takes on the value (v), and divide it by the total number of rows. For the “potato_salad?” column we get 9/15 for the unique value of (1) and 6/15 for the unique value of (0).Next, we multiply the results by the entropy of the rows where (A) is (v). For the left split( split on 1 for “potato_salad?”) we get 9/15 * .764204. For the right side of the split ( split on 0 for “potato_salad?”) we get 6/15 * 1.We add all of these subset products together, 9/14*.764204 + 6/15 = .8585224." }, { "code": null, "e": 9824, "s": 9746, "text": "First, we’ll calculate the orginal entropy for (T) before the split , .918278" }, { "code": null, "e": 10092, "s": 9824, "text": "Then, for each unique value (v) in variable (A), we compute the number of rows in which (A) takes on the value (v), and divide it by the total number of rows. For the “potato_salad?” column we get 9/15 for the unique value of (1) and 6/15 for the unique value of (0)." }, { "code": null, "e": 10325, "s": 10092, "text": "Next, we multiply the results by the entropy of the rows where (A) is (v). For the left split( split on 1 for “potato_salad?”) we get 9/15 * .764204. For the right side of the split ( split on 0 for “potato_salad?”) we get 6/15 * 1." }, { "code": null, "e": 10403, "s": 10325, "text": "We add all of these subset products together, 9/14*.764204 + 6/15 = .8585224." }, { "code": null, "e": 10501, "s": 10403, "text": "5. We then subtract from the overall entropy to get information gain, .918278 -.8585224 = .059754" }, { "code": null, "e": 10558, "s": 10501, "text": "Our information gain is .059754. What does that tell us?" }, { "code": null, "e": 10858, "s": 10558, "text": "Here’s an alternate explanation. We’re finding the entropy of each set post-split, weighting it by the number of items in each split, then subtracting from the current entropy. If the result is positive, we’ve lowered entropy with our split. The higher the result is, the more we’ve lowered entropy." }, { "code": null, "e": 11125, "s": 10858, "text": "We end up with .059754, which means that we gain .059754 bits of information by splitting our data set on the “potato_salad?” variable/column. Our information gain is low, but it’s still positive which is because we lowered the entropy on the left side of the split." }, { "code": null, "e": 11251, "s": 11125, "text": "Now we need to repeat this process for every column we are using. Instead of doing this by hand let’s write some Python code." }, { "code": null, "e": 11452, "s": 11251, "text": "Now that we understand information gain, we need a way to repeat this process to find the variable/column with the largest information gain. To do this, we can create a few simple functions in Python." }, { "code": null, "e": 11620, "s": 11452, "text": "Let’s turn our above table into a DataFrame using the Python pandas library. We will import pandas and use the read_csv() function to make a DataFrame named “midwest”." }, { "code": null, "e": 11675, "s": 11620, "text": "import pandas as pdmidwest = pd.read_csv('midwes.csv')" }, { "code": null, "e": 11803, "s": 11675, "text": "For this function, we will need the NumPy library to use the bincount() function and the math module to use the log() function." }, { "code": null, "e": 11827, "s": 11803, "text": "import numpyimport math" }, { "code": null, "e": 11990, "s": 11827, "text": "Next, we will define our function with one parameter. The argument given will be the series, list, or NumPy array in which we are trying to calculate the entropy." }, { "code": null, "e": 12016, "s": 11990, "text": "def calc_entropy(column):" }, { "code": null, "e": 12261, "s": 12016, "text": "We will need to find the percentage of each case in the column. We can use the numpy.bincount() function for this. The return value is a NumPy array which will store the count of each unique value from the column that was passed as an argument." }, { "code": null, "e": 12293, "s": 12261, "text": "counts = numpy.bincount(column)" }, { "code": null, "e": 12404, "s": 12293, "text": "We’ll store the probabilities of each unique value by dividing the “counts” array by the length of the column." }, { "code": null, "e": 12442, "s": 12404, "text": "probabilities = counts / len(column)" }, { "code": null, "e": 12509, "s": 12442, "text": "We can then initialize a variable named “entropy” and set it to 0." }, { "code": null, "e": 12521, "s": 12509, "text": "entropy = 0" }, { "code": null, "e": 12839, "s": 12521, "text": "Next, we can use a “for loop” to loop through each probability in our probabilities array and multiply it by the logarithm base 2 of probability using the math.log() function. Then, add each case to our stored entropy variable. *be sure to check your probability is great than 0 otherwise log(0) will return undefined" }, { "code": null, "e": 12924, "s": 12839, "text": "for prob in probabilities: if prob > 0: endtropy += prob * math.log(prob,2)" }, { "code": null, "e": 12976, "s": 12924, "text": "Finally, we’ll return our negated entropy variable." }, { "code": null, "e": 12992, "s": 12976, "text": "return -entropy" }, { "code": null, "e": 13010, "s": 12992, "text": "All together now:" }, { "code": null, "e": 13076, "s": 13010, "text": "Great! Now we can build a function to calculate information gain." }, { "code": null, "e": 13264, "s": 13076, "text": "We’ll need to define a function that will have three parameters, one for the entire dataset, one for the name of the column we want to split on, and one for the name of our target column." }, { "code": null, "e": 13322, "s": 13264, "text": "def calc_information_gain(data, split_name, target_name):" }, { "code": null, "e": 13429, "s": 13322, "text": "Next, we can use the entropy function from earlier to calculate the original entropy of our target column." }, { "code": null, "e": 13479, "s": 13429, "text": "orginal_entropy = calc_entropy(data[target_name])" }, { "code": null, "e": 13512, "s": 13479, "text": "Now we need to split our column." }, { "code": null, "e": 14283, "s": 13512, "text": "*For this example we will only use the variables/columns with two unique. If you want to split on a variable/column such as “age”, there are several ways to do this. One way is to split on every unique value. Another way is to simplify the calculation of information gain and make splits simpler by not splitting for each unique value. Instead, the median is found for the variable/coumn being split on. Any rows where the value of the variable is below the median will go to the left branch, and the rest of the rows will go to the right branch. To compute information gain, we’ll only have to compute entropies for two subsets. We won’t be walking through this method but once the split on the median is performed the rest of steps would be the same as outlined below." }, { "code": null, "e": 14394, "s": 14283, "text": "Since the columns we are working with only have two unique values we will make a left split and a right split." }, { "code": null, "e": 14497, "s": 14394, "text": "We’ll start by using the pandas.Series.unique() to give us an array of the unique values in the column" }, { "code": null, "e": 14532, "s": 14497, "text": "values = data[split_name].unique()" }, { "code": null, "e": 14592, "s": 14532, "text": "Next, we will create a left and right split using “values”." }, { "code": null, "e": 14690, "s": 14592, "text": "left_split = data[data[split_name] == values[0]]right_split = data[data[split_name] == values[1]]" }, { "code": null, "e": 14760, "s": 14690, "text": "Now we can initiate a variable to subtract from our original entropy." }, { "code": null, "e": 14776, "s": 14760, "text": "to_subtract = 0" }, { "code": null, "e": 14963, "s": 14776, "text": "Then we’ll iterate through each subset created by our split, calculate the probability of the subset, and then add the product of the probability and the subsets target column’s entropy." }, { "code": null, "e": 15107, "s": 14963, "text": "for subset in [left_split, right_split]: prob = (subset.shape[0] / data.shape[0]) to_subtract += prob * calc_entropy(subset[target_name])" }, { "code": null, "e": 15203, "s": 15107, "text": "Finally, we can return the difference of to_subract being subtracted from the original entropy." }, { "code": null, "e": 15241, "s": 15203, "text": "return original_entropy - to_subtract" }, { "code": null, "e": 15271, "s": 15241, "text": "The entire function is below." }, { "code": null, "e": 15379, "s": 15271, "text": "Our final function will be one that will return the variable/column name with the highest information gain." }, { "code": null, "e": 15732, "s": 15379, "text": "As mentioned earlier we are only using the columns with two unique values for this example. We’ll store those column names in a list to use in the function. To get to the point we’ll hard code this for this example but in a large dataset, it would be best to write code to build this list dynamically based on the criteria we use to choose the columns." }, { "code": null, "e": 15784, "s": 15732, "text": "columns = ['apple_pie?', 'potato_salad?', 'sushi?']" }, { "code": null, "e": 15952, "s": 15784, "text": "Let’s wrap the final step in a function so we can reuse it as needed. It will have one parameter, the list of columns we want to find the highest information gain for." }, { "code": null, "e": 15984, "s": 15952, "text": "def highest_info_gain(columns):" }, { "code": null, "e": 16052, "s": 15984, "text": "We’ll intialize an empty dictionary to store our information gains." }, { "code": null, "e": 16075, "s": 16052, "text": "information_gains = {}" }, { "code": null, "e": 16185, "s": 16075, "text": "And then we can iterate through the list of columns and store the result in our information_gains dictionary." }, { "code": null, "e": 16319, "s": 16185, "text": "for col in columns: information_gain = calc_information_gain(midwest, col, 'midwest?) information_gains[col] = information_gain" }, { "code": null, "e": 16390, "s": 16319, "text": "Finally, we can return the key of the highest value in our dictionary." }, { "code": null, "e": 16447, "s": 16390, "text": "return max(information_gains, key=information_gains.get)" }, { "code": null, "e": 16465, "s": 16447, "text": "All together now:" }, { "code": null, "e": 16500, "s": 16465, "text": "Once we execute our final function" }, { "code": null, "e": 16562, "s": 16500, "text": "print(highest_info_gain(midwest, columns, 'midwest?'))//sushi" }, { "code": null, "e": 16636, "s": 16562, "text": "we see the variable/column with the highest information gain is ‘sushi?’." }, { "code": null, "e": 16677, "s": 16636, "text": "We can visualize a split on sushi below:" }, { "code": null, "e": 17001, "s": 16677, "text": "Our left split has two people out of six from the midwest. The right split has eight out of the nine people from the midwest. This was an efficient split and lowered our entropy on both sides. If we were to continue we would use recursion to keep splitting each split with a goal to end each branch with an entropy of zero." } ]
Natural Language Processing with Spark | by Suraj Malpani | Towards Data Science
This is an introductory tutorial on developing predictive machine learning models using PySpark. I am going to demonstrate the basics of Natural Language Processing (NLP) while utilizing the power of Spark. We will use PySpark; which is a Python API for Spark. The dataset for this tutorial is fetched from the ‘NLP with Disaster Tweets’ Kaggle competition. The full code is available on GitHub. The data consists of tweets and our task is to predict which tweets are related to a disaster. This may improve the response time for several interested parties, such as Police Force, Fire Brigade or News Agencies, etc. We will be performing text classification, by building predictive machine learning models, which is a category of NLP. The following algorithms can help you get instigated in your Text Analytics or NLP endeavor and has numerous applications. Text classification is the process of assigning tags or categories to text according to its content. It’s one of the fundamental tasks in Natural Language Processing (NLP) with broad applications such as sentiment analysis, topic labeling, spam detection, and intent detection. — From Monkeylearn Let’s dive into the data without further delay. For that, we need to know a bit about Spark Dataframes. Now, we need to start a Spark session within Python to use Spark. We start the session using the following command, appName parameter, i.e. ‘nlp’ in this case could be of the user’s choice. spark = SparkSession.builder.appName('nlp').getOrCreate() Once we start the Spark Session, we will load the data using ‘spark.read.csv’ function. After loading the data files into the workspace, we need to perform pre-processing on the text data. The head of the dataframe looks as displayed in the below image. We will be working on the ‘text’ field to predict the ‘target’ field. The following workflow details the process that we will follow for extracting features from the data. The descriptions of each stage follow the image. 1) Drop null values: We drop all the records having a null/na value in the text. We can use dropna() function for this purpose. 2) Remove numbers from the tweets: We use Regular expressions (regex) operators for further cleaning the text data. The following code drops all the numbers from the text. We are dealing with the words rather than numbers to recognize the disaster tweets. regexp_replace(col(‘text’), ‘\d+’, ‘’) 3) Segregate the words: Then we break the tweets into individual words to analyze them. We use RegexTokenizer() for this purpose. 4) Remove stop words: We remove stop words from the segregated words using StopWordsRemover() function from the pyspark.ml library. Some of the examples of stop words are I, the, a, has, etc. As you can notice from these examples, these words don’t carry much information and thus we remove them from the analysis. 5) Create the features column: After removing the unimportant words from the data, we use CountVectorizer() function. This function converts words to a numeric vector to be able to feed it to a machine learning model. Now our data is ready to be fed to predictive models. The data looks like this after finishing the above process. Let me shed light on all the fields in the above dataframe; we started with the ‘text’ field. The ‘words’ display segregated words after performing the first 3 steps from our above workflow. The ‘filtered’ column shows words after removing stop words as described in step 4. The ‘features’ field is the numeric vector field after finishing step 5, this is the field we will be using for training machine learning models. The ‘target’ field is our predictor variable which shows whether the tweet is related to a disaster or not. We separate the data obtained from the previous process into train and validate. We use the train dataframe for training the machine learning models and validate dataframe to validate their accuracy on the unseen data. There are several criteria for validating the classification models, we will use ROC and accuracy for our analysis. After validating, we will make predictions on the test data. I will illustrate some of the common classification machine learning algorithms. I am assuming you are familiar with these algorithms and I will try not to bore you with these algorithms. Naive Bayes model is one of the most common algorithms for text classification. Naive Bayes algorithm assumes that all the predictor variables are independent of each other. Simply put, it assumes that the presence of one particular feature is unrelated to any other feature in the data. This assumption is not always correct in real life, however, it makes sense in text classification. The following code is used for training and validating the Naive Bayes Model using PySpark. from pyspark.ml.classification import NaiveBayesfrom pyspark.ml.evaluation import MulticlassClassificationEvaluator## Fitting the modelnb = NaiveBayes(modelType="multinomial",labelCol="label", featuresCol="features")nbModel = nb.fit(train)nb_predictions = nbModel.transform(validate)## Evaluating the modelevaluator = MulticlassClassificationEvaluator(labelCol="label", predictionCol="prediction", metricName="accuracy")nb_accuracy = evaluator.evaluate(nb_predictions)print("Accuracy of NaiveBayes is = %g"% (nb_accuracy))#Accuracy of NaiveBayes is = 0.803448 It is a variant of regression that uses a logistic function for modeling a binary outcome variable. The following code demonstrates how to train and validate Logistic Regression. from pyspark.ml.classification import LogisticRegression## Fitting the modellr = LogisticRegression(featuresCol = 'features', labelCol = 'target', maxIter=10)lrModel = lr.fit(train)lrPreds = lrModel.transform(validate)## Evaluating the modelevaluator = MulticlassClassificationEvaluator(labelCol="label", predictionCol="prediction", metricName="accuracy")lr_accuracy = evaluator.evaluate(lrPreds)print("Accuracy of Logistic Regression is = %g"% (lr_accuracy))#Accuracy of Logistic Regression is = 0.768276 Decision trees essentially split the dataset based on columns trying to learn their behavior concerning the outcome variable, i.e. we segment the predictor space into simple regions. This article by Will Koehrsen could help understand decision trees and random forests in detail. We can use the following code for training and validating decision trees. from pyspark.ml.classification import DecisionTreeClassifier## Fitting the modeldt = DecisionTreeClassifier(featuresCol = 'features', labelCol = 'target', maxDepth = 3)dtModel = dt.fit(train)dtPreds = dtModel.transform(validate)## Evaluating the modelevaluator = MulticlassClassificationEvaluator(labelCol="label", predictionCol="prediction", metricName="accuracy")dt_accuracy = evaluator.evaluate(dtPreds)print("Accuracy of Decision Trees is = %g"% (dt_accuracy))#Accuracy of Decision Trees is = 0.651034 Random forests are an ensemble machine learning method. They use bootstrapping techniques and are fundamentally a combination of numerous weak learners, specifically decision trees. Check the following code to learn to implement random forests in spark. from pyspark.ml.classification import RandomForestClassifier## Fitting the modelrf = RandomForestClassifier(featuresCol = 'features', labelCol = 'target')rfModel = rf.fit(train)rfPreds = rfModel.transform(validate)## Evaluating the modelevaluator = MulticlassClassificationEvaluator(labelCol="label", predictionCol="prediction", metricName="accuracy")rf_accuracy = evaluator.evaluate(rfPreds)print("Accuracy of Random Forests is = %g"% (rf_accuracy))#Accuracy of Random Forests is = 0.581379 Gradient boosting tree is an ensemble method analogous to random forests. The approach to building trees differs from the random forest; each new tree built by gradient boosting tree attempts to correct errors made by the previous tree. We use GBTClassifier from the pyspark.ml.classification library for training and validating the data. from pyspark.ml.classification import GBTClassifier## Fitting the modelgbt = GBTClassifier(maxIter=10)gbtModel = gbt.fit(train)gbtPreds = gbtModel.transform(validate)## Evaluating the modelevaluator = MulticlassClassificationEvaluator(labelCol="label", predictionCol="prediction", metricName="accuracy")gb_accuracy = evaluator.evaluate(gbtPreds)print("Accuracy of GBT is = %g"% (gb_accuracy))#Accuracy of GBT is = 0.681379 Now that we’ve trained and validated several models, we make predictions on unseen test data. We can retrain the model on all available training data and then make predictions. The following code demonstrates how to make predictions using the Gradient boosting model. However, you can repeat the same for any of the trained models and also the full code for prediction using other models is available on Github. ## Fitting the modelgbt = GBTClassifier(maxIter=10)gbtModel = gbt.fit(trainData)## Make predictionsgbtPreds = gbtModel.transform(testData)gbtPreds.select('id','prediction').show(5)+---+----------+| id|prediction|+---+----------+| 0| 0.0|| 2| 0.0|| 3| 1.0|| 9| 0.0|| 11| 0.0|+---+----------+only showing top 5 rows Once you’ve made the predictions, you can convert the dataframe to a CSV format and submit it to the competition. You are now armed to use Spark for developing Machine Learning models. There are myriad applications of Text Classification, such as identifying spam emails, tagging website/product content, etc. and the above algorithms are applicable for all such tasks. Hopefully, you find this useful and will let me know what you think. Happy Learning! Thank you for reading. I hope you find this helpful. If you have any suggestions, please add them in the comments section. Feel free to connect with me on my Website or LinkedIn. Spark documentation: https://spark.apache.org/docs/2.2.0/ml-classification-regression.htmlhttps://monkeylearn.com/text-classification/Kaggle Notebook: https://www.kaggle.com/palmer0/binary-classification-with-pyspark-and-mllibGithub Notebook: https://github.com/lp-dataninja/SparkML/blob/master/pyspark-nlp-kaggle.ipynb Spark documentation: https://spark.apache.org/docs/2.2.0/ml-classification-regression.html https://monkeylearn.com/text-classification/ Kaggle Notebook: https://www.kaggle.com/palmer0/binary-classification-with-pyspark-and-mllib Github Notebook: https://github.com/lp-dataninja/SparkML/blob/master/pyspark-nlp-kaggle.ipynb
[ { "code": null, "e": 567, "s": 171, "text": "This is an introductory tutorial on developing predictive machine learning models using PySpark. I am going to demonstrate the basics of Natural Language Processing (NLP) while utilizing the power of Spark. We will use PySpark; which is a Python API for Spark. The dataset for this tutorial is fetched from the ‘NLP with Disaster Tweets’ Kaggle competition. The full code is available on GitHub." }, { "code": null, "e": 1029, "s": 567, "text": "The data consists of tweets and our task is to predict which tweets are related to a disaster. This may improve the response time for several interested parties, such as Police Force, Fire Brigade or News Agencies, etc. We will be performing text classification, by building predictive machine learning models, which is a category of NLP. The following algorithms can help you get instigated in your Text Analytics or NLP endeavor and has numerous applications." }, { "code": null, "e": 1326, "s": 1029, "text": "Text classification is the process of assigning tags or categories to text according to its content. It’s one of the fundamental tasks in Natural Language Processing (NLP) with broad applications such as sentiment analysis, topic labeling, spam detection, and intent detection. — From Monkeylearn" }, { "code": null, "e": 1620, "s": 1326, "text": "Let’s dive into the data without further delay. For that, we need to know a bit about Spark Dataframes. Now, we need to start a Spark session within Python to use Spark. We start the session using the following command, appName parameter, i.e. ‘nlp’ in this case could be of the user’s choice." }, { "code": null, "e": 1678, "s": 1620, "text": "spark = SparkSession.builder.appName('nlp').getOrCreate()" }, { "code": null, "e": 2002, "s": 1678, "text": "Once we start the Spark Session, we will load the data using ‘spark.read.csv’ function. After loading the data files into the workspace, we need to perform pre-processing on the text data. The head of the dataframe looks as displayed in the below image. We will be working on the ‘text’ field to predict the ‘target’ field." }, { "code": null, "e": 2153, "s": 2002, "text": "The following workflow details the process that we will follow for extracting features from the data. The descriptions of each stage follow the image." }, { "code": null, "e": 2281, "s": 2153, "text": "1) Drop null values: We drop all the records having a null/na value in the text. We can use dropna() function for this purpose." }, { "code": null, "e": 2537, "s": 2281, "text": "2) Remove numbers from the tweets: We use Regular expressions (regex) operators for further cleaning the text data. The following code drops all the numbers from the text. We are dealing with the words rather than numbers to recognize the disaster tweets." }, { "code": null, "e": 2576, "s": 2537, "text": "regexp_replace(col(‘text’), ‘\\d+’, ‘’)" }, { "code": null, "e": 2706, "s": 2576, "text": "3) Segregate the words: Then we break the tweets into individual words to analyze them. We use RegexTokenizer() for this purpose." }, { "code": null, "e": 3021, "s": 2706, "text": "4) Remove stop words: We remove stop words from the segregated words using StopWordsRemover() function from the pyspark.ml library. Some of the examples of stop words are I, the, a, has, etc. As you can notice from these examples, these words don’t carry much information and thus we remove them from the analysis." }, { "code": null, "e": 3239, "s": 3021, "text": "5) Create the features column: After removing the unimportant words from the data, we use CountVectorizer() function. This function converts words to a numeric vector to be able to feed it to a machine learning model." }, { "code": null, "e": 3353, "s": 3239, "text": "Now our data is ready to be fed to predictive models. The data looks like this after finishing the above process." }, { "code": null, "e": 3882, "s": 3353, "text": "Let me shed light on all the fields in the above dataframe; we started with the ‘text’ field. The ‘words’ display segregated words after performing the first 3 steps from our above workflow. The ‘filtered’ column shows words after removing stop words as described in step 4. The ‘features’ field is the numeric vector field after finishing step 5, this is the field we will be using for training machine learning models. The ‘target’ field is our predictor variable which shows whether the tweet is related to a disaster or not." }, { "code": null, "e": 4278, "s": 3882, "text": "We separate the data obtained from the previous process into train and validate. We use the train dataframe for training the machine learning models and validate dataframe to validate their accuracy on the unseen data. There are several criteria for validating the classification models, we will use ROC and accuracy for our analysis. After validating, we will make predictions on the test data." }, { "code": null, "e": 4466, "s": 4278, "text": "I will illustrate some of the common classification machine learning algorithms. I am assuming you are familiar with these algorithms and I will try not to bore you with these algorithms." }, { "code": null, "e": 4946, "s": 4466, "text": "Naive Bayes model is one of the most common algorithms for text classification. Naive Bayes algorithm assumes that all the predictor variables are independent of each other. Simply put, it assumes that the presence of one particular feature is unrelated to any other feature in the data. This assumption is not always correct in real life, however, it makes sense in text classification. The following code is used for training and validating the Naive Bayes Model using PySpark." }, { "code": null, "e": 5506, "s": 4946, "text": "from pyspark.ml.classification import NaiveBayesfrom pyspark.ml.evaluation import MulticlassClassificationEvaluator## Fitting the modelnb = NaiveBayes(modelType=\"multinomial\",labelCol=\"label\", featuresCol=\"features\")nbModel = nb.fit(train)nb_predictions = nbModel.transform(validate)## Evaluating the modelevaluator = MulticlassClassificationEvaluator(labelCol=\"label\", predictionCol=\"prediction\", metricName=\"accuracy\")nb_accuracy = evaluator.evaluate(nb_predictions)print(\"Accuracy of NaiveBayes is = %g\"% (nb_accuracy))#Accuracy of NaiveBayes is = 0.803448" }, { "code": null, "e": 5685, "s": 5506, "text": "It is a variant of regression that uses a logistic function for modeling a binary outcome variable. The following code demonstrates how to train and validate Logistic Regression." }, { "code": null, "e": 6191, "s": 5685, "text": "from pyspark.ml.classification import LogisticRegression## Fitting the modellr = LogisticRegression(featuresCol = 'features', labelCol = 'target', maxIter=10)lrModel = lr.fit(train)lrPreds = lrModel.transform(validate)## Evaluating the modelevaluator = MulticlassClassificationEvaluator(labelCol=\"label\", predictionCol=\"prediction\", metricName=\"accuracy\")lr_accuracy = evaluator.evaluate(lrPreds)print(\"Accuracy of Logistic Regression is = %g\"% (lr_accuracy))#Accuracy of Logistic Regression is = 0.768276" }, { "code": null, "e": 6545, "s": 6191, "text": "Decision trees essentially split the dataset based on columns trying to learn their behavior concerning the outcome variable, i.e. we segment the predictor space into simple regions. This article by Will Koehrsen could help understand decision trees and random forests in detail. We can use the following code for training and validating decision trees." }, { "code": null, "e": 7051, "s": 6545, "text": "from pyspark.ml.classification import DecisionTreeClassifier## Fitting the modeldt = DecisionTreeClassifier(featuresCol = 'features', labelCol = 'target', maxDepth = 3)dtModel = dt.fit(train)dtPreds = dtModel.transform(validate)## Evaluating the modelevaluator = MulticlassClassificationEvaluator(labelCol=\"label\", predictionCol=\"prediction\", metricName=\"accuracy\")dt_accuracy = evaluator.evaluate(dtPreds)print(\"Accuracy of Decision Trees is = %g\"% (dt_accuracy))#Accuracy of Decision Trees is = 0.651034" }, { "code": null, "e": 7305, "s": 7051, "text": "Random forests are an ensemble machine learning method. They use bootstrapping techniques and are fundamentally a combination of numerous weak learners, specifically decision trees. Check the following code to learn to implement random forests in spark." }, { "code": null, "e": 7797, "s": 7305, "text": "from pyspark.ml.classification import RandomForestClassifier## Fitting the modelrf = RandomForestClassifier(featuresCol = 'features', labelCol = 'target')rfModel = rf.fit(train)rfPreds = rfModel.transform(validate)## Evaluating the modelevaluator = MulticlassClassificationEvaluator(labelCol=\"label\", predictionCol=\"prediction\", metricName=\"accuracy\")rf_accuracy = evaluator.evaluate(rfPreds)print(\"Accuracy of Random Forests is = %g\"% (rf_accuracy))#Accuracy of Random Forests is = 0.581379" }, { "code": null, "e": 8136, "s": 7797, "text": "Gradient boosting tree is an ensemble method analogous to random forests. The approach to building trees differs from the random forest; each new tree built by gradient boosting tree attempts to correct errors made by the previous tree. We use GBTClassifier from the pyspark.ml.classification library for training and validating the data." }, { "code": null, "e": 8559, "s": 8136, "text": "from pyspark.ml.classification import GBTClassifier## Fitting the modelgbt = GBTClassifier(maxIter=10)gbtModel = gbt.fit(train)gbtPreds = gbtModel.transform(validate)## Evaluating the modelevaluator = MulticlassClassificationEvaluator(labelCol=\"label\", predictionCol=\"prediction\", metricName=\"accuracy\")gb_accuracy = evaluator.evaluate(gbtPreds)print(\"Accuracy of GBT is = %g\"% (gb_accuracy))#Accuracy of GBT is = 0.681379" }, { "code": null, "e": 8971, "s": 8559, "text": "Now that we’ve trained and validated several models, we make predictions on unseen test data. We can retrain the model on all available training data and then make predictions. The following code demonstrates how to make predictions using the Gradient boosting model. However, you can repeat the same for any of the trained models and also the full code for prediction using other models is available on Github." }, { "code": null, "e": 9319, "s": 8971, "text": "## Fitting the modelgbt = GBTClassifier(maxIter=10)gbtModel = gbt.fit(trainData)## Make predictionsgbtPreds = gbtModel.transform(testData)gbtPreds.select('id','prediction').show(5)+---+----------+| id|prediction|+---+----------+| 0| 0.0|| 2| 0.0|| 3| 1.0|| 9| 0.0|| 11| 0.0|+---+----------+only showing top 5 rows" }, { "code": null, "e": 9774, "s": 9319, "text": "Once you’ve made the predictions, you can convert the dataframe to a CSV format and submit it to the competition. You are now armed to use Spark for developing Machine Learning models. There are myriad applications of Text Classification, such as identifying spam emails, tagging website/product content, etc. and the above algorithms are applicable for all such tasks. Hopefully, you find this useful and will let me know what you think. Happy Learning!" }, { "code": null, "e": 9953, "s": 9774, "text": "Thank you for reading. I hope you find this helpful. If you have any suggestions, please add them in the comments section. Feel free to connect with me on my Website or LinkedIn." }, { "code": null, "e": 10273, "s": 9953, "text": "Spark documentation: https://spark.apache.org/docs/2.2.0/ml-classification-regression.htmlhttps://monkeylearn.com/text-classification/Kaggle Notebook: https://www.kaggle.com/palmer0/binary-classification-with-pyspark-and-mllibGithub Notebook: https://github.com/lp-dataninja/SparkML/blob/master/pyspark-nlp-kaggle.ipynb" }, { "code": null, "e": 10364, "s": 10273, "text": "Spark documentation: https://spark.apache.org/docs/2.2.0/ml-classification-regression.html" }, { "code": null, "e": 10409, "s": 10364, "text": "https://monkeylearn.com/text-classification/" }, { "code": null, "e": 10502, "s": 10409, "text": "Kaggle Notebook: https://www.kaggle.com/palmer0/binary-classification-with-pyspark-and-mllib" } ]
MachineX: Image Data Augmentation Using Keras | by Shubham Goyal | Towards Data Science
In this blog, we will focus on Image Data Augmentation using Keras and how we can implement the same. When we work with image classification projects, the input which a user will give can vary in many aspects, like angles, zoom and stability while clicking the picture. So we should train our model to accept and make sense of almost all types of inputs. This can be done by training the model for all possibilities. But we can’t go around clicking the same training picture in every possible angle when the training set is as big as 10000 pictures! This can be easily be solved by a technique called Image Data Augmentation, which takes an image, converts it and saves it in all the possible forms we specify. Image augmentation is a technique that is used to artificially expand the data-set. This is helpful when we are given a data-set with very few data samples. In the case of Deep Learning, this situation is bad as the model tends to over-fit when we train it on a limited number of data samples. Image augmentation parameters that are generally used to increase the data sample count are zoom, shear, rotation, preprocessing_function and so on. Usage of these parameters results in the generation of images having these attributes during the training of the Deep Learning model. Image samples generated using image augmentation, in general results in the increase of existing data sample set by nearly 3x to 4x times. Let’s start with importing all necessary libraries: pip install tensorflowpip install scipypip install numpypip install h5pypip install pyyamlpip install keras We have installed scipy ,numpy ,h5py ,pyyaml because they are dependencies required for keras and since keras works on a tensorflow backend, there is a need to install that as well. You can read more about tensorflow installation here. We will be using keras for performing Image Augmentation. Let’s import keras image preprocessing. from keras.preprocessing.image import ImageDataGenerator,img_to_array, load_img Here, ImageDataGenerator is used to specify the parameters like rotation, zoom, width we will be using to generate images, more of which will be covered later. img_to_array is used to convert the given image to a numpy array which will be used by the ImageDataGenerator, load_img will be used to load the image to modify into our program. datagen = ImageDataGenerator( rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest') We have used ImageDataGenerator() here to specify the parameters for generating our image, which can be explained as follows: rotation_range : amount of rotation width_shift_range , height_shift_range : amount of shift in width, height shear_range : shear angle in counter-clockwise direction as radians zoom_range : range for random zoom horizontal_flip : Boolean (True or False). Randomly flip inputs horizontally fill_mode : One of {“constant”, “nearest”, “reflect” or “wrap”}. Points outside the boundaries of the input are filled according to the given mode After specifying the parameters and storing them in datagen variable, we move towards importing our image. img = load_img('lion.jpg') Here, I am using a lion image, you can simply use your own sample image. x = img_to_array(img) # creating a Numpy array with shape (3, 150, 150)x = x.reshape((1,) + x.shape) # converting to a Numpy array with shape (1, 3, 150, 150) load_img is used to load the required image, you can use any image you like but I would recommend an image with a face like that of a cat, a dog or a human! Next, we use img_to_array to convert the image to something numerical, in this case, a numpy array, which can be easily fed into our flow() function (don’t worry it is explained later!). We store our converted numpy array to a variable x. Then, we have to reshape the numpy array, adding another parameter of size 1. We do so in order to make it a numpy array of order 4 instead of order 3, to accommodate a parameter called channels axis. In the case of grayscale data, the channels axis should have value 1, and in the case of RGB data, it should have value 3. This is my input image (a lion): Now that we have our input in form, let’s start producing some output. i = 0for batch in datagen.flow(x,save_to_dir='output', save_prefix='lion', save_format='jpeg'): i += 1 if i > 20: break we use datatgen.flow() function in each iteration. We have given x– the numpy array for the input image, save_to_dir– the directory to save output, save_prefix– the prefix for the names of the images and save_format– the image format as input. This is how our output images will look like: Notice that each image is a bit different from the other due to zoom, rotation, width or height shift etc. This will help the model you will be building to recognize a large number of images, thus making it more efficient. So, this is an overview of image augmentation in keras. Moreover, follow Machinex page for more updates for the same:
[ { "code": null, "e": 274, "s": 172, "text": "In this blog, we will focus on Image Data Augmentation using Keras and how we can implement the same." }, { "code": null, "e": 527, "s": 274, "text": "When we work with image classification projects, the input which a user will give can vary in many aspects, like angles, zoom and stability while clicking the picture. So we should train our model to accept and make sense of almost all types of inputs." }, { "code": null, "e": 722, "s": 527, "text": "This can be done by training the model for all possibilities. But we can’t go around clicking the same training picture in every possible angle when the training set is as big as 10000 pictures!" }, { "code": null, "e": 883, "s": 722, "text": "This can be easily be solved by a technique called Image Data Augmentation, which takes an image, converts it and saves it in all the possible forms we specify." }, { "code": null, "e": 1177, "s": 883, "text": "Image augmentation is a technique that is used to artificially expand the data-set. This is helpful when we are given a data-set with very few data samples. In the case of Deep Learning, this situation is bad as the model tends to over-fit when we train it on a limited number of data samples." }, { "code": null, "e": 1599, "s": 1177, "text": "Image augmentation parameters that are generally used to increase the data sample count are zoom, shear, rotation, preprocessing_function and so on. Usage of these parameters results in the generation of images having these attributes during the training of the Deep Learning model. Image samples generated using image augmentation, in general results in the increase of existing data sample set by nearly 3x to 4x times." }, { "code": null, "e": 1651, "s": 1599, "text": "Let’s start with importing all necessary libraries:" }, { "code": null, "e": 1759, "s": 1651, "text": "pip install tensorflowpip install scipypip install numpypip install h5pypip install pyyamlpip install keras" }, { "code": null, "e": 2053, "s": 1759, "text": "We have installed scipy ,numpy ,h5py ,pyyaml because they are dependencies required for keras and since keras works on a tensorflow backend, there is a need to install that as well. You can read more about tensorflow installation here. We will be using keras for performing Image Augmentation." }, { "code": null, "e": 2093, "s": 2053, "text": "Let’s import keras image preprocessing." }, { "code": null, "e": 2173, "s": 2093, "text": "from keras.preprocessing.image import ImageDataGenerator,img_to_array, load_img" }, { "code": null, "e": 2512, "s": 2173, "text": "Here, ImageDataGenerator is used to specify the parameters like rotation, zoom, width we will be using to generate images, more of which will be covered later. img_to_array is used to convert the given image to a numpy array which will be used by the ImageDataGenerator, load_img will be used to load the image to modify into our program." }, { "code": null, "e": 2733, "s": 2512, "text": "datagen = ImageDataGenerator( rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest')" }, { "code": null, "e": 2859, "s": 2733, "text": "We have used ImageDataGenerator() here to specify the parameters for generating our image, which can be explained as follows:" }, { "code": null, "e": 2895, "s": 2859, "text": "rotation_range : amount of rotation" }, { "code": null, "e": 2969, "s": 2895, "text": "width_shift_range , height_shift_range : amount of shift in width, height" }, { "code": null, "e": 3037, "s": 2969, "text": "shear_range : shear angle in counter-clockwise direction as radians" }, { "code": null, "e": 3072, "s": 3037, "text": "zoom_range : range for random zoom" }, { "code": null, "e": 3149, "s": 3072, "text": "horizontal_flip : Boolean (True or False). Randomly flip inputs horizontally" }, { "code": null, "e": 3296, "s": 3149, "text": "fill_mode : One of {“constant”, “nearest”, “reflect” or “wrap”}. Points outside the boundaries of the input are filled according to the given mode" }, { "code": null, "e": 3403, "s": 3296, "text": "After specifying the parameters and storing them in datagen variable, we move towards importing our image." }, { "code": null, "e": 3430, "s": 3403, "text": "img = load_img('lion.jpg')" }, { "code": null, "e": 3503, "s": 3430, "text": "Here, I am using a lion image, you can simply use your own sample image." }, { "code": null, "e": 3664, "s": 3503, "text": "x = img_to_array(img) # creating a Numpy array with shape (3, 150, 150)x = x.reshape((1,) + x.shape) # converting to a Numpy array with shape (1, 3, 150, 150)" }, { "code": null, "e": 3821, "s": 3664, "text": "load_img is used to load the required image, you can use any image you like but I would recommend an image with a face like that of a cat, a dog or a human!" }, { "code": null, "e": 4060, "s": 3821, "text": "Next, we use img_to_array to convert the image to something numerical, in this case, a numpy array, which can be easily fed into our flow() function (don’t worry it is explained later!). We store our converted numpy array to a variable x." }, { "code": null, "e": 4384, "s": 4060, "text": "Then, we have to reshape the numpy array, adding another parameter of size 1. We do so in order to make it a numpy array of order 4 instead of order 3, to accommodate a parameter called channels axis. In the case of grayscale data, the channels axis should have value 1, and in the case of RGB data, it should have value 3." }, { "code": null, "e": 4417, "s": 4384, "text": "This is my input image (a lion):" }, { "code": null, "e": 4488, "s": 4417, "text": "Now that we have our input in form, let’s start producing some output." }, { "code": null, "e": 4621, "s": 4488, "text": "i = 0for batch in datagen.flow(x,save_to_dir='output', save_prefix='lion', save_format='jpeg'): i += 1 if i > 20: break" }, { "code": null, "e": 4865, "s": 4621, "text": "we use datatgen.flow() function in each iteration. We have given x– the numpy array for the input image, save_to_dir– the directory to save output, save_prefix– the prefix for the names of the images and save_format– the image format as input." }, { "code": null, "e": 4911, "s": 4865, "text": "This is how our output images will look like:" }, { "code": null, "e": 5134, "s": 4911, "text": "Notice that each image is a bit different from the other due to zoom, rotation, width or height shift etc. This will help the model you will be building to recognize a large number of images, thus making it more efficient." }, { "code": null, "e": 5190, "s": 5134, "text": "So, this is an overview of image augmentation in keras." } ]
JavaScript | Passing parameters to a callback function - GeeksforGeeks
29 Jun, 2020 Callback Function:Passing a function to another function or passing a function inside another function is known as a Callback Function.In other words, a callback is an already defined function which is passed as an argument to the other code Syntax: function geekOne(z) { alert(z); } function geekTwo(a, callback) { callback(a); } prevfn(2, newfn); Above is an example of a callback variable in JavaScript function.“geekOne” accepts an argument and generates an alert with z as the argument.“geekTwo” accepts an argument and a function.“geekTwo” moves the argument it accepted to the function to passed it to.“geekOne” is the callback function in this case. Example: <script>function GFGexample(fact, callback){ var myFact = "GeeksforGeeks Is Awesome, " + fact; callback(myFact); // 2} function logFact(fact){ document.write(fact);}GFGexample("Learning is easy since", logFact);</script> Output: GeeksforGeeks Is Awesome, Learning is easy since Approach:In this, The “GFGexample” is the main function and accepts 2 arguments, the “callback” is the second one. The logFact function is used as the callback function. When we execute the “GFGexample” function, observe that we are not using parentheses to logFact since it is being passed as an argument. This is because we don’t want to run the callback spontaneously, we only need to pass the function to our main function for later execution.Make sure that if the callback function is expecting an argument. Then we supply those arguments while executing.Moreover, you don’t need to use the word “callback” as the argument name, JavaScript only needs to know it’s the correct argument name. JavaScript callback functions are easy and efficient to use and are of great importance Web applications and code. sai shiva hari prasad javascript-functions Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Convert a string to an integer in JavaScript Form validation using HTML and JavaScript JavaScript | console.log() with Examples Installation of Node.js on Linux Express.js express.Router() Function Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24351, "s": 24323, "text": "\n29 Jun, 2020" }, { "code": null, "e": 24593, "s": 24351, "text": "Callback Function:Passing a function to another function or passing a function inside another function is known as a Callback Function.In other words, a callback is an already defined function which is passed as an argument to the other code" }, { "code": null, "e": 24601, "s": 24593, "text": "Syntax:" }, { "code": null, "e": 24712, "s": 24601, "text": "function geekOne(z) { alert(z); }\nfunction geekTwo(a, callback) {\n callback(a); \n}\nprevfn(2, newfn);" }, { "code": null, "e": 25021, "s": 24712, "text": "Above is an example of a callback variable in JavaScript function.“geekOne” accepts an argument and generates an alert with z as the argument.“geekTwo” accepts an argument and a function.“geekTwo” moves the argument it accepted to the function to passed it to.“geekOne” is the callback function in this case." }, { "code": null, "e": 25030, "s": 25021, "text": "Example:" }, { "code": "<script>function GFGexample(fact, callback){ var myFact = \"GeeksforGeeks Is Awesome, \" + fact; callback(myFact); // 2} function logFact(fact){ document.write(fact);}GFGexample(\"Learning is easy since\", logFact);</script>", "e": 25256, "s": 25030, "text": null }, { "code": null, "e": 25264, "s": 25256, "text": "Output:" }, { "code": null, "e": 25313, "s": 25264, "text": "GeeksforGeeks Is Awesome, Learning is easy since" }, { "code": null, "e": 26009, "s": 25313, "text": "Approach:In this, The “GFGexample” is the main function and accepts 2 arguments, the “callback” is the second one. The logFact function is used as the callback function. When we execute the “GFGexample” function, observe that we are not using parentheses to logFact since it is being passed as an argument. This is because we don’t want to run the callback spontaneously, we only need to pass the function to our main function for later execution.Make sure that if the callback function is expecting an argument. Then we supply those arguments while executing.Moreover, you don’t need to use the word “callback” as the argument name, JavaScript only needs to know it’s the correct argument name." }, { "code": null, "e": 26124, "s": 26009, "text": "JavaScript callback functions are easy and efficient to use and are of great importance Web applications and code." }, { "code": null, "e": 26146, "s": 26124, "text": "sai shiva hari prasad" }, { "code": null, "e": 26167, "s": 26146, "text": "javascript-functions" }, { "code": null, "e": 26174, "s": 26167, "text": "Picked" }, { "code": null, "e": 26185, "s": 26174, "text": "JavaScript" }, { "code": null, "e": 26202, "s": 26185, "text": "Web Technologies" }, { "code": null, "e": 26300, "s": 26202, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26309, "s": 26300, "text": "Comments" }, { "code": null, "e": 26322, "s": 26309, "text": "Old Comments" }, { "code": null, "e": 26383, "s": 26322, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26455, "s": 26383, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 26500, "s": 26455, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26542, "s": 26500, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 26583, "s": 26542, "text": "JavaScript | console.log() with Examples" }, { "code": null, "e": 26616, "s": 26583, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26653, "s": 26616, "text": "Express.js express.Router() Function" }, { "code": null, "e": 26715, "s": 26653, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26758, "s": 26715, "text": "How to fetch data from an API in ReactJS ?" } ]
Zero-Shot Text Classification with Hugging Face | by Andrej Baranovskij | Towards Data Science
A few weeks ago I was implementing POC with one of the requirements to be able to detect text sentiment in an unsupervised way (without having training data in advance and building a model). More specifically it was about data extraction. Based on some predefined topics, my task was to automate information extraction from text data. While doing research and checking for the best ways to solve this problem, I found out that Hugging Face NLP supports zero-shot text classification. What is zero-shot text classification? Check this post — Zero-Shot Learning in Modern NLP. There is a live demo from Hugging Face team, along with a sample Colab notebook. In simple words, zero-shot model allows us to classify data, which wasn’t used to build a model. What I mean here — the model was built by someone else, we are using it to run against our data. I thought it would be a useful example, where I fetch Twitter messages and run classification to group messages into topics. This can be used as a starting point for more complex use cases. I’m using GetOldTweets3 library to scrap Twitter messages. Zero-shot classification with transformers is straightforward, I was following Colab example provided by Hugging Face. List of imports: import GetOldTweets3 as gotimport pandas as pdfrom tqdm import tqdmimport matplotlib.pyplot as pltimport seaborn as snsfrom transformers import pipeline Getting classifier from transformers pipeline: classifier = pipeline("zero-shot-classification") I scrape 500 latest messages from Twitter, based on a predefined query — “climate fight”. We are going to fetch messages related to climate change fight into Pandas data frame and then try to split them into topics using zero-shot classification: txt = 'climate fight'max_recs = 500tweets_df = text_query_to_df(txt, max_recs) In zero-shot classification, you can define your own labels and then run classifier to assign a probability to each label. There is an option to do multi-class classification too, in this case, the scores will be independent, each will fall between 0 and 1. I’m going to use the default option, when the pipeline assumes that only one of the candidate labels is true, returning a list of scores for each label which adds up to 1. Candidate labels for topics — this would allow us to understand what are people actually talking about climate change fight. Some messages are simple adverts, we would like to ignore them. Zero-shot classification is able to detect adverts pretty well, this helps to clean the data: candidate_labels = ["renewable", "politics", "emission", "temperature", "emergency", "advertisment"] I’m going in the loop and classifying each message: res = classifier(sent, candidate_labels) Then I’m checking the classification result. It is enough to check the first label, as I’m using the default option when pipeline assumes only one of the candidate labels is true. If the classification score is greater than 0.5, I’m logging it for further processing: if res['labels'][0] == 'renewable' and res['scores'][0] > 0.5: candidate_results[0] = candidate_results[0] + 1 From the result, we can see that political topic dominates climate change fight discussion, perhaps as expected. Topics related to emission and emergency are close to each other by popularity. There were around 20 cases of adverts from scrapped 500 messages: Let’s see some examples, for each topic. renewable Eco-friendly Hydrogen: The clean fuel of the future Germany is promoting the use of #eco-friendly hydrogen in the fight against climate change. Hydrogen can replace fossil fuels in virtually every situation, in an engine or fuel cell! politics This is so crazy and wrong. It’s as if the ACA isn’t better than what we had before, that the fight for voting rights doesn’t matter, or equal pay for women, or marriage equality, or the Paris climate agreement. Just because Biden isn’t what we want doesn’t mean Dems = GOP emission A simpler, more useful way to tax carbon to fight climate change - Vox temperature I've noticed any time someone tries to tell me global warming is not a big deal and how climate change has happened before, my body goes into fight or flight. emergency (+ the next few years are CRUCIAL in the fight against climate change. if we don't address it, we'll pass the point of IRREVERSIBLE damage. biden supports the green new deal. trump... well, ya know.) advertisement What is your favorite party game? Have a look on @ClumsyRush https://www.nintendo.com/games/detail/clumsy-rush-switch/ #party #game #NintendoSwitch Classification results are very good, I think Hugging Face zero-shot model does a really good job. Sample sentences from above didn't have direct mention of the topic label and still, they were classified correctly. Conclusion Unsupervised text classification with zero-shot model allows us to solve text sentiment detection tasks when you don’t have training data to train the model. Instead, you rely on a large trained model from transformers. For specialized use cases, when text is based on specific words or terms — is better to go with a supervised classification model, based on the training set. But for general topics, zero-shot model works amazingly well. Source code GitHub repo Run it yourself in Colab notebook
[ { "code": null, "e": 656, "s": 172, "text": "A few weeks ago I was implementing POC with one of the requirements to be able to detect text sentiment in an unsupervised way (without having training data in advance and building a model). More specifically it was about data extraction. Based on some predefined topics, my task was to automate information extraction from text data. While doing research and checking for the best ways to solve this problem, I found out that Hugging Face NLP supports zero-shot text classification." }, { "code": null, "e": 1022, "s": 656, "text": "What is zero-shot text classification? Check this post — Zero-Shot Learning in Modern NLP. There is a live demo from Hugging Face team, along with a sample Colab notebook. In simple words, zero-shot model allows us to classify data, which wasn’t used to build a model. What I mean here — the model was built by someone else, we are using it to run against our data." }, { "code": null, "e": 1212, "s": 1022, "text": "I thought it would be a useful example, where I fetch Twitter messages and run classification to group messages into topics. This can be used as a starting point for more complex use cases." }, { "code": null, "e": 1390, "s": 1212, "text": "I’m using GetOldTweets3 library to scrap Twitter messages. Zero-shot classification with transformers is straightforward, I was following Colab example provided by Hugging Face." }, { "code": null, "e": 1407, "s": 1390, "text": "List of imports:" }, { "code": null, "e": 1560, "s": 1407, "text": "import GetOldTweets3 as gotimport pandas as pdfrom tqdm import tqdmimport matplotlib.pyplot as pltimport seaborn as snsfrom transformers import pipeline" }, { "code": null, "e": 1607, "s": 1560, "text": "Getting classifier from transformers pipeline:" }, { "code": null, "e": 1657, "s": 1607, "text": "classifier = pipeline(\"zero-shot-classification\")" }, { "code": null, "e": 1904, "s": 1657, "text": "I scrape 500 latest messages from Twitter, based on a predefined query — “climate fight”. We are going to fetch messages related to climate change fight into Pandas data frame and then try to split them into topics using zero-shot classification:" }, { "code": null, "e": 1983, "s": 1904, "text": "txt = 'climate fight'max_recs = 500tweets_df = text_query_to_df(txt, max_recs)" }, { "code": null, "e": 2413, "s": 1983, "text": "In zero-shot classification, you can define your own labels and then run classifier to assign a probability to each label. There is an option to do multi-class classification too, in this case, the scores will be independent, each will fall between 0 and 1. I’m going to use the default option, when the pipeline assumes that only one of the candidate labels is true, returning a list of scores for each label which adds up to 1." }, { "code": null, "e": 2696, "s": 2413, "text": "Candidate labels for topics — this would allow us to understand what are people actually talking about climate change fight. Some messages are simple adverts, we would like to ignore them. Zero-shot classification is able to detect adverts pretty well, this helps to clean the data:" }, { "code": null, "e": 2797, "s": 2696, "text": "candidate_labels = [\"renewable\", \"politics\", \"emission\", \"temperature\", \"emergency\", \"advertisment\"]" }, { "code": null, "e": 2849, "s": 2797, "text": "I’m going in the loop and classifying each message:" }, { "code": null, "e": 2890, "s": 2849, "text": "res = classifier(sent, candidate_labels)" }, { "code": null, "e": 3158, "s": 2890, "text": "Then I’m checking the classification result. It is enough to check the first label, as I’m using the default option when pipeline assumes only one of the candidate labels is true. If the classification score is greater than 0.5, I’m logging it for further processing:" }, { "code": null, "e": 3272, "s": 3158, "text": "if res['labels'][0] == 'renewable' and res['scores'][0] > 0.5: candidate_results[0] = candidate_results[0] + 1" }, { "code": null, "e": 3531, "s": 3272, "text": "From the result, we can see that political topic dominates climate change fight discussion, perhaps as expected. Topics related to emission and emergency are close to each other by popularity. There were around 20 cases of adverts from scrapped 500 messages:" }, { "code": null, "e": 3572, "s": 3531, "text": "Let’s see some examples, for each topic." }, { "code": null, "e": 3582, "s": 3572, "text": "renewable" }, { "code": null, "e": 3817, "s": 3582, "text": "Eco-friendly Hydrogen: The clean fuel of the future Germany is promoting the use of #eco-friendly hydrogen in the fight against climate change. Hydrogen can replace fossil fuels in virtually every situation, in an engine or fuel cell!" }, { "code": null, "e": 3826, "s": 3817, "text": "politics" }, { "code": null, "e": 4100, "s": 3826, "text": "This is so crazy and wrong. It’s as if the ACA isn’t better than what we had before, that the fight for voting rights doesn’t matter, or equal pay for women, or marriage equality, or the Paris climate agreement. Just because Biden isn’t what we want doesn’t mean Dems = GOP" }, { "code": null, "e": 4109, "s": 4100, "text": "emission" }, { "code": null, "e": 4180, "s": 4109, "text": "A simpler, more useful way to tax carbon to fight climate change - Vox" }, { "code": null, "e": 4192, "s": 4180, "text": "temperature" }, { "code": null, "e": 4351, "s": 4192, "text": "I've noticed any time someone tries to tell me global warming is not a big deal and how climate change has happened before, my body goes into fight or flight." }, { "code": null, "e": 4361, "s": 4351, "text": "emergency" }, { "code": null, "e": 4561, "s": 4361, "text": "(+ the next few years are CRUCIAL in the fight against climate change. if we don't address it, we'll pass the point of IRREVERSIBLE damage. biden supports the green new deal. trump... well, ya know.)" }, { "code": null, "e": 4575, "s": 4561, "text": "advertisement" }, { "code": null, "e": 4723, "s": 4575, "text": "What is your favorite party game? Have a look on @ClumsyRush https://www.nintendo.com/games/detail/clumsy-rush-switch/ #party #game #NintendoSwitch" }, { "code": null, "e": 4939, "s": 4723, "text": "Classification results are very good, I think Hugging Face zero-shot model does a really good job. Sample sentences from above didn't have direct mention of the topic label and still, they were classified correctly." }, { "code": null, "e": 4950, "s": 4939, "text": "Conclusion" }, { "code": null, "e": 5390, "s": 4950, "text": "Unsupervised text classification with zero-shot model allows us to solve text sentiment detection tasks when you don’t have training data to train the model. Instead, you rely on a large trained model from transformers. For specialized use cases, when text is based on specific words or terms — is better to go with a supervised classification model, based on the training set. But for general topics, zero-shot model works amazingly well." }, { "code": null, "e": 5402, "s": 5390, "text": "Source code" }, { "code": null, "e": 5414, "s": 5402, "text": "GitHub repo" } ]
Sort Python Dictionaries by Key or Value
When it is required to sort the dictionaries in Python using a key or a value, a dictionary can be defined, and key value pairs can be inserted into it. A ‘for’ loop can be used to iterate through the key value pair, and sort it using ‘sort’ method. This method can be called. Below is the demonstration of the same − def my_dict(): my_key_value_pair ={} my_key_value_pair[2] = 56 my_key_value_pair[1] = 2 my_key_value_pair[5] = 12 my_key_value_pair[4] = 24 my_key_value_pair[6] = 18 my_key_value_pair[3] = 323 print ("The keys and values after sorting in alphabetical order based on the key are : ") for i in sorted (my_key_value_pair) : print((i, my_key_value_pair[i])) my_dict() The keys and values after sorting in alphabetical order based on the key are : (1, 2) (2, 56) (3, 323) (4, 24) (5, 12) (6, 18) A method is defined, that initially assigns an empty dictionary to a variable. A method is defined, that initially assigns an empty dictionary to a variable. The index of the empty dictionary is accessed and elements are assigned to indices. The index of the empty dictionary is accessed and elements are assigned to indices. The ‘sorted’ method is used to iterate through the dictionary, and display it on the console. The ‘sorted’ method is used to iterate through the dictionary, and display it on the console. This method is called. This method is called. The output is displayed on the console. The output is displayed on the console.
[ { "code": null, "e": 1339, "s": 1062, "text": "When it is required to sort the dictionaries in Python using a key or a value, a dictionary can be defined, and key value pairs can be inserted into it. A ‘for’ loop can be used to iterate through the key value pair, and sort it using ‘sort’ method. This method can be called." }, { "code": null, "e": 1380, "s": 1339, "text": "Below is the demonstration of the same −" }, { "code": null, "e": 1752, "s": 1380, "text": "def my_dict():\n\nmy_key_value_pair ={}\n\nmy_key_value_pair[2] = 56\nmy_key_value_pair[1] = 2\nmy_key_value_pair[5] = 12\nmy_key_value_pair[4] = 24\nmy_key_value_pair[6] = 18\nmy_key_value_pair[3] = 323\n\nprint (\"The keys and values after sorting in alphabetical order based on the key are : \")\n\nfor i in sorted (my_key_value_pair) :\n print((i, my_key_value_pair[i]))\n\nmy_dict()" }, { "code": null, "e": 1879, "s": 1752, "text": "The keys and values after sorting in alphabetical order based on the key are :\n(1, 2)\n(2, 56)\n(3, 323)\n(4, 24)\n(5, 12)\n(6, 18)" }, { "code": null, "e": 1958, "s": 1879, "text": "A method is defined, that initially assigns an empty dictionary to a variable." }, { "code": null, "e": 2037, "s": 1958, "text": "A method is defined, that initially assigns an empty dictionary to a variable." }, { "code": null, "e": 2121, "s": 2037, "text": "The index of the empty dictionary is accessed and elements are assigned to indices." }, { "code": null, "e": 2205, "s": 2121, "text": "The index of the empty dictionary is accessed and elements are assigned to indices." }, { "code": null, "e": 2299, "s": 2205, "text": "The ‘sorted’ method is used to iterate through the dictionary, and display it on the console." }, { "code": null, "e": 2393, "s": 2299, "text": "The ‘sorted’ method is used to iterate through the dictionary, and display it on the console." }, { "code": null, "e": 2416, "s": 2393, "text": "This method is called." }, { "code": null, "e": 2439, "s": 2416, "text": "This method is called." }, { "code": null, "e": 2479, "s": 2439, "text": "The output is displayed on the console." }, { "code": null, "e": 2519, "s": 2479, "text": "The output is displayed on the console." } ]
How do I invoke a Java method when given the method name as a string?
The java.lang.reflect.Method class provides information about, and access to, a single method on a class or interface. The reflected method may be a class method or an instance method (including an abstract method). A Method permits widening conversions to occur when matching the actual parameters to invoke with the underlying method's formal parameters, but it throws an IllegalArgumentException if a narrowing conversion would occur. You can invoke the method using the class named method of the package java.lang.reflect. The constructor of this class accepts the method name in the form of a string. And you can invoke this method using the invoke() method. import java.lang.reflect.Method; public class DemoTest { private void sampleMethod(){ System.out.println("hello"); } } public class SampleTest { public static void main(String args[]) throws Exception{ Class c = Class.forName("DemoTest"); Object obj = c.newInstance(); Method method = c.getDeclaredMethod("sampleMethod", null); method.setAccessible(true); method.invoke(obj, null); } }
[ { "code": null, "e": 1500, "s": 1062, "text": "The java.lang.reflect.Method class provides information about, and access to, a single method on a class or interface. The reflected method may be a class method or an instance method (including an abstract method). A Method permits widening conversions to occur when matching the actual parameters to invoke with the underlying method's formal parameters, but it throws an IllegalArgumentException if a narrowing conversion would occur." }, { "code": null, "e": 1726, "s": 1500, "text": "You can invoke the method using the class named method of the package java.lang.reflect. The constructor of this class accepts the method name in the form of a string. And you can invoke this method using the invoke() method." }, { "code": null, "e": 2168, "s": 1726, "text": "import java.lang.reflect.Method;\n\npublic class DemoTest {\n private void sampleMethod(){\n System.out.println(\"hello\");\n }\n}\npublic class SampleTest {\n public static void main(String args[]) throws Exception{\n Class c = Class.forName(\"DemoTest\");\n Object obj = c.newInstance();\n \n Method method = c.getDeclaredMethod(\"sampleMethod\", null);\n method.setAccessible(true);\n method.invoke(obj, null);\n }\n}" } ]
Python program to create a sorted merged list of two unsorted list
Here two user input list is given, the elements of two lists are unsorted. Our task is to merged these two unsorted array and after that sort the list. Input: A [] = {100, 50, 150} B [] = {200, 30, 20} Output: Merge List:{20, 30, 50, 100, 150, 200} Step 1: first we create two user input list. Step 2: Final merge list size is (size of the first list + the size of the second list). Step 3: then sort two list using sort() method. Step 4: Merge two sorted list and store it into a third list. Step 5: Merging remaining elements of a[] (if any).Merging remaining elements of b[] (if any). Step 6: display merged sorted list. # Python program to merge two unsorted lists # in sorted order # Function to merge array in sorted order def unsortedarray (a, b, res, n, m): # Sorting a[] and b[] a.sort() b.sort() # Merge two sorted arrays into res[] i, j, k = 0, 0, 0 while (i < n and j < m): if (a[i] <= b[j]): res[k] = a[i] i += 1 k += 1 else: res[k] = b[j] j += 1 k += 1 while (i < n): # Merging remaining # elements of a[] (if any) res[k] = a[i] i += 1 k += 1 while (j < m): # Merging remaining # elements of b[] (if any) res[k] = b[j] j += 1 k += 1 # Driver code A=list() n=int(input("Enter the size of the First List ::")) print("Enter the Element of First List ::") for i in range(int(n)): k=int(input("")) A.append(k) B=list() m=int(input("Enter the size of the Second List ::")) print("Enter the Element of Second List ::") for i in range(int(n)): k=int(input("")) B.append(k) # Final merge list res = [0 for i in range(n + m)] unsortedarray(A, B, res, n, m) print ("Sorted merged list :") for i in range(n + m): print (res[i],) Enter the size of the First List: 4 Enter the Element of First List:: 8 79 56 3 Enter the size of the Second List: 4 Enter the Element of Second List:: 67 1 9 45 Sorted merged list: 1 3 8 9 45 56 67 79
[ { "code": null, "e": 1214, "s": 1062, "text": "Here two user input list is given, the elements of two lists are unsorted. Our task is to merged these two unsorted array and after that sort the list." }, { "code": null, "e": 1319, "s": 1214, "text": "Input: A [] = {100, 50, 150}\n B [] = {200, 30, 20}\nOutput: Merge List:{20, 30, 50, 100, 150, 200}\n" }, { "code": null, "e": 1695, "s": 1319, "text": "Step 1: first we create two user input list.\nStep 2: Final merge list size is (size of the first list + the size of the second list).\nStep 3: then sort two list using sort() method.\nStep 4: Merge two sorted list and store it into a third list.\nStep 5: Merging remaining elements of a[] (if any).Merging remaining elements of b[] (if any).\nStep 6: display merged sorted list.\n" }, { "code": null, "e": 2858, "s": 1695, "text": "# Python program to merge two unsorted lists \n# in sorted order\n# Function to merge array in sorted order\ndef unsortedarray (a, b, res, n, m):\n # Sorting a[] and b[]\n a.sort()\n b.sort()\n # Merge two sorted arrays into res[]\n i, j, k = 0, 0, 0\n while (i < n and j < m):\n if (a[i] <= b[j]):\n res[k] = a[i]\n i += 1\n k += 1\n else:\n res[k] = b[j]\n j += 1\n k += 1\n while (i < n): # Merging remaining\n # elements of a[] (if any)\n res[k] = a[i]\n i += 1\n k += 1\n while (j < m): # Merging remaining\n # elements of b[] (if any)\n res[k] = b[j]\n j += 1\n k += 1\n# Driver code\nA=list()\nn=int(input(\"Enter the size of the First List ::\"))\nprint(\"Enter the Element of First List ::\")\nfor i in range(int(n)):\n k=int(input(\"\"))\n A.append(k)\nB=list()\nm=int(input(\"Enter the size of the Second List ::\"))\nprint(\"Enter the Element of Second List ::\")\nfor i in range(int(n)):\n k=int(input(\"\"))\n B.append(k)\n# Final merge list\nres = [0 for i in range(n + m)]\nunsortedarray(A, B, res, n, m)\nprint (\"Sorted merged list :\")\nfor i in range(n + m):\n print (res[i],)" }, { "code": null, "e": 3061, "s": 2858, "text": "Enter the size of the First List: 4\nEnter the Element of First List::\n8\n79\n56\n3\nEnter the size of the Second List: 4\nEnter the Element of Second List::\n67\n1\n9\n45\nSorted merged list:\n1\n3\n8\n9\n45\n56\n67\n79\n" } ]
How to detect search engine bots with PHP?
A search engine directory of the spider names can be used as a reference. Next, $_SERVER['HTTP_USER_AGENT']; can be used to check if the agent is a spider (bot). Below is an example demonstrating the same − if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']), "some_bot_name")) { //other steps that need to be used } Code explanation − The agent, along with the user agent is passed to the strtolower function, whose output in turn is passed to the strstr function. Both the user agent and the bot are compared to see if the spider is a bot or not. Another option is shown below − function _bot_detected() { return ( isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|crawl|slurp|spider|mediapartners/i', $_SERVER['HTTP_USER_AGENT']); } Code explanation − The preg_match function helps in finding specific patterns in the string. To the preg_match function, the bot name is passed and it is compared with the user agent that detects if the spider is a search engine bot or not.
[ { "code": null, "e": 1224, "s": 1062, "text": "A search engine directory of the spider names can be used as a reference. Next, $_SERVER['HTTP_USER_AGENT']; can be used to check if the agent is a spider (bot)." }, { "code": null, "e": 1269, "s": 1224, "text": "Below is an example demonstrating the same −" }, { "code": null, "e": 1380, "s": 1269, "text": "if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']), \"some_bot_name\")) {\n //other steps that need to be used\n}" }, { "code": null, "e": 1612, "s": 1380, "text": "Code explanation − The agent, along with the user agent is passed to the strtolower function, whose output in turn is passed to the strstr function. Both the user agent and the bot are compared to see if the spider is a bot or not." }, { "code": null, "e": 1644, "s": 1612, "text": "Another option is shown below −" }, { "code": null, "e": 1819, "s": 1644, "text": "function _bot_detected() {\n return (\n isset($_SERVER['HTTP_USER_AGENT'])\n && preg_match('/bot|crawl|slurp|spider|mediapartners/i', $_SERVER['HTTP_USER_AGENT']);\n}" }, { "code": null, "e": 2060, "s": 1819, "text": "Code explanation − The preg_match function helps in finding specific patterns in the string. To the preg_match function, the bot name is passed and it is compared with the user agent that detects if the spider is a search engine bot or not." } ]
Strongly Connected Graphs
In a directed graph is said to be strongly connected, when there is a path between each pair of vertices in one component. To solve this algorithm, firstly, DFS algorithm is used to get the finish time of each vertex, now find the finish time of the transposed graph, then the vertices are sorted in descending order by topological sort. Input: Adjacency matrix of the graph. 0 0 1 1 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 Output: Following are strongly connected components in given graph: 0 1 2 3 4 traverse(graph, start, visited) Input: The graph which will be traversed, the starting vertex, and flags of visited nodes. Output: Go through each node in the DFS technique and display nodes. Begin mark start as visited for all vertices v connected with start, do if v is not visited, then traverse(graph, v, visited) done End topoSort(u, visited, stack) Input − The start node, flag for visited vertices, stack. Output − Fill stack while sorting the graph. Begin mark u as visited for all node v, connected with u, do if v is not visited, then topoSort(v, visited, stack) done push u into the stack End getStrongConComponents(graph) Input: The given graph. Output − All strongly connected components. Begin initially all nodes are unvisited for all vertex i in the graph, do if i is not visited, then topoSort(i, vis, stack) done make all nodes unvisited again transGraph := transpose of given graph while stack is not empty, do pop node from stack and take into v if v is not visited, then traverse(transGraph, v, visited) done End #include <iostream> #include <stack> #define NODE 5 using namespace std; int graph[NODE][NODE] = { {0, 0, 1, 1, 0}, {1, 0, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 0, 0, 1}, {0, 0, 0, 0, 0} }; int transGraph[NODE][NODE]; void transpose() { //transpose the graph and store to transGraph for(int i = 0; i<NODE; i++) for(int j = 0; j<NODE; j++) transGraph[i][j] = graph[j][i]; } void traverse(int g[NODE][NODE], int u, bool visited[]) { visited[u] = true; //mark v as visited cout << u << " "; for(int v = 0; v<NODE; v++) { if(g[u][v]) { if(!visited[v]) traverse(g, v, visited); } } } void topoSort(int u, bool visited[], stack<int>&stk) { visited[u] = true; //set as the node v is visited for(int v = 0; v<NODE; v++) { if(graph[u][v]) { //for allvertices v adjacent to u if(!visited[v]) topoSort(v, visited, stk); } } stk.push(u); //push starting vertex into the stack } void getStrongConComponents() { stack<int> stk; bool vis[NODE]; for(int i = 0; i<NODE; i++) vis[i] = false; //initially all nodes are unvisited for(int i = 0; i<NODE; i++) if(!vis[i]) //when node is not visited topoSort(i, vis, stk); for(int i = 0; i<NODE; i++) vis[i] = false; //make all nodes are unvisited for traversal transpose(); //make reversed graph while(!stk.empty()) { //when stack contains element, process in topological order int v = stk.top(); stk.pop(); if(!vis[v]) { traverse(transGraph, v, vis); cout << endl; } } } int main() { cout << "Following are strongly connected components in given graph: "<<endl; getStrongConComponents(); } Following are strongly connected components in given graph: 0 1 2 3 4
[ { "code": null, "e": 1185, "s": 1062, "text": "In a directed graph is said to be strongly connected, when there is a path between each pair of vertices in one component." }, { "code": null, "e": 1400, "s": 1185, "text": "To solve this algorithm, firstly, DFS algorithm is used to get the finish time of each vertex, now find the finish time of the transposed graph, then the vertices are sorted in descending order by topological sort." }, { "code": null, "e": 1567, "s": 1400, "text": "Input:\nAdjacency matrix of the graph.\n0 0 1 1 0\n1 0 0 0 0\n0 1 0 0 0\n0 0 0 0 1\n0 0 0 0 0\n\nOutput:\nFollowing are strongly connected components in given graph:\n0 1 2\n3\n4" }, { "code": null, "e": 1599, "s": 1567, "text": "traverse(graph, start, visited)" }, { "code": null, "e": 1690, "s": 1599, "text": "Input: The graph which will be traversed, the starting vertex, and flags of visited nodes." }, { "code": null, "e": 1759, "s": 1690, "text": "Output: Go through each node in the DFS technique and display nodes." }, { "code": null, "e": 1918, "s": 1759, "text": "Begin\n mark start as visited\n for all vertices v connected with start, do\n if v is not visited, then\n traverse(graph, v, visited)\n done\nEnd" }, { "code": null, "e": 1946, "s": 1918, "text": "topoSort(u, visited, stack)" }, { "code": null, "e": 2004, "s": 1946, "text": "Input − The start node, flag for visited vertices, stack." }, { "code": null, "e": 2049, "s": 2004, "text": "Output − Fill stack while sorting the graph." }, { "code": null, "e": 2222, "s": 2049, "text": "Begin\n mark u as visited\n for all node v, connected with u, do\n if v is not visited, then\n topoSort(v, visited, stack)\n done\n push u into the stack\nEnd" }, { "code": null, "e": 2252, "s": 2222, "text": "getStrongConComponents(graph)" }, { "code": null, "e": 2276, "s": 2252, "text": "Input: The given graph." }, { "code": null, "e": 2320, "s": 2276, "text": "Output − All strongly connected components." }, { "code": null, "e": 2711, "s": 2320, "text": "Begin\n initially all nodes are unvisited\n for all vertex i in the graph, do\n if i is not visited, then\n topoSort(i, vis, stack)\n done\n\n make all nodes unvisited again\n transGraph := transpose of given graph\n\n while stack is not empty, do\n pop node from stack and take into v\n if v is not visited, then\n traverse(transGraph, v, visited)\n done\nEnd" }, { "code": null, "e": 4590, "s": 2711, "text": "#include <iostream>\n#include <stack>\n#define NODE 5\nusing namespace std;\n\nint graph[NODE][NODE] = {\n {0, 0, 1, 1, 0},\n {1, 0, 0, 0, 0},\n {0, 1, 0, 0, 0},\n {0, 0, 0, 0, 1},\n {0, 0, 0, 0, 0}\n};\n \nint transGraph[NODE][NODE];\n\nvoid transpose() { //transpose the graph and store to transGraph\n for(int i = 0; i<NODE; i++)\n for(int j = 0; j<NODE; j++)\n transGraph[i][j] = graph[j][i];\n} \n \nvoid traverse(int g[NODE][NODE], int u, bool visited[]) {\n visited[u] = true; //mark v as visited\n cout << u << \" \";\n\n for(int v = 0; v<NODE; v++) {\n if(g[u][v]) {\n if(!visited[v])\n traverse(g, v, visited);\n }\n }\n} \n \nvoid topoSort(int u, bool visited[], stack<int>&stk) {\n visited[u] = true; //set as the node v is visited\n\n for(int v = 0; v<NODE; v++) {\n if(graph[u][v]) { //for allvertices v adjacent to u\n if(!visited[v])\n topoSort(v, visited, stk);\n }\n }\n\n stk.push(u); //push starting vertex into the stack\n}\n\nvoid getStrongConComponents() {\n stack<int> stk;\n bool vis[NODE];\n\n for(int i = 0; i<NODE; i++)\n vis[i] = false; //initially all nodes are unvisited\n \n for(int i = 0; i<NODE; i++)\n if(!vis[i]) //when node is not visited\n topoSort(i, vis, stk);\n \n for(int i = 0; i<NODE; i++)\n vis[i] = false; //make all nodes are unvisited for traversal \n transpose(); //make reversed graph\n \n while(!stk.empty()) { //when stack contains element, process in topological order\n int v = stk.top(); stk.pop();\n if(!vis[v]) {\n traverse(transGraph, v, vis);\n cout << endl;\n }\n }\n}\n\nint main() {\n cout << \"Following are strongly connected components in given graph: \"<<endl;\n getStrongConComponents();\n}" }, { "code": null, "e": 4660, "s": 4590, "text": "Following are strongly connected components in given graph:\n0 1 2\n3\n4" } ]
Reading and Writing Files in Perl
Once you have an open file handle in Perl, you need to be able to read and write information. There are a number of different ways of reading and writing data into the file. The main method of reading the information from an open filehandle is the <FILEHANDLE> operator. In a scalar context, it returns a single line from the filehandle. For example − #!/usr/bin/perl print "What is your name?\n"; $name = <STDIN>; print "Hello $name\n"; When you use the <FILEHANDLE> operator in a list context, it returns a list of lines from the specified filehandle. For example, to import all the lines from a file into an array − #!/usr/bin/perl open(DATA,"<import.txt") or die "Can't open data"; @lines = <DATA>; close(DATA); The getc function returns a single character from the specified FILEHANDLE, or STDIN if none is specified − getc FILEHANDLE getc If there was an error, or the filehandle is at end of file, then undef is returned instead. The read function reads a block of information from the buffered filehandle: This function is used to read binary data from the file. read FILEHANDLE, SCALAR, LENGTH, OFFSET read FILEHANDLE, SCALAR, LENGTH The length of the data read is defined by LENGTH, and the data is placed at the start of SCALAR if no OFFSET is specified. Otherwise data is placed after OFFSET bytes in SCALAR. The function returns the number of bytes read on success, zero at end of file, or undef if there was an error. For all the different methods used for reading information from filehandles, the main function for writing information back is the print function. print FILEHANDLE LIST print LIST print The print function prints the evaluated value of LIST to FILEHANDLE, or to the current output filehandle (STDOUT by default). For example − print "Hello World!\n";
[ { "code": null, "e": 1236, "s": 1062, "text": "Once you have an open file handle in Perl, you need to be able to read and write information. There are a number of different ways of reading and writing data into the file." }, { "code": null, "e": 1414, "s": 1236, "text": "The main method of reading the information from an open filehandle is the <FILEHANDLE> operator. In a scalar context, it returns a single line from the filehandle. For example −" }, { "code": null, "e": 1500, "s": 1414, "text": "#!/usr/bin/perl\nprint \"What is your name?\\n\";\n$name = <STDIN>;\nprint \"Hello $name\\n\";" }, { "code": null, "e": 1681, "s": 1500, "text": "When you use the <FILEHANDLE> operator in a list context, it returns a list of lines from the specified filehandle. For example, to import all the lines from a file into an array −" }, { "code": null, "e": 1778, "s": 1681, "text": "#!/usr/bin/perl\nopen(DATA,\"<import.txt\") or die \"Can't open data\";\n@lines = <DATA>;\nclose(DATA);" }, { "code": null, "e": 1886, "s": 1778, "text": "The getc function returns a single character from the specified FILEHANDLE, or STDIN if none is specified −" }, { "code": null, "e": 1907, "s": 1886, "text": "getc FILEHANDLE\ngetc" }, { "code": null, "e": 1999, "s": 1907, "text": "If there was an error, or the filehandle is at end of file, then undef is returned instead." }, { "code": null, "e": 2133, "s": 1999, "text": "The read function reads a block of information from the buffered filehandle: This function is used to read binary data from the file." }, { "code": null, "e": 2205, "s": 2133, "text": "read FILEHANDLE, SCALAR, LENGTH, OFFSET\nread FILEHANDLE, SCALAR, LENGTH" }, { "code": null, "e": 2494, "s": 2205, "text": "The length of the data read is defined by LENGTH, and the data is placed at the start of SCALAR if no OFFSET is specified. Otherwise data is placed after OFFSET bytes in SCALAR. The function returns the number of bytes read on success, zero at end of file, or undef if there was an error." }, { "code": null, "e": 2641, "s": 2494, "text": "For all the different methods used for reading information from filehandles, the main function for writing information back is the print function." }, { "code": null, "e": 2680, "s": 2641, "text": "print FILEHANDLE LIST\nprint LIST\nprint" }, { "code": null, "e": 2820, "s": 2680, "text": "The print function prints the evaluated value of LIST to FILEHANDLE, or to the current output filehandle (STDOUT by default). For example −" }, { "code": null, "e": 2844, "s": 2820, "text": "print \"Hello World!\\n\";" } ]
Conversion of ArrayList to Array in C#
To convert an ArrayList to Array, use the ToArray() method in C#. Firstly, set an ArrayList − ArrayList arrList = new ArrayList(); arrList.Add("one"); arrList.Add("two"); arrList.Add("three"); Now, to convert, use the ToArray() method − arrList.ToArray(typeof(string)) as string[]; Let us see the complete code − Live Demo using System; using System.Collections; public class Program { public static void Main() { ArrayList arrList = new ArrayList(); arrList.Add("one"); arrList.Add("two"); arrList.Add("three"); string[] arr = arrList.ToArray(typeof(string)) as string[]; foreach (string res in arr) { Console.WriteLine(res); } } } one two three
[ { "code": null, "e": 1128, "s": 1062, "text": "To convert an ArrayList to Array, use the ToArray() method in C#." }, { "code": null, "e": 1156, "s": 1128, "text": "Firstly, set an ArrayList −" }, { "code": null, "e": 1255, "s": 1156, "text": "ArrayList arrList = new ArrayList();\narrList.Add(\"one\");\narrList.Add(\"two\");\narrList.Add(\"three\");" }, { "code": null, "e": 1299, "s": 1255, "text": "Now, to convert, use the ToArray() method −" }, { "code": null, "e": 1344, "s": 1299, "text": "arrList.ToArray(typeof(string)) as string[];" }, { "code": null, "e": 1375, "s": 1344, "text": "Let us see the complete code −" }, { "code": null, "e": 1386, "s": 1375, "text": " Live Demo" }, { "code": null, "e": 1756, "s": 1386, "text": "using System;\nusing System.Collections;\n\npublic class Program {\n public static void Main() {\n ArrayList arrList = new ArrayList();\n arrList.Add(\"one\");\n arrList.Add(\"two\");\n arrList.Add(\"three\");\n\n string[] arr = arrList.ToArray(typeof(string)) as string[];\n\n foreach (string res in arr) {\n Console.WriteLine(res);\n }\n }\n}" }, { "code": null, "e": 1770, "s": 1756, "text": "one\ntwo\nthree" } ]
Matplotlib.figure.Figure.set_facecolor() in Python - GeeksforGeeks
03 May, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements. The set_facecolor() method figure module of matplotlib library is used to set the face color of the Figure rectangle. Syntax: set_facecolor(self, color) Parameters: This method accept the following parameters that are discussed below: color : This parameter is the color. Returns: This method does not returns any value. Below examples illustrate the matplotlib.figure.Figure.set_facecolor() function in matplotlib.figure: Example 1: # Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np fig = plt.figure() ax = Subplot(fig, 111) fig.add_subplot(ax) fig.set_facecolor("green") fig.suptitle("""matplotlib.figure.Figure.set_facecolor()function Example\n\n""", fontweight ="bold") plt.show() Output: Example 2: # Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np fig = plt.figure(figsize =(7, 6)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx)) fig.set_facecolor("red") fig.suptitle("""matplotlib.figure.Figure.set_facecolor()function Example\n\n""", fontweight ="bold") plt.show() Output: Matplotlib figure-class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python
[ { "code": null, "e": 25695, "s": 25667, "text": "\n03 May, 2020" }, { "code": null, "e": 26006, "s": 25695, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements." }, { "code": null, "e": 26124, "s": 26006, "text": "The set_facecolor() method figure module of matplotlib library is used to set the face color of the Figure rectangle." }, { "code": null, "e": 26159, "s": 26124, "text": "Syntax: set_facecolor(self, color)" }, { "code": null, "e": 26241, "s": 26159, "text": "Parameters: This method accept the following parameters that are discussed below:" }, { "code": null, "e": 26278, "s": 26241, "text": "color : This parameter is the color." }, { "code": null, "e": 26327, "s": 26278, "text": "Returns: This method does not returns any value." }, { "code": null, "e": 26429, "s": 26327, "text": "Below examples illustrate the matplotlib.figure.Figure.set_facecolor() function in matplotlib.figure:" }, { "code": null, "e": 26440, "s": 26429, "text": "Example 1:" }, { "code": "# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np fig = plt.figure() ax = Subplot(fig, 111) fig.add_subplot(ax) fig.set_facecolor(\"green\") fig.suptitle(\"\"\"matplotlib.figure.Figure.set_facecolor()function Example\\n\\n\"\"\", fontweight =\"bold\") plt.show()", "e": 26846, "s": 26440, "text": null }, { "code": null, "e": 26854, "s": 26846, "text": "Output:" }, { "code": null, "e": 26865, "s": 26854, "text": "Example 2:" }, { "code": "# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np fig = plt.figure(figsize =(7, 6)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx)) fig.set_facecolor(\"red\") fig.suptitle(\"\"\"matplotlib.figure.Figure.set_facecolor()function Example\\n\\n\"\"\", fontweight =\"bold\") plt.show() ", "e": 27296, "s": 26865, "text": null }, { "code": null, "e": 27304, "s": 27296, "text": "Output:" }, { "code": null, "e": 27328, "s": 27304, "text": "Matplotlib figure-class" }, { "code": null, "e": 27346, "s": 27328, "text": "Python-matplotlib" }, { "code": null, "e": 27353, "s": 27346, "text": "Python" }, { "code": null, "e": 27451, "s": 27353, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27469, "s": 27451, "text": "Python Dictionary" }, { "code": null, "e": 27504, "s": 27469, "text": "Read a file line by line in Python" }, { "code": null, "e": 27536, "s": 27504, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27578, "s": 27536, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27604, "s": 27578, "text": "Python String | replace()" }, { "code": null, "e": 27633, "s": 27604, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27677, "s": 27633, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27714, "s": 27677, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27750, "s": 27714, "text": "Convert integer to string in Python" } ]
Tailwind CSS Grayscale - GeeksforGeeks
23 Mar, 2022 The Grayscale class is used to apply a filter to the image to set the grayscale of the image. In CSS, we do that by using the CSS grayscale() Function. Tailwind CSS newly added feature brightness in 2.1 version. Grayscale: grayscale-0: This class is used to represents the original image.grayscale: This class is used to represents the linear multipliers on the effect. grayscale-0: This class is used to represents the original image. grayscale: This class is used to represents the linear multipliers on the effect. Syntax: <element class="filter grayscale | grayscale-0">..</element> Example: HTML <!DOCTYPE html><html><head> <link href="https://unpkg.com/tailwindcss@^2.1/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center mx-20 space-y-2"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Grayscale Class</b> <div class="grid grid-flow-col text-center mx-44"> <img class="rounded-lg filter grayscale" src="https://media.geeksforgeeks.org/wp-content/uploads/20210604014825/QNHrwL2q-100x100.jpg" alt="image"> <img class="rounded-lg filter grayscale-0" src="https://media.geeksforgeeks.org/wp-content/uploads/20210604014825/QNHrwL2q-100x100.jpg" alt="image"> </div></body> </html> Output: Tailwind CSS Tailwind-Filters 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": 37597, "s": 37385, "text": "The Grayscale class is used to apply a filter to the image to set the grayscale of the image. In CSS, we do that by using the CSS grayscale() Function. Tailwind CSS newly added feature brightness in 2.1 version." }, { "code": null, "e": 37608, "s": 37597, "text": "Grayscale:" }, { "code": null, "e": 37755, "s": 37608, "text": "grayscale-0: This class is used to represents the original image.grayscale: This class is used to represents the linear multipliers on the effect." }, { "code": null, "e": 37821, "s": 37755, "text": "grayscale-0: This class is used to represents the original image." }, { "code": null, "e": 37903, "s": 37821, "text": "grayscale: This class is used to represents the linear multipliers on the effect." }, { "code": null, "e": 37911, "s": 37903, "text": "Syntax:" }, { "code": null, "e": 37972, "s": 37911, "text": "<element class=\"filter grayscale | grayscale-0\">..</element>" }, { "code": null, "e": 37981, "s": 37972, "text": "Example:" }, { "code": null, "e": 37986, "s": 37981, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <link href=\"https://unpkg.com/tailwindcss@^2.1/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body class=\"text-center mx-20 space-y-2\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Grayscale Class</b> <div class=\"grid grid-flow-col text-center mx-44\"> <img class=\"rounded-lg filter grayscale\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210604014825/QNHrwL2q-100x100.jpg\" alt=\"image\"> <img class=\"rounded-lg filter grayscale-0\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210604014825/QNHrwL2q-100x100.jpg\" alt=\"image\"> </div></body> </html>", "e": 38731, "s": 37986, "text": null }, { "code": null, "e": 38739, "s": 38731, "text": "Output:" }, { "code": null, "e": 38752, "s": 38739, "text": "Tailwind CSS" }, { "code": null, "e": 38769, "s": 38752, "text": "Tailwind-Filters" }, { "code": null, "e": 38773, "s": 38769, "text": "CSS" }, { "code": null, "e": 38790, "s": 38773, "text": "Web Technologies" }, { "code": null, "e": 38888, "s": 38790, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38938, "s": 38888, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 39000, "s": 38938, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 39048, "s": 39000, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 39106, "s": 39048, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 39161, "s": 39106, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 39201, "s": 39161, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 39234, "s": 39201, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 39279, "s": 39234, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 39322, "s": 39279, "text": "How to fetch data from an API in ReactJS ?" } ]
K-th digit in 'a' raised to power 'b' - GeeksforGeeks
17 Dec, 2021 Given three numbers a, b and k, find k-th digit in ab from right sideExamples: Input : a = 3, b = 3, k = 1 Output : 7 Explanation 3^3 = 27 for k = 1. First digit is 7 in 27 Input : a = 5, b = 2, k = 2 Output : 2 Explanation 5^2 = 25 for k = 2. First digit is 2 in 25 Method 1) Compute a^b 2) Iteratively remove the last digit until k-th digit is not meet C++ Java Python3 C# PHP Javascript // CPP program for finding k-th digit in a^b#include <bits/stdc++.h>using namespace std; // To compute k-th digit in a^bint kthdigit(int a, int b, int k){ // computing a^b int p = pow(a, b); int count = 0; while (p > 0 && count < k) { // getting last digit int rem = p % 10; // increasing count by 1 count++; // if current number is required digit if (count == k) return rem; // remove last digit p = p / 10; } return 0;} // Driver codeint main(){ int a = 5, b = 2; int k = 1; cout << kthdigit(a, b, k); return 0;} // Java program for finding k-th digit in a^bimport java.util.*;import java.lang.*; public class GfG { // To compute k-th digit in a^b public static int kthdigit(int a, int b, int k) { // Computing a^b int p = (int)Math.pow(a, b); int count = 0; while (p > 0 && count < k) { // Getting last digit int rem = p % 10; // Increasing count by 1 count++; // If current number is required digit if (count == k) return rem; // Remove last digit p = p / 10; } return 0; } // Driver Code public static void main(String argc[]) { int a = 5, b = 2; int k = 1; System.out.println(kthdigit(a, b, k)); } } // This code is contributed by Sagar Shukla. # Python3 code to compute k-th# digit in a^bdef kthdigit(a, b, k): # computing a^b in python p = a ** b count = 0 while (p > 0 and count < k): # getting last digit rem = p % 10 # increasing count by 1 count = count + 1 # if current number is # required digit if (count == k): return rem # remove last digit p = p / 10; # driver code a = 5b = 2k = 1ans = kthdigit(a, b, k)print (ans) # This code is contributed by Saloni Gupta // C# program for finding k-th digit in a^busing System; public class GfG { // To compute k-th digit in a^b public static int kthdigit(int a, int b, int k) { // Computing a^b int p = (int)Math.Pow(a, b); int count = 0; while (p > 0 && count < k) { // Getting last digit int rem = p % 10; // Increasing count by 1 count++; // If current number is required digit if (count == k) return rem; // Remove last digit p = p / 10; } return 0; } // Driver Code public static void Main() { int a = 5, b = 2; int k = 1; Console.WriteLine(kthdigit(a, b, k)); } } // This code is contributed by vt_m. <?php// PHP program for finding// k-th digit in a^b // To compute k-th// digit in a^bfunction kthdigit($a, $b, $k){ // computing a^b $p = pow($a, $b); $count = 0; while ($p > 0 and $count < $k) { // getting last digit $rem = $p % 10; // increasing count by 1 $count++; // if current number is // required digit if ($count == $k) return $rem; // remove last digit $p = $p / 10; } return 0;} // Driver Code $a = 5; $b = 2; $k = 1; echo kthdigit($a, $b, $k); // This code is contributed by anuj_67.?> <script> // JavaScript program for finding k-th digit in a^b // To compute k-th digit in a^b function kthdigit(a, b, k) { // Computing a^b let p = Math.pow(a, b); let count = 0; while (p > 0 && count < k) { // Getting last digit let rem = p % 10; // Increasing count by 1 count++; // If current number is required digit if (count == k) return rem; // Remove last digit p = p / 10; } return 0; } // Driver code let a = 5, b = 2; let k = 1; document.write(kthdigit(a, b, k)); </script> Output: 5 How to avoid overflow? We can find power under modulo 10sup>k to avoid overflow. After finding the power under modulo, we need to return first digit of the power. vt_m splevel62 varshagumber28 Flipkart number-digits Mathematical Flipkart Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Print all possible combinations of r elements in a given array of size n Program for factorial of a number The Knight's tour problem | Backtracking-1 Operators in C / C++ Find minimum number of coins that make a given value Program to find sum of elements in a given array Minimum number of jumps to reach end Program to print prime numbers from 1 to N.
[ { "code": null, "e": 25823, "s": 25795, "text": "\n17 Dec, 2021" }, { "code": null, "e": 25903, "s": 25823, "text": "Given three numbers a, b and k, find k-th digit in ab from right sideExamples: " }, { "code": null, "e": 26110, "s": 25903, "text": "Input : a = 3, b = 3, \n k = 1\nOutput : 7\nExplanation\n3^3 = 27 for k = 1. First digit is 7 in 27\n\nInput : a = 5, b = 2, \n k = 2\nOutput : 2\nExplanation\n5^2 = 25 for k = 2. First digit is 2 in 25" }, { "code": null, "e": 26201, "s": 26112, "text": "Method 1) Compute a^b 2) Iteratively remove the last digit until k-th digit is not meet " }, { "code": null, "e": 26205, "s": 26201, "text": "C++" }, { "code": null, "e": 26210, "s": 26205, "text": "Java" }, { "code": null, "e": 26218, "s": 26210, "text": "Python3" }, { "code": null, "e": 26221, "s": 26218, "text": "C#" }, { "code": null, "e": 26225, "s": 26221, "text": "PHP" }, { "code": null, "e": 26236, "s": 26225, "text": "Javascript" }, { "code": "// CPP program for finding k-th digit in a^b#include <bits/stdc++.h>using namespace std; // To compute k-th digit in a^bint kthdigit(int a, int b, int k){ // computing a^b int p = pow(a, b); int count = 0; while (p > 0 && count < k) { // getting last digit int rem = p % 10; // increasing count by 1 count++; // if current number is required digit if (count == k) return rem; // remove last digit p = p / 10; } return 0;} // Driver codeint main(){ int a = 5, b = 2; int k = 1; cout << kthdigit(a, b, k); return 0;}", "e": 26854, "s": 26236, "text": null }, { "code": "// Java program for finding k-th digit in a^bimport java.util.*;import java.lang.*; public class GfG { // To compute k-th digit in a^b public static int kthdigit(int a, int b, int k) { // Computing a^b int p = (int)Math.pow(a, b); int count = 0; while (p > 0 && count < k) { // Getting last digit int rem = p % 10; // Increasing count by 1 count++; // If current number is required digit if (count == k) return rem; // Remove last digit p = p / 10; } return 0; } // Driver Code public static void main(String argc[]) { int a = 5, b = 2; int k = 1; System.out.println(kthdigit(a, b, k)); } } // This code is contributed by Sagar Shukla.", "e": 27692, "s": 26854, "text": null }, { "code": "# Python3 code to compute k-th# digit in a^bdef kthdigit(a, b, k): # computing a^b in python p = a ** b count = 0 while (p > 0 and count < k): # getting last digit rem = p % 10 # increasing count by 1 count = count + 1 # if current number is # required digit if (count == k): return rem # remove last digit p = p / 10; # driver code a = 5b = 2k = 1ans = kthdigit(a, b, k)print (ans) # This code is contributed by Saloni Gupta", "e": 28232, "s": 27692, "text": null }, { "code": "// C# program for finding k-th digit in a^busing System; public class GfG { // To compute k-th digit in a^b public static int kthdigit(int a, int b, int k) { // Computing a^b int p = (int)Math.Pow(a, b); int count = 0; while (p > 0 && count < k) { // Getting last digit int rem = p % 10; // Increasing count by 1 count++; // If current number is required digit if (count == k) return rem; // Remove last digit p = p / 10; } return 0; } // Driver Code public static void Main() { int a = 5, b = 2; int k = 1; Console.WriteLine(kthdigit(a, b, k)); } } // This code is contributed by vt_m.", "e": 29026, "s": 28232, "text": null }, { "code": "<?php// PHP program for finding// k-th digit in a^b // To compute k-th// digit in a^bfunction kthdigit($a, $b, $k){ // computing a^b $p = pow($a, $b); $count = 0; while ($p > 0 and $count < $k) { // getting last digit $rem = $p % 10; // increasing count by 1 $count++; // if current number is // required digit if ($count == $k) return $rem; // remove last digit $p = $p / 10; } return 0;} // Driver Code $a = 5; $b = 2; $k = 1; echo kthdigit($a, $b, $k); // This code is contributed by anuj_67.?>", "e": 29646, "s": 29026, "text": null }, { "code": "<script> // JavaScript program for finding k-th digit in a^b // To compute k-th digit in a^b function kthdigit(a, b, k) { // Computing a^b let p = Math.pow(a, b); let count = 0; while (p > 0 && count < k) { // Getting last digit let rem = p % 10; // Increasing count by 1 count++; // If current number is required digit if (count == k) return rem; // Remove last digit p = p / 10; } return 0; } // Driver code let a = 5, b = 2; let k = 1; document.write(kthdigit(a, b, k)); </script>", "e": 30341, "s": 29646, "text": null }, { "code": null, "e": 30350, "s": 30341, "text": "Output: " }, { "code": null, "e": 30352, "s": 30350, "text": "5" }, { "code": null, "e": 30515, "s": 30352, "text": "How to avoid overflow? We can find power under modulo 10sup>k to avoid overflow. After finding the power under modulo, we need to return first digit of the power." }, { "code": null, "e": 30520, "s": 30515, "text": "vt_m" }, { "code": null, "e": 30530, "s": 30520, "text": "splevel62" }, { "code": null, "e": 30545, "s": 30530, "text": "varshagumber28" }, { "code": null, "e": 30554, "s": 30545, "text": "Flipkart" }, { "code": null, "e": 30568, "s": 30554, "text": "number-digits" }, { "code": null, "e": 30581, "s": 30568, "text": "Mathematical" }, { "code": null, "e": 30590, "s": 30581, "text": "Flipkart" }, { "code": null, "e": 30603, "s": 30590, "text": "Mathematical" }, { "code": null, "e": 30701, "s": 30603, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30725, "s": 30701, "text": "Merge two sorted arrays" }, { "code": null, "e": 30768, "s": 30725, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 30841, "s": 30768, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 30875, "s": 30841, "text": "Program for factorial of a number" }, { "code": null, "e": 30918, "s": 30875, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 30939, "s": 30918, "text": "Operators in C / C++" }, { "code": null, "e": 30992, "s": 30939, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 31041, "s": 30992, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 31078, "s": 31041, "text": "Minimum number of jumps to reach end" } ]
Python | Encoding Decoding using Matrix - GeeksforGeeks
30 Dec, 2020 This article is about how we use the matrix to encode and decode a text message and simple strings.Encoding process : Take a String convert to corresponding number shown belowconvert to 2D matrix(array). Now we have 2×2 matrix!When we multiply this matrix with encoding matrix we get encoded 2×2 matrix.now convert to vector(1D array) and Display to user Take a String convert to corresponding number shown below convert to 2D matrix(array). Now we have 2×2 matrix! When we multiply this matrix with encoding matrix we get encoded 2×2 matrix. now convert to vector(1D array) and Display to user Decoding process Take Encoded number convert into 2D matrix(array) Inverse Encoding matrix! Multiply Encoded matrix with inverse of encoding matrix. convert to 1D Matrix(array).then convert to corresponding Alphabets.Code : Encode.py# loading librariesimport numpy as np a = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]c = [[0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0]] # encode matrixecm = [[3,4], [3,6]]i = 0l = 0 # Lists of Alphabets and its valuessmallalpha = [" ","a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]capitalalpha = [" ","A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]alphavalues = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27] # string to convert b = "India"listb = list(b)lenb = len(listb) # Loop to convert Word to Values that # are further useful for Encodingfor i in range(lenb): for j in range(27): if(listb[i] == smallalpha[j]): a[i] = alphavalues[j] if(j == 23): j = 0 break if(j == 23): for k in range(27): if(listb[i] == capitalalpha[k]): a[i] = alphavalues[k] break if(lenb%2 == 1): lenb = lenb+1a = a[0:lenb]tb = b # convert this array to 2D array for further # multiplication with encoding matrix j = 0k = 0 # b[m][n] m is always 2n = int(lenb/2)for i in range(0,lenb): if(j<n): c[k][j] = a[i] j = j+1 else: k = k+1 j = 0 c[k][j] = a[i] j = j+1 # Multiplay matrix by Encoding 2x2 matrix c = np.matmul(ecm, c) # Convert to 1D array for displaying i = 0j = 0k = 0for i in range(2): for j in range(int(lenb/2)): a[k] = c[i][j] k = k+1 a = a[0:lenb]print("Encoding matrix = ", ecm)print("encrypted form = ", a)Time Complexity : O(n)(where n is length of message)Space Complexity : O(n) Output:Encoding matrix = [[3, 4], [3, 6]] Encrypted form = [63, 46, 12, 81, 48, 12] Code : Decode.py# importing librariesimport numpy as npfrom numpy.linalg import inv # Initial valuesa =[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] tdm =[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] # encoding matrixecm =[[3, 4], [3, 6]] # Lists of Alphabets and its valuessmallalpha = [" ","a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]capitalalpha = [" ","A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]alphavalues = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27] # Take inputs# elements in Encrypted Matrixlenb = 6a = [63, 46, 12, 81, 48, 12] sobj = slice(lenb)a = a[sobj] # convert array to 2d matrix to further # multiplication with inverse of 2d matrixj = 0k = 0 # b[m][n] m is always 2n = int(lenb / 2)for i in range(0, lenb): if(j<n): tdm[k][j]= a[i] j = j + 1 else: k = k + 1 j = 0 tdm[k][j]= a[i] j = j + 1 # Multiply by inverse matrixdcm = inv(ecm)dcm = np.matmul(dcm, tdm) # Convert to 1d array for extracting wordi = 0j = 0k = 0for i in range(2): for j in range(int(lenb / 2)): a[k]= dcm[i][j] k = k + 1 # Creating a decoded wordtext = ""for i in range(0, lenb): for j in range(0, 27): if(a[i]== alphavalues[j]): text =''.join([text, smallalpha[j]]) print("Decoded message = "+text)Time Complexity : O(n)(where n is number of elements)Space Complexity : O(n)Output:Decoded message = india My Personal Notes arrow_drop_upSave # loading librariesimport numpy as np a = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]c = [[0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0]] # encode matrixecm = [[3,4], [3,6]]i = 0l = 0 # Lists of Alphabets and its valuessmallalpha = [" ","a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]capitalalpha = [" ","A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]alphavalues = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27] # string to convert b = "India"listb = list(b)lenb = len(listb) # Loop to convert Word to Values that # are further useful for Encodingfor i in range(lenb): for j in range(27): if(listb[i] == smallalpha[j]): a[i] = alphavalues[j] if(j == 23): j = 0 break if(j == 23): for k in range(27): if(listb[i] == capitalalpha[k]): a[i] = alphavalues[k] break if(lenb%2 == 1): lenb = lenb+1a = a[0:lenb]tb = b # convert this array to 2D array for further # multiplication with encoding matrix j = 0k = 0 # b[m][n] m is always 2n = int(lenb/2)for i in range(0,lenb): if(j<n): c[k][j] = a[i] j = j+1 else: k = k+1 j = 0 c[k][j] = a[i] j = j+1 # Multiplay matrix by Encoding 2x2 matrix c = np.matmul(ecm, c) # Convert to 1D array for displaying i = 0j = 0k = 0for i in range(2): for j in range(int(lenb/2)): a[k] = c[i][j] k = k+1 a = a[0:lenb]print("Encoding matrix = ", ecm)print("encrypted form = ", a) Time Complexity : O(n)(where n is length of message)Space Complexity : O(n) Output: Encoding matrix = [[3, 4], [3, 6]] Encrypted form = [63, 46, 12, 81, 48, 12] # importing librariesimport numpy as npfrom numpy.linalg import inv # Initial valuesa =[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] tdm =[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] # encoding matrixecm =[[3, 4], [3, 6]] # Lists of Alphabets and its valuessmallalpha = [" ","a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]capitalalpha = [" ","A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]alphavalues = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27] # Take inputs# elements in Encrypted Matrixlenb = 6a = [63, 46, 12, 81, 48, 12] sobj = slice(lenb)a = a[sobj] # convert array to 2d matrix to further # multiplication with inverse of 2d matrixj = 0k = 0 # b[m][n] m is always 2n = int(lenb / 2)for i in range(0, lenb): if(j<n): tdm[k][j]= a[i] j = j + 1 else: k = k + 1 j = 0 tdm[k][j]= a[i] j = j + 1 # Multiply by inverse matrixdcm = inv(ecm)dcm = np.matmul(dcm, tdm) # Convert to 1d array for extracting wordi = 0j = 0k = 0for i in range(2): for j in range(int(lenb / 2)): a[k]= dcm[i][j] k = k + 1 # Creating a decoded wordtext = ""for i in range(0, lenb): for j in range(0, 27): if(a[i]== alphavalues[j]): text =''.join([text, smallalpha[j]]) print("Decoded message = "+text) Time Complexity : O(n)(where n is number of elements)Space Complexity : O(n) Output: Decoded message = india Python matrix-program Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n30 Dec, 2020" }, { "code": null, "e": 25655, "s": 25537, "text": "This article is about how we use the matrix to encode and decode a text message and simple strings.Encoding process :" }, { "code": null, "e": 25892, "s": 25655, "text": "Take a String convert to corresponding number shown belowconvert to 2D matrix(array). Now we have 2×2 matrix!When we multiply this matrix with encoding matrix we get encoded 2×2 matrix.now convert to vector(1D array) and Display to user" }, { "code": null, "e": 25950, "s": 25892, "text": "Take a String convert to corresponding number shown below" }, { "code": null, "e": 26003, "s": 25950, "text": "convert to 2D matrix(array). Now we have 2×2 matrix!" }, { "code": null, "e": 26080, "s": 26003, "text": "When we multiply this matrix with encoding matrix we get encoded 2×2 matrix." }, { "code": null, "e": 26132, "s": 26080, "text": "now convert to vector(1D array) and Display to user" }, { "code": null, "e": 26149, "s": 26132, "text": "Decoding process" }, { "code": null, "e": 26199, "s": 26149, "text": "Take Encoded number convert into 2D matrix(array)" }, { "code": null, "e": 26224, "s": 26199, "text": "Inverse Encoding matrix!" }, { "code": null, "e": 26281, "s": 26224, "text": "Multiply Encoded matrix with inverse of encoding matrix." }, { "code": null, "e": 30253, "s": 26281, "text": "convert to 1D Matrix(array).then convert to corresponding Alphabets.Code : Encode.py# loading librariesimport numpy as np a = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]c = [[0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0]] # encode matrixecm = [[3,4], [3,6]]i = 0l = 0 # Lists of Alphabets and its valuessmallalpha = [\" \",\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"]capitalalpha = [\" \",\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\"]alphavalues = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27] # string to convert b = \"India\"listb = list(b)lenb = len(listb) # Loop to convert Word to Values that # are further useful for Encodingfor i in range(lenb): for j in range(27): if(listb[i] == smallalpha[j]): a[i] = alphavalues[j] if(j == 23): j = 0 break if(j == 23): for k in range(27): if(listb[i] == capitalalpha[k]): a[i] = alphavalues[k] break if(lenb%2 == 1): lenb = lenb+1a = a[0:lenb]tb = b # convert this array to 2D array for further # multiplication with encoding matrix j = 0k = 0 # b[m][n] m is always 2n = int(lenb/2)for i in range(0,lenb): if(j<n): c[k][j] = a[i] j = j+1 else: k = k+1 j = 0 c[k][j] = a[i] j = j+1 # Multiplay matrix by Encoding 2x2 matrix c = np.matmul(ecm, c) # Convert to 1D array for displaying i = 0j = 0k = 0for i in range(2): for j in range(int(lenb/2)): a[k] = c[i][j] k = k+1 a = a[0:lenb]print(\"Encoding matrix = \", ecm)print(\"encrypted form = \", a)Time Complexity : O(n)(where n is length of message)Space Complexity : O(n) Output:Encoding matrix = [[3, 4], [3, 6]]\nEncrypted form = [63, 46, 12, 81, 48, 12]\nCode : Decode.py# importing librariesimport numpy as npfrom numpy.linalg import inv # Initial valuesa =[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] tdm =[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] # encoding matrixecm =[[3, 4], [3, 6]] # Lists of Alphabets and its valuessmallalpha = [\" \",\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"]capitalalpha = [\" \",\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\"]alphavalues = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27] # Take inputs# elements in Encrypted Matrixlenb = 6a = [63, 46, 12, 81, 48, 12] sobj = slice(lenb)a = a[sobj] # convert array to 2d matrix to further # multiplication with inverse of 2d matrixj = 0k = 0 # b[m][n] m is always 2n = int(lenb / 2)for i in range(0, lenb): if(j<n): tdm[k][j]= a[i] j = j + 1 else: k = k + 1 j = 0 tdm[k][j]= a[i] j = j + 1 # Multiply by inverse matrixdcm = inv(ecm)dcm = np.matmul(dcm, tdm) # Convert to 1d array for extracting wordi = 0j = 0k = 0for i in range(2): for j in range(int(lenb / 2)): a[k]= dcm[i][j] k = k + 1 # Creating a decoded wordtext = \"\"for i in range(0, lenb): for j in range(0, 27): if(a[i]== alphavalues[j]): text =''.join([text, smallalpha[j]]) print(\"Decoded message = \"+text)Time Complexity : O(n)(where n is number of elements)Space Complexity : O(n)Output:Decoded message = india My Personal Notes\narrow_drop_upSave" }, { "code": "# loading librariesimport numpy as np a = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]c = [[0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0]] # encode matrixecm = [[3,4], [3,6]]i = 0l = 0 # Lists of Alphabets and its valuessmallalpha = [\" \",\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"]capitalalpha = [\" \",\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\"]alphavalues = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27] # string to convert b = \"India\"listb = list(b)lenb = len(listb) # Loop to convert Word to Values that # are further useful for Encodingfor i in range(lenb): for j in range(27): if(listb[i] == smallalpha[j]): a[i] = alphavalues[j] if(j == 23): j = 0 break if(j == 23): for k in range(27): if(listb[i] == capitalalpha[k]): a[i] = alphavalues[k] break if(lenb%2 == 1): lenb = lenb+1a = a[0:lenb]tb = b # convert this array to 2D array for further # multiplication with encoding matrix j = 0k = 0 # b[m][n] m is always 2n = int(lenb/2)for i in range(0,lenb): if(j<n): c[k][j] = a[i] j = j+1 else: k = k+1 j = 0 c[k][j] = a[i] j = j+1 # Multiplay matrix by Encoding 2x2 matrix c = np.matmul(ecm, c) # Convert to 1D array for displaying i = 0j = 0k = 0for i in range(2): for j in range(int(lenb/2)): a[k] = c[i][j] k = k+1 a = a[0:lenb]print(\"Encoding matrix = \", ecm)print(\"encrypted form = \", a)", "e": 32163, "s": 30253, "text": null }, { "code": null, "e": 32240, "s": 32163, "text": "Time Complexity : O(n)(where n is length of message)Space Complexity : O(n) " }, { "code": null, "e": 32248, "s": 32240, "text": "Output:" }, { "code": null, "e": 32328, "s": 32248, "text": "Encoding matrix = [[3, 4], [3, 6]]\nEncrypted form = [63, 46, 12, 81, 48, 12]\n" }, { "code": "# importing librariesimport numpy as npfrom numpy.linalg import inv # Initial valuesa =[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] tdm =[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] # encoding matrixecm =[[3, 4], [3, 6]] # Lists of Alphabets and its valuessmallalpha = [\" \",\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"]capitalalpha = [\" \",\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\"]alphavalues = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27] # Take inputs# elements in Encrypted Matrixlenb = 6a = [63, 46, 12, 81, 48, 12] sobj = slice(lenb)a = a[sobj] # convert array to 2d matrix to further # multiplication with inverse of 2d matrixj = 0k = 0 # b[m][n] m is always 2n = int(lenb / 2)for i in range(0, lenb): if(j<n): tdm[k][j]= a[i] j = j + 1 else: k = k + 1 j = 0 tdm[k][j]= a[i] j = j + 1 # Multiply by inverse matrixdcm = inv(ecm)dcm = np.matmul(dcm, tdm) # Convert to 1d array for extracting wordi = 0j = 0k = 0for i in range(2): for j in range(int(lenb / 2)): a[k]= dcm[i][j] k = k + 1 # Creating a decoded wordtext = \"\"for i in range(0, lenb): for j in range(0, 27): if(a[i]== alphavalues[j]): text =''.join([text, smallalpha[j]]) print(\"Decoded message = \"+text)", "e": 33987, "s": 32328, "text": null }, { "code": null, "e": 34064, "s": 33987, "text": "Time Complexity : O(n)(where n is number of elements)Space Complexity : O(n)" }, { "code": null, "e": 34072, "s": 34064, "text": "Output:" }, { "code": null, "e": 34097, "s": 34072, "text": "Decoded message = india " }, { "code": null, "e": 34119, "s": 34097, "text": "Python matrix-program" }, { "code": null, "e": 34126, "s": 34119, "text": "Python" }, { "code": null, "e": 34142, "s": 34126, "text": "Python Programs" }, { "code": null, "e": 34240, "s": 34142, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34272, "s": 34240, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 34314, "s": 34272, "text": "Check if element exists in list in Python" }, { "code": null, "e": 34356, "s": 34314, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 34383, "s": 34356, "text": "Python Classes and Objects" }, { "code": null, "e": 34439, "s": 34383, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 34461, "s": 34439, "text": "Defaultdict in Python" }, { "code": null, "e": 34500, "s": 34461, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 34546, "s": 34500, "text": "Python | Split string into list of characters" }, { "code": null, "e": 34584, "s": 34546, "text": "Python | Convert a list to dictionary" } ]
Solve Sudoku with Computer Vision and Constraint Satisfaction Algorithm - GeeksforGeeks
18 Jan, 2022 This article explains a program in python 2.7 to solve a Sudoku 9×9 of the Android application “Sudoku” of genina.com. To solve a sudoku of the Android application “Sudoku” of genina.com, a screenshot of the game is taken (a 720×1280 image is obtained), then the number found in each of the 81 squares is obtained using KNN algorithm, once each element is determined, the sudoku is solved using a constraint satisfaction algorithm with backtracking. On the left is our input: Screenshot that we are going to analyze. On the right is the solution. How this work? Step 1: Image Preprocessing First step, Image Preprocessing: Extract each sudoku square individually and save them sequentially as photo # .png (where # goes from 0 to 80). Images of 80×75 pixels are obtained.Code: Input: photo0.png. This is the photo that we are going to analyze. Code: python #/Preprocessing.py / import cv2import numpy as npimport Functions # Relative pathpath ="./Screenshots/" # Image to analyzenumber = input("Enter image number: ")globalPath = path+"photo"+str(number)+".png"image = cv2.imread(globalPath) # Save the name of the image to analyze after in Main.pyfile = open("image.txt", "w")file.write(globalPath)file.close() # MAINif __name__ == '__main__': # PREPROCESSING -> Crop the edges, ads and all # the images outside the sudoku board image = Functions.cropImage(image, 218) image = Functions.rotateImage(image, 180) image = Functions.cropImage(image, 348) image = Functions.rotateImage(image, 180) # Crop each box in the sudoku board cont = 0 w = 0 for j in range(9): h = 0 for i in range(9): nombre = "image"+ str(cont) + ".png" image1 = Functions.cropBox(image, w, h, 75, 80) # Save the image Functions.saveImage(image1, nombre) h = h + 80 cont = cont + 1 # Position of the pixel where start the image w = 80*(j + 1) Code: create a library with functions for only preprocessing and image transformation called “Functions”. python #/Functions.py / import cv2import numpy as np # Function to rotate the imagedef rotateImage(image, angle): image_center = tuple(np.array(image.shape[1::-1]) / 2) rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0) result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags = cv2.INTER_LINEAR) return result # Function to crop top border in the imagedef cropImage(image, x): # x determine how far to cut the image # fileb determines with what name we are going to save the image # Determine image dimensions height, width, channels = image.shape crop_img = image[x:height, 0:width] return crop_img # Function to crop every box (there are 81 boxes in total)def cropBox(image, x, y, h, w): # Each side of the square / box has a side of length 10 crop_img = image[x:(x + h), y:(y + w)] return crop_img # Function to save the imagedef saveImage(image, fileb): new_path = "./Images/" cv2.imwrite(new_path + fileb, image) cv2.waitKey(0) cv2.destroyAllWindows() # Function to crop all borders of each boxdef cropBorder(image): # Determine image dimensions height, width, channels = image.shape crop_img = image[12:height-12, 12:width-12] return crop_img Step 2: Image Transformation Cut out the borders of each box, in case there is any black border that can be inferred in our analysis.Each image has 56×51 pixels.Code: python #/Transformation.py / import cv2import numpy as npimport Functions # Relative pathpath ="./Images/" if __name__ == '__main__': for x in range(81): # Image to analyze nameImage = "image" + str(x) + ".png" image = cv2.imread(path + nameImage) image = Functions.cropBorder(image) Functions.saveImage(image, nameImage) Step 3: KNN ClassificationAnalyze what number is in the box. In this case, Canny algorithm is used to determine if there is a number or it is an empty box. Then through the KNN algorithm it is determined which number is in the box. For the extraction of characteristics, the moments of Hu: 1 and 2, Gaussian filter for filtering and unsupervised thresholding were used.Code: python #/Preprocessing.py / import cv2import numpy as npimport Functions # Relative pathpath ="./Screenshots/" # Image to analyzenumber = input("Enter image number: ")globalPath = path+"photo"+str(number)+".png"image = cv2.imread(globalPath) # Save the name of the image to analyze after in Main.pyfile = open("image.txt", "w")file.write(globalPath)file.close() # MAINif __name__ == '__main__': # PREPROCESSING -> Crop the edges, ads and all # the images outside the sudoku board image = Functions.cropImage(image, 218) image = Functions.rotateImage(image, 180) image = Functions.cropImage(image, 348) image = Functions.rotateImage(image, 180) # Crop each box in the sudoku board cont = 0 w = 0 for j in range(9): h = 0 for i in range(9): nombre = "image"+ str(cont) + ".png" image1 = Functions.cropBox(image, w, h, 75, 80) # Save the image Functions.saveImage(image1, nombre) h = h + 80 cont = cont + 1 # Position of the pixel where start the image w = 80*(j + 1) Show performance KNN algorithm Result of the recognition of all the digits of the sudoku grid of the image photo0.jpg Step4: Now solve the sudoku! A restriction satisfaction algorithm with backtracking is presented to solve the sudoku. Code: python #/Solver.py / import numpy as np # Dictionary with grid numbersdef solverGrid(grid): values = valuesGrid(grid) return searchValues(values) # Exchange of itemsdef exchangeValues(A, B): return [a + b for a in A for b in B] # Define initial valuesdef initialValues(grid): return dict(zip(sections, grid)) # Define values in the griddef valuesGrid(grid): numbers = [] for c in grid: if c == '.': numbers.append('123456789') elif c in '123456789': numbers.append(c) return dict(zip(sections, numbers)) # Delete the values that are already inside the griddef eliminateValues(numbers): solved_values = [box for box in numbers.keys() if len(numbers[box]) == 1] for box in solved_values: digit = numbers[box] for vecino in neighbors[box]: numbers[vecino] = numbers[vecino].replace(digit, '') return numbers def onlyOption(numbers): for unit in unitlist: for digit in '123456789': dplaces = [box for box in unit if digit in numbers[box]] if len(dplaces) == 1: numbers[dplaces[0]] = digit return numbers def reduceSudoku(numbers): stalled = False while not stalled: # Check how many boxes have a determined value solved_values_before = len([box for box in numbers.keys() if len(numbers[box]) == 1]) # Set the Eliminate Strategy numbers = eliminateValues(numbers) # Use the Only Choice Strategy numbers = onlyOption(numbers) # Check how many boxes have a determined value, to compare solved_values_after = len([box for box in numbers.keys() if len(numbers[box]) == 1]) # If no new values were added, stop the loop. stalled = solved_values_before == solved_values_after # Sanity check, return False if there is a box with zero available values: if len([box for box in numbers.keys() if len(numbers[box]) == 0]): return False return numbers def searchValues(numbers): numbers = reduceSudoku(numbers) if numbers is False: return False ## Failure if all(len(numbers[s]) == 1 for s in sections): return numbers ## Ok # Choose one of the unfilled boxes unfilled_squares = [(len(numbers[s]), s) for s in sections if len(numbers[s]) > 1] n, s = min(unfilled_squares) # Solve the next boxes for value in numbers[s]: nova_sudoku = numbers.copy() nova_sudoku[s] = value attempt = searchValues(nova_sudoku) if attempt: return attempt # Define valuesrows = 'ABCDEFGHI'columns = '123456789' sections = exchangeValues(rows, columns)rowsUnit = [exchangeValues(r, columns) for r in rows]columnUnits = [exchangeValues(rows, c) for c in columns]boxUnits = [exchangeValues(rs, cs) for rs in ('ABC', 'DEF', 'GHI') for cs in ('123', '456', '789')] unitlist = rowsUnit + columnUnits + boxUnits units = dict((s, [u for u in unitlist if s in u]) for s in sections)neighbors = dict((s, set(sum(units[s], []))-set([s])) for s in sections) # MAINif __name__ == '__main__': # With file manager to read the file vector.txt # that has all the values of the screenshot file = open("vector.txt", "r") lines = file.read() file.close() # Access the dictionary a = solverGrid(lines) b = sorted(a.items()) # Save the dictionary solution np.save('Solution', b) Step 5: Interface Improves the way the solution is displayed compared to the original screenshot.Code: python #/Interface.py /import numpy as npimport matplotlib.pyplot as pltimport cv2 # Read dictionary from Solution.npyreadDictionary = np.load('Solution.npy')values = (readDictionary[:, 1]) # Read vector.txtfile = open("vector.txt", "r")lines = file.read()file.close() # Read the path of the image the we want to analyzefileTxt = open("image.txt", "r")pathGlobal = fileTxt.read()fileTxt.close() # Obtain the coordinates to be able to# locate them in the imagerow = ["A", "B", "C", "D", "E", "F", "G", "H", "I"]column = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] # Assign the coordinates of each number within the image planedef coordinate(): positionx = list() positiony = list() for k in range(9): for i in range(9): if (row[k] == "A"): y = 270 elif (row[k] == "B"): y = 350 elif (row[k] == "C"): y = 430 elif (row[k] == "D"): y = 510 elif (row[k] == "E"): y = 590 elif (row[k] == "F"): y = 670 elif (row[k] == "G"): y = 750 elif (row[k] == "H"): y = 830 elif (row[k] == "I"): y = 915 if (column[i] == "1"): x = 19 elif (column[i] == "2"): x = 98 elif (column[i] == "3"): x = 182 elif (column[i] == "4"): x = 261 elif (column[i] == "5"): x = 335 elif (column[i] == "6"): x = 419 elif (column[i] == "7"): x = 499 elif (column[i] == "8"): x = 580 elif (column[i] == "9"): x = 660 positionx.append(x) positiony.append(y) return (positionx, positiony) # Function to write value in each box in the imagedef writeValue(image, valor, x, y): font = cv2.FONT_HERSHEY_SIMPLEX text = str(valor) # Write text in the image cv2.putText(image, text, (x, y), font, 2, (255, 0, 0), 5) # cv2.putText(image, text, (coordinates), size font, (color RGB), thickness) return image # Load imageimage = cv2.imread(pathGlobal)image2 = image.copy() # Load coordinatespositionx, positiony = coordinate() for i in range(81): if (lines[i] == "."): image = writeValue(image, values[i], positionx[i], positiony[i]) # Concatenate images horizontallyimage = np.concatenate((image2, image), axis = 1) # Show image concatenation plt.imshow(image)plt.axis("off")plt.show() # Save imagecv2.imwrite("./Interface / example.png", image) Output: Results for photo1.png Results for photo2.png All the images for the training of the KNN algorithm and the screenshots of example can be found in given repository nnr223442 Image-Processing Machine Learning Pattern Searching Project Python Pattern Searching Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm Intuition of Adam Optimizer CNN | Introduction to Pooling Layer Convolutional Neural Network (CNN) in Machine Learning KMP Algorithm for Pattern Searching Rabin-Karp Algorithm for Pattern Searching Naive algorithm for Pattern Searching Check if a string is substring of another Boyer Moore Algorithm for Pattern Searching
[ { "code": null, "e": 25667, "s": 25639, "text": "\n18 Jan, 2022" }, { "code": null, "e": 26118, "s": 25667, "text": "This article explains a program in python 2.7 to solve a Sudoku 9×9 of the Android application “Sudoku” of genina.com. To solve a sudoku of the Android application “Sudoku” of genina.com, a screenshot of the game is taken (a 720×1280 image is obtained), then the number found in each of the 81 squares is obtained using KNN algorithm, once each element is determined, the sudoku is solved using a constraint satisfaction algorithm with backtracking. " }, { "code": null, "e": 26215, "s": 26118, "text": "On the left is our input: Screenshot that we are going to analyze. On the right is the solution." }, { "code": null, "e": 26447, "s": 26215, "text": "How this work? Step 1: Image Preprocessing First step, Image Preprocessing: Extract each sudoku square individually and save them sequentially as photo # .png (where # goes from 0 to 80). Images of 80×75 pixels are obtained.Code: " }, { "code": null, "e": 26514, "s": 26447, "text": "Input: photo0.png. This is the photo that we are going to analyze." }, { "code": null, "e": 26521, "s": 26514, "text": "Code: " }, { "code": null, "e": 26528, "s": 26521, "text": "python" }, { "code": "#/Preprocessing.py / import cv2import numpy as npimport Functions # Relative pathpath =\"./Screenshots/\" # Image to analyzenumber = input(\"Enter image number: \")globalPath = path+\"photo\"+str(number)+\".png\"image = cv2.imread(globalPath) # Save the name of the image to analyze after in Main.pyfile = open(\"image.txt\", \"w\")file.write(globalPath)file.close() # MAINif __name__ == '__main__': # PREPROCESSING -> Crop the edges, ads and all # the images outside the sudoku board image = Functions.cropImage(image, 218) image = Functions.rotateImage(image, 180) image = Functions.cropImage(image, 348) image = Functions.rotateImage(image, 180) # Crop each box in the sudoku board cont = 0 w = 0 for j in range(9): h = 0 for i in range(9): nombre = \"image\"+ str(cont) + \".png\" image1 = Functions.cropBox(image, w, h, 75, 80) # Save the image Functions.saveImage(image1, nombre) h = h + 80 cont = cont + 1 # Position of the pixel where start the image w = 80*(j + 1)", "e": 27627, "s": 26528, "text": null }, { "code": null, "e": 27735, "s": 27627, "text": "Code: create a library with functions for only preprocessing and image transformation called “Functions”. " }, { "code": null, "e": 27742, "s": 27735, "text": "python" }, { "code": "#/Functions.py / import cv2import numpy as np # Function to rotate the imagedef rotateImage(image, angle): image_center = tuple(np.array(image.shape[1::-1]) / 2) rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0) result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags = cv2.INTER_LINEAR) return result # Function to crop top border in the imagedef cropImage(image, x): # x determine how far to cut the image # fileb determines with what name we are going to save the image # Determine image dimensions height, width, channels = image.shape crop_img = image[x:height, 0:width] return crop_img # Function to crop every box (there are 81 boxes in total)def cropBox(image, x, y, h, w): # Each side of the square / box has a side of length 10 crop_img = image[x:(x + h), y:(y + w)] return crop_img # Function to save the imagedef saveImage(image, fileb): new_path = \"./Images/\" cv2.imwrite(new_path + fileb, image) cv2.waitKey(0) cv2.destroyAllWindows() # Function to crop all borders of each boxdef cropBorder(image): # Determine image dimensions height, width, channels = image.shape crop_img = image[12:height-12, 12:width-12] return crop_img", "e": 28973, "s": 27742, "text": null }, { "code": null, "e": 29141, "s": 28973, "text": "Step 2: Image Transformation Cut out the borders of each box, in case there is any black border that can be inferred in our analysis.Each image has 56×51 pixels.Code: " }, { "code": null, "e": 29148, "s": 29141, "text": "python" }, { "code": "#/Transformation.py / import cv2import numpy as npimport Functions # Relative pathpath =\"./Images/\" if __name__ == '__main__': for x in range(81): # Image to analyze nameImage = \"image\" + str(x) + \".png\" image = cv2.imread(path + nameImage) image = Functions.cropBorder(image) Functions.saveImage(image, nameImage)", "e": 29507, "s": 29148, "text": null }, { "code": null, "e": 29883, "s": 29507, "text": "Step 3: KNN ClassificationAnalyze what number is in the box. In this case, Canny algorithm is used to determine if there is a number or it is an empty box. Then through the KNN algorithm it is determined which number is in the box. For the extraction of characteristics, the moments of Hu: 1 and 2, Gaussian filter for filtering and unsupervised thresholding were used.Code: " }, { "code": null, "e": 29890, "s": 29883, "text": "python" }, { "code": "#/Preprocessing.py / import cv2import numpy as npimport Functions # Relative pathpath =\"./Screenshots/\" # Image to analyzenumber = input(\"Enter image number: \")globalPath = path+\"photo\"+str(number)+\".png\"image = cv2.imread(globalPath) # Save the name of the image to analyze after in Main.pyfile = open(\"image.txt\", \"w\")file.write(globalPath)file.close() # MAINif __name__ == '__main__': # PREPROCESSING -> Crop the edges, ads and all # the images outside the sudoku board image = Functions.cropImage(image, 218) image = Functions.rotateImage(image, 180) image = Functions.cropImage(image, 348) image = Functions.rotateImage(image, 180) # Crop each box in the sudoku board cont = 0 w = 0 for j in range(9): h = 0 for i in range(9): nombre = \"image\"+ str(cont) + \".png\" image1 = Functions.cropBox(image, w, h, 75, 80) # Save the image Functions.saveImage(image1, nombre) h = h + 80 cont = cont + 1 # Position of the pixel where start the image w = 80*(j + 1)", "e": 30989, "s": 29890, "text": null }, { "code": null, "e": 31020, "s": 30989, "text": "Show performance KNN algorithm" }, { "code": null, "e": 31107, "s": 31020, "text": "Result of the recognition of all the digits of the sudoku grid of the image photo0.jpg" }, { "code": null, "e": 31232, "s": 31107, "text": "Step4: Now solve the sudoku! A restriction satisfaction algorithm with backtracking is presented to solve the sudoku. Code: " }, { "code": null, "e": 31239, "s": 31232, "text": "python" }, { "code": "#/Solver.py / import numpy as np # Dictionary with grid numbersdef solverGrid(grid): values = valuesGrid(grid) return searchValues(values) # Exchange of itemsdef exchangeValues(A, B): return [a + b for a in A for b in B] # Define initial valuesdef initialValues(grid): return dict(zip(sections, grid)) # Define values in the griddef valuesGrid(grid): numbers = [] for c in grid: if c == '.': numbers.append('123456789') elif c in '123456789': numbers.append(c) return dict(zip(sections, numbers)) # Delete the values that are already inside the griddef eliminateValues(numbers): solved_values = [box for box in numbers.keys() if len(numbers[box]) == 1] for box in solved_values: digit = numbers[box] for vecino in neighbors[box]: numbers[vecino] = numbers[vecino].replace(digit, '') return numbers def onlyOption(numbers): for unit in unitlist: for digit in '123456789': dplaces = [box for box in unit if digit in numbers[box]] if len(dplaces) == 1: numbers[dplaces[0]] = digit return numbers def reduceSudoku(numbers): stalled = False while not stalled: # Check how many boxes have a determined value solved_values_before = len([box for box in numbers.keys() if len(numbers[box]) == 1]) # Set the Eliminate Strategy numbers = eliminateValues(numbers) # Use the Only Choice Strategy numbers = onlyOption(numbers) # Check how many boxes have a determined value, to compare solved_values_after = len([box for box in numbers.keys() if len(numbers[box]) == 1]) # If no new values were added, stop the loop. stalled = solved_values_before == solved_values_after # Sanity check, return False if there is a box with zero available values: if len([box for box in numbers.keys() if len(numbers[box]) == 0]): return False return numbers def searchValues(numbers): numbers = reduceSudoku(numbers) if numbers is False: return False ## Failure if all(len(numbers[s]) == 1 for s in sections): return numbers ## Ok # Choose one of the unfilled boxes unfilled_squares = [(len(numbers[s]), s) for s in sections if len(numbers[s]) > 1] n, s = min(unfilled_squares) # Solve the next boxes for value in numbers[s]: nova_sudoku = numbers.copy() nova_sudoku[s] = value attempt = searchValues(nova_sudoku) if attempt: return attempt # Define valuesrows = 'ABCDEFGHI'columns = '123456789' sections = exchangeValues(rows, columns)rowsUnit = [exchangeValues(r, columns) for r in rows]columnUnits = [exchangeValues(rows, c) for c in columns]boxUnits = [exchangeValues(rs, cs) for rs in ('ABC', 'DEF', 'GHI') for cs in ('123', '456', '789')] unitlist = rowsUnit + columnUnits + boxUnits units = dict((s, [u for u in unitlist if s in u]) for s in sections)neighbors = dict((s, set(sum(units[s], []))-set([s])) for s in sections) # MAINif __name__ == '__main__': # With file manager to read the file vector.txt # that has all the values of the screenshot file = open(\"vector.txt\", \"r\") lines = file.read() file.close() # Access the dictionary a = solverGrid(lines) b = sorted(a.items()) # Save the dictionary solution np.save('Solution', b)", "e": 34652, "s": 31239, "text": null }, { "code": null, "e": 34756, "s": 34652, "text": "Step 5: Interface Improves the way the solution is displayed compared to the original screenshot.Code: " }, { "code": null, "e": 34763, "s": 34756, "text": "python" }, { "code": "#/Interface.py /import numpy as npimport matplotlib.pyplot as pltimport cv2 # Read dictionary from Solution.npyreadDictionary = np.load('Solution.npy')values = (readDictionary[:, 1]) # Read vector.txtfile = open(\"vector.txt\", \"r\")lines = file.read()file.close() # Read the path of the image the we want to analyzefileTxt = open(\"image.txt\", \"r\")pathGlobal = fileTxt.read()fileTxt.close() # Obtain the coordinates to be able to# locate them in the imagerow = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\"]column = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"] # Assign the coordinates of each number within the image planedef coordinate(): positionx = list() positiony = list() for k in range(9): for i in range(9): if (row[k] == \"A\"): y = 270 elif (row[k] == \"B\"): y = 350 elif (row[k] == \"C\"): y = 430 elif (row[k] == \"D\"): y = 510 elif (row[k] == \"E\"): y = 590 elif (row[k] == \"F\"): y = 670 elif (row[k] == \"G\"): y = 750 elif (row[k] == \"H\"): y = 830 elif (row[k] == \"I\"): y = 915 if (column[i] == \"1\"): x = 19 elif (column[i] == \"2\"): x = 98 elif (column[i] == \"3\"): x = 182 elif (column[i] == \"4\"): x = 261 elif (column[i] == \"5\"): x = 335 elif (column[i] == \"6\"): x = 419 elif (column[i] == \"7\"): x = 499 elif (column[i] == \"8\"): x = 580 elif (column[i] == \"9\"): x = 660 positionx.append(x) positiony.append(y) return (positionx, positiony) # Function to write value in each box in the imagedef writeValue(image, valor, x, y): font = cv2.FONT_HERSHEY_SIMPLEX text = str(valor) # Write text in the image cv2.putText(image, text, (x, y), font, 2, (255, 0, 0), 5) # cv2.putText(image, text, (coordinates), size font, (color RGB), thickness) return image # Load imageimage = cv2.imread(pathGlobal)image2 = image.copy() # Load coordinatespositionx, positiony = coordinate() for i in range(81): if (lines[i] == \".\"): image = writeValue(image, values[i], positionx[i], positiony[i]) # Concatenate images horizontallyimage = np.concatenate((image2, image), axis = 1) # Show image concatenation plt.imshow(image)plt.axis(\"off\")plt.show() # Save imagecv2.imwrite(\"./Interface / example.png\", image)", "e": 37183, "s": 34763, "text": null }, { "code": null, "e": 37192, "s": 37183, "text": "Output: " }, { "code": null, "e": 37215, "s": 37192, "text": "Results for photo1.png" }, { "code": null, "e": 37240, "s": 37217, "text": "Results for photo2.png" }, { "code": null, "e": 37358, "s": 37240, "text": "All the images for the training of the KNN algorithm and the screenshots of example can be found in given repository " }, { "code": null, "e": 37368, "s": 37358, "text": "nnr223442" }, { "code": null, "e": 37385, "s": 37368, "text": "Image-Processing" }, { "code": null, "e": 37402, "s": 37385, "text": "Machine Learning" }, { "code": null, "e": 37420, "s": 37402, "text": "Pattern Searching" }, { "code": null, "e": 37428, "s": 37420, "text": "Project" }, { "code": null, "e": 37435, "s": 37428, "text": "Python" }, { "code": null, "e": 37453, "s": 37435, "text": "Pattern Searching" }, { "code": null, "e": 37470, "s": 37453, "text": "Machine Learning" }, { "code": null, "e": 37568, "s": 37470, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37609, "s": 37568, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 37642, "s": 37609, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 37670, "s": 37642, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 37706, "s": 37670, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 37761, "s": 37706, "text": "Convolutional Neural Network (CNN) in Machine Learning" }, { "code": null, "e": 37797, "s": 37761, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 37840, "s": 37797, "text": "Rabin-Karp Algorithm for Pattern Searching" }, { "code": null, "e": 37878, "s": 37840, "text": "Naive algorithm for Pattern Searching" }, { "code": null, "e": 37920, "s": 37878, "text": "Check if a string is substring of another" } ]
Pair with largest sum which is less than K in the array - GeeksforGeeks
04 May, 2022 Given an array arr of size N and an integer K. The task is to find the pair of integers such that their sum is maximum and but less than K Examples: Input : arr = {30, 20, 50} , K = 70 Output : 30, 20 30 + 20 = 50, which is the maximum possible sum which is less than K Input : arr = {5, 20, 110, 100, 10}, K = 85 Output : 20, 10 Approach : An efficient approach is to sort the given array and find the element which is greater than or equal to K. If found at index p, we have to find pairs only between arr[0, ..., p-1]. Run nested loops. One to take care of the first element in the pair and the other to take care of the second element in the pair. Maintain a variable maxsum and two other variables a and b to keep track of the possible solution. Initialize maxsum to 0. Find A[i] + A[j] (assuming i runs in the outer loop and j in the inner loop). If it is greater than maxsum then update maxsum with this sum and change a and b to the i’th and j’th elements of this array.Below is the implementation of the above approach : C++ Java Python3 C# Javascript // CPP program to find pair with largest// sum which is less than K in the array#include <bits/stdc++.h>using namespace std; // Function to find pair with largest// sum which is less than K in the arrayvoid Max_Sum(int arr[], int n, int k){ // To store the break point int p = n; // Sort the given array sort(arr, arr + n); // Find the break point for (int i = 0; i < n; i++) { // No need to look beyond i'th index if (arr[i] >= k) { p = i; break; } } int maxsum = 0, a, b; // Find the required pair for (int i = 0; i < p; i++) { for (int j = i + 1; j < p; j++) { if (arr[i] + arr[j] < k and arr[i] + arr[j] > maxsum) { maxsum = arr[i] + arr[j]; a = arr[i]; b = arr[j]; } } } // Print the required answer cout << a << " " << b;} // Driver codeint main(){ int arr[] = {5, 20, 110, 100, 10}, k = 85; int n = sizeof(arr) / sizeof(arr[0]); // Function call Max_Sum(arr, n, k); return 0;} // Java program to find pair with largest// sum which is less than K in the arrayimport java.util.Arrays; class GFG{ // Function to find pair with largest// sum which is less than K in the arraystatic void Max_Sum(int arr[], int n, int k){ // To store the break point int p = n; // Sort the given array Arrays.sort(arr); // Find the break point for (int i = 0; i < n; i++) { // No need to look beyond i'th index if (arr[i] >= k) { p = i; break; } } int maxsum = 0, a = 0, b = 0; // Find the required pair for (int i = 0; i < p; i++) { for (int j = i + 1; j < p; j++) { if (arr[i] + arr[j] < k && arr[i] + arr[j] > maxsum) { maxsum = arr[i] + arr[j]; a = arr[i]; b = arr[j]; } } } // Print the required answer System.out.print( a + " " + b);} // Driver codepublic static void main (String[] args){ int []arr = {5, 20, 110, 100, 10}; int k = 85; int n = arr.length; // Function call Max_Sum(arr, n, k);}} // This code is contributed by anuj_67.. # Python3 program to find pair with largest# sum which is less than K in the array # Function to find pair with largest# sum which is less than K in the arraydef Max_Sum(arr, n, k): # To store the break point p = n # Sort the given array arr.sort() # Find the break point for i in range(0, n): # No need to look beyond i'th index if (arr[i] >= k): p = i break maxsum = 0 a = 0 b = 0 # Find the required pair for i in range(0, p): for j in range(i + 1, p): if(arr[i] + arr[j] < k and arr[i] + arr[j] > maxsum): maxsum = arr[i] + arr[j] a = arr[i] b = arr[j] # Print the required answer print(a, b) # Driver codearr = [5, 20, 110, 100, 10]k = 85 n = len(arr) # Function callMax_Sum(arr, n, k) # This code is contributed by Sanjit_Prasad // C# program to find pair with largest// sum which is less than K in the arrayusing System; class GFG{ // Function to find pair with largest// sum which is less than K in the arraystatic void Max_Sum(int []arr, int n, int k){ // To store the break point int p = n; // Sort the given array Array.Sort(arr); // Find the break point for (int i = 0; i < n; i++) { // No need to look beyond i'th index if (arr[i] >= k) { p = i; break; } } int maxsum = 0, a = 0, b = 0; // Find the required pair for (int i = 0; i < p; i++) { for (int j = i + 1; j < p; j++) { if (arr[i] + arr[j] < k && arr[i] + arr[j] > maxsum) { maxsum = arr[i] + arr[j]; a = arr[i]; b = arr[j]; } } } // Print the required answer Console.WriteLine( a + " " + b);} // Driver codepublic static void Main (){ int []arr = {5, 20, 110, 100, 10}; int k = 85; int n = arr.Length; // Function call Max_Sum(arr, n, k);}} // This code is contributed by anuj_67.. <script> // Javascript program to find pair with largest // sum which is less than K in the array // Function to find pair with largest // sum which is less than K in the array function Max_Sum(arr, n, k) { // To store the break point let p = n; // Sort the given array arr.sort(function(a, b){return a - b}); // Find the break point for (let i = 0; i < n; i++) { // No need to look beyond i'th index if (arr[i] >= k) { p = i; break; } } let maxsum = 0, a = 0, b = 0; // Find the required pair for (let i = 0; i < p; i++) { for (let j = i + 1; j < p; j++) { if (arr[i] + arr[j] < k && arr[i] + arr[j] > maxsum) { maxsum = arr[i] + arr[j]; a = arr[i]; b = arr[j]; } } } // Print the required answer document.write( a + " " + b + "</br>"); } let arr = [5, 20, 110, 100, 10]; let k = 85; let n = arr.length; // Function call Max_Sum(arr, n, k); </script> 10 20 Time complexity: O(N^2) Efficient Approach: Two Pointer MethodAfter sorting, we can place two pointers at the left and right extremes of the array. The desired pair can be found by the following steps: Find the current sum of the values at both the pointers.If the sum is lesser than k:update the answer with the maximum of the previous answer and the current sum.increase the left pointer.Else Decrease the right pointer. Find the current sum of the values at both the pointers. If the sum is lesser than k:update the answer with the maximum of the previous answer and the current sum.increase the left pointer. update the answer with the maximum of the previous answer and the current sum.increase the left pointer. update the answer with the maximum of the previous answer and the current sum. increase the left pointer. Else Decrease the right pointer. C++ Python3 C# Javascript // CPP program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find max sum less than kint maxSum(vector<int> arr, int k){ // Sort the array sort(arr.begin(), arr.end()); int n = arr.size(), l = 0, r = n - 1, ans = 0; // While l is less than r while (l < r) { if (arr[l] + arr[r] < k) { ans = max(ans, arr[l] + arr[r]); l++; } else { r--; } } return ans;} // Driver Codeint main(){ vector<int> A = { 20, 10, 30, 100, 110 }; int k = 85; // Function Call cout << maxSum(A, k) << endl;} # Python program for above approach # Function to find max sum less than kdef maxSum(arr, k): # Sort the array arr.sort() n,l = len(arr),0 r,ans = n - 1,0 # While l is less than r while (l < r): if (arr[l] + arr[r] < k): ans = max(ans, arr[l] + arr[r]) l += 1 else: r -= 1 return ans # Driver CodeA = [20, 10, 30, 100, 110]k = 85 # Function Callprint(maxSum(A, k)) # This code is contributed by shinjanpatra // C# implementation of the approachusing System; class GFG{ // Function to find max sum less than kstatic int maxSum(int[] arr, int k){ // Sort the array Array.Sort(arr); int n = arr.Length, l = 0, r = n - 1, ans = 0; // While l is less than r while (l < r) { if (arr[l] + arr[r] < k) { ans = Math.Max(ans, arr[l] + arr[r]); l++; } else { r--; } } return ans;} // Driver codepublic static void Main (){ int[] A = { 20, 10, 30, 100, 110 }; int k = 85; // Function Call Console.WriteLine(maxSum(A, k));}} // This code is contributed by target_2. <script> // Javascript program for the above approach // Function to find max sum less than kfunction maxSum(arr, k){ // Sort the array arr.sort((a,b)=>a-b); var n = arr.length, l = 0, r = n - 1, ans = 0; // While l is less than r while (l < r) { if (arr[l] + arr[r] < k) { ans = Math.max(ans, arr[l] + arr[r]); l++; } else { r--; } } return ans;} // Driver Codevar A = [20, 10, 30, 100, 110];var k = 85;// Function Calldocument.write( maxSum(A, k)); </script> 50 Time complexity: O(NlogN) Space complexity: O(1) vt_m Sanjit_Prasad arorakashish0911 muskaanjain3 divyesh072019 rutvik_56 target_2 shinjanpatra Arrays Searching Sorting Arrays Searching Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Binary Search Median of two sorted arrays of different sizes Find the index of an array element in Java Two Pointers Technique Count number of occurrences (or frequency) in a sorted array
[ { "code": null, "e": 26065, "s": 26037, "text": "\n04 May, 2022" }, { "code": null, "e": 26204, "s": 26065, "text": "Given an array arr of size N and an integer K. The task is to find the pair of integers such that their sum is maximum and but less than K" }, { "code": null, "e": 26215, "s": 26204, "text": "Examples: " }, { "code": null, "e": 26337, "s": 26215, "text": "Input : arr = {30, 20, 50} , K = 70 Output : 30, 20 30 + 20 = 50, which is the maximum possible sum which is less than K " }, { "code": null, "e": 26398, "s": 26337, "text": "Input : arr = {5, 20, 110, 100, 10}, K = 85 Output : 20, 10 " }, { "code": null, "e": 27099, "s": 26398, "text": "Approach : An efficient approach is to sort the given array and find the element which is greater than or equal to K. If found at index p, we have to find pairs only between arr[0, ..., p-1]. Run nested loops. One to take care of the first element in the pair and the other to take care of the second element in the pair. Maintain a variable maxsum and two other variables a and b to keep track of the possible solution. Initialize maxsum to 0. Find A[i] + A[j] (assuming i runs in the outer loop and j in the inner loop). If it is greater than maxsum then update maxsum with this sum and change a and b to the i’th and j’th elements of this array.Below is the implementation of the above approach : " }, { "code": null, "e": 27103, "s": 27099, "text": "C++" }, { "code": null, "e": 27108, "s": 27103, "text": "Java" }, { "code": null, "e": 27116, "s": 27108, "text": "Python3" }, { "code": null, "e": 27119, "s": 27116, "text": "C#" }, { "code": null, "e": 27130, "s": 27119, "text": "Javascript" }, { "code": "// CPP program to find pair with largest// sum which is less than K in the array#include <bits/stdc++.h>using namespace std; // Function to find pair with largest// sum which is less than K in the arrayvoid Max_Sum(int arr[], int n, int k){ // To store the break point int p = n; // Sort the given array sort(arr, arr + n); // Find the break point for (int i = 0; i < n; i++) { // No need to look beyond i'th index if (arr[i] >= k) { p = i; break; } } int maxsum = 0, a, b; // Find the required pair for (int i = 0; i < p; i++) { for (int j = i + 1; j < p; j++) { if (arr[i] + arr[j] < k and arr[i] + arr[j] > maxsum) { maxsum = arr[i] + arr[j]; a = arr[i]; b = arr[j]; } } } // Print the required answer cout << a << \" \" << b;} // Driver codeint main(){ int arr[] = {5, 20, 110, 100, 10}, k = 85; int n = sizeof(arr) / sizeof(arr[0]); // Function call Max_Sum(arr, n, k); return 0;}", "e": 28332, "s": 27130, "text": null }, { "code": "// Java program to find pair with largest// sum which is less than K in the arrayimport java.util.Arrays; class GFG{ // Function to find pair with largest// sum which is less than K in the arraystatic void Max_Sum(int arr[], int n, int k){ // To store the break point int p = n; // Sort the given array Arrays.sort(arr); // Find the break point for (int i = 0; i < n; i++) { // No need to look beyond i'th index if (arr[i] >= k) { p = i; break; } } int maxsum = 0, a = 0, b = 0; // Find the required pair for (int i = 0; i < p; i++) { for (int j = i + 1; j < p; j++) { if (arr[i] + arr[j] < k && arr[i] + arr[j] > maxsum) { maxsum = arr[i] + arr[j]; a = arr[i]; b = arr[j]; } } } // Print the required answer System.out.print( a + \" \" + b);} // Driver codepublic static void main (String[] args){ int []arr = {5, 20, 110, 100, 10}; int k = 85; int n = arr.length; // Function call Max_Sum(arr, n, k);}} // This code is contributed by anuj_67..", "e": 29548, "s": 28332, "text": null }, { "code": "# Python3 program to find pair with largest# sum which is less than K in the array # Function to find pair with largest# sum which is less than K in the arraydef Max_Sum(arr, n, k): # To store the break point p = n # Sort the given array arr.sort() # Find the break point for i in range(0, n): # No need to look beyond i'th index if (arr[i] >= k): p = i break maxsum = 0 a = 0 b = 0 # Find the required pair for i in range(0, p): for j in range(i + 1, p): if(arr[i] + arr[j] < k and arr[i] + arr[j] > maxsum): maxsum = arr[i] + arr[j] a = arr[i] b = arr[j] # Print the required answer print(a, b) # Driver codearr = [5, 20, 110, 100, 10]k = 85 n = len(arr) # Function callMax_Sum(arr, n, k) # This code is contributed by Sanjit_Prasad", "e": 30486, "s": 29548, "text": null }, { "code": "// C# program to find pair with largest// sum which is less than K in the arrayusing System; class GFG{ // Function to find pair with largest// sum which is less than K in the arraystatic void Max_Sum(int []arr, int n, int k){ // To store the break point int p = n; // Sort the given array Array.Sort(arr); // Find the break point for (int i = 0; i < n; i++) { // No need to look beyond i'th index if (arr[i] >= k) { p = i; break; } } int maxsum = 0, a = 0, b = 0; // Find the required pair for (int i = 0; i < p; i++) { for (int j = i + 1; j < p; j++) { if (arr[i] + arr[j] < k && arr[i] + arr[j] > maxsum) { maxsum = arr[i] + arr[j]; a = arr[i]; b = arr[j]; } } } // Print the required answer Console.WriteLine( a + \" \" + b);} // Driver codepublic static void Main (){ int []arr = {5, 20, 110, 100, 10}; int k = 85; int n = arr.Length; // Function call Max_Sum(arr, n, k);}} // This code is contributed by anuj_67..", "e": 31676, "s": 30486, "text": null }, { "code": "<script> // Javascript program to find pair with largest // sum which is less than K in the array // Function to find pair with largest // sum which is less than K in the array function Max_Sum(arr, n, k) { // To store the break point let p = n; // Sort the given array arr.sort(function(a, b){return a - b}); // Find the break point for (let i = 0; i < n; i++) { // No need to look beyond i'th index if (arr[i] >= k) { p = i; break; } } let maxsum = 0, a = 0, b = 0; // Find the required pair for (let i = 0; i < p; i++) { for (let j = i + 1; j < p; j++) { if (arr[i] + arr[j] < k && arr[i] + arr[j] > maxsum) { maxsum = arr[i] + arr[j]; a = arr[i]; b = arr[j]; } } } // Print the required answer document.write( a + \" \" + b + \"</br>\"); } let arr = [5, 20, 110, 100, 10]; let k = 85; let n = arr.length; // Function call Max_Sum(arr, n, k); </script>", "e": 32921, "s": 31676, "text": null }, { "code": null, "e": 32927, "s": 32921, "text": "10 20" }, { "code": null, "e": 32951, "s": 32927, "text": "Time complexity: O(N^2)" }, { "code": null, "e": 33129, "s": 32951, "text": "Efficient Approach: Two Pointer MethodAfter sorting, we can place two pointers at the left and right extremes of the array. The desired pair can be found by the following steps:" }, { "code": null, "e": 33350, "s": 33129, "text": "Find the current sum of the values at both the pointers.If the sum is lesser than k:update the answer with the maximum of the previous answer and the current sum.increase the left pointer.Else Decrease the right pointer." }, { "code": null, "e": 33407, "s": 33350, "text": "Find the current sum of the values at both the pointers." }, { "code": null, "e": 33540, "s": 33407, "text": "If the sum is lesser than k:update the answer with the maximum of the previous answer and the current sum.increase the left pointer." }, { "code": null, "e": 33645, "s": 33540, "text": "update the answer with the maximum of the previous answer and the current sum.increase the left pointer." }, { "code": null, "e": 33724, "s": 33645, "text": "update the answer with the maximum of the previous answer and the current sum." }, { "code": null, "e": 33751, "s": 33724, "text": "increase the left pointer." }, { "code": null, "e": 33784, "s": 33751, "text": "Else Decrease the right pointer." }, { "code": null, "e": 33788, "s": 33784, "text": "C++" }, { "code": null, "e": 33796, "s": 33788, "text": "Python3" }, { "code": null, "e": 33799, "s": 33796, "text": "C#" }, { "code": null, "e": 33810, "s": 33799, "text": "Javascript" }, { "code": "// CPP program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find max sum less than kint maxSum(vector<int> arr, int k){ // Sort the array sort(arr.begin(), arr.end()); int n = arr.size(), l = 0, r = n - 1, ans = 0; // While l is less than r while (l < r) { if (arr[l] + arr[r] < k) { ans = max(ans, arr[l] + arr[r]); l++; } else { r--; } } return ans;} // Driver Codeint main(){ vector<int> A = { 20, 10, 30, 100, 110 }; int k = 85; // Function Call cout << maxSum(A, k) << endl;}", "e": 34430, "s": 33810, "text": null }, { "code": "# Python program for above approach # Function to find max sum less than kdef maxSum(arr, k): # Sort the array arr.sort() n,l = len(arr),0 r,ans = n - 1,0 # While l is less than r while (l < r): if (arr[l] + arr[r] < k): ans = max(ans, arr[l] + arr[r]) l += 1 else: r -= 1 return ans # Driver CodeA = [20, 10, 30, 100, 110]k = 85 # Function Callprint(maxSum(A, k)) # This code is contributed by shinjanpatra", "e": 34913, "s": 34430, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to find max sum less than kstatic int maxSum(int[] arr, int k){ // Sort the array Array.Sort(arr); int n = arr.Length, l = 0, r = n - 1, ans = 0; // While l is less than r while (l < r) { if (arr[l] + arr[r] < k) { ans = Math.Max(ans, arr[l] + arr[r]); l++; } else { r--; } } return ans;} // Driver codepublic static void Main (){ int[] A = { 20, 10, 30, 100, 110 }; int k = 85; // Function Call Console.WriteLine(maxSum(A, k));}} // This code is contributed by target_2.", "e": 35562, "s": 34913, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to find max sum less than kfunction maxSum(arr, k){ // Sort the array arr.sort((a,b)=>a-b); var n = arr.length, l = 0, r = n - 1, ans = 0; // While l is less than r while (l < r) { if (arr[l] + arr[r] < k) { ans = Math.max(ans, arr[l] + arr[r]); l++; } else { r--; } } return ans;} // Driver Codevar A = [20, 10, 30, 100, 110];var k = 85;// Function Calldocument.write( maxSum(A, k)); </script>", "e": 36113, "s": 35562, "text": null }, { "code": null, "e": 36116, "s": 36113, "text": "50" }, { "code": null, "e": 36142, "s": 36116, "text": "Time complexity: O(NlogN)" }, { "code": null, "e": 36165, "s": 36142, "text": "Space complexity: O(1)" }, { "code": null, "e": 36170, "s": 36165, "text": "vt_m" }, { "code": null, "e": 36184, "s": 36170, "text": "Sanjit_Prasad" }, { "code": null, "e": 36201, "s": 36184, "text": "arorakashish0911" }, { "code": null, "e": 36214, "s": 36201, "text": "muskaanjain3" }, { "code": null, "e": 36228, "s": 36214, "text": "divyesh072019" }, { "code": null, "e": 36238, "s": 36228, "text": "rutvik_56" }, { "code": null, "e": 36247, "s": 36238, "text": "target_2" }, { "code": null, "e": 36260, "s": 36247, "text": "shinjanpatra" }, { "code": null, "e": 36267, "s": 36260, "text": "Arrays" }, { "code": null, "e": 36277, "s": 36267, "text": "Searching" }, { "code": null, "e": 36285, "s": 36277, "text": "Sorting" }, { "code": null, "e": 36292, "s": 36285, "text": "Arrays" }, { "code": null, "e": 36302, "s": 36292, "text": "Searching" }, { "code": null, "e": 36310, "s": 36302, "text": "Sorting" }, { "code": null, "e": 36408, "s": 36310, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36435, "s": 36408, "text": "Count pairs with given sum" }, { "code": null, "e": 36466, "s": 36435, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 36491, "s": 36466, "text": "Window Sliding Technique" }, { "code": null, "e": 36529, "s": 36491, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 36550, "s": 36529, "text": "Next Greater Element" }, { "code": null, "e": 36564, "s": 36550, "text": "Binary Search" }, { "code": null, "e": 36611, "s": 36564, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 36654, "s": 36611, "text": "Find the index of an array element in Java" }, { "code": null, "e": 36677, "s": 36654, "text": "Two Pointers Technique" } ]
Node.js Events - GeeksforGeeks
18 Jun, 2019 According to the official documentation of Node.js, it is an asynchronous event-driven JavaScript runtime. Node.js has an event-driven architecture which can perform asynchronous tasks. Node.js has ‘events’ module which emits named events that can cause corresponding functions or callbacks to be called. Functions(Callbacks) listen or subscribe to a particular event to occur and when that event triggers, all the callbacks subscribed to that event are fired one by one in order to which they were registered. The EventEmmitter class: All objects that emit events are instances of the EventEmitter class. The event can be emitted or listen to an event with the help of EventEmitter. Syntax: const EventEmitter=require('events'); var eventEmitter=new EventEmitter(); Listening events: Before emits any event, it must register functions(callbacks) to listen to the events.Syntax: eventEmitter.addListener(event, listener) eventEmitter.on(event, listener) eventEmitter.once(event, listener) eventEmmitter.on(event, listener) and eventEmitter.addListener(event, listener) are pretty much similar. It adds the listener at the end of the listener’s array for the specified event. Multiple calls to the same event and listener will add the listener multiple times and correspondingly fire multiple times. Both functions return emitter, so calls can be chained. eventEmitter.once(event, listener) fires at most once for a particular event and will be removed from listeners array after it has listened once. Returns emitter, so calls can be chained. Emitting events: Every event is named event in nodejs. We can trigger an event by emit(event, [arg1], [arg2], [...]) function. We can pass an arbitrary set of arguments to the listener functions. Syntax: eventEmitter.emit(event, [arg1], [arg2], [...]) Simple Event: // Importing eventsconst EventEmitter = require('events'); // Initializing event emitter instances var eventEmitter = new EventEmitter(); // Registering to myEvent eventEmitter.on('myEvent', (msg) => { console.log(msg);}); // Triggering myEventeventEmitter.emit('myEvent', "First event"); Output: First event Removing Listener: The eventEmitter.removeListener() takes two argument event and listener, and removes that listener from the listeners array that is subscribed to that event. While eventEmitter.removeAllListeners() removes all the listener from the array which are subscribed to the mentioned event. Syntax: eventEmitter.removeListener(event, listener) eventEmitter.removeAllListeners([event]) Note: Removing the listener from the array will change the sequence of the listener’s array, hence it must be carefully used. The eventEmitter.removeListener() will remove at most one instance of the listener which is in front of the queue. // Importing eventsconst EventEmitter = require('events'); // Initializing event emitter instances var eventEmitter = new EventEmitter(); var fun1 = (msg) => { console.log("Message from fun1: " + msg);}; var fun2 = (msg) => { console.log("Message from fun2: " + msg);}; // Registering fun1 and fun2eventEmitter.on('myEvent', fun1);eventEmitter.on('myEvent', fun1);eventEmitter.on('myEvent', fun2); // Removing listener fun1 that was// registered on the line 13eventEmitter.removeListener('myEvent', fun1); // Triggering myEventeventEmitter.emit('myEvent', "Event occurred"); // Removing all the listeners to myEventeventEmitter.removeAllListeners('myEvent'); // Triggering myEventeventEmitter.emit('myEvent', "Event occurred"); Output: Message from fun1: Event occurred Message from fun2: Event occurred We registered two times fun1 and one time fun2 for calling eventEmitter.removeListener(‘myEvent’, fun1) one instance of fun1 will be removed. Finally, removing all listener by removeAllListeners() will remove all listeners to myEvent. Other Methods: By default, a maximum of 10 listeners can be registered for any single event. To change the default value for all EventEmitter instances, the EventEmitter.defaultMaxListeners property can be used. The eventEmitter.getMaxListeners() will return the max listeners value set by setMaxListeners() or default value 10. Note: This is not a hard limit. EventEmitter will allow the new instance to be added but will print a warning message indicating possible EventEmitter memory leak. Syntax: eventEmitter.setMaxListeners(n) eventEmitter.getMaxListeners() // Importing eventsconst EventEmitter = require('events'); // Initializing event emitter instances var eventEmitter1 = new EventEmitter();var eventEmitter2 = new EventEmitter(); // Getting max listenerconsole.log("Default max listener for eventEmitter1 is: ", eventEmitter1.getMaxListeners());console.log("Default max listener for eventEmitter2 is: ", eventEmitter2.getMaxListeners()); // Set global deaultMaxListeners to 2EventEmitter.defaultMaxListeners = 2; // Getting max listenerconsole.log("Default max listener for eventEmitter1 is: ", eventEmitter1.getMaxListeners());console.log("Default max listener for eventEmitter2 is: ", eventEmitter2.getMaxListeners()); // Set max listener of eventEmitter1 to 5eventEmitter1.setMaxListeners(5); // Getting max listenerconsole.log("Default max listener for eventEmitter1 is: ", eventEmitter1.getMaxListeners());console.log("Default max listener for eventEmitter2 is: ", eventEmitter2.getMaxListeners()); // Declaring listener fun1 to myEvent1var fun1 = (msg) => { console.log("Message from fun1: " + msg);}; // Declaring listener fun2 to myEvent2var fun2 = (msg) => { console.log("Message from fun2: " + msg);}; // Listening to myEvent1 with 3 instance of fun1for(var i = 0; i < 3; i++) { eventEmitter1.addListener('myEvent1', fun1)} // Listening to myEvent2 with 3 instance of fun2for(var i = 0; i < 3; i++){ eventEmitter2.addListener('myEvent2', fun2)} // Emitting myEvent1 and myEvent2eventEmitter1.emit('myEvent1', 'Event1 occurred');eventEmitter2.emit('myEvent2', 'Event2 occurred'); Output: Default max listener for eventEmitter1 is: 10 Default max listener for eventEmitter2 is: 10 Default max listener for eventEmitter1 is: 2 Default max listener for eventEmitter2 is: 2 Default max listener for eventEmitter1 is: 5 Default max listener for eventEmitter2 is: 2 Message from fun1: Event1 occurred Message from fun1: Event1 occurred Message from fun1: Event1 occurred Message from fun2: Event2 occurred Message from fun2: Event2 occurred Message from fun2: Event2 occurred (node:16240) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 3 myEvent2 listeners added. Use emitter.setMaxListeners() to increase limit eventEmitter.listeners(): It returns an array of listeners for the specified event.Syntax: eventEmitter.listeners(event) eventEmitter.listenerCount(): It returns the number of listeners listening to the specified event.Syntax: eventEmitter.listenerCount(event) eventEmitter.prependOnceListener(): It will add the one-time listener to the beginning of the array.Syntax: eventEmitter.prependOnceListener(event, listener) eventEmitter.prependListener(): It will add the listener to the beginning of the array.Syntax: eventEmitter.prependListener(event, listener) // Importing eventsconst EventEmitter = require('events'); // Initializing event emitter instances var eventEmitter = new EventEmitter(); // Declaring listener fun1 to myEvent1var fun1 = (msg) => { console.log("Message from fun1: " + msg);}; // Declaring listener fun2 to myEvent2var fun2 = (msg) => { console.log("Message from fun2: " + msg);}; // Listening to myEvent with fun1 and fun2eventEmitter.addListener('myEvent', fun1); // fun2 will be inserted in front of listeners arrayeventEmitter.prependListener('myEvent', fun2); // Listing listenersconsole.log(eventEmitter.listeners('myEvent')); // Count the listeners registered to myEventconsole.log(eventEmitter.listenerCount('myEvent')); // Triggering myEventeventEmitter.emit('myEvent', 'Event occurred'); Output: [ [Function: fun2], [Function: fun1] ] 2 Message from fun2: Event occurred Message from fun1: Event occurred Special Events: All EventEmitter instances emit the event ‘newListener’ when new listeners are added and ‘removeListener’ existing listeners are removed. Event: ‘newListener’ The EventEmitter instance will emit its own ‘newListener’ event before a listener is added to its internal array of listeners. Listeners registered for the ‘newListener’ event will be passed to the event name and reference to the listener being added. The event ‘newListener’ is triggered before adding the listener to the array.eventEmitter.once( 'newListener', listener) eventEmitter.on( 'newListener', listener) eventEmitter.once( 'newListener', listener) eventEmitter.on( 'newListener', listener) Event: ‘removeListener’ The ‘removeListener’ event is emitted after a listener is removed.eventEmitter.once( ‘removeListener’, listener) eventEmitter.on( 'removeListener’, listener) eventEmitter.once( ‘removeListener’, listener) eventEmitter.on( 'removeListener’, listener) Event: ‘error’ When an error occurs within an EventEmitter instance, the typical action is for an ‘error’ event to be emitted. If an EventEmitter does not have at least one listener registered for the ‘error’ event, and an ‘error’ event is emitted, the error is thrown, a stack trace is printed, and the Node.js process exits.eventEmitter.on('error', listener) eventEmitter.on('error', listener) // Importing eventsconst EventEmitter = require('events'); // Initializing event emitter instances var eventEmitter = new EventEmitter(); // Register to erroreventEmitter.on('error', (err) => { console.error('whoops! there was an error');}); // Register to newListenereventEmitter.on( 'newListener', (event, listener) => { console.log(`The listener is added to ${event}`);}); // Register to removeListenereventEmitter.on( 'removeListener', (event, listener) => { console.log(`The listener is removed from ${event}`);}); // Declaring listener fun1 to myEvent1var fun1 = (msg) => { console.log("Message from fun1: " + msg);}; // Declaring listener fun2 to myEvent2var fun2 = (msg) => { console.log("Message from fun2: " + msg);}; // Listening to myEvent with fun1 and fun2eventEmitter.on('myEvent', fun1);eventEmitter.on('myEvent', fun2); // Removing listenereventEmitter.off('myEvent', fun1); // Triggering myEventeventEmitter.emit('myEvent', 'Event occurred'); // Triggering erroreventEmitter.emit('error', new Error('whoops!')); Output: The listener is added to removeListener The listener is added to myEvent The listener is added to myEvent The listener is removed from myEvent Message from fun2: Event occurred whoops! there was an error Asynchronous events: The EventEmitter calls all listeners synchronously in order to which they were registered. However, we can perform asynchronous calls by using setImmediate() or process.nextTick(). // Importing eventsconst EventEmitter = require('events'); // Initializing event emitter instances var eventEmitter = new EventEmitter(); // Async function listening to myEventeventEmitter.on('myEvent', (msg) => { setImmediate( () => { console.log("Message from async: " + msg); });}); // Declaring listener fun to myEventvar fun = (msg) => { console.log("Message from fun: " + msg);}; // Listening to myEvent with funeventEmitter.on('myEvent', fun); // Triggering myEventeventEmitter.emit('myEvent', "Event occurred"); Output: Message from fun: Event occurred Message from async: Event occurred Reference: https://nodejs.org/api/events.html Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method Node.js fs.readFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Remove elements from a JavaScript Array 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? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25929, "s": 25901, "text": "\n18 Jun, 2019" }, { "code": null, "e": 26440, "s": 25929, "text": "According to the official documentation of Node.js, it is an asynchronous event-driven JavaScript runtime. Node.js has an event-driven architecture which can perform asynchronous tasks. Node.js has ‘events’ module which emits named events that can cause corresponding functions or callbacks to be called. Functions(Callbacks) listen or subscribe to a particular event to occur and when that event triggers, all the callbacks subscribed to that event are fired one by one in order to which they were registered." }, { "code": null, "e": 26613, "s": 26440, "text": "The EventEmmitter class: All objects that emit events are instances of the EventEmitter class. The event can be emitted or listen to an event with the help of EventEmitter." }, { "code": null, "e": 26621, "s": 26613, "text": "Syntax:" }, { "code": null, "e": 26697, "s": 26621, "text": "const EventEmitter=require('events');\nvar eventEmitter=new EventEmitter();\n" }, { "code": null, "e": 26809, "s": 26697, "text": "Listening events: Before emits any event, it must register functions(callbacks) to listen to the events.Syntax:" }, { "code": null, "e": 26920, "s": 26809, "text": "eventEmitter.addListener(event, listener)\neventEmitter.on(event, listener)\neventEmitter.once(event, listener)\n" }, { "code": null, "e": 27286, "s": 26920, "text": "eventEmmitter.on(event, listener) and eventEmitter.addListener(event, listener) are pretty much similar. It adds the listener at the end of the listener’s array for the specified event. Multiple calls to the same event and listener will add the listener multiple times and correspondingly fire multiple times. Both functions return emitter, so calls can be chained." }, { "code": null, "e": 27474, "s": 27286, "text": "eventEmitter.once(event, listener) fires at most once for a particular event and will be removed from listeners array after it has listened once. Returns emitter, so calls can be chained." }, { "code": null, "e": 27670, "s": 27474, "text": "Emitting events: Every event is named event in nodejs. We can trigger an event by emit(event, [arg1], [arg2], [...]) function. We can pass an arbitrary set of arguments to the listener functions." }, { "code": null, "e": 27678, "s": 27670, "text": "Syntax:" }, { "code": null, "e": 27727, "s": 27678, "text": "eventEmitter.emit(event, [arg1], [arg2], [...])\n" }, { "code": null, "e": 27741, "s": 27727, "text": "Simple Event:" }, { "code": "// Importing eventsconst EventEmitter = require('events'); // Initializing event emitter instances var eventEmitter = new EventEmitter(); // Registering to myEvent eventEmitter.on('myEvent', (msg) => { console.log(msg);}); // Triggering myEventeventEmitter.emit('myEvent', \"First event\");", "e": 28036, "s": 27741, "text": null }, { "code": null, "e": 28044, "s": 28036, "text": "Output:" }, { "code": null, "e": 28057, "s": 28044, "text": "First event\n" }, { "code": null, "e": 28359, "s": 28057, "text": "Removing Listener: The eventEmitter.removeListener() takes two argument event and listener, and removes that listener from the listeners array that is subscribed to that event. While eventEmitter.removeAllListeners() removes all the listener from the array which are subscribed to the mentioned event." }, { "code": null, "e": 28367, "s": 28359, "text": "Syntax:" }, { "code": null, "e": 28454, "s": 28367, "text": "eventEmitter.removeListener(event, listener)\neventEmitter.removeAllListeners([event])\n" }, { "code": null, "e": 28460, "s": 28454, "text": "Note:" }, { "code": null, "e": 28580, "s": 28460, "text": "Removing the listener from the array will change the sequence of the listener’s array, hence it must be carefully used." }, { "code": null, "e": 28695, "s": 28580, "text": "The eventEmitter.removeListener() will remove at most one instance of the listener which is in front of the queue." }, { "code": "// Importing eventsconst EventEmitter = require('events'); // Initializing event emitter instances var eventEmitter = new EventEmitter(); var fun1 = (msg) => { console.log(\"Message from fun1: \" + msg);}; var fun2 = (msg) => { console.log(\"Message from fun2: \" + msg);}; // Registering fun1 and fun2eventEmitter.on('myEvent', fun1);eventEmitter.on('myEvent', fun1);eventEmitter.on('myEvent', fun2); // Removing listener fun1 that was// registered on the line 13eventEmitter.removeListener('myEvent', fun1); // Triggering myEventeventEmitter.emit('myEvent', \"Event occurred\"); // Removing all the listeners to myEventeventEmitter.removeAllListeners('myEvent'); // Triggering myEventeventEmitter.emit('myEvent', \"Event occurred\");", "e": 29441, "s": 28695, "text": null }, { "code": null, "e": 29449, "s": 29441, "text": "Output:" }, { "code": null, "e": 29518, "s": 29449, "text": "Message from fun1: Event occurred\nMessage from fun2: Event occurred\n" }, { "code": null, "e": 29753, "s": 29518, "text": "We registered two times fun1 and one time fun2 for calling eventEmitter.removeListener(‘myEvent’, fun1) one instance of fun1 will be removed. Finally, removing all listener by removeAllListeners() will remove all listeners to myEvent." }, { "code": null, "e": 30082, "s": 29753, "text": "Other Methods: By default, a maximum of 10 listeners can be registered for any single event. To change the default value for all EventEmitter instances, the EventEmitter.defaultMaxListeners property can be used. The eventEmitter.getMaxListeners() will return the max listeners value set by setMaxListeners() or default value 10." }, { "code": null, "e": 30246, "s": 30082, "text": "Note: This is not a hard limit. EventEmitter will allow the new instance to be added but will print a warning message indicating possible EventEmitter memory leak." }, { "code": null, "e": 30254, "s": 30246, "text": "Syntax:" }, { "code": null, "e": 30318, "s": 30254, "text": "eventEmitter.setMaxListeners(n)\neventEmitter.getMaxListeners()\n" }, { "code": "// Importing eventsconst EventEmitter = require('events'); // Initializing event emitter instances var eventEmitter1 = new EventEmitter();var eventEmitter2 = new EventEmitter(); // Getting max listenerconsole.log(\"Default max listener for eventEmitter1 is: \", eventEmitter1.getMaxListeners());console.log(\"Default max listener for eventEmitter2 is: \", eventEmitter2.getMaxListeners()); // Set global deaultMaxListeners to 2EventEmitter.defaultMaxListeners = 2; // Getting max listenerconsole.log(\"Default max listener for eventEmitter1 is: \", eventEmitter1.getMaxListeners());console.log(\"Default max listener for eventEmitter2 is: \", eventEmitter2.getMaxListeners()); // Set max listener of eventEmitter1 to 5eventEmitter1.setMaxListeners(5); // Getting max listenerconsole.log(\"Default max listener for eventEmitter1 is: \", eventEmitter1.getMaxListeners());console.log(\"Default max listener for eventEmitter2 is: \", eventEmitter2.getMaxListeners()); // Declaring listener fun1 to myEvent1var fun1 = (msg) => { console.log(\"Message from fun1: \" + msg);}; // Declaring listener fun2 to myEvent2var fun2 = (msg) => { console.log(\"Message from fun2: \" + msg);}; // Listening to myEvent1 with 3 instance of fun1for(var i = 0; i < 3; i++) { eventEmitter1.addListener('myEvent1', fun1)} // Listening to myEvent2 with 3 instance of fun2for(var i = 0; i < 3; i++){ eventEmitter2.addListener('myEvent2', fun2)} // Emitting myEvent1 and myEvent2eventEmitter1.emit('myEvent1', 'Event1 occurred');eventEmitter2.emit('myEvent2', 'Event2 occurred');", "e": 31961, "s": 30318, "text": null }, { "code": null, "e": 31969, "s": 31961, "text": "Output:" }, { "code": null, "e": 32620, "s": 31969, "text": "Default max listener for eventEmitter1 is: 10\nDefault max listener for eventEmitter2 is: 10\nDefault max listener for eventEmitter1 is: 2\nDefault max listener for eventEmitter2 is: 2\nDefault max listener for eventEmitter1 is: 5\nDefault max listener for eventEmitter2 is: 2\nMessage from fun1: Event1 occurred\nMessage from fun1: Event1 occurred\nMessage from fun1: Event1 occurred\nMessage from fun2: Event2 occurred\nMessage from fun2: Event2 occurred\nMessage from fun2: Event2 occurred\n(node:16240) MaxListenersExceededWarning: Possible EventEmitter memory leak detected.\n3 myEvent2 listeners added. Use emitter.setMaxListeners() to increase limit\n" }, { "code": null, "e": 32711, "s": 32620, "text": "eventEmitter.listeners(): It returns an array of listeners for the specified event.Syntax:" }, { "code": null, "e": 32741, "s": 32711, "text": "eventEmitter.listeners(event)" }, { "code": null, "e": 32847, "s": 32741, "text": "eventEmitter.listenerCount(): It returns the number of listeners listening to the specified event.Syntax:" }, { "code": null, "e": 32881, "s": 32847, "text": "eventEmitter.listenerCount(event)" }, { "code": null, "e": 32989, "s": 32881, "text": "eventEmitter.prependOnceListener(): It will add the one-time listener to the beginning of the array.Syntax:" }, { "code": null, "e": 33039, "s": 32989, "text": "eventEmitter.prependOnceListener(event, listener)" }, { "code": null, "e": 33134, "s": 33039, "text": "eventEmitter.prependListener(): It will add the listener to the beginning of the array.Syntax:" }, { "code": null, "e": 33180, "s": 33134, "text": "eventEmitter.prependListener(event, listener)" }, { "code": "// Importing eventsconst EventEmitter = require('events'); // Initializing event emitter instances var eventEmitter = new EventEmitter(); // Declaring listener fun1 to myEvent1var fun1 = (msg) => { console.log(\"Message from fun1: \" + msg);}; // Declaring listener fun2 to myEvent2var fun2 = (msg) => { console.log(\"Message from fun2: \" + msg);}; // Listening to myEvent with fun1 and fun2eventEmitter.addListener('myEvent', fun1); // fun2 will be inserted in front of listeners arrayeventEmitter.prependListener('myEvent', fun2); // Listing listenersconsole.log(eventEmitter.listeners('myEvent')); // Count the listeners registered to myEventconsole.log(eventEmitter.listenerCount('myEvent')); // Triggering myEventeventEmitter.emit('myEvent', 'Event occurred');", "e": 33957, "s": 33180, "text": null }, { "code": null, "e": 33965, "s": 33957, "text": "Output:" }, { "code": null, "e": 34075, "s": 33965, "text": "[ [Function: fun2], [Function: fun1] ]\n2\nMessage from fun2: Event occurred\nMessage from fun1: Event occurred\n" }, { "code": null, "e": 34229, "s": 34075, "text": "Special Events: All EventEmitter instances emit the event ‘newListener’ when new listeners are added and ‘removeListener’ existing listeners are removed." }, { "code": null, "e": 34665, "s": 34229, "text": "Event: ‘newListener’ The EventEmitter instance will emit its own ‘newListener’ event before a listener is added to its internal array of listeners. Listeners registered for the ‘newListener’ event will be passed to the event name and reference to the listener being added. The event ‘newListener’ is triggered before adding the listener to the array.eventEmitter.once( 'newListener', listener)\neventEmitter.on( 'newListener', listener)" }, { "code": null, "e": 34751, "s": 34665, "text": "eventEmitter.once( 'newListener', listener)\neventEmitter.on( 'newListener', listener)" }, { "code": null, "e": 34933, "s": 34751, "text": "Event: ‘removeListener’ The ‘removeListener’ event is emitted after a listener is removed.eventEmitter.once( ‘removeListener’, listener)\neventEmitter.on( 'removeListener’, listener)" }, { "code": null, "e": 35025, "s": 34933, "text": "eventEmitter.once( ‘removeListener’, listener)\neventEmitter.on( 'removeListener’, listener)" }, { "code": null, "e": 35387, "s": 35025, "text": "Event: ‘error’ When an error occurs within an EventEmitter instance, the typical action is for an ‘error’ event to be emitted. If an EventEmitter does not have at least one listener registered for the ‘error’ event, and an ‘error’ event is emitted, the error is thrown, a stack trace is printed, and the Node.js process exits.eventEmitter.on('error', listener)\n" }, { "code": null, "e": 35423, "s": 35387, "text": "eventEmitter.on('error', listener)\n" }, { "code": "// Importing eventsconst EventEmitter = require('events'); // Initializing event emitter instances var eventEmitter = new EventEmitter(); // Register to erroreventEmitter.on('error', (err) => { console.error('whoops! there was an error');}); // Register to newListenereventEmitter.on( 'newListener', (event, listener) => { console.log(`The listener is added to ${event}`);}); // Register to removeListenereventEmitter.on( 'removeListener', (event, listener) => { console.log(`The listener is removed from ${event}`);}); // Declaring listener fun1 to myEvent1var fun1 = (msg) => { console.log(\"Message from fun1: \" + msg);}; // Declaring listener fun2 to myEvent2var fun2 = (msg) => { console.log(\"Message from fun2: \" + msg);}; // Listening to myEvent with fun1 and fun2eventEmitter.on('myEvent', fun1);eventEmitter.on('myEvent', fun2); // Removing listenereventEmitter.off('myEvent', fun1); // Triggering myEventeventEmitter.emit('myEvent', 'Event occurred'); // Triggering erroreventEmitter.emit('error', new Error('whoops!'));", "e": 36478, "s": 35423, "text": null }, { "code": null, "e": 36486, "s": 36478, "text": "Output:" }, { "code": null, "e": 36691, "s": 36486, "text": "The listener is added to removeListener\nThe listener is added to myEvent\nThe listener is added to myEvent\nThe listener is removed from myEvent\nMessage from fun2: Event occurred\nwhoops! there was an error\n" }, { "code": null, "e": 36893, "s": 36691, "text": "Asynchronous events: The EventEmitter calls all listeners synchronously in order to which they were registered. However, we can perform asynchronous calls by using setImmediate() or process.nextTick()." }, { "code": "// Importing eventsconst EventEmitter = require('events'); // Initializing event emitter instances var eventEmitter = new EventEmitter(); // Async function listening to myEventeventEmitter.on('myEvent', (msg) => { setImmediate( () => { console.log(\"Message from async: \" + msg); });}); // Declaring listener fun to myEventvar fun = (msg) => { console.log(\"Message from fun: \" + msg);}; // Listening to myEvent with funeventEmitter.on('myEvent', fun); // Triggering myEventeventEmitter.emit('myEvent', \"Event occurred\");", "e": 37434, "s": 36893, "text": null }, { "code": null, "e": 37442, "s": 37434, "text": "Output:" }, { "code": null, "e": 37511, "s": 37442, "text": "Message from fun: Event occurred\nMessage from async: Event occurred\n" }, { "code": null, "e": 37557, "s": 37511, "text": "Reference: https://nodejs.org/api/events.html" }, { "code": null, "e": 37564, "s": 37557, "text": "Picked" }, { "code": null, "e": 37572, "s": 37564, "text": "Node.js" }, { "code": null, "e": 37589, "s": 37572, "text": "Web Technologies" }, { "code": null, "e": 37687, "s": 37589, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37717, "s": 37687, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 37746, "s": 37717, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 37803, "s": 37746, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 37857, "s": 37803, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 37894, "s": 37857, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 37934, "s": 37894, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 37979, "s": 37934, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 38022, "s": 37979, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 38072, "s": 38022, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Split Date-Time column into Date and Time variables in R - GeeksforGeeks
09 Nov, 2021 R programming language provides a variety of ways for dealing with both date and date/time data. The builtin framework as.Date function is responsible for the handling of dates alone, the library chron in R handles both dates and times, without any support for time zones; whereas the POSIXct and POSIXlt classes provides the support for handling datetime objects as well as timezones. Easy conversion of date time objects can be performed to other date related objects. A date string can be first converted to POSIXct objects and then basic arithmetic can be performed on it easily. POSIXct objects ease the process of mathematical operations since they rely on seconds as the major unit of time management. The dates are converted to standard time zone, UTC. A string type date object can be converted to POSIXct object, using the as.POSIXct(date) method in R. Syntax: as.POSIXct ( date , format) Parameter : date – The string date object format – The format specifier of the date The date objects are stored as the number of days calculated starting January 1, 1970, where negative numbers are used to refer earlier dates. The Date objects support basic arithmetic directly, where in the integers are added or subtracted directly from the Dates. n number of days are added or subtracted directly and the standard date format is returned as an output. The Date object can also specify different formats to contain the dates. The as.Date() method takes as input a string date object and converts it to a Date object. Syntax: as.Date(character date object) The format() method in R is used to format the specified date time object in the required format. Syntax: format (datetime , format = ) Example: R # declaring a datetime vectorvec <- c("2021-05-08 08:32:07","2021-07-18 00:21:07", "2020-11-28 23:32:09","2021-05-11 18:32:07") # creating datetime column in the dataframedata_frame <- data.frame(datetime = as.POSIXct( vec, format = "%Y-%m-%d %H:%M:%S")) print ("Original DataFrame")print (data_frame) # extracting timedata_frame$time <- format(as.POSIXct( data_frame$datetime),format = "%H:%M:%S") # extracting datedata_frame$date <- as.Date (data_frame$datetime) print ("Modified DataFrame")print (data_frame) Output [1] "Original DataFrame" datetime 1 2021-05-08 08:32:07 2 2021-07-18 00:21:07 3 2020-11-28 23:32:09 4 2021-05-11 18:32:07 [1] "Modified DataFrame" datetime time date 1 2021-05-08 08:32:07 08:32:07 2021-05-08 2 2021-07-18 00:21:07 00:21:07 2021-07-17 3 2020-11-28 23:32:09 23:32:09 2020-11-28 4 2021-05-11 18:32:07 18:32:07 2021-05-11 Lubridate package in R programming language is used to work with date and time objects. It makes it easier to parse and manipulate the objects and needs to be installed and loaded into the working space. The Sys.time() function in R is used to fetch the current date and time object according the IST zone. The hours() method in R is used to take an input an integer denoting the number of hours. The “lubridate” package objects allow direct arithmetic over its various components, therefore the number of hours can be directly subtracted from the lubridate time object. A result is also an object belonging to this class. Sys.Date() function is used to return the system’s date. Syntax: Sys.Date() Parameters:Does not accept any parameters The ymd_hms() method in R is used to input a datetime object into the working space. Example: R library("lubridate") # declaring a datetime vectorvec <- c("2021-05-08 08:32:07","2021-07-18 00:21:07", "2020-11-28 23:32:09","2021-05-11 18:32:07") # creating datetime column in the dataframedata_frame <- data.frame(datetime = ymd_hms(vec))print ("Original DataFrame")print (data_frame) # extracting timedata_frame$time <- format(as.POSIXct( data_frame$datetime),format = "%H:%M:%S") # extracting datedata_frame$date <- as.Date (data_frame$datetime)print ("Modified DataFrame")print (data_frame) Output [1] "Original DataFrame" datetime 1 2021-05-08 08:32:07 2 2021-07-18 00:21:07 3 2020-11-28 23:32:09 4 2021-05-11 18:32:07 [1] "Modified DataFrame" datetime time date 1 2021-05-08 08:32:07 08:32:07 2021-05-08 2 2021-07-18 00:21:07 00:21:07 2021-07-17 3 2020-11-28 23:32:09 23:32:09 2020-11-28 4 2021-05-11 18:32:07 18:32:07 2021-05-11 gulshankumarar231 Picked R-DateTime R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to import an Excel File into R ? Time Series Analysis in R R - if statement How to filter R dataframe by multiple conditions?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n09 Nov, 2021" }, { "code": null, "e": 26958, "s": 26487, "text": "R programming language provides a variety of ways for dealing with both date and date/time data. The builtin framework as.Date function is responsible for the handling of dates alone, the library chron in R handles both dates and times, without any support for time zones; whereas the POSIXct and POSIXlt classes provides the support for handling datetime objects as well as timezones. Easy conversion of date time objects can be performed to other date related objects." }, { "code": null, "e": 27351, "s": 26958, "text": "A date string can be first converted to POSIXct objects and then basic arithmetic can be performed on it easily. POSIXct objects ease the process of mathematical operations since they rely on seconds as the major unit of time management. The dates are converted to standard time zone, UTC. A string type date object can be converted to POSIXct object, using the as.POSIXct(date) method in R. " }, { "code": null, "e": 27359, "s": 27351, "text": "Syntax:" }, { "code": null, "e": 27387, "s": 27359, "text": "as.POSIXct ( date , format)" }, { "code": null, "e": 27399, "s": 27387, "text": "Parameter :" }, { "code": null, "e": 27429, "s": 27399, "text": "date – The string date object" }, { "code": null, "e": 27471, "s": 27429, "text": "format – The format specifier of the date" }, { "code": null, "e": 28006, "s": 27471, "text": "The date objects are stored as the number of days calculated starting January 1, 1970, where negative numbers are used to refer earlier dates. The Date objects support basic arithmetic directly, where in the integers are added or subtracted directly from the Dates. n number of days are added or subtracted directly and the standard date format is returned as an output. The Date object can also specify different formats to contain the dates. The as.Date() method takes as input a string date object and converts it to a Date object." }, { "code": null, "e": 28014, "s": 28006, "text": "Syntax:" }, { "code": null, "e": 28045, "s": 28014, "text": "as.Date(character date object)" }, { "code": null, "e": 28144, "s": 28045, "text": "The format() method in R is used to format the specified date time object in the required format. " }, { "code": null, "e": 28152, "s": 28144, "text": "Syntax:" }, { "code": null, "e": 28182, "s": 28152, "text": "format (datetime , format = )" }, { "code": null, "e": 28191, "s": 28182, "text": "Example:" }, { "code": null, "e": 28193, "s": 28191, "text": "R" }, { "code": "# declaring a datetime vectorvec <- c(\"2021-05-08 08:32:07\",\"2021-07-18 00:21:07\", \"2020-11-28 23:32:09\",\"2021-05-11 18:32:07\") # creating datetime column in the dataframedata_frame <- data.frame(datetime = as.POSIXct( vec, format = \"%Y-%m-%d %H:%M:%S\")) print (\"Original DataFrame\")print (data_frame) # extracting timedata_frame$time <- format(as.POSIXct( data_frame$datetime),format = \"%H:%M:%S\") # extracting datedata_frame$date <- as.Date (data_frame$datetime) print (\"Modified DataFrame\")print (data_frame)", "e": 28715, "s": 28193, "text": null }, { "code": null, "e": 28722, "s": 28715, "text": "Output" }, { "code": null, "e": 29083, "s": 28722, "text": "[1] \"Original DataFrame\"\ndatetime\n1 \n2021-05-08 08:32:07\n2 \n2021-07-18 00:21:07\n3 \n2020-11-28 23:32:09\n4 \n2021-05-11 18:32:07\n[1] \"Modified DataFrame\"\n datetime time date\n1 2021-05-08 08:32:07 08:32:07 2021-05-08\n2 2021-07-18 00:21:07 00:21:07 2021-07-17\n3 2020-11-28 23:32:09 23:32:09 2020-11-28\n4 2021-05-11 18:32:07 18:32:07 2021-05-11" }, { "code": null, "e": 29287, "s": 29083, "text": "Lubridate package in R programming language is used to work with date and time objects. It makes it easier to parse and manipulate the objects and needs to be installed and loaded into the working space." }, { "code": null, "e": 29707, "s": 29287, "text": "The Sys.time() function in R is used to fetch the current date and time object according the IST zone. The hours() method in R is used to take an input an integer denoting the number of hours. The “lubridate” package objects allow direct arithmetic over its various components, therefore the number of hours can be directly subtracted from the lubridate time object. A result is also an object belonging to this class." }, { "code": null, "e": 29764, "s": 29707, "text": "Sys.Date() function is used to return the system’s date." }, { "code": null, "e": 29783, "s": 29764, "text": "Syntax: Sys.Date()" }, { "code": null, "e": 29825, "s": 29783, "text": "Parameters:Does not accept any parameters" }, { "code": null, "e": 29911, "s": 29825, "text": "The ymd_hms() method in R is used to input a datetime object into the working space. " }, { "code": null, "e": 29920, "s": 29911, "text": "Example:" }, { "code": null, "e": 29922, "s": 29920, "text": "R" }, { "code": "library(\"lubridate\") # declaring a datetime vectorvec <- c(\"2021-05-08 08:32:07\",\"2021-07-18 00:21:07\", \"2020-11-28 23:32:09\",\"2021-05-11 18:32:07\") # creating datetime column in the dataframedata_frame <- data.frame(datetime = ymd_hms(vec))print (\"Original DataFrame\")print (data_frame) # extracting timedata_frame$time <- format(as.POSIXct( data_frame$datetime),format = \"%H:%M:%S\") # extracting datedata_frame$date <- as.Date (data_frame$datetime)print (\"Modified DataFrame\")print (data_frame)", "e": 30428, "s": 29922, "text": null }, { "code": null, "e": 30435, "s": 30428, "text": "Output" }, { "code": null, "e": 30796, "s": 30435, "text": "[1] \"Original DataFrame\"\ndatetime\n1 \n2021-05-08 08:32:07\n2 \n2021-07-18 00:21:07\n3 \n2020-11-28 23:32:09\n4 \n2021-05-11 18:32:07\n[1] \"Modified DataFrame\"\n datetime time date\n1 2021-05-08 08:32:07 08:32:07 2021-05-08\n2 2021-07-18 00:21:07 00:21:07 2021-07-17\n3 2020-11-28 23:32:09 23:32:09 2020-11-28\n4 2021-05-11 18:32:07 18:32:07 2021-05-11" }, { "code": null, "e": 30814, "s": 30796, "text": "gulshankumarar231" }, { "code": null, "e": 30821, "s": 30814, "text": "Picked" }, { "code": null, "e": 30832, "s": 30821, "text": "R-DateTime" }, { "code": null, "e": 30843, "s": 30832, "text": "R Language" }, { "code": null, "e": 30941, "s": 30843, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30993, "s": 30941, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 31028, "s": 30993, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 31066, "s": 31028, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 31124, "s": 31066, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 31167, "s": 31124, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 31216, "s": 31167, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 31253, "s": 31216, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 31279, "s": 31253, "text": "Time Series Analysis in R" }, { "code": null, "e": 31296, "s": 31279, "text": "R - if statement" } ]
PostgreSQL - LAG Function - GeeksforGeeks
08 Oct, 2021 In PostgreSQL, the LAG() function is used to access a row that comes exactly before the current row at a specific physical offset. The LAG() comes in handy while comparing the values of the current row with the previous row. The following shows the syntax of LAG() function: Syntax: LAG(expression [, offset [, default_value]]) OVER ( [PARTITION BY partition_expression, ... ] ORDER BY sort_expression [ASC | DESC], ... ) Let’s analyze the above syntax: The expression is used to set a comparision basis for the comparision of current and exactly previous rows at a specified offset. It can any among the following, be a column, an expression, or a subquery. The offset is a positive integer that is used to set in the query the number of rows that that come before the current row. The offset can be an expression, a subquery, or a column. If it is not specified, it defaults to 1. The LAG() function will return the default_value when the offset goes beyond the scope of the partition. The LAG() function is applied on the partitions created by the PARTITION BY clause.If partition is not specified, the function treats the whole result set as a single partition. The ORDER BY clause sets the order of the rows in each partition to which the LAG() function is applied. Example 1: Let’s set up a new table for the demonstration named sales: CREATE TABLE sales( year SMALLINT CHECK(year > 0), group_id INT NOT NULL, amount DECIMAL(10, 2) NOT NULL, PRIMARY KEY(year, group_id) ); Add some data to it: INSERT INTO sales(year, group_id, amount) VALUES (2018, 1, 1474), (2018, 2, 1787), (2018, 3, 1760), (2019, 1, 1915), (2019, 2, 1911), (2019, 3, 1118), (2020, 1, 1646), (2020, 2, 1975), (2020, 3, 1516); Here the LAG() function to return the sales amount of the current year and the previous year: WITH cte AS ( SELECT year, SUM(amount) amount FROM sales GROUP BY year ) SELECT year, amount, LAG(amount, 1) OVER ( ORDER BY year ) last_year_sales FROM cte; Output: Example 2: This example uses the LAG() function to compare the sales of the current year with the sales of the previous year of each product group: SELECT year, amount, group_id, LAG(amount, 1) OVER ( PARTITION BY group_id ORDER BY year ) last_year_sales FROM sales; Output: sooda367 PostgreSQL-function PostgreSQL-Window-function PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. PostgreSQL - CREATE PROCEDURE PostgreSQL - GROUP BY clause PostgreSQL - DROP INDEX PostgreSQL - TIME Data Type PostgreSQL - REPLACE Function PostgreSQL - Copy Table PostgreSQL - CREATE SCHEMA PostgreSQL - Rename Table PostgreSQL - ROW_NUMBER Function PostgreSQL - Identity Column
[ { "code": null, "e": 25175, "s": 25147, "text": "\n08 Oct, 2021" }, { "code": null, "e": 25400, "s": 25175, "text": "In PostgreSQL, the LAG() function is used to access a row that comes exactly before the current row at a specific physical offset. The LAG() comes in handy while comparing the values of the current row with the previous row." }, { "code": null, "e": 25450, "s": 25400, "text": "The following shows the syntax of LAG() function:" }, { "code": null, "e": 25606, "s": 25450, "text": "Syntax:\nLAG(expression [, offset [, default_value]]) \nOVER (\n [PARTITION BY partition_expression, ... ]\n ORDER BY sort_expression [ASC | DESC], ...\n)" }, { "code": null, "e": 25638, "s": 25606, "text": "Let’s analyze the above syntax:" }, { "code": null, "e": 25843, "s": 25638, "text": "The expression is used to set a comparision basis for the comparision of current and exactly previous rows at a specified offset. It can any among the following, be a column, an expression, or a subquery." }, { "code": null, "e": 26067, "s": 25843, "text": "The offset is a positive integer that is used to set in the query the number of rows that that come before the current row. The offset can be an expression, a subquery, or a column. If it is not specified, it defaults to 1." }, { "code": null, "e": 26172, "s": 26067, "text": "The LAG() function will return the default_value when the offset goes beyond the scope of the partition." }, { "code": null, "e": 26350, "s": 26172, "text": "The LAG() function is applied on the partitions created by the PARTITION BY clause.If partition is not specified, the function treats the whole result set as a single partition." }, { "code": null, "e": 26455, "s": 26350, "text": "The ORDER BY clause sets the order of the rows in each partition to which the LAG() function is applied." }, { "code": null, "e": 26466, "s": 26455, "text": "Example 1:" }, { "code": null, "e": 26526, "s": 26466, "text": "Let’s set up a new table for the demonstration named sales:" }, { "code": null, "e": 26679, "s": 26526, "text": "CREATE TABLE sales(\n year SMALLINT CHECK(year > 0),\n group_id INT NOT NULL,\n amount DECIMAL(10, 2) NOT NULL,\n PRIMARY KEY(year, group_id)\n);" }, { "code": null, "e": 26700, "s": 26679, "text": "Add some data to it:" }, { "code": null, "e": 26944, "s": 26700, "text": "INSERT INTO \n sales(year, group_id, amount) \nVALUES\n (2018, 1, 1474),\n (2018, 2, 1787),\n (2018, 3, 1760),\n (2019, 1, 1915),\n (2019, 2, 1911),\n (2019, 3, 1118),\n (2020, 1, 1646),\n (2020, 2, 1975),\n (2020, 3, 1516);" }, { "code": null, "e": 27038, "s": 26944, "text": "Here the LAG() function to return the sales amount of the current year and the previous year:" }, { "code": null, "e": 27256, "s": 27038, "text": "WITH cte AS (\n SELECT \n year, \n SUM(amount) amount\n FROM sales\n GROUP BY year\n) \nSELECT\n year, \n amount,\n LAG(amount, 1) OVER (\n ORDER BY year\n ) last_year_sales\nFROM\n cte;" }, { "code": null, "e": 27264, "s": 27256, "text": "Output:" }, { "code": null, "e": 27275, "s": 27264, "text": "Example 2:" }, { "code": null, "e": 27412, "s": 27275, "text": "This example uses the LAG() function to compare the sales of the current year with the sales of the previous year of each product group:" }, { "code": null, "e": 27572, "s": 27412, "text": "SELECT\n year, \n amount,\n group_id,\n LAG(amount, 1) OVER (\n PARTITION BY group_id\n ORDER BY year\n ) last_year_sales\nFROM\n sales;" }, { "code": null, "e": 27580, "s": 27572, "text": "Output:" }, { "code": null, "e": 27589, "s": 27580, "text": "sooda367" }, { "code": null, "e": 27609, "s": 27589, "text": "PostgreSQL-function" }, { "code": null, "e": 27636, "s": 27609, "text": "PostgreSQL-Window-function" }, { "code": null, "e": 27647, "s": 27636, "text": "PostgreSQL" }, { "code": null, "e": 27745, "s": 27647, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27775, "s": 27745, "text": "PostgreSQL - CREATE PROCEDURE" }, { "code": null, "e": 27804, "s": 27775, "text": "PostgreSQL - GROUP BY clause" }, { "code": null, "e": 27828, "s": 27804, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 27856, "s": 27828, "text": "PostgreSQL - TIME Data Type" }, { "code": null, "e": 27886, "s": 27856, "text": "PostgreSQL - REPLACE Function" }, { "code": null, "e": 27910, "s": 27886, "text": "PostgreSQL - Copy Table" }, { "code": null, "e": 27937, "s": 27910, "text": "PostgreSQL - CREATE SCHEMA" }, { "code": null, "e": 27963, "s": 27937, "text": "PostgreSQL - Rename Table" }, { "code": null, "e": 27996, "s": 27963, "text": "PostgreSQL - ROW_NUMBER Function" } ]
CheckedTextView in Kotlin - GeeksforGeeks
18 Feb, 2021 CheckedTextView is used to implement checkable interface where one can tick or check the needed or required items and leave out the rest. In this article, we will be discussing how to make a CheckedTextView manually. The first step is to make or create a project in Android Studio. Here, we will be creating a project named CheckedTextViewInKotlin. For creating a new project: Click on File, then New => New ProjectThen, check Include Kotlin Support and click next button.Select minimum SDK, whatever you need.Select Empty activity and then click finish. Click on File, then New => New Project Then, check Include Kotlin Support and click next button. Select minimum SDK, whatever you need. Select Empty activity and then click finish. In this file, we will add the CheckedTextView and use different attributes like checked, gravity etc. Later, it will be called in Kotlin file to add more functionalities. <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"> <CheckedTextView android:id="@+id/ctv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:gravity="center" android:text="@string/checkedTextView"/> </LinearLayout> Make some changes in strings.xml file like app_name and other strings used in Kotlin file. <resources> <string name="app_name">CheckedTextViewInKotlin</string> <string name="msg_shown">CTView is:</string> <string name="checked">checked</string> <string name="unchecked">unchecked</string> <string name="checkedTextView">CheckedTextView</string></resources> Here, we first declare a checkedTextView variable and find the xml checkedTextView by using id. val CTView = findViewById(R.id.ctv) then, check using the conditional statement like if (CTView.isChecked) android.R.drawable.checkbox_on_background else android.R.drawable.checkbox_off_background) In the end, we declare a variable msg to print the value when we checked the text view. package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.CheckedTextViewimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val CTView = findViewById<CheckedTextView>(R.id.ctv) if (CTView != null) { CTView.isChecked = false CTView.setCheckMarkDrawable( android.R.drawable.checkbox_off_background) CTView.setOnClickListener { CTView.isChecked = !CTView.isChecked CTView.setCheckMarkDrawable( if (CTView.isChecked) android.R.drawable.checkbox_on_background else android.R.drawable.checkbox_off_background) val msg = getString(R.string.msg_shown)+ " " + getString(if (CTView.isChecked) R.string.checked else R.string.unchecked) Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show() } } }} This file contains the information like app_name specified in the strings.xml and other important android information. <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.geeksforgeeks.myfirstkotlinapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity></application> </manifest> Android-View Kotlin Android Picked Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Resource Raw Folder in Android Studio Services in Android with Example Content Providers in Android with Example Broadcast Receiver in Android With Example Android UI Layouts Kotlin Array Services in Android with Example Content Providers in Android with Example
[ { "code": null, "e": 25237, "s": 25209, "text": "\n18 Feb, 2021" }, { "code": null, "e": 25454, "s": 25237, "text": "CheckedTextView is used to implement checkable interface where one can tick or check the needed or required items and leave out the rest. In this article, we will be discussing how to make a CheckedTextView manually." }, { "code": null, "e": 25586, "s": 25454, "text": "The first step is to make or create a project in Android Studio. Here, we will be creating a project named CheckedTextViewInKotlin." }, { "code": null, "e": 25614, "s": 25586, "text": "For creating a new project:" }, { "code": null, "e": 25792, "s": 25614, "text": "Click on File, then New => New ProjectThen, check Include Kotlin Support and click next button.Select minimum SDK, whatever you need.Select Empty activity and then click finish." }, { "code": null, "e": 25831, "s": 25792, "text": "Click on File, then New => New Project" }, { "code": null, "e": 25889, "s": 25831, "text": "Then, check Include Kotlin Support and click next button." }, { "code": null, "e": 25928, "s": 25889, "text": "Select minimum SDK, whatever you need." }, { "code": null, "e": 25973, "s": 25928, "text": "Select Empty activity and then click finish." }, { "code": null, "e": 26144, "s": 25973, "text": "In this file, we will add the CheckedTextView and use different attributes like checked, gravity etc. Later, it will be called in Kotlin file to add more functionalities." }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/container\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" android:orientation=\"vertical\"> <CheckedTextView android:id=\"@+id/ctv\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:checked=\"true\" android:gravity=\"center\" android:text=\"@string/checkedTextView\"/> </LinearLayout>", "e": 26751, "s": 26144, "text": null }, { "code": null, "e": 26842, "s": 26751, "text": "Make some changes in strings.xml file like app_name and other strings used in Kotlin file." }, { "code": "<resources> <string name=\"app_name\">CheckedTextViewInKotlin</string> <string name=\"msg_shown\">CTView is:</string> <string name=\"checked\">checked</string> <string name=\"unchecked\">unchecked</string> <string name=\"checkedTextView\">CheckedTextView</string></resources>", "e": 27123, "s": 26842, "text": null }, { "code": null, "e": 27219, "s": 27123, "text": "Here, we first declare a checkedTextView variable and find the xml checkedTextView by using id." }, { "code": null, "e": 27255, "s": 27219, "text": "val CTView = findViewById(R.id.ctv)" }, { "code": null, "e": 27304, "s": 27255, "text": "then, check using the conditional statement like" }, { "code": null, "e": 27426, "s": 27304, "text": "if (CTView.isChecked)\n android.R.drawable.checkbox_on_background\nelse\n android.R.drawable.checkbox_off_background)\n" }, { "code": null, "e": 27514, "s": 27426, "text": "In the end, we declare a variable msg to print the value when we checked the text view." }, { "code": "package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.CheckedTextViewimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val CTView = findViewById<CheckedTextView>(R.id.ctv) if (CTView != null) { CTView.isChecked = false CTView.setCheckMarkDrawable( android.R.drawable.checkbox_off_background) CTView.setOnClickListener { CTView.isChecked = !CTView.isChecked CTView.setCheckMarkDrawable( if (CTView.isChecked) android.R.drawable.checkbox_on_background else android.R.drawable.checkbox_off_background) val msg = getString(R.string.msg_shown)+ \" \" + getString(if (CTView.isChecked) R.string.checked else R.string.unchecked) Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show() } } }}", "e": 28760, "s": 27514, "text": null }, { "code": null, "e": 28879, "s": 28760, "text": "This file contains the information like app_name specified in the strings.xml and other important android information." }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"package=\"com.geeksforgeeks.myfirstkotlinapp\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity></application> </manifest>", "e": 29534, "s": 28879, "text": null }, { "code": null, "e": 29549, "s": 29536, "text": "Android-View" }, { "code": null, "e": 29564, "s": 29549, "text": "Kotlin Android" }, { "code": null, "e": 29571, "s": 29564, "text": "Picked" }, { "code": null, "e": 29579, "s": 29571, "text": "Android" }, { "code": null, "e": 29586, "s": 29579, "text": "Kotlin" }, { "code": null, "e": 29594, "s": 29586, "text": "Android" }, { "code": null, "e": 29692, "s": 29594, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29750, "s": 29692, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 29793, "s": 29750, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 29831, "s": 29793, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 29864, "s": 29831, "text": "Services in Android with Example" }, { "code": null, "e": 29906, "s": 29864, "text": "Content Providers in Android with Example" }, { "code": null, "e": 29949, "s": 29906, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 29968, "s": 29949, "text": "Android UI Layouts" }, { "code": null, "e": 29981, "s": 29968, "text": "Kotlin Array" }, { "code": null, "e": 30014, "s": 29981, "text": "Services in Android with Example" } ]
How to Change the Color of a Graph Plot in Matplotlib with Python? - GeeksforGeeks
12 Nov, 2020 Prerequisite: Matplotlib Python offers a wide range of libraries for plotting graphs and Matplotlib is one of them. Matplotlib is simple and easy to use a library that is used to create quality graphs. The pyplot library of matplotlib comprises commands and methods that makes matplotlib work like matlab. The pyplot module is used to set the graph labels, type of chart and the color of the chart. The following methods are used for the creation of graph and corresponding color change of the graph. Syntax: matplotlib.pyplot.bar(x, height, width, bottom, align, **kwargs) Parameter: x : sequence of scalers along the x axis height : sequence of scaler determining the height of bar ie y-axis width : width of each bar bottom : Used to specify the starting value along the Y axis.(Optional) align : alignment of the bar **kwargs : other parameters one of which is color which obviously specifies the color of the graph. Return Value: Returns the graph plotted from the specified columns of the dataset. In this article, we are using a dataset downloaded from kaggel.com for the examples given below. The dataset used represent countries against the number of confirmed covid-19 cases. The dataset can be downloaded from the given link: Link to the dataset: Corona virus report Example 1: Python3 # import packagesimport pandas as pdimport matplotlibimport matplotlib.pyplot as plt # import datasetdf = pd.read_csv('country_wise_latest.csv') # select required columnscountry = df['Country/Region'].head(10)confirmed = df['Confirmed'].head(10) # plotting graphplt.xlabel('Country')plt.ylabel('Confirmed Cases')plt.bar(country, confirmed, color='green', width=0.4) # display plotplt.show() Output Example 2: Python3 # import packagesimport pandas as pdimport matplotlibimport matplotlib.pyplot as plt # import datasetdf = pd.read_csv('country_wise_latest.csv') # select required datacountry = df['Country/Region'].head(20)confirmed = df['Active'].head(20) # plot graphplt.xlabel('Country')plt.ylabel('Active Cases')plt.bar(country, confirmed, color='maroon', width=0.4) # display plotplt.show() Output Python-matplotlib Technical Scripter 2020 Python Technical Scripter 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": 25562, "s": 25537, "text": "Prerequisite: Matplotlib" }, { "code": null, "e": 26038, "s": 25562, "text": "Python offers a wide range of libraries for plotting graphs and Matplotlib is one of them. Matplotlib is simple and easy to use a library that is used to create quality graphs. The pyplot library of matplotlib comprises commands and methods that makes matplotlib work like matlab. The pyplot module is used to set the graph labels, type of chart and the color of the chart. The following methods are used for the creation of graph and corresponding color change of the graph." }, { "code": null, "e": 26111, "s": 26038, "text": "Syntax: matplotlib.pyplot.bar(x, height, width, bottom, align, **kwargs)" }, { "code": null, "e": 26122, "s": 26111, "text": "Parameter:" }, { "code": null, "e": 26163, "s": 26122, "text": "x : sequence of scalers along the x axis" }, { "code": null, "e": 26231, "s": 26163, "text": "height : sequence of scaler determining the height of bar ie y-axis" }, { "code": null, "e": 26257, "s": 26231, "text": "width : width of each bar" }, { "code": null, "e": 26329, "s": 26257, "text": "bottom : Used to specify the starting value along the Y axis.(Optional)" }, { "code": null, "e": 26358, "s": 26329, "text": "align : alignment of the bar" }, { "code": null, "e": 26458, "s": 26358, "text": "**kwargs : other parameters one of which is color which obviously specifies the color of the graph." }, { "code": null, "e": 26541, "s": 26458, "text": "Return Value: Returns the graph plotted from the specified columns of the dataset." }, { "code": null, "e": 26774, "s": 26541, "text": "In this article, we are using a dataset downloaded from kaggel.com for the examples given below. The dataset used represent countries against the number of confirmed covid-19 cases. The dataset can be downloaded from the given link:" }, { "code": null, "e": 26815, "s": 26774, "text": "Link to the dataset: Corona virus report" }, { "code": null, "e": 26826, "s": 26815, "text": "Example 1:" }, { "code": null, "e": 26834, "s": 26826, "text": "Python3" }, { "code": "# import packagesimport pandas as pdimport matplotlibimport matplotlib.pyplot as plt # import datasetdf = pd.read_csv('country_wise_latest.csv') # select required columnscountry = df['Country/Region'].head(10)confirmed = df['Confirmed'].head(10) # plotting graphplt.xlabel('Country')plt.ylabel('Confirmed Cases')plt.bar(country, confirmed, color='green', width=0.4) # display plotplt.show()", "e": 27229, "s": 26834, "text": null }, { "code": null, "e": 27236, "s": 27229, "text": "Output" }, { "code": null, "e": 27247, "s": 27236, "text": "Example 2:" }, { "code": null, "e": 27255, "s": 27247, "text": "Python3" }, { "code": "# import packagesimport pandas as pdimport matplotlibimport matplotlib.pyplot as plt # import datasetdf = pd.read_csv('country_wise_latest.csv') # select required datacountry = df['Country/Region'].head(20)confirmed = df['Active'].head(20) # plot graphplt.xlabel('Country')plt.ylabel('Active Cases')plt.bar(country, confirmed, color='maroon', width=0.4) # display plotplt.show()", "e": 27638, "s": 27255, "text": null }, { "code": null, "e": 27645, "s": 27638, "text": "Output" }, { "code": null, "e": 27663, "s": 27645, "text": "Python-matplotlib" }, { "code": null, "e": 27687, "s": 27663, "text": "Technical Scripter 2020" }, { "code": null, "e": 27694, "s": 27687, "text": "Python" }, { "code": null, "e": 27713, "s": 27694, "text": "Technical Scripter" }, { "code": null, "e": 27811, "s": 27713, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27843, "s": 27811, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27885, "s": 27843, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27927, "s": 27885, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27954, "s": 27927, "text": "Python Classes and Objects" }, { "code": null, "e": 28010, "s": 27954, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28032, "s": 28010, "text": "Defaultdict in Python" }, { "code": null, "e": 28071, "s": 28032, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28102, "s": 28071, "text": "Python | os.path.join() method" }, { "code": null, "e": 28131, "s": 28102, "text": "Create a directory in Python" } ]
Selection Sort VS Bubble Sort - GeeksforGeeks
21 Jan, 2022 In this, we will cover the comparison between Selection Sort VS Bubble Sort. The resources required by Selection Sort & Bubble Sort algorithms on the basis of Time and Space Complexity are as follows. Time Complexity - Space Complexity - Let’s dive deep into the working of these algorithms. Selection Sort : The selection sort algorithm generally is the first sorting algorithm that is taught to us. Here in every iteration of the inner loop, the smallest element is replaced with the starting element in each loop. After the end of each loop, we increment the starting position by 1 and run it till the second last element in the array. Hence, by doing so at the end of the outer loop we will be having a sorted array. The image below explains the iteration of Selection Sort Algorithm. Here we can simplify the selection sort algorithm by saying that the sorting here is done on the basis of the smallest to the largest element. The smallest element is first sorted and then the second smallest element and so on. Implementation of Selection Sort : Below is the implementation of the above-explained algorithm. C++ Java Python3 C# Javascript #include <iostream>using namespace std;void Selection_Sort(int arr[], int n) { for(int i = 0; i < n - 1; ++i) { int min_index = i; for(int j = i + 1; j < n; ++j) { if(arr[j] < arr[min_index]) min_index = j; } swap(arr[i], arr[min_index]); }}int main(){ int n = 5; int arr[5] = {2, 0, 1, 4, 3}; Selection_Sort(arr, n); cout<<"The Sorted Array by using Selection Sort is : "; for(int i = 0; i < n; ++i) cout<<arr[i]<<" "; return 0;} class GFG{ static void Selection_Sort(int arr[], int n) { for(int i = 0; i < n - 1; ++i) { int min_index = i; for(int j = i + 1; j < n; ++j) { if(arr[j] < arr[min_index]) min_index = j; } int temp = arr[i]; arr[i] = arr[min_index]; arr[min_index] = temp; } } // Driver code public static void main(String[] args) { int n = 5; int arr[] = {2, 0, 1, 4, 3}; Selection_Sort(arr, n); System.out.print("The Sorted Array by using Selection Sort is : "); for(int i = 0; i < n; ++i) System.out.print(arr[i] + " "); }} // This code is contributed by aashish1995 def Selection_Sort(arr, n): for i in range(n - 1): min_index = i for j in range(i + 1, n): if (arr[j] < arr[min_index]): min_index = j arr[i], arr[min_index] = arr[min_index], arr[i] # Driver Coden = 5arr = [ 2, 0, 1, 4, 3 ]Selection_Sort(arr, n) print("The Sorted Array by using " \ "Selection Sort is : ", end = '')for i in range(n): print(arr[i], end = " ") # This code is contributed by SHUBHAMSINGH10 using System; public class GFG{ static void Selection_Sort(int []arr, int n) { for(int i = 0; i < n - 1; ++i) { int min_index = i; for(int j = i + 1; j < n; ++j) { if(arr[j] < arr[min_index]) min_index = j; } int temp = arr[i]; arr[i] = arr[min_index]; arr[min_index] = temp; } } // Driver code public static void Main(String[] args) { int n = 5; int []arr = {2, 0, 1, 4, 3}; Selection_Sort(arr, n); Console.Write("The Sorted Array by using Selection Sort is : "); for(int i = 0; i < n; ++i) Console.Write(arr[i] + " "); }} // This code is contributed by aashish1995 <script> // JavaScript program for above approach function Selection_Sort(arr, n) { for(let i = 0; i < n - 1; ++i) { let min_index = i; for(let j = i + 1; j < n; ++j) { if(arr[j] < arr[min_index]) min_index = j; } let temp = arr[i]; arr[i] = arr[min_index]; arr[min_index] = temp; } } // Driver Code let n = 5; let arr = [2, 0, 1, 4, 3]; Selection_Sort(arr, n); document.write("The Sorted Array by using Selection Sort is : "); for(let i = 0; i < n; ++i) document.write(arr[i] + " "); </script> The Sorted Array by using Selection Sort is : 0 1 2 3 4 Bubble Sort : The bubble sort algorithm might look a little bit confusing when we first study it. But here is the easy explanation of it. Here swapping is carried on in two ways. In every iteration of the outer loop, the largest element is found and swapped with the last element in the loop. In the inner loop, we do pairwise swapping of two consecutive elements. In every inner loop, we go from the first element to the one less element we went in the previous loop. The image below shows the 1st iteration of the inner loop in the Bubble Sort Algorithm. Here we can simplify the bubble sort algorithm by saying that the sorting here is done on the basis of the largest to the smallest element. The largest element is first kept in the last location in the array. Then the second largest element in the second last location as so on. Implementation of Bubble Sort : Below is the implementation of the above-explained algorithm. C++ Java Python3 C# Javascript #include <iostream>using namespace std;void Bubble_Sort(int arr[], int n) { for(int i = 1; i < n; ++i) { for(int j = 0; j <= (n - i - 1); ++j) { if(arr[j] > arr[j + 1]) swap(arr[j], arr[j + 1]); } }} int main(){ int n = 5; int arr[5] = {2, 0, 1, 4, 3}; Bubble_Sort(arr, n); cout<<"The Sorted Array by using Bubble Sort is : "; for(int i = 0; i < n; ++i) cout<<arr[i]<<" "; return 0;} import java.io.*; class GFG{ static void Bubble_Sort(int arr[], int n) { for(int i = 1; i < n; ++i) { for(int j = 0; j <= (n - i - 1); ++j) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } }} // Driver codepublic static void main(String[] args){ int n = 5; int arr[] = { 2, 0, 1, 4, 3 }; Bubble_Sort(arr, n); System.out.print("The Sorted Array by using Bubble Sort is : "); for(int i = 0; i < n; ++i) System.out.print(arr[i]+" ");}} // This code is contributed by Shubhamsingh10 def Bubble_Sort(arr, n): for i in range(1, n): for j in range(0, n - i): if (arr[j] > arr[j + 1]): arr[j], arr[j + 1] = arr[j + 1], arr[j] return arr # Driver Coden = 5arr = [ 2, 0, 1, 4, 3 ]arr = Bubble_Sort(arr, n) print("The Sorted Array by using Bubble Sort is : ", end = '')for i in range(n): print(arr[i], end = " ") # This code is contributed by Shubhamsingh10 // C# program for the above approachusing System; public class GFG{ static void Bubble_Sort(int[] arr, int n) { for(int i = 1; i < n; ++i) { for(int j = 0; j <= (n - i - 1); ++j) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } // Driver Code static public void Main () { int n = 5; int[] arr = { 2, 0, 1, 4, 3 }; Bubble_Sort(arr, n); Console.Write("The Sorted Array by using Bubble Sort is : "); for(int i = 0; i < n; ++i){ Console.Write(arr[i]+" "); } }} // This code is contributed by Shubhamsingh10 <script>// Javascript program for the above approach function Bubble_Sort( arr, n) { for(var i = 1; i < n; ++i) { for(var j = 0; j <= (n - i - 1); ++j) { if(arr[j] > arr[j + 1]){ var temm = arr[j]; arr[j] = arr[j + 1]; arr[j+1] = temm; } } }} var n = 5;var arr = [2, 0, 1, 4, 3];Bubble_Sort(arr, n);document.write("The Sorted Array by using Bubble Sort is : ");for(var i = 0; i < n; i++){ document.write(arr[i]+" ");} // This code is contributed by Shubhamsingh10</script> The Sorted Array by using Bubble Sort is : 0 1 2 3 4 Adding Intelligence To Bubble Sort: We must account for the fact that even if our data is in sorted form initially, our current algorithm will perform all the iterations.As shown by above code, we swap two elements (say i and i+1) when arr[i] > arr[i+1]. Therefore, even if our data is sorted already (or is sorted just after few iterations) our algorithm will still run,However, we can tweak our code so that our algorithm recognizes when given data is sorted and no further iterations are required. We can achieve this by simply adding a “flag” variable. Initialize this “flag” variable to false outside inner loop and set it to true if at any point ( arr[j] > arr[j+1] ) condition is true.After inner loop is exited, check flag. If flag == true i.e, it was changed and swap operation was carried out. However, if flag == false, it means that no swap was carried out for entire iteration and hence our data is now sorted and no further iterations are required. We must account for the fact that even if our data is in sorted form initially, our current algorithm will perform all the iterations. As shown by above code, we swap two elements (say i and i+1) when arr[i] > arr[i+1]. Therefore, even if our data is sorted already (or is sorted just after few iterations) our algorithm will still run, However, we can tweak our code so that our algorithm recognizes when given data is sorted and no further iterations are required. We can achieve this by simply adding a “flag” variable. Initialize this “flag” variable to false outside inner loop and set it to true if at any point ( arr[j] > arr[j+1] ) condition is true. After inner loop is exited, check flag. If flag == true i.e, it was changed and swap operation was carried out. However, if flag == false, it means that no swap was carried out for entire iteration and hence our data is now sorted and no further iterations are required. C++ Java Python3 C# Javascript // C++ program for the above approach#include <iostream>using namespace std; // Function for bubble sortvoid Bubble_Sort(int arr[], int n){ bool flag; // Iterate from 1 to n - 1 for (int i = 1; i < n; ++i) { flag = false; // Iterate from 0 to n - i - 1 for (int j = 0; j <= (n - i - 1); ++j) { if (arr[j] > arr[j + 1]) { swap(arr[j], arr[j + 1]); flag = true; } } if (flag == false) break; }} // Driver Codeint main(){ int n = 5; int arr[5] = { 2, 0, 1, 4, 3 }; Bubble_Sort(arr, n); cout << "The Sorted Array by using Bubble Sort is : "; for (int i = 0; i < n; ++i) cout << arr[i] << " "; return 0;} // Java program for the above approachimport java.io.*; class GFG{ // Function for bubble sortstatic void Bubble_Sort(int[] arr, int n){ boolean flag; // Iterate from 1 to n - 1 for(int i = 1; i < n; ++i) { flag = false; // Iterate from 0 to n - i - 1 for(int j = 0; j <= (n - i - 1); ++j) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; flag = true; } } if (flag == false) break; }} // Driver Codepublic static void main(String[] args){ int n = 5; int[] arr = { 2, 0, 1, 4, 3 }; Bubble_Sort(arr, n); System.out.print("The Sorted Array by " + "using Bubble Sort is : "); for(int i = 0; i < n; ++i) System.out.print(arr[i] + " ");}} // This code is contributed by shubhamsingh10 # Python3 program for the above approach # Function for bubble sortdef Bubble_Sort(arr, n): flag = True # Iterate from 1 to n - 1 for i in range(1,n): flag = False # Iterate from 0 to n - i - 1 for j in range(n-i): if (arr[j] > arr[j + 1]): arr[j], arr[j + 1] = arr[j + 1], arr[j] flag = True if (flag == False): break # Driver Coden = 5arr = [2, 0, 1, 4, 3]Bubble_Sort(arr, n)print("The Sorted Array by using Bubble Sort is : ", end='')for i in range(n): print(arr[i], end= " ") # This code is contributed by ShubhamSingh10 // C# program for the above approachusing System;public class GFG{ // Function for bubble sort static void Bubble_Sort(int[] arr, int n) { bool flag; // Iterate from 1 to n - 1 for (int i = 1; i < n; ++i) { flag = false; // Iterate from 0 to n - i - 1 for (int j = 0; j <= (n - i - 1); ++j) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; flag = true; } } if (flag == false) break; } } // Driver Code static public void Main () { int n = 5; int[] arr = { 2, 0, 1, 4, 3 }; Bubble_Sort(arr, n); Console.Write("The Sorted Array by using Bubble Sort is : "); for (int i = 0; i < n; ++i) Console.Write(arr[i] + " "); } } // This code is contributed by shubhamsingh10. <script> // JavaScript program for the above approach // Function for bubble sortfunction Bubble_Sort(arr, n){ Boolean(flag = true); // Iterate from 1 to n - 1 for(var i = 1; i < n; ++i) { flag = false; // Iterate from 0 to n - i - 1 for(var j = 0; j <= (n - i - 1); ++j) { if (arr[j] > arr[j + 1]) { var temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; flag = true; } } if (flag == false) break; }} // Driver Codevar n = 5;var arr = [ 2, 0, 1, 4, 3 ];Bubble_Sort(arr, n); document.write("The Sorted Array by " + "using Bubble Sort is : "); for(var i = 0; i < n; ++i) document.write(arr[i] + " "); // This code is contributed by shivanisinghss2110 </script> The Sorted Array by using Bubble Sort is : 0 1 2 3 4 NOTE: This little tweak doesn’t change the worst case time complexity of the bubble sort algorithm but can improve its run time for particular cases. References : Lectures readingImplement bubble sort c aashish1995 nerdcore chinmoy1997pal SHUBHAMSINGH10 shivanisinghss2110 shivamdhyani15 defaultacc BubbleSort selection-sort Algorithms C++ Difference Between Sorting Sorting Algorithms CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? Difference between Algorithm, Pseudocode and Program K means Clustering - Introduction Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Vector in C++ STL Arrays in C/C++ Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL)
[ { "code": null, "e": 25942, "s": 25914, "text": "\n21 Jan, 2022" }, { "code": null, "e": 26144, "s": 25942, "text": "In this, we will cover the comparison between Selection Sort VS Bubble Sort. The resources required by Selection Sort & Bubble Sort algorithms on the basis of Time and Space Complexity are as follows. " }, { "code": null, "e": 26183, "s": 26144, "text": "Time Complexity - \nSpace Complexity - " }, { "code": null, "e": 26238, "s": 26183, "text": "Let’s dive deep into the working of these algorithms. " }, { "code": null, "e": 26667, "s": 26238, "text": "Selection Sort : The selection sort algorithm generally is the first sorting algorithm that is taught to us. Here in every iteration of the inner loop, the smallest element is replaced with the starting element in each loop. After the end of each loop, we increment the starting position by 1 and run it till the second last element in the array. Hence, by doing so at the end of the outer loop we will be having a sorted array." }, { "code": null, "e": 26737, "s": 26667, "text": "The image below explains the iteration of Selection Sort Algorithm. " }, { "code": null, "e": 26966, "s": 26737, "text": "Here we can simplify the selection sort algorithm by saying that the sorting here is done on the basis of the smallest to the largest element. The smallest element is first sorted and then the second smallest element and so on. " }, { "code": null, "e": 27002, "s": 26966, "text": "Implementation of Selection Sort : " }, { "code": null, "e": 27064, "s": 27002, "text": "Below is the implementation of the above-explained algorithm." }, { "code": null, "e": 27068, "s": 27064, "text": "C++" }, { "code": null, "e": 27073, "s": 27068, "text": "Java" }, { "code": null, "e": 27081, "s": 27073, "text": "Python3" }, { "code": null, "e": 27084, "s": 27081, "text": "C#" }, { "code": null, "e": 27095, "s": 27084, "text": "Javascript" }, { "code": "#include <iostream>using namespace std;void Selection_Sort(int arr[], int n) { for(int i = 0; i < n - 1; ++i) { int min_index = i; for(int j = i + 1; j < n; ++j) { if(arr[j] < arr[min_index]) min_index = j; } swap(arr[i], arr[min_index]); }}int main(){ int n = 5; int arr[5] = {2, 0, 1, 4, 3}; Selection_Sort(arr, n); cout<<\"The Sorted Array by using Selection Sort is : \"; for(int i = 0; i < n; ++i) cout<<arr[i]<<\" \"; return 0;}", "e": 27626, "s": 27095, "text": null }, { "code": "class GFG{ static void Selection_Sort(int arr[], int n) { for(int i = 0; i < n - 1; ++i) { int min_index = i; for(int j = i + 1; j < n; ++j) { if(arr[j] < arr[min_index]) min_index = j; } int temp = arr[i]; arr[i] = arr[min_index]; arr[min_index] = temp; } } // Driver code public static void main(String[] args) { int n = 5; int arr[] = {2, 0, 1, 4, 3}; Selection_Sort(arr, n); System.out.print(\"The Sorted Array by using Selection Sort is : \"); for(int i = 0; i < n; ++i) System.out.print(arr[i] + \" \"); }} // This code is contributed by aashish1995", "e": 28272, "s": 27626, "text": null }, { "code": "def Selection_Sort(arr, n): for i in range(n - 1): min_index = i for j in range(i + 1, n): if (arr[j] < arr[min_index]): min_index = j arr[i], arr[min_index] = arr[min_index], arr[i] # Driver Coden = 5arr = [ 2, 0, 1, 4, 3 ]Selection_Sort(arr, n) print(\"The Sorted Array by using \" \\ \"Selection Sort is : \", end = '')for i in range(n): print(arr[i], end = \" \") # This code is contributed by SHUBHAMSINGH10", "e": 28781, "s": 28272, "text": null }, { "code": "using System; public class GFG{ static void Selection_Sort(int []arr, int n) { for(int i = 0; i < n - 1; ++i) { int min_index = i; for(int j = i + 1; j < n; ++j) { if(arr[j] < arr[min_index]) min_index = j; } int temp = arr[i]; arr[i] = arr[min_index]; arr[min_index] = temp; } } // Driver code public static void Main(String[] args) { int n = 5; int []arr = {2, 0, 1, 4, 3}; Selection_Sort(arr, n); Console.Write(\"The Sorted Array by using Selection Sort is : \"); for(int i = 0; i < n; ++i) Console.Write(arr[i] + \" \"); }} // This code is contributed by aashish1995", "e": 29442, "s": 28781, "text": null }, { "code": "<script> // JavaScript program for above approach function Selection_Sort(arr, n) { for(let i = 0; i < n - 1; ++i) { let min_index = i; for(let j = i + 1; j < n; ++j) { if(arr[j] < arr[min_index]) min_index = j; } let temp = arr[i]; arr[i] = arr[min_index]; arr[min_index] = temp; } } // Driver Code let n = 5; let arr = [2, 0, 1, 4, 3]; Selection_Sort(arr, n); document.write(\"The Sorted Array by using Selection Sort is : \"); for(let i = 0; i < n; ++i) document.write(arr[i] + \" \"); </script>", "e": 30024, "s": 29442, "text": null }, { "code": null, "e": 30081, "s": 30024, "text": "The Sorted Array by using Selection Sort is : 0 1 2 3 4 " }, { "code": null, "e": 30638, "s": 30081, "text": "Bubble Sort : The bubble sort algorithm might look a little bit confusing when we first study it. But here is the easy explanation of it. Here swapping is carried on in two ways. In every iteration of the outer loop, the largest element is found and swapped with the last element in the loop. In the inner loop, we do pairwise swapping of two consecutive elements. In every inner loop, we go from the first element to the one less element we went in the previous loop. The image below shows the 1st iteration of the inner loop in the Bubble Sort Algorithm." }, { "code": null, "e": 30917, "s": 30638, "text": "Here we can simplify the bubble sort algorithm by saying that the sorting here is done on the basis of the largest to the smallest element. The largest element is first kept in the last location in the array. Then the second largest element in the second last location as so on." }, { "code": null, "e": 31011, "s": 30917, "text": "Implementation of Bubble Sort : Below is the implementation of the above-explained algorithm." }, { "code": null, "e": 31015, "s": 31011, "text": "C++" }, { "code": null, "e": 31020, "s": 31015, "text": "Java" }, { "code": null, "e": 31028, "s": 31020, "text": "Python3" }, { "code": null, "e": 31031, "s": 31028, "text": "C#" }, { "code": null, "e": 31042, "s": 31031, "text": "Javascript" }, { "code": "#include <iostream>using namespace std;void Bubble_Sort(int arr[], int n) { for(int i = 1; i < n; ++i) { for(int j = 0; j <= (n - i - 1); ++j) { if(arr[j] > arr[j + 1]) swap(arr[j], arr[j + 1]); } }} int main(){ int n = 5; int arr[5] = {2, 0, 1, 4, 3}; Bubble_Sort(arr, n); cout<<\"The Sorted Array by using Bubble Sort is : \"; for(int i = 0; i < n; ++i) cout<<arr[i]<<\" \"; return 0;}", "e": 31529, "s": 31042, "text": null }, { "code": "import java.io.*; class GFG{ static void Bubble_Sort(int arr[], int n) { for(int i = 1; i < n; ++i) { for(int j = 0; j <= (n - i - 1); ++j) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } }} // Driver codepublic static void main(String[] args){ int n = 5; int arr[] = { 2, 0, 1, 4, 3 }; Bubble_Sort(arr, n); System.out.print(\"The Sorted Array by using Bubble Sort is : \"); for(int i = 0; i < n; ++i) System.out.print(arr[i]+\" \");}} // This code is contributed by Shubhamsingh10", "e": 32206, "s": 31529, "text": null }, { "code": "def Bubble_Sort(arr, n): for i in range(1, n): for j in range(0, n - i): if (arr[j] > arr[j + 1]): arr[j], arr[j + 1] = arr[j + 1], arr[j] return arr # Driver Coden = 5arr = [ 2, 0, 1, 4, 3 ]arr = Bubble_Sort(arr, n) print(\"The Sorted Array by using Bubble Sort is : \", end = '')for i in range(n): print(arr[i], end = \" \") # This code is contributed by Shubhamsingh10", "e": 32637, "s": 32206, "text": null }, { "code": "// C# program for the above approachusing System; public class GFG{ static void Bubble_Sort(int[] arr, int n) { for(int i = 1; i < n; ++i) { for(int j = 0; j <= (n - i - 1); ++j) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } // Driver Code static public void Main () { int n = 5; int[] arr = { 2, 0, 1, 4, 3 }; Bubble_Sort(arr, n); Console.Write(\"The Sorted Array by using Bubble Sort is : \"); for(int i = 0; i < n; ++i){ Console.Write(arr[i]+\" \"); } }} // This code is contributed by Shubhamsingh10", "e": 33457, "s": 32637, "text": null }, { "code": "<script>// Javascript program for the above approach function Bubble_Sort( arr, n) { for(var i = 1; i < n; ++i) { for(var j = 0; j <= (n - i - 1); ++j) { if(arr[j] > arr[j + 1]){ var temm = arr[j]; arr[j] = arr[j + 1]; arr[j+1] = temm; } } }} var n = 5;var arr = [2, 0, 1, 4, 3];Bubble_Sort(arr, n);document.write(\"The Sorted Array by using Bubble Sort is : \");for(var i = 0; i < n; i++){ document.write(arr[i]+\" \");} // This code is contributed by Shubhamsingh10</script>", "e": 34045, "s": 33457, "text": null }, { "code": null, "e": 34099, "s": 34045, "text": "The Sorted Array by using Bubble Sort is : 0 1 2 3 4 " }, { "code": null, "e": 34135, "s": 34099, "text": "Adding Intelligence To Bubble Sort:" }, { "code": null, "e": 35062, "s": 34135, "text": "We must account for the fact that even if our data is in sorted form initially, our current algorithm will perform all the iterations.As shown by above code, we swap two elements (say i and i+1) when arr[i] > arr[i+1]. Therefore, even if our data is sorted already (or is sorted just after few iterations) our algorithm will still run,However, we can tweak our code so that our algorithm recognizes when given data is sorted and no further iterations are required. We can achieve this by simply adding a “flag” variable. Initialize this “flag” variable to false outside inner loop and set it to true if at any point ( arr[j] > arr[j+1] ) condition is true.After inner loop is exited, check flag. If flag == true i.e, it was changed and swap operation was carried out. However, if flag == false, it means that no swap was carried out for entire iteration and hence our data is now sorted and no further iterations are required." }, { "code": null, "e": 35197, "s": 35062, "text": "We must account for the fact that even if our data is in sorted form initially, our current algorithm will perform all the iterations." }, { "code": null, "e": 35399, "s": 35197, "text": "As shown by above code, we swap two elements (say i and i+1) when arr[i] > arr[i+1]. Therefore, even if our data is sorted already (or is sorted just after few iterations) our algorithm will still run," }, { "code": null, "e": 35530, "s": 35399, "text": "However, we can tweak our code so that our algorithm recognizes when given data is sorted and no further iterations are required. " }, { "code": null, "e": 35722, "s": 35530, "text": "We can achieve this by simply adding a “flag” variable. Initialize this “flag” variable to false outside inner loop and set it to true if at any point ( arr[j] > arr[j+1] ) condition is true." }, { "code": null, "e": 35993, "s": 35722, "text": "After inner loop is exited, check flag. If flag == true i.e, it was changed and swap operation was carried out. However, if flag == false, it means that no swap was carried out for entire iteration and hence our data is now sorted and no further iterations are required." }, { "code": null, "e": 35997, "s": 35993, "text": "C++" }, { "code": null, "e": 36002, "s": 35997, "text": "Java" }, { "code": null, "e": 36010, "s": 36002, "text": "Python3" }, { "code": null, "e": 36013, "s": 36010, "text": "C#" }, { "code": null, "e": 36024, "s": 36013, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <iostream>using namespace std; // Function for bubble sortvoid Bubble_Sort(int arr[], int n){ bool flag; // Iterate from 1 to n - 1 for (int i = 1; i < n; ++i) { flag = false; // Iterate from 0 to n - i - 1 for (int j = 0; j <= (n - i - 1); ++j) { if (arr[j] > arr[j + 1]) { swap(arr[j], arr[j + 1]); flag = true; } } if (flag == false) break; }} // Driver Codeint main(){ int n = 5; int arr[5] = { 2, 0, 1, 4, 3 }; Bubble_Sort(arr, n); cout << \"The Sorted Array by using Bubble Sort is : \"; for (int i = 0; i < n; ++i) cout << arr[i] << \" \"; return 0;}", "e": 36770, "s": 36024, "text": null }, { "code": "// Java program for the above approachimport java.io.*; class GFG{ // Function for bubble sortstatic void Bubble_Sort(int[] arr, int n){ boolean flag; // Iterate from 1 to n - 1 for(int i = 1; i < n; ++i) { flag = false; // Iterate from 0 to n - i - 1 for(int j = 0; j <= (n - i - 1); ++j) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; flag = true; } } if (flag == false) break; }} // Driver Codepublic static void main(String[] args){ int n = 5; int[] arr = { 2, 0, 1, 4, 3 }; Bubble_Sort(arr, n); System.out.print(\"The Sorted Array by \" + \"using Bubble Sort is : \"); for(int i = 0; i < n; ++i) System.out.print(arr[i] + \" \");}} // This code is contributed by shubhamsingh10", "e": 37711, "s": 36770, "text": null }, { "code": "# Python3 program for the above approach # Function for bubble sortdef Bubble_Sort(arr, n): flag = True # Iterate from 1 to n - 1 for i in range(1,n): flag = False # Iterate from 0 to n - i - 1 for j in range(n-i): if (arr[j] > arr[j + 1]): arr[j], arr[j + 1] = arr[j + 1], arr[j] flag = True if (flag == False): break # Driver Coden = 5arr = [2, 0, 1, 4, 3]Bubble_Sort(arr, n)print(\"The Sorted Array by using Bubble Sort is : \", end='')for i in range(n): print(arr[i], end= \" \") # This code is contributed by ShubhamSingh10", "e": 38350, "s": 37711, "text": null }, { "code": "// C# program for the above approachusing System;public class GFG{ // Function for bubble sort static void Bubble_Sort(int[] arr, int n) { bool flag; // Iterate from 1 to n - 1 for (int i = 1; i < n; ++i) { flag = false; // Iterate from 0 to n - i - 1 for (int j = 0; j <= (n - i - 1); ++j) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; flag = true; } } if (flag == false) break; } } // Driver Code static public void Main () { int n = 5; int[] arr = { 2, 0, 1, 4, 3 }; Bubble_Sort(arr, n); Console.Write(\"The Sorted Array by using Bubble Sort is : \"); for (int i = 0; i < n; ++i) Console.Write(arr[i] + \" \"); } } // This code is contributed by shubhamsingh10.", "e": 39361, "s": 38350, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function for bubble sortfunction Bubble_Sort(arr, n){ Boolean(flag = true); // Iterate from 1 to n - 1 for(var i = 1; i < n; ++i) { flag = false; // Iterate from 0 to n - i - 1 for(var j = 0; j <= (n - i - 1); ++j) { if (arr[j] > arr[j + 1]) { var temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; flag = true; } } if (flag == false) break; }} // Driver Codevar n = 5;var arr = [ 2, 0, 1, 4, 3 ];Bubble_Sort(arr, n); document.write(\"The Sorted Array by \" + \"using Bubble Sort is : \"); for(var i = 0; i < n; ++i) document.write(arr[i] + \" \"); // This code is contributed by shivanisinghss2110 </script>", "e": 40219, "s": 39361, "text": null }, { "code": null, "e": 40273, "s": 40219, "text": "The Sorted Array by using Bubble Sort is : 0 1 2 3 4 " }, { "code": null, "e": 40423, "s": 40273, "text": "NOTE: This little tweak doesn’t change the worst case time complexity of the bubble sort algorithm but can improve its run time for particular cases." }, { "code": null, "e": 40477, "s": 40423, "text": "References : Lectures readingImplement bubble sort c " }, { "code": null, "e": 40489, "s": 40477, "text": "aashish1995" }, { "code": null, "e": 40498, "s": 40489, "text": "nerdcore" }, { "code": null, "e": 40513, "s": 40498, "text": "chinmoy1997pal" }, { "code": null, "e": 40528, "s": 40513, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 40547, "s": 40528, "text": "shivanisinghss2110" }, { "code": null, "e": 40562, "s": 40547, "text": "shivamdhyani15" }, { "code": null, "e": 40573, "s": 40562, "text": "defaultacc" }, { "code": null, "e": 40584, "s": 40573, "text": "BubbleSort" }, { "code": null, "e": 40599, "s": 40584, "text": "selection-sort" }, { "code": null, "e": 40610, "s": 40599, "text": "Algorithms" }, { "code": null, "e": 40614, "s": 40610, "text": "C++" }, { "code": null, "e": 40633, "s": 40614, "text": "Difference Between" }, { "code": null, "e": 40641, "s": 40633, "text": "Sorting" }, { "code": null, "e": 40649, "s": 40641, "text": "Sorting" }, { "code": null, "e": 40660, "s": 40649, "text": "Algorithms" }, { "code": null, "e": 40664, "s": 40660, "text": "CPP" }, { "code": null, "e": 40762, "s": 40664, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40787, "s": 40762, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 40814, "s": 40787, "text": "How to Start Learning DSA?" }, { "code": null, "e": 40867, "s": 40814, "text": "Difference between Algorithm, Pseudocode and Program" }, { "code": null, "e": 40901, "s": 40867, "text": "K means Clustering - Introduction" }, { "code": null, "e": 40968, "s": 40901, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 40986, "s": 40968, "text": "Vector in C++ STL" }, { "code": null, "e": 41002, "s": 40986, "text": "Arrays in C/C++" }, { "code": null, "e": 41048, "s": 41002, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 41067, "s": 41048, "text": "Inheritance in C++" } ]
How to get COVID 19 update using Covid module in Python? - GeeksforGeeks
03 Jun, 2020 A new Python library which tells the COVID-19 related information (country-wise) and it show that how many cases of confirmed, active, deaths, recovered found in that particular Country. Requirement:You have python package named COVID and python >= 3.6 Installation: pip install covid Dependencies: pydantic requests Example: from covid import Covid covid = Covid()india = covid.get_status_by_country_name("india") data ={ key:india[key] for key in india.keys() and {'confirmed', 'active', 'deaths', 'recovered'}} print(data) Output: {‘confirmed’: 119419, ‘active’: 66863, ‘recovered’: 48957, ‘deaths’: 3599} Let’s look at the modules basic functionality – List Countries and their Id’s: This comes in need when you need to know the names of countries while using get_status_by_country_name, eg to use ‘America’ or ‘United States of America’ or ‘US’from covid import Covid covid = Covid()countries = covid.list_countries() print(countries)Output:[{‘id’: ’18’, ‘name’: ‘US’}, {‘id’: ’14’, ‘name’: ‘Russia’}, {‘id’: ’22’, ‘name’: ‘Brazil’}, {‘id’: ’17’, ‘name’: ‘United Kingdom’}, {‘id’: ’19’, ‘name’: ‘Spain’}, {‘id’: ’11’, ‘name’: ‘Italy’}, {‘id’: ‘7’, ‘name’: ‘France’}, {‘id’: ‘8’, ‘name’: ‘Germany’}, {‘id’: ‘176’, ‘name’: ‘Turkey’}, {‘id’: ’93’, ‘name’: ‘Iran’}, {‘id’: ’91’, ‘name’: ‘India’}, {‘id’: ‘141’, ‘name’: ‘Peru’}, {‘id’: ‘4’, ‘name’: ‘China’}, {‘id’: ‘3’, ‘name’: ‘Canada’}, {‘id’: ‘153’, ‘name’: ‘Saudi Arabia’}, {‘id’: ’20’, ‘name’: ‘Mexico’},Note: The list is too long, the above output is just a part of the list. from covid import Covid covid = Covid()countries = covid.list_countries() print(countries) Output: [{‘id’: ’18’, ‘name’: ‘US’}, {‘id’: ’14’, ‘name’: ‘Russia’}, {‘id’: ’22’, ‘name’: ‘Brazil’}, {‘id’: ’17’, ‘name’: ‘United Kingdom’}, {‘id’: ’19’, ‘name’: ‘Spain’}, {‘id’: ’11’, ‘name’: ‘Italy’}, {‘id’: ‘7’, ‘name’: ‘France’}, {‘id’: ‘8’, ‘name’: ‘Germany’}, {‘id’: ‘176’, ‘name’: ‘Turkey’}, {‘id’: ’93’, ‘name’: ‘Iran’}, {‘id’: ’91’, ‘name’: ‘India’}, {‘id’: ‘141’, ‘name’: ‘Peru’}, {‘id’: ‘4’, ‘name’: ‘China’}, {‘id’: ‘3’, ‘name’: ‘Canada’}, {‘id’: ‘153’, ‘name’: ‘Saudi Arabia’}, {‘id’: ’20’, ‘name’: ‘Mexico’}, Note: The list is too long, the above output is just a part of the list. Get Data: To get COVID-19 related information.from covid import Covid covid = Covid()print(covid.get_data())Output:[{‘id’: ’18’, ‘country’: ‘US’, ‘confirmed’: 1577758, ‘active’: 1181132, ‘deaths’: 94729, ‘recovered’: 298418, ‘latitude’: 40.0, ‘longitude’: -100.0, ‘last_update’: 1590143562000}, {‘id’: ’14’, ‘country’: ‘Russia’, ‘confirmed’: 326448, ‘active’: 223374, ‘deaths’: 3249, ‘recovered’: 99825, ‘latitude’: 61.524, ‘longitude’: 105.3188, ‘last_update’: 1590143562000},Note: The list is too long, the above output is just a part of the list. from covid import Covid covid = Covid()print(covid.get_data()) Output: [{‘id’: ’18’, ‘country’: ‘US’, ‘confirmed’: 1577758, ‘active’: 1181132, ‘deaths’: 94729, ‘recovered’: 298418, ‘latitude’: 40.0, ‘longitude’: -100.0, ‘last_update’: 1590143562000}, {‘id’: ’14’, ‘country’: ‘Russia’, ‘confirmed’: 326448, ‘active’: 223374, ‘deaths’: 3249, ‘recovered’: 99825, ‘latitude’: 61.524, ‘longitude’: 105.3188, ‘last_update’: 1590143562000}, Note: The list is too long, the above output is just a part of the list. Get Status By Country ID: To get COVID-19 related information by Country Idfrom covid import Covid covid = Covid()cases = covid.get_status_by_country_id(18) print(cases)Output:{‘id’: ’18’, ‘country’: ‘US’, ‘confirmed’: 1541110, ‘active’: 1154535, ‘deaths’: 92712, ‘recovered’: 289392, ‘latitude’: 40.0, ‘longitude’: -100.0, ‘last_update’: 1590003166000} from covid import Covid covid = Covid()cases = covid.get_status_by_country_id(18) print(cases) Output: {‘id’: ’18’, ‘country’: ‘US’, ‘confirmed’: 1541110, ‘active’: 1154535, ‘deaths’: 92712, ‘recovered’: 289392, ‘latitude’: 40.0, ‘longitude’: -100.0, ‘last_update’: 1590003166000} Get Status By Country Namefrom covid import Covid covid = Covid()italy_cases = covid.get_status_by_country_name("italy") print(italy_cases)Output:{‘id’: ’11’, ‘country’: ‘Italy’, ‘confirmed’: 227364, ‘active’: 62752, ‘deaths’: 32330, ‘recovered’: 132282, ‘latitude’: 41.8719, ‘longitude’: 12.5674, ‘last_update’: 1590003166000} from covid import Covid covid = Covid()italy_cases = covid.get_status_by_country_name("italy") print(italy_cases) Output: {‘id’: ’11’, ‘country’: ‘Italy’, ‘confirmed’: 227364, ‘active’: 62752, ‘deaths’: 32330, ‘recovered’: 132282, ‘latitude’: 41.8719, ‘longitude’: 12.5674, ‘last_update’: 1590003166000} Get Total Confirmed cases, Active cases, Recovered cases and Deathsfrom covid import Covid covid = Covid() confirmed = covid.get_total_confirmed_cases()print('Confirmed :', end =" ")print(confirmed) active = covid.get_total_active_cases()print("Active:", end =" ")print(active) recovered = covid.get_total_recovered()print('Recovered:', end =" ")print(recovered) deaths = covid.get_total_deaths()print('Deaths:', end =" ")print(deaths)Output:Confirmed : 4955312 Active: 2750033 Recovered: 1874998 Deaths: 325810 from covid import Covid covid = Covid() confirmed = covid.get_total_confirmed_cases()print('Confirmed :', end =" ")print(confirmed) active = covid.get_total_active_cases()print("Active:", end =" ")print(active) recovered = covid.get_total_recovered()print('Recovered:', end =" ")print(recovered) deaths = covid.get_total_deaths()print('Deaths:', end =" ")print(deaths) Output: Confirmed : 4955312 Active: 2750033 Recovered: 1874998 Deaths: 325810 python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Defaultdict in Python How to Install PIP on Windows ? Deque in Python Bar Plot in Matplotlib Check if element exists in list in Python Python math function | sqrt() Python | Output Formatting Python - Pandas dataframe.append() How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects
[ { "code": null, "e": 25537, "s": 25509, "text": "\n03 Jun, 2020" }, { "code": null, "e": 25724, "s": 25537, "text": "A new Python library which tells the COVID-19 related information (country-wise) and it show that how many cases of confirmed, active, deaths, recovered found in that particular Country." }, { "code": null, "e": 25790, "s": 25724, "text": "Requirement:You have python package named COVID and python >= 3.6" }, { "code": null, "e": 25804, "s": 25790, "text": "Installation:" }, { "code": null, "e": 25822, "s": 25804, "text": "pip install covid" }, { "code": null, "e": 25836, "s": 25822, "text": "Dependencies:" }, { "code": null, "e": 25845, "s": 25836, "text": "pydantic" }, { "code": null, "e": 25854, "s": 25845, "text": "requests" }, { "code": null, "e": 25863, "s": 25854, "text": "Example:" }, { "code": "from covid import Covid covid = Covid()india = covid.get_status_by_country_name(\"india\") data ={ key:india[key] for key in india.keys() and {'confirmed', 'active', 'deaths', 'recovered'}} print(data)", "e": 26171, "s": 25863, "text": null }, { "code": null, "e": 26179, "s": 26171, "text": "Output:" }, { "code": null, "e": 26254, "s": 26179, "text": "{‘confirmed’: 119419, ‘active’: 66863, ‘recovered’: 48957, ‘deaths’: 3599}" }, { "code": null, "e": 26302, "s": 26254, "text": "Let’s look at the modules basic functionality –" }, { "code": null, "e": 27180, "s": 26302, "text": "List Countries and their Id’s: This comes in need when you need to know the names of countries while using get_status_by_country_name, eg to use ‘America’ or ‘United States of America’ or ‘US’from covid import Covid covid = Covid()countries = covid.list_countries() print(countries)Output:[{‘id’: ’18’, ‘name’: ‘US’}, {‘id’: ’14’, ‘name’: ‘Russia’}, {‘id’: ’22’, ‘name’: ‘Brazil’}, {‘id’: ’17’, ‘name’: ‘United Kingdom’}, {‘id’: ’19’, ‘name’: ‘Spain’}, {‘id’: ’11’, ‘name’: ‘Italy’}, {‘id’: ‘7’, ‘name’: ‘France’}, {‘id’: ‘8’, ‘name’: ‘Germany’}, {‘id’: ‘176’, ‘name’: ‘Turkey’}, {‘id’: ’93’, ‘name’: ‘Iran’}, {‘id’: ’91’, ‘name’: ‘India’}, {‘id’: ‘141’, ‘name’: ‘Peru’}, {‘id’: ‘4’, ‘name’: ‘China’}, {‘id’: ‘3’, ‘name’: ‘Canada’}, {‘id’: ‘153’, ‘name’: ‘Saudi Arabia’}, {‘id’: ’20’, ‘name’: ‘Mexico’},Note: The list is too long, the above output is just a part of the list." }, { "code": "from covid import Covid covid = Covid()countries = covid.list_countries() print(countries)", "e": 27273, "s": 27180, "text": null }, { "code": null, "e": 27281, "s": 27273, "text": "Output:" }, { "code": null, "e": 27796, "s": 27281, "text": "[{‘id’: ’18’, ‘name’: ‘US’}, {‘id’: ’14’, ‘name’: ‘Russia’}, {‘id’: ’22’, ‘name’: ‘Brazil’}, {‘id’: ’17’, ‘name’: ‘United Kingdom’}, {‘id’: ’19’, ‘name’: ‘Spain’}, {‘id’: ’11’, ‘name’: ‘Italy’}, {‘id’: ‘7’, ‘name’: ‘France’}, {‘id’: ‘8’, ‘name’: ‘Germany’}, {‘id’: ‘176’, ‘name’: ‘Turkey’}, {‘id’: ’93’, ‘name’: ‘Iran’}, {‘id’: ’91’, ‘name’: ‘India’}, {‘id’: ‘141’, ‘name’: ‘Peru’}, {‘id’: ‘4’, ‘name’: ‘China’}, {‘id’: ‘3’, ‘name’: ‘Canada’}, {‘id’: ‘153’, ‘name’: ‘Saudi Arabia’}, {‘id’: ’20’, ‘name’: ‘Mexico’}," }, { "code": null, "e": 27869, "s": 27796, "text": "Note: The list is too long, the above output is just a part of the list." }, { "code": null, "e": 28422, "s": 27869, "text": "Get Data: To get COVID-19 related information.from covid import Covid covid = Covid()print(covid.get_data())Output:[{‘id’: ’18’, ‘country’: ‘US’, ‘confirmed’: 1577758, ‘active’: 1181132, ‘deaths’: 94729, ‘recovered’: 298418, ‘latitude’: 40.0, ‘longitude’: -100.0, ‘last_update’: 1590143562000}, {‘id’: ’14’, ‘country’: ‘Russia’, ‘confirmed’: 326448, ‘active’: 223374, ‘deaths’: 3249, ‘recovered’: 99825, ‘latitude’: 61.524, ‘longitude’: 105.3188, ‘last_update’: 1590143562000},Note: The list is too long, the above output is just a part of the list." }, { "code": "from covid import Covid covid = Covid()print(covid.get_data())", "e": 28488, "s": 28422, "text": null }, { "code": null, "e": 28496, "s": 28488, "text": "Output:" }, { "code": null, "e": 28859, "s": 28496, "text": "[{‘id’: ’18’, ‘country’: ‘US’, ‘confirmed’: 1577758, ‘active’: 1181132, ‘deaths’: 94729, ‘recovered’: 298418, ‘latitude’: 40.0, ‘longitude’: -100.0, ‘last_update’: 1590143562000}, {‘id’: ’14’, ‘country’: ‘Russia’, ‘confirmed’: 326448, ‘active’: 223374, ‘deaths’: 3249, ‘recovered’: 99825, ‘latitude’: 61.524, ‘longitude’: 105.3188, ‘last_update’: 1590143562000}," }, { "code": null, "e": 28932, "s": 28859, "text": "Note: The list is too long, the above output is just a part of the list." }, { "code": null, "e": 29288, "s": 28932, "text": "Get Status By Country ID: To get COVID-19 related information by Country Idfrom covid import Covid covid = Covid()cases = covid.get_status_by_country_id(18) print(cases)Output:{‘id’: ’18’, ‘country’: ‘US’, ‘confirmed’: 1541110, ‘active’: 1154535, ‘deaths’: 92712, ‘recovered’: 289392, ‘latitude’: 40.0, ‘longitude’: -100.0, ‘last_update’: 1590003166000}" }, { "code": "from covid import Covid covid = Covid()cases = covid.get_status_by_country_id(18) print(cases)", "e": 29385, "s": 29288, "text": null }, { "code": null, "e": 29393, "s": 29385, "text": "Output:" }, { "code": null, "e": 29571, "s": 29393, "text": "{‘id’: ’18’, ‘country’: ‘US’, ‘confirmed’: 1541110, ‘active’: 1154535, ‘deaths’: 92712, ‘recovered’: 289392, ‘latitude’: 40.0, ‘longitude’: -100.0, ‘last_update’: 1590003166000}" }, { "code": null, "e": 29901, "s": 29571, "text": "Get Status By Country Namefrom covid import Covid covid = Covid()italy_cases = covid.get_status_by_country_name(\"italy\") print(italy_cases)Output:{‘id’: ’11’, ‘country’: ‘Italy’, ‘confirmed’: 227364, ‘active’: 62752, ‘deaths’: 32330, ‘recovered’: 132282, ‘latitude’: 41.8719, ‘longitude’: 12.5674, ‘last_update’: 1590003166000}" }, { "code": "from covid import Covid covid = Covid()italy_cases = covid.get_status_by_country_name(\"italy\") print(italy_cases)", "e": 30017, "s": 29901, "text": null }, { "code": null, "e": 30025, "s": 30017, "text": "Output:" }, { "code": null, "e": 30207, "s": 30025, "text": "{‘id’: ’11’, ‘country’: ‘Italy’, ‘confirmed’: 227364, ‘active’: 62752, ‘deaths’: 32330, ‘recovered’: 132282, ‘latitude’: 41.8719, ‘longitude’: 12.5674, ‘last_update’: 1590003166000}" }, { "code": null, "e": 30726, "s": 30207, "text": "Get Total Confirmed cases, Active cases, Recovered cases and Deathsfrom covid import Covid covid = Covid() confirmed = covid.get_total_confirmed_cases()print('Confirmed :', end =\" \")print(confirmed) active = covid.get_total_active_cases()print(\"Active:\", end =\" \")print(active) recovered = covid.get_total_recovered()print('Recovered:', end =\" \")print(recovered) deaths = covid.get_total_deaths()print('Deaths:', end =\" \")print(deaths)Output:Confirmed : 4955312\nActive: 2750033\nRecovered: 1874998\nDeaths: 325810" }, { "code": "from covid import Covid covid = Covid() confirmed = covid.get_total_confirmed_cases()print('Confirmed :', end =\" \")print(confirmed) active = covid.get_total_active_cases()print(\"Active:\", end =\" \")print(active) recovered = covid.get_total_recovered()print('Recovered:', end =\" \")print(recovered) deaths = covid.get_total_deaths()print('Deaths:', end =\" \")print(deaths)", "e": 31102, "s": 30726, "text": null }, { "code": null, "e": 31110, "s": 31102, "text": "Output:" }, { "code": null, "e": 31180, "s": 31110, "text": "Confirmed : 4955312\nActive: 2750033\nRecovered: 1874998\nDeaths: 325810" }, { "code": null, "e": 31195, "s": 31180, "text": "python-utility" }, { "code": null, "e": 31202, "s": 31195, "text": "Python" }, { "code": null, "e": 31300, "s": 31202, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31322, "s": 31300, "text": "Defaultdict in Python" }, { "code": null, "e": 31354, "s": 31322, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31370, "s": 31354, "text": "Deque in Python" }, { "code": null, "e": 31393, "s": 31370, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 31435, "s": 31393, "text": "Check if element exists in list in Python" }, { "code": null, "e": 31465, "s": 31435, "text": "Python math function | sqrt()" }, { "code": null, "e": 31492, "s": 31465, "text": "Python | Output Formatting" }, { "code": null, "e": 31527, "s": 31492, "text": "Python - Pandas dataframe.append()" }, { "code": null, "e": 31583, "s": 31527, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
Maximum occurring character in an input string | Set-2 - GeeksforGeeks
11 Mar, 2022 Given a string containing lowercase characters. The task is to print the maximum occurring character in the input string. If 2 or more characters appear the same number of times, print the lexicographically (alphabetically) lowest (first) character.Examples: Input: test sample Output: e ‘t’, ‘e’ and ‘s’ appears 2 times, but ‘e’ is the lexicographically smallest character. Input: sample program Output: a In the previous article, if there are more than one characters occurring the maximum number of time, then any of the characters is returned. In this post, the lexicographically smallest character of all the characters is returned.Approach: Declare a freq[26] array which is used as a hash table to store the frequencies of each character in the input string. Iterate in the string and increase the count of freq[s[i]] for every character. Traverse the freq[] array from left to right and keep track of the character having the maximum frequency so far. The value at freq[i] represents the frequency of character (i + ‘a’).Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find// the maximum occurring character in// an input string which is lexicographically first#include <bits/stdc++.h>using namespace std; // function to find the maximum occurring character in// an input string which is lexicographically firstchar getMaxOccurringChar(char str[]){ // freq[] used as hash table int freq[26] = { 0 }; // to store maximum frequency int max = -1; // to store the maximum occurring character char result; // length of 'str' int len = strlen(str); // get frequency of each character of 'str' for (int i = 0; i < len; i++) freq[str[i]]++; // for each character, where character is obtained by // (i + 'a') check whether it is the maximum character // so far and accodingly update 'result' for (int i = 0; i < 26; i++) if (max < freq[i]) { max = freq[i]; result = (char)(i + 'a'); } // maximum occurring character return result;} // Driver Codeint main(){ char str[] = "sample program"; cout << "Maximum occurring character = " << getMaxOccurringChar(str); return 0;} // Java implementation to find// the maximum occurring character in// an input string which is lexicographically first class GFG { // function to find the maximum occurring character in// an input string which is lexicographically first static char getMaxOccurringChar(char str[]) { // freq[] used as hash table int freq[] = new int[26]; // to store maximum frequency int max = -1; // to store the maximum occurring character char result = 0; // length of 'str' int len = str.length; // get frequency of each character of 'str' for (int i = 0; i < len; i++) { if (str[i] != ' ') { freq[str[i] - 'a']++; } } // for each character, where character is obtained by // (i + 'a') check whether it is the maximum character // so far and accodingly update 'result' for (int i = 0; i < 26; i++) { if (max < freq[i]) { max = freq[i]; result = (char) (i + 'a'); } } // maximum occurring character return result; } // Driver Code public static void main(String[] args) { char str[] = "sample program".toCharArray(); System.out.println("Maximum occurring character = " + getMaxOccurringChar(str)); }} // This code is contributed by 29AjayKumar # Python 3 implementation to find the# maximum occurring character in an input# string which is lexicographically first # function to find the maximum occurring# character in an input string which is# lexicographically firstdef getMaxOccurringChar(str): # freq[] used as hash table freq = [0 for i in range(100)] # to store maximum frequency max = -1 # to store the maximum occurring # character length of 'str' len__ = len(str) # get frequency of each character of 'str' for i in range(0, len__, 1): freq[ord(str[i]) - ord('a')] += 1 # for each character, where character # is obtained by (i + 'a') check whether # it is the maximum character so far and # accodingly update 'result' for i in range(26): if (max < freq[i]): max = freq[i] result = chr(ord('a') + i) # maximum occurring character return result # Driver Codeif __name__ == '__main__': str = "sample program" print("Maximum occurring character =", getMaxOccurringChar(str)) # This code is contributed by# Surendra_Gangwar // C# implementation to find// the maximum occurring character in// an input string which is lexicographically first using System;class GFG { // function to find the maximum occurring character in// an input string which is lexicographically first static char getMaxOccurringChar(string str) { // freq[] used as hash table int[] freq = new int[26]; // to store maximum frequency int max = -1; // to store the maximum occurring character char result = (char)0; // length of 'str' int len = str.Length; // get frequency of each character of 'str' for (int i = 0; i < len; i++) { if (str[i] != ' ') { freq[str[i] - 'a']++; } } // for each character, where character is obtained by // (i + 'a') check whether it is the maximum character // so far and accodingly update 'result' for (int i = 0; i < 26; i++) { if (max < freq[i]) { max = freq[i]; result = (char) (i + 'a'); } } // maximum occurring character return result; } // Driver Code public static void Main() { string str = "sample program"; Console.WriteLine("Maximum occurring character = " + getMaxOccurringChar(str)); }} <script>// Javascript implementation to find// the maximum occurring character in// an input string which is lexicographically first // function to find the maximum occurring character in // an input string which is lexicographically first function getMaxOccurringChar(str) { // freq[] used as hash table let freq = new Array(26); for(let i=0;i<freq.length;i++) { freq[i]=0; } // to store maximum frequency let max = -1; // to store the maximum occurring character let result = 0; // length of 'str' let len = str.length; // get frequency of each character of 'str' for (let i = 0; i < len; i++) { if (str[i] != ' ') { freq[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } } // for each character, where character is obtained by // (i + 'a') check whether it is the maximum character // so far and accodingly update 'result' for (let i = 0; i < 26; i++) { if (max < freq[i]) { max = freq[i]; result = String.fromCharCode(i + 'a'.charCodeAt(0)); } } // maximum occurring character return result; } // Driver Code let str="sample program".split(""); document.write("Maximum occurring character = " + getMaxOccurringChar(str)); // This code is contributed by rag2127</script> Maximum occurring character = a Time Complexity: O(n). Auxiliary Space: O(1).Source: Sabre Interview Experience | Set 2 29AjayKumar ukasp SURENDRA_GANGWAR rag2127 kumarharshmahour000 C-String-Question Hash Sabre Hash Strings Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Most frequent element in an array Sorting a Map by value in C++ STL Double Hashing Longest Consecutive Subsequence C++ program for hashing with chaining Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4
[ { "code": null, "e": 26361, "s": 26333, "text": "\n11 Mar, 2022" }, { "code": null, "e": 26622, "s": 26361, "text": "Given a string containing lowercase characters. The task is to print the maximum occurring character in the input string. If 2 or more characters appear the same number of times, print the lexicographically (alphabetically) lowest (first) character.Examples: " }, { "code": null, "e": 26770, "s": 26622, "text": "Input: test sample Output: e ‘t’, ‘e’ and ‘s’ appears 2 times, but ‘e’ is the lexicographically smallest character. Input: sample program Output: a" }, { "code": null, "e": 27447, "s": 26772, "text": "In the previous article, if there are more than one characters occurring the maximum number of time, then any of the characters is returned. In this post, the lexicographically smallest character of all the characters is returned.Approach: Declare a freq[26] array which is used as a hash table to store the frequencies of each character in the input string. Iterate in the string and increase the count of freq[s[i]] for every character. Traverse the freq[] array from left to right and keep track of the character having the maximum frequency so far. The value at freq[i] represents the frequency of character (i + ‘a’).Below is the implementation of the above approach: " }, { "code": null, "e": 27451, "s": 27447, "text": "C++" }, { "code": null, "e": 27456, "s": 27451, "text": "Java" }, { "code": null, "e": 27464, "s": 27456, "text": "Python3" }, { "code": null, "e": 27467, "s": 27464, "text": "C#" }, { "code": null, "e": 27478, "s": 27467, "text": "Javascript" }, { "code": "// C++ implementation to find// the maximum occurring character in// an input string which is lexicographically first#include <bits/stdc++.h>using namespace std; // function to find the maximum occurring character in// an input string which is lexicographically firstchar getMaxOccurringChar(char str[]){ // freq[] used as hash table int freq[26] = { 0 }; // to store maximum frequency int max = -1; // to store the maximum occurring character char result; // length of 'str' int len = strlen(str); // get frequency of each character of 'str' for (int i = 0; i < len; i++) freq[str[i]]++; // for each character, where character is obtained by // (i + 'a') check whether it is the maximum character // so far and accodingly update 'result' for (int i = 0; i < 26; i++) if (max < freq[i]) { max = freq[i]; result = (char)(i + 'a'); } // maximum occurring character return result;} // Driver Codeint main(){ char str[] = \"sample program\"; cout << \"Maximum occurring character = \" << getMaxOccurringChar(str); return 0;}", "e": 28609, "s": 27478, "text": null }, { "code": "// Java implementation to find// the maximum occurring character in// an input string which is lexicographically first class GFG { // function to find the maximum occurring character in// an input string which is lexicographically first static char getMaxOccurringChar(char str[]) { // freq[] used as hash table int freq[] = new int[26]; // to store maximum frequency int max = -1; // to store the maximum occurring character char result = 0; // length of 'str' int len = str.length; // get frequency of each character of 'str' for (int i = 0; i < len; i++) { if (str[i] != ' ') { freq[str[i] - 'a']++; } } // for each character, where character is obtained by // (i + 'a') check whether it is the maximum character // so far and accodingly update 'result' for (int i = 0; i < 26; i++) { if (max < freq[i]) { max = freq[i]; result = (char) (i + 'a'); } } // maximum occurring character return result; } // Driver Code public static void main(String[] args) { char str[] = \"sample program\".toCharArray(); System.out.println(\"Maximum occurring character = \" + getMaxOccurringChar(str)); }} // This code is contributed by 29AjayKumar", "e": 30002, "s": 28609, "text": null }, { "code": "# Python 3 implementation to find the# maximum occurring character in an input# string which is lexicographically first # function to find the maximum occurring# character in an input string which is# lexicographically firstdef getMaxOccurringChar(str): # freq[] used as hash table freq = [0 for i in range(100)] # to store maximum frequency max = -1 # to store the maximum occurring # character length of 'str' len__ = len(str) # get frequency of each character of 'str' for i in range(0, len__, 1): freq[ord(str[i]) - ord('a')] += 1 # for each character, where character # is obtained by (i + 'a') check whether # it is the maximum character so far and # accodingly update 'result' for i in range(26): if (max < freq[i]): max = freq[i] result = chr(ord('a') + i) # maximum occurring character return result # Driver Codeif __name__ == '__main__': str = \"sample program\" print(\"Maximum occurring character =\", getMaxOccurringChar(str)) # This code is contributed by# Surendra_Gangwar", "e": 31107, "s": 30002, "text": null }, { "code": "// C# implementation to find// the maximum occurring character in// an input string which is lexicographically first using System;class GFG { // function to find the maximum occurring character in// an input string which is lexicographically first static char getMaxOccurringChar(string str) { // freq[] used as hash table int[] freq = new int[26]; // to store maximum frequency int max = -1; // to store the maximum occurring character char result = (char)0; // length of 'str' int len = str.Length; // get frequency of each character of 'str' for (int i = 0; i < len; i++) { if (str[i] != ' ') { freq[str[i] - 'a']++; } } // for each character, where character is obtained by // (i + 'a') check whether it is the maximum character // so far and accodingly update 'result' for (int i = 0; i < 26; i++) { if (max < freq[i]) { max = freq[i]; result = (char) (i + 'a'); } } // maximum occurring character return result; } // Driver Code public static void Main() { string str = \"sample program\"; Console.WriteLine(\"Maximum occurring character = \" + getMaxOccurringChar(str)); }}", "e": 32455, "s": 31107, "text": null }, { "code": "<script>// Javascript implementation to find// the maximum occurring character in// an input string which is lexicographically first // function to find the maximum occurring character in // an input string which is lexicographically first function getMaxOccurringChar(str) { // freq[] used as hash table let freq = new Array(26); for(let i=0;i<freq.length;i++) { freq[i]=0; } // to store maximum frequency let max = -1; // to store the maximum occurring character let result = 0; // length of 'str' let len = str.length; // get frequency of each character of 'str' for (let i = 0; i < len; i++) { if (str[i] != ' ') { freq[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } } // for each character, where character is obtained by // (i + 'a') check whether it is the maximum character // so far and accodingly update 'result' for (let i = 0; i < 26; i++) { if (max < freq[i]) { max = freq[i]; result = String.fromCharCode(i + 'a'.charCodeAt(0)); } } // maximum occurring character return result; } // Driver Code let str=\"sample program\".split(\"\"); document.write(\"Maximum occurring character = \" + getMaxOccurringChar(str)); // This code is contributed by rag2127</script>", "e": 33952, "s": 32455, "text": null }, { "code": null, "e": 33984, "s": 33952, "text": "Maximum occurring character = a" }, { "code": null, "e": 34075, "s": 33986, "text": "Time Complexity: O(n). Auxiliary Space: O(1).Source: Sabre Interview Experience | Set 2 " }, { "code": null, "e": 34087, "s": 34075, "text": "29AjayKumar" }, { "code": null, "e": 34093, "s": 34087, "text": "ukasp" }, { "code": null, "e": 34110, "s": 34093, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 34118, "s": 34110, "text": "rag2127" }, { "code": null, "e": 34138, "s": 34118, "text": "kumarharshmahour000" }, { "code": null, "e": 34156, "s": 34138, "text": "C-String-Question" }, { "code": null, "e": 34161, "s": 34156, "text": "Hash" }, { "code": null, "e": 34167, "s": 34161, "text": "Sabre" }, { "code": null, "e": 34172, "s": 34167, "text": "Hash" }, { "code": null, "e": 34180, "s": 34172, "text": "Strings" }, { "code": null, "e": 34185, "s": 34180, "text": "Hash" }, { "code": null, "e": 34193, "s": 34185, "text": "Strings" }, { "code": null, "e": 34291, "s": 34193, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34325, "s": 34291, "text": "Most frequent element in an array" }, { "code": null, "e": 34359, "s": 34325, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 34374, "s": 34359, "text": "Double Hashing" }, { "code": null, "e": 34406, "s": 34374, "text": "Longest Consecutive Subsequence" }, { "code": null, "e": 34444, "s": 34406, "text": "C++ program for hashing with chaining" }, { "code": null, "e": 34490, "s": 34444, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 34515, "s": 34490, "text": "Reverse a string in Java" }, { "code": null, "e": 34575, "s": 34515, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34590, "s": 34575, "text": "C++ Data Types" } ]
Ways to import CSV files in Google Colab - GeeksforGeeks
16 Feb, 2022 Colab (short for Collaboratory) is Google’s free platform which enables users to code in Python. It is a Jupyter Notebook-based cloud service, provided by Google. This platform allows us to train the Machine Learning models directly in the cloud and all for free. Google Colab does whatever your Jupyter Notebook does and a bit more, i.e. you can use GPU and TPU for free. Some of Google Colab’s advantages include quick installation and real-time sharing of Notebooks between users. However, loading a CSV file requires writing some extra lines of codes. In this article, we will be discussing three different ways to load a CSV file and store it in a pandas dataframe. To get started, sign in to your Google Account, and then go to “https://colab.research.google.com” and click on “New Notebook”. To upload the file from the local drive write the following code in the cell and run it Python3 from google.colab import files uploaded = files.upload() you will get a screen as, Click on “choose files”, then select and download the CSV file from your local drive. Later write the following code snippet to import it into a pandas dataframe. Python3 import pandas as pdimport io df = pd.read_csv(io.BytesIO(uploaded['file.csv']))print(df) Output: It is the easiest way to upload a CSV file in Colab. For this go to the dataset in your GitHub repository, and then click on “View Raw”. Copy the link to the raw dataset and pass it as a parameter to the read_csv() in pandas to get the dataframe. Python3 url = 'copied_raw_github_link'df = pd.read_csv(url) Output: We can import datasets that are uploaded on our google drive in two ways : 1. Using PyDrive This is the most complex method for importing datasets among all. For this, we are first required to install the PyDrive library from the python installer(pip) and execute the following. Python3 !pip install -U -q PyDrive from pydrive.auth import GoogleAuthfrom pydrive.drive import GoogleDrivefrom google.colab import authfrom oauth2client.client import GoogleCredentials # Authenticate and create the PyDrive client.auth.authenticate_user()gauth = GoogleAuth()gauth.credentials = GoogleCredentials.get_application_default()drive = GoogleDrive(gauth) Output: Click on the link prompted to get the authentication to allow Google to access your Drive. You will see a screen with “Google Cloud SDK wants to access your Google Account” at the top. After you allow permission, copy the given verification code and paste it into the box in Colab. Now, go to the CSV file in your Drive and get the shareable link and store it in a string variable in Colab. Now, to get this file in the dataframe run the following code. Python3 link = 'https://drive.google.com/file/d/1KiYk09VqGI6tjNpalom5wI90GrC2p-lz/view' import pandas as pd # to get the id part of the fileid = link.split("/")[-2] downloaded = drive.CreateFile({'id':id})downloaded.GetContentFile('xclara.csv') df = pd.read_csv('xclara.csv')print(df) Output: 2. Mounting the drive This method is quite simple and clean than the above-mentioned method. Create a folder in your Google Drive. Upload the CSV file in this folder. Write the following code in your Colab Notebook : from google.colab import drive drive.mount(‘/content/drive’) Just like with the previous method, the commands will bring you to a Google Authentication step. Later complete the verification as we did in the last method. Now in the Notebook, at the top-left, there is a File menu and then click on Locate in Drive, and then find your data. Then copy the path of the CSV file in a variable in your notebook, and read the file using read_csv(). path = "copied path" df_bonus = pd.read_csv(path) Now, to read the file run the following code. Python3 import pandas as pd df = pd.read_csv("file_path")print(df) Output: kumaripunam984122 python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python *args and **kwargs in Python Reading and Writing to text files in Python Convert integer to string in Python Check if element exists in list in Python
[ { "code": null, "e": 26062, "s": 26034, "text": "\n16 Feb, 2022" }, { "code": null, "e": 26863, "s": 26062, "text": "Colab (short for Collaboratory) is Google’s free platform which enables users to code in Python. It is a Jupyter Notebook-based cloud service, provided by Google. This platform allows us to train the Machine Learning models directly in the cloud and all for free. Google Colab does whatever your Jupyter Notebook does and a bit more, i.e. you can use GPU and TPU for free. Some of Google Colab’s advantages include quick installation and real-time sharing of Notebooks between users. However, loading a CSV file requires writing some extra lines of codes. In this article, we will be discussing three different ways to load a CSV file and store it in a pandas dataframe. To get started, sign in to your Google Account, and then go to “https://colab.research.google.com” and click on “New Notebook”. " }, { "code": null, "e": 26952, "s": 26863, "text": "To upload the file from the local drive write the following code in the cell and run it " }, { "code": null, "e": 26960, "s": 26952, "text": "Python3" }, { "code": "from google.colab import files uploaded = files.upload()", "e": 27018, "s": 26960, "text": null }, { "code": null, "e": 27049, "s": 27021, "text": "you will get a screen as, " }, { "code": null, "e": 27217, "s": 27053, "text": "Click on “choose files”, then select and download the CSV file from your local drive. Later write the following code snippet to import it into a pandas dataframe." }, { "code": null, "e": 27227, "s": 27219, "text": "Python3" }, { "code": "import pandas as pdimport io df = pd.read_csv(io.BytesIO(uploaded['file.csv']))print(df)", "e": 27316, "s": 27227, "text": null }, { "code": null, "e": 27327, "s": 27319, "text": "Output:" }, { "code": null, "e": 27580, "s": 27331, "text": "It is the easiest way to upload a CSV file in Colab. For this go to the dataset in your GitHub repository, and then click on “View Raw”. Copy the link to the raw dataset and pass it as a parameter to the read_csv() in pandas to get the dataframe. " }, { "code": null, "e": 27590, "s": 27582, "text": "Python3" }, { "code": "url = 'copied_raw_github_link'df = pd.read_csv(url)", "e": 27642, "s": 27590, "text": null }, { "code": null, "e": 27653, "s": 27645, "text": "Output:" }, { "code": null, "e": 27938, "s": 27659, "text": "We can import datasets that are uploaded on our google drive in two ways : 1. Using PyDrive This is the most complex method for importing datasets among all. For this, we are first required to install the PyDrive library from the python installer(pip) and execute the following." }, { "code": null, "e": 27948, "s": 27940, "text": "Python3" }, { "code": "!pip install -U -q PyDrive from pydrive.auth import GoogleAuthfrom pydrive.drive import GoogleDrivefrom google.colab import authfrom oauth2client.client import GoogleCredentials # Authenticate and create the PyDrive client.auth.authenticate_user()gauth = GoogleAuth()gauth.credentials = GoogleCredentials.get_application_default()drive = GoogleDrive(gauth)", "e": 28306, "s": 27948, "text": null }, { "code": null, "e": 28317, "s": 28309, "text": "Output:" }, { "code": null, "e": 28775, "s": 28321, "text": "Click on the link prompted to get the authentication to allow Google to access your Drive. You will see a screen with “Google Cloud SDK wants to access your Google Account” at the top. After you allow permission, copy the given verification code and paste it into the box in Colab. Now, go to the CSV file in your Drive and get the shareable link and store it in a string variable in Colab. Now, to get this file in the dataframe run the following code." }, { "code": null, "e": 28785, "s": 28777, "text": "Python3" }, { "code": "link = 'https://drive.google.com/file/d/1KiYk09VqGI6tjNpalom5wI90GrC2p-lz/view' import pandas as pd # to get the id part of the fileid = link.split(\"/\")[-2] downloaded = drive.CreateFile({'id':id})downloaded.GetContentFile('xclara.csv') df = pd.read_csv('xclara.csv')print(df)", "e": 29063, "s": 28785, "text": null }, { "code": null, "e": 29074, "s": 29066, "text": "Output:" }, { "code": null, "e": 29172, "s": 29078, "text": "2. Mounting the drive This method is quite simple and clean than the above-mentioned method. " }, { "code": null, "e": 29212, "s": 29174, "text": "Create a folder in your Google Drive." }, { "code": null, "e": 29248, "s": 29212, "text": "Upload the CSV file in this folder." }, { "code": null, "e": 29300, "s": 29248, "text": "Write the following code in your Colab Notebook : " }, { "code": null, "e": 29362, "s": 29300, "text": "from google.colab import drive\n\ndrive.mount(‘/content/drive’)" }, { "code": null, "e": 29746, "s": 29364, "text": "Just like with the previous method, the commands will bring you to a Google Authentication step. Later complete the verification as we did in the last method. Now in the Notebook, at the top-left, there is a File menu and then click on Locate in Drive, and then find your data. Then copy the path of the CSV file in a variable in your notebook, and read the file using read_csv(). " }, { "code": null, "e": 29798, "s": 29748, "text": "path = \"copied path\"\ndf_bonus = pd.read_csv(path)" }, { "code": null, "e": 29846, "s": 29800, "text": "Now, to read the file run the following code." }, { "code": null, "e": 29856, "s": 29848, "text": "Python3" }, { "code": "import pandas as pd df = pd.read_csv(\"file_path\")print(df)", "e": 29915, "s": 29856, "text": null }, { "code": null, "e": 29926, "s": 29918, "text": "Output:" }, { "code": null, "e": 29948, "s": 29930, "text": "kumaripunam984122" }, { "code": null, "e": 29963, "s": 29948, "text": "python-utility" }, { "code": null, "e": 29970, "s": 29963, "text": "Python" }, { "code": null, "e": 30068, "s": 29970, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30086, "s": 30068, "text": "Python Dictionary" }, { "code": null, "e": 30121, "s": 30086, "text": "Read a file line by line in Python" }, { "code": null, "e": 30153, "s": 30121, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30175, "s": 30153, "text": "Enumerate() in Python" }, { "code": null, "e": 30217, "s": 30175, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30247, "s": 30217, "text": "Iterate over a list in Python" }, { "code": null, "e": 30276, "s": 30247, "text": "*args and **kwargs in Python" }, { "code": null, "e": 30320, "s": 30276, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 30356, "s": 30320, "text": "Convert integer to string in Python" } ]
8 Most Used Data Science Tools - GeeksforGeeks
18 Jul, 2020 Data Science is the art of drawing and visualizing useful insights from data. Basically, it is the process of collecting, analyzing, and modeling data to solve problems related to the real-world. To implement the operations we have to use such tools to manipulate the data and entities to solve the issues. With the help of these tools, no need to use core programming languages in order to implement Data Science. There are pre-defined functions, algorithms, and a user-friendly Graphical User Interface (GUI). As we know that Data Science has a very fast execution process, one tool is not enough to implement this. Apache Hadoop is a free, open-source framework by Apache Software Foundation authorized under the Apache License 2.0 that can manage and store tons and tons of data. It is used for high-level computations and data processing. By using its parallel processing nature, we can work with the number of clusters of nodes. It also facilitates solving highly complex computational problems and tasks related to data-intensive. Latest Version: Apache Hadoop 3.1.1 Hadoop offers standard libraries and functions for the subsystems. Effectively scale large data on thousands of Hadoop clusters. It speeds up disk-powered performance by up to 10 times per project. Provides the functionalities of modules like Hadoop Common, Hadoop YARN, Hadoop MapReduce.2. SAS (Statistical Analysis System)SAS is a statistical tool developed by SAS Institute. It is a closed source proprietary software that is used by large organizations to analyze data. It is one of the oldest tools developed for Data Science. It is used in areas like Data Mining, Statistical Analysis, Business Intelligence Applications, Clinical Trial Analysis, Econometrics & Time-Series Analysis.Latest Version: SAS 9.4It is a suite of well-defined tools.It has a simple but most effective GUI.It provides a Granular analysis of textual content.Easy to learn and execute as there is a lot of available tutorials with appropriate knowledge.Can make visually appealing reports with seamless and dedicated technical support.3. Apache SparkApache Spark is the data science tool developed by Apache Software Foundation used for analyzing and working on large-scale data. It is a unified analytics engine for large-scale data processing. It is specially designed to handle batch processing and stream processing. It allows you to create a program to clusters of data for processing them along with incorporating data parallelism and fault-tolerance. It inherits some of the features of Hadoop like YARN, MapReduce, and HDFS.Latest Version: Apache Spark 2.4.5It offers data cleansing, transformation, model building & evaluation.It has the ability to work in-memory makes it extremely fast for processing data and writing to disk.It provides many APIs that facilitate repeated access to data.4. Data RobotDataRobot Founded in 2012, is the leader in enterprise AI, that aids in developing accurate predictive models for the real-world problems of any organization. It facilitates the environment to automate the end-to-end process of building, deploying, and maintaining your AI. DataRobot’s Prediction Explanations help you understand the reasons behind your machine learning model results.Highly Interpretable.It has the ability to making the model’s predictions easy to explain to anyone.It provides the suitability to implement the whole Data Science process at a large scale.5. TableauTableau is the most popular data visualization tool used in the market, is an American interactive data visualization software company founded in January 2003, was recently acquired by Salesforce. It provides the facilities to break down raw, unformatted data into a processable and understandable format. It has the ability to visualize geographical data and for plotting longitudes and latitudes in maps.Latest Version: Tableau 2020.2It offers comprehensive end-to-end analytics.It is a fully protected system that reduces security risks to the maximum state.It provides a responsive user interface that fits all types of devices and screen dimensions.6. BigMLBigML, founded in 2011, is a Data Science tool that provides a fully interactable, cloud-based GUI environment that you can use for processing Complex Machine Learning Algorithms. The main goal of using BigML is to make building and sharing datasets and models easier for everyone. It provides an environment with just one framework for reduced dependencies.Latest Version: BigML Winter 2020It specializes in predictive modeling.It has ability to export models via JSON PML and PMML makes for a seamless transition from one platform to another.It provides an easy to use web-interface using Rest APIs.7. TensorFlowTensorFlow, developed by Google Brain team, is a free and open-source software library for dataflow and differentiable programming across a range of tasks. It provides an environment for building and training models, deploying platforms such as computers, smartphones, and servers, to achieving maximum potential with finite resources. It is one of the very useful tools that is used in the fields of Artificial Intelligence, Deep Learning, & Machine Learning.Latest Version: TensorFlow 2.2.0It provides good performance and high computational abilities.Can run on both CPUs and GPUs.It provides features like easily trainable and responsive construct.8. JupyterJupyter, developed by Project Jupyter on February 2015 open-source software, open-standards, and services for interactive computing across dozens of programming languages. It is a web-based application tool running on the kernel, used for writing live code, visualizations, and presentations. It is one of the best tools, used by scratch level programmers & data science aspirants, by which they can easily learn and adapt the functionalities related to the Data Science field.Latest Version: Jupyter Notebook 6.0.3It provides an environment to perform data cleaning, statistical computation, visualization and create predictive machine learning models.It has the ability to display plots that are the output of running code cells.It is quite extensible, supports many programming languages, easily hosted on almost any server.My Personal Notes arrow_drop_upSave SAS is a statistical tool developed by SAS Institute. It is a closed source proprietary software that is used by large organizations to analyze data. It is one of the oldest tools developed for Data Science. It is used in areas like Data Mining, Statistical Analysis, Business Intelligence Applications, Clinical Trial Analysis, Econometrics & Time-Series Analysis. Latest Version: SAS 9.4 It is a suite of well-defined tools. It has a simple but most effective GUI. It provides a Granular analysis of textual content. Easy to learn and execute as there is a lot of available tutorials with appropriate knowledge. Can make visually appealing reports with seamless and dedicated technical support. Apache Spark is the data science tool developed by Apache Software Foundation used for analyzing and working on large-scale data. It is a unified analytics engine for large-scale data processing. It is specially designed to handle batch processing and stream processing. It allows you to create a program to clusters of data for processing them along with incorporating data parallelism and fault-tolerance. It inherits some of the features of Hadoop like YARN, MapReduce, and HDFS. Latest Version: Apache Spark 2.4.5 It offers data cleansing, transformation, model building & evaluation. It has the ability to work in-memory makes it extremely fast for processing data and writing to disk. It provides many APIs that facilitate repeated access to data. DataRobot Founded in 2012, is the leader in enterprise AI, that aids in developing accurate predictive models for the real-world problems of any organization. It facilitates the environment to automate the end-to-end process of building, deploying, and maintaining your AI. DataRobot’s Prediction Explanations help you understand the reasons behind your machine learning model results. Highly Interpretable. It has the ability to making the model’s predictions easy to explain to anyone. It provides the suitability to implement the whole Data Science process at a large scale. Tableau is the most popular data visualization tool used in the market, is an American interactive data visualization software company founded in January 2003, was recently acquired by Salesforce. It provides the facilities to break down raw, unformatted data into a processable and understandable format. It has the ability to visualize geographical data and for plotting longitudes and latitudes in maps. Latest Version: Tableau 2020.2 It offers comprehensive end-to-end analytics. It is a fully protected system that reduces security risks to the maximum state. It provides a responsive user interface that fits all types of devices and screen dimensions. BigML, founded in 2011, is a Data Science tool that provides a fully interactable, cloud-based GUI environment that you can use for processing Complex Machine Learning Algorithms. The main goal of using BigML is to make building and sharing datasets and models easier for everyone. It provides an environment with just one framework for reduced dependencies. Latest Version: BigML Winter 2020 It specializes in predictive modeling. It has ability to export models via JSON PML and PMML makes for a seamless transition from one platform to another. It provides an easy to use web-interface using Rest APIs. TensorFlow, developed by Google Brain team, is a free and open-source software library for dataflow and differentiable programming across a range of tasks. It provides an environment for building and training models, deploying platforms such as computers, smartphones, and servers, to achieving maximum potential with finite resources. It is one of the very useful tools that is used in the fields of Artificial Intelligence, Deep Learning, & Machine Learning. Latest Version: TensorFlow 2.2.0 It provides good performance and high computational abilities. Can run on both CPUs and GPUs. It provides features like easily trainable and responsive construct. Jupyter, developed by Project Jupyter on February 2015 open-source software, open-standards, and services for interactive computing across dozens of programming languages. It is a web-based application tool running on the kernel, used for writing live code, visualizations, and presentations. It is one of the best tools, used by scratch level programmers & data science aspirants, by which they can easily learn and adapt the functionalities related to the Data Science field. Latest Version: Jupyter Notebook 6.0.3 It provides an environment to perform data cleaning, statistical computation, visualization and create predictive machine learning models. It has the ability to display plots that are the output of running code cells. It is quite extensible, supports many programming languages, easily hosted on almost any server. data-science Picked GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? Introduction to Recurrent Neural Network 12 pip Commands For Python Developers A Freshers Guide To Programming ML | Underfitting and Overfitting What is web socket and how it is different from the HTTP? Virtualization In Cloud Computing and Types Software Testing | Basics Top 10 Programming Languages to Learn in 2022
[ { "code": null, "e": 26273, "s": 26245, "text": "\n18 Jul, 2020" }, { "code": null, "e": 26891, "s": 26273, "text": "Data Science is the art of drawing and visualizing useful insights from data. Basically, it is the process of collecting, analyzing, and modeling data to solve problems related to the real-world. To implement the operations we have to use such tools to manipulate the data and entities to solve the issues. With the help of these tools, no need to use core programming languages in order to implement Data Science. There are pre-defined functions, algorithms, and a user-friendly Graphical User Interface (GUI). As we know that Data Science has a very fast execution process, one tool is not enough to implement this." }, { "code": null, "e": 27311, "s": 26891, "text": "Apache Hadoop is a free, open-source framework by Apache Software Foundation authorized under the Apache License 2.0 that can manage and store tons and tons of data. It is used for high-level computations and data processing. By using its parallel processing nature, we can work with the number of clusters of nodes. It also facilitates solving highly complex computational problems and tasks related to data-intensive." }, { "code": null, "e": 27347, "s": 27311, "text": "Latest Version: Apache Hadoop 3.1.1" }, { "code": null, "e": 27414, "s": 27347, "text": "Hadoop offers standard libraries and functions for the subsystems." }, { "code": null, "e": 27476, "s": 27414, "text": "Effectively scale large data on thousands of Hadoop clusters." }, { "code": null, "e": 27545, "s": 27476, "text": "It speeds up disk-powered performance by up to 10 times per project." }, { "code": null, "e": 32523, "s": 27545, "text": "Provides the functionalities of modules like Hadoop Common, Hadoop YARN, Hadoop MapReduce.2. SAS (Statistical Analysis System)SAS is a statistical tool developed by SAS Institute. It is a closed source proprietary software that is used by large organizations to analyze data. It is one of the oldest tools developed for Data Science. It is used in areas like Data Mining, Statistical Analysis, Business Intelligence Applications, Clinical Trial Analysis, Econometrics & Time-Series Analysis.Latest Version: SAS 9.4It is a suite of well-defined tools.It has a simple but most effective GUI.It provides a Granular analysis of textual content.Easy to learn and execute as there is a lot of available tutorials with appropriate knowledge.Can make visually appealing reports with seamless and dedicated technical support.3. Apache SparkApache Spark is the data science tool developed by Apache Software Foundation used for analyzing and working on large-scale data. It is a unified analytics engine for large-scale data processing. It is specially designed to handle batch processing and stream processing. It allows you to create a program to clusters of data for processing them along with incorporating data parallelism and fault-tolerance. It inherits some of the features of Hadoop like YARN, MapReduce, and HDFS.Latest Version: Apache Spark 2.4.5It offers data cleansing, transformation, model building & evaluation.It has the ability to work in-memory makes it extremely fast for processing data and writing to disk.It provides many APIs that facilitate repeated access to data.4. Data RobotDataRobot Founded in 2012, is the leader in enterprise AI, that aids in developing accurate predictive models for the real-world problems of any organization. It facilitates the environment to automate the end-to-end process of building, deploying, and maintaining your AI. DataRobot’s Prediction Explanations help you understand the reasons behind your machine learning model results.Highly Interpretable.It has the ability to making the model’s predictions easy to explain to anyone.It provides the suitability to implement the whole Data Science process at a large scale.5. TableauTableau is the most popular data visualization tool used in the market, is an American interactive data visualization software company founded in January 2003, was recently acquired by Salesforce. It provides the facilities to break down raw, unformatted data into a processable and understandable format. It has the ability to visualize geographical data and for plotting longitudes and latitudes in maps.Latest Version: Tableau 2020.2It offers comprehensive end-to-end analytics.It is a fully protected system that reduces security risks to the maximum state.It provides a responsive user interface that fits all types of devices and screen dimensions.6. BigMLBigML, founded in 2011, is a Data Science tool that provides a fully interactable, cloud-based GUI environment that you can use for processing Complex Machine Learning Algorithms. The main goal of using BigML is to make building and sharing datasets and models easier for everyone. It provides an environment with just one framework for reduced dependencies.Latest Version: BigML Winter 2020It specializes in predictive modeling.It has ability to export models via JSON PML and PMML makes for a seamless transition from one platform to another.It provides an easy to use web-interface using Rest APIs.7. TensorFlowTensorFlow, developed by Google Brain team, is a free and open-source software library for dataflow and differentiable programming across a range of tasks. It provides an environment for building and training models, deploying platforms such as computers, smartphones, and servers, to achieving maximum potential with finite resources. It is one of the very useful tools that is used in the fields of Artificial Intelligence, Deep Learning, & Machine Learning.Latest Version: TensorFlow 2.2.0It provides good performance and high computational abilities.Can run on both CPUs and GPUs.It provides features like easily trainable and responsive construct.8. JupyterJupyter, developed by Project Jupyter on February 2015 open-source software, open-standards, and services for interactive computing across dozens of programming languages. It is a web-based application tool running on the kernel, used for writing live code, visualizations, and presentations. It is one of the best tools, used by scratch level programmers & data science aspirants, by which they can easily learn and adapt the functionalities related to the Data Science field.Latest Version: Jupyter Notebook 6.0.3It provides an environment to perform data cleaning, statistical computation, visualization and create predictive machine learning models.It has the ability to display plots that are the output of running code cells.It is quite extensible, supports many programming languages, easily hosted on almost any server.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 32889, "s": 32523, "text": "SAS is a statistical tool developed by SAS Institute. It is a closed source proprietary software that is used by large organizations to analyze data. It is one of the oldest tools developed for Data Science. It is used in areas like Data Mining, Statistical Analysis, Business Intelligence Applications, Clinical Trial Analysis, Econometrics & Time-Series Analysis." }, { "code": null, "e": 32913, "s": 32889, "text": "Latest Version: SAS 9.4" }, { "code": null, "e": 32950, "s": 32913, "text": "It is a suite of well-defined tools." }, { "code": null, "e": 32990, "s": 32950, "text": "It has a simple but most effective GUI." }, { "code": null, "e": 33042, "s": 32990, "text": "It provides a Granular analysis of textual content." }, { "code": null, "e": 33137, "s": 33042, "text": "Easy to learn and execute as there is a lot of available tutorials with appropriate knowledge." }, { "code": null, "e": 33220, "s": 33137, "text": "Can make visually appealing reports with seamless and dedicated technical support." }, { "code": null, "e": 33703, "s": 33220, "text": "Apache Spark is the data science tool developed by Apache Software Foundation used for analyzing and working on large-scale data. It is a unified analytics engine for large-scale data processing. It is specially designed to handle batch processing and stream processing. It allows you to create a program to clusters of data for processing them along with incorporating data parallelism and fault-tolerance. It inherits some of the features of Hadoop like YARN, MapReduce, and HDFS." }, { "code": null, "e": 33738, "s": 33703, "text": "Latest Version: Apache Spark 2.4.5" }, { "code": null, "e": 33809, "s": 33738, "text": "It offers data cleansing, transformation, model building & evaluation." }, { "code": null, "e": 33911, "s": 33809, "text": "It has the ability to work in-memory makes it extremely fast for processing data and writing to disk." }, { "code": null, "e": 33974, "s": 33911, "text": "It provides many APIs that facilitate repeated access to data." }, { "code": null, "e": 34360, "s": 33974, "text": "DataRobot Founded in 2012, is the leader in enterprise AI, that aids in developing accurate predictive models for the real-world problems of any organization. It facilitates the environment to automate the end-to-end process of building, deploying, and maintaining your AI. DataRobot’s Prediction Explanations help you understand the reasons behind your machine learning model results." }, { "code": null, "e": 34382, "s": 34360, "text": "Highly Interpretable." }, { "code": null, "e": 34462, "s": 34382, "text": "It has the ability to making the model’s predictions easy to explain to anyone." }, { "code": null, "e": 34552, "s": 34462, "text": "It provides the suitability to implement the whole Data Science process at a large scale." }, { "code": null, "e": 34959, "s": 34552, "text": "Tableau is the most popular data visualization tool used in the market, is an American interactive data visualization software company founded in January 2003, was recently acquired by Salesforce. It provides the facilities to break down raw, unformatted data into a processable and understandable format. It has the ability to visualize geographical data and for plotting longitudes and latitudes in maps." }, { "code": null, "e": 34990, "s": 34959, "text": "Latest Version: Tableau 2020.2" }, { "code": null, "e": 35036, "s": 34990, "text": "It offers comprehensive end-to-end analytics." }, { "code": null, "e": 35117, "s": 35036, "text": "It is a fully protected system that reduces security risks to the maximum state." }, { "code": null, "e": 35211, "s": 35117, "text": "It provides a responsive user interface that fits all types of devices and screen dimensions." }, { "code": null, "e": 35570, "s": 35211, "text": "BigML, founded in 2011, is a Data Science tool that provides a fully interactable, cloud-based GUI environment that you can use for processing Complex Machine Learning Algorithms. The main goal of using BigML is to make building and sharing datasets and models easier for everyone. It provides an environment with just one framework for reduced dependencies." }, { "code": null, "e": 35604, "s": 35570, "text": "Latest Version: BigML Winter 2020" }, { "code": null, "e": 35643, "s": 35604, "text": "It specializes in predictive modeling." }, { "code": null, "e": 35759, "s": 35643, "text": "It has ability to export models via JSON PML and PMML makes for a seamless transition from one platform to another." }, { "code": null, "e": 35817, "s": 35759, "text": "It provides an easy to use web-interface using Rest APIs." }, { "code": null, "e": 36278, "s": 35817, "text": "TensorFlow, developed by Google Brain team, is a free and open-source software library for dataflow and differentiable programming across a range of tasks. It provides an environment for building and training models, deploying platforms such as computers, smartphones, and servers, to achieving maximum potential with finite resources. It is one of the very useful tools that is used in the fields of Artificial Intelligence, Deep Learning, & Machine Learning." }, { "code": null, "e": 36311, "s": 36278, "text": "Latest Version: TensorFlow 2.2.0" }, { "code": null, "e": 36374, "s": 36311, "text": "It provides good performance and high computational abilities." }, { "code": null, "e": 36405, "s": 36374, "text": "Can run on both CPUs and GPUs." }, { "code": null, "e": 36474, "s": 36405, "text": "It provides features like easily trainable and responsive construct." }, { "code": null, "e": 36952, "s": 36474, "text": "Jupyter, developed by Project Jupyter on February 2015 open-source software, open-standards, and services for interactive computing across dozens of programming languages. It is a web-based application tool running on the kernel, used for writing live code, visualizations, and presentations. It is one of the best tools, used by scratch level programmers & data science aspirants, by which they can easily learn and adapt the functionalities related to the Data Science field." }, { "code": null, "e": 36991, "s": 36952, "text": "Latest Version: Jupyter Notebook 6.0.3" }, { "code": null, "e": 37130, "s": 36991, "text": "It provides an environment to perform data cleaning, statistical computation, visualization and create predictive machine learning models." }, { "code": null, "e": 37209, "s": 37130, "text": "It has the ability to display plots that are the output of running code cells." }, { "code": null, "e": 37306, "s": 37209, "text": "It is quite extensible, supports many programming languages, easily hosted on almost any server." }, { "code": null, "e": 37319, "s": 37306, "text": "data-science" }, { "code": null, "e": 37326, "s": 37319, "text": "Picked" }, { "code": null, "e": 37332, "s": 37326, "text": "GBlog" }, { "code": null, "e": 37430, "s": 37332, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37455, "s": 37430, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 37482, "s": 37455, "text": "How to Start Learning DSA?" }, { "code": null, "e": 37523, "s": 37482, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 37561, "s": 37523, "text": "12 pip Commands For Python Developers" }, { "code": null, "e": 37593, "s": 37561, "text": "A Freshers Guide To Programming" }, { "code": null, "e": 37627, "s": 37593, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 37685, "s": 37627, "text": "What is web socket and how it is different from the HTTP?" }, { "code": null, "e": 37729, "s": 37685, "text": "Virtualization In Cloud Computing and Types" }, { "code": null, "e": 37755, "s": 37729, "text": "Software Testing | Basics" } ]
How to Install Popcorn Time on Ubuntu, Mint, Kali Linux? - GeeksforGeeks
07 Mar, 2021 Popcorn Time is a BitTorrent client with multi-platform, free software that provides an integrated media player. A free alternative to subscription-based video streaming services, such as Netflix, is offered by the application. To stream video identified by several torrent websites, Popcorn Time uses sequential downloading and third-party trackers can also be added manually. The software’s legality is contingent on the jurisdiction. Popcorn Time Features Great Movies and TV ShowsAwesome catalogNo restrictionsThe best qualityNo, wait or download time Great Movies and TV Shows Awesome catalog No restrictions The best quality No, wait or download time Step 1: Create a new directory $ mkdir /opt/popcorn-time Make Directory Step 2: Download Popcorn Time You can download Popcorn Time from its official website. The download link is present on the homepage itself click here to download. Now go to the Downloads directory. $ cd Downloads/ Go to download directory Now copy the download link and download popcorn time using the below command $ sudo wget https://get.popcorntime.app/build/Popcorn-Time-0.4.4-linux64.zip Download Popcorn Time Step 3: Extract it into your choice of directory Now extract the zip to the previously created directory. $ sudo unzip Popcorn-Time-0.4.4-linux64.zip -d /opt/popcorntime/ Unzip File Step 4: Create Soft Link You want every user on your device to be able to execute Popcorn Time without access to sudo, right? To do this, you need to construct an executable soft link in the /usr/bin directory. $ sudo ln -sf /opt/popcorn-time/Popcorn-Time /usr/bin/Popcorn-Time Create soft link Step 5: Create Desktop launcher to launch Popcorn time So good so far. But, in the application menu, you would also like to see Popcorn Time, add it to your favorite application list, etc. You need to build a desktop entry for that. Open a terminal and build a new file under /usr/share/applications called popcorntime.desktop. Any command-line-based text editor can be used. Ubuntu has built the default Nano so that you can use it. $ sudo nano /usr/share/applications/popcorntime.desktop Create new entry Add the content in the newly created file as shown below. [Desktop Entry] Version = 1.0 Type = Application Terminal = false Name = Popcorn Time Exec = /usr/bin/Popcorn-Time Icon = /opt/popcorntime/popcorn.png Categories = Application; Add these line If you have used the Nano Editor, save it with the Ctrl+X shortcut. Enter Y when you are asked to save, and then click enter again to save and leave. We’re nearly there. Getting the right icon for Popcorn Time is one more thing to do here. The Popcorn Time icon can be downloaded and saved as popcorn.png in the /opt/popcorntime directory. You may use the command below to do that: sudo wget -O /opt/popcorntime/popcorn.png https://upload.wikimedia.org/wikipedia/commons/d/df/Pctlogo.png Add icon Step 6: Set Desktop shortcut executable Run the below command to make it executable: $ sudo chmod +x /usr/share/applications/popcorntime.desktop Make executable Step 7: Install dependencies (optional) Install the following dependencies if you get an error showing ‘Error loading shared libraries: libgconf-2.so.4: Unable to open shared object file: No such file or directory’ when loading shared libraries. First update your system source: $ sudo apt-get update Update system source Then install dependencies using the below command: sudo apt-get install libcanberra-gtk-module libgconf-2-4 libatomic1 Install dependencies Now Popcorn Time successfully installed on Linux. Now search Popcorn Time on the search bar. Search Accept license Agreement: Accept license Agreement Kali-Linux Picked Technical Scripter 2020 How To Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Add External JAR File to an IntelliJ IDEA Project? How to Set Git Username and Password in GitBash? How to Install Jupyter Notebook on MacOS? How to Create and Setup Spring Boot Project in Eclipse IDE? Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux cut command in Linux with examples cp command in Linux with examples
[ { "code": null, "e": 26223, "s": 26195, "text": "\n07 Mar, 2021" }, { "code": null, "e": 26660, "s": 26223, "text": "Popcorn Time is a BitTorrent client with multi-platform, free software that provides an integrated media player. A free alternative to subscription-based video streaming services, such as Netflix, is offered by the application. To stream video identified by several torrent websites, Popcorn Time uses sequential downloading and third-party trackers can also be added manually. The software’s legality is contingent on the jurisdiction." }, { "code": null, "e": 26682, "s": 26660, "text": "Popcorn Time Features" }, { "code": null, "e": 26779, "s": 26682, "text": "Great Movies and TV ShowsAwesome catalogNo restrictionsThe best qualityNo, wait or download time" }, { "code": null, "e": 26805, "s": 26779, "text": "Great Movies and TV Shows" }, { "code": null, "e": 26821, "s": 26805, "text": "Awesome catalog" }, { "code": null, "e": 26837, "s": 26821, "text": "No restrictions" }, { "code": null, "e": 26854, "s": 26837, "text": "The best quality" }, { "code": null, "e": 26880, "s": 26854, "text": "No, wait or download time" }, { "code": null, "e": 26911, "s": 26880, "text": "Step 1: Create a new directory" }, { "code": null, "e": 26937, "s": 26911, "text": "$ mkdir /opt/popcorn-time" }, { "code": null, "e": 26952, "s": 26937, "text": "Make Directory" }, { "code": null, "e": 26982, "s": 26952, "text": "Step 2: Download Popcorn Time" }, { "code": null, "e": 27115, "s": 26982, "text": "You can download Popcorn Time from its official website. The download link is present on the homepage itself click here to download." }, { "code": null, "e": 27150, "s": 27115, "text": "Now go to the Downloads directory." }, { "code": null, "e": 27166, "s": 27150, "text": "$ cd Downloads/" }, { "code": null, "e": 27191, "s": 27166, "text": "Go to download directory" }, { "code": null, "e": 27268, "s": 27191, "text": "Now copy the download link and download popcorn time using the below command" }, { "code": null, "e": 27345, "s": 27268, "text": "$ sudo wget https://get.popcorntime.app/build/Popcorn-Time-0.4.4-linux64.zip" }, { "code": null, "e": 27367, "s": 27345, "text": "Download Popcorn Time" }, { "code": null, "e": 27416, "s": 27367, "text": "Step 3: Extract it into your choice of directory" }, { "code": null, "e": 27473, "s": 27416, "text": "Now extract the zip to the previously created directory." }, { "code": null, "e": 27538, "s": 27473, "text": "$ sudo unzip Popcorn-Time-0.4.4-linux64.zip -d /opt/popcorntime/" }, { "code": null, "e": 27549, "s": 27538, "text": "Unzip File" }, { "code": null, "e": 27574, "s": 27549, "text": "Step 4: Create Soft Link" }, { "code": null, "e": 27760, "s": 27574, "text": "You want every user on your device to be able to execute Popcorn Time without access to sudo, right? To do this, you need to construct an executable soft link in the /usr/bin directory." }, { "code": null, "e": 27827, "s": 27760, "text": "$ sudo ln -sf /opt/popcorn-time/Popcorn-Time /usr/bin/Popcorn-Time" }, { "code": null, "e": 27844, "s": 27827, "text": "Create soft link" }, { "code": null, "e": 27899, "s": 27844, "text": "Step 5: Create Desktop launcher to launch Popcorn time" }, { "code": null, "e": 28077, "s": 27899, "text": "So good so far. But, in the application menu, you would also like to see Popcorn Time, add it to your favorite application list, etc. You need to build a desktop entry for that." }, { "code": null, "e": 28172, "s": 28077, "text": "Open a terminal and build a new file under /usr/share/applications called popcorntime.desktop." }, { "code": null, "e": 28278, "s": 28172, "text": "Any command-line-based text editor can be used. Ubuntu has built the default Nano so that you can use it." }, { "code": null, "e": 28334, "s": 28278, "text": "$ sudo nano /usr/share/applications/popcorntime.desktop" }, { "code": null, "e": 28351, "s": 28334, "text": "Create new entry" }, { "code": null, "e": 28409, "s": 28351, "text": "Add the content in the newly created file as shown below." }, { "code": null, "e": 28586, "s": 28409, "text": "[Desktop Entry]\nVersion = 1.0\nType = Application\nTerminal = false\nName = Popcorn Time\nExec = /usr/bin/Popcorn-Time\nIcon = /opt/popcorntime/popcorn.png\nCategories = Application;" }, { "code": null, "e": 28601, "s": 28586, "text": "Add these line" }, { "code": null, "e": 28751, "s": 28601, "text": "If you have used the Nano Editor, save it with the Ctrl+X shortcut. Enter Y when you are asked to save, and then click enter again to save and leave." }, { "code": null, "e": 28941, "s": 28751, "text": "We’re nearly there. Getting the right icon for Popcorn Time is one more thing to do here. The Popcorn Time icon can be downloaded and saved as popcorn.png in the /opt/popcorntime directory." }, { "code": null, "e": 28983, "s": 28941, "text": "You may use the command below to do that:" }, { "code": null, "e": 29089, "s": 28983, "text": "sudo wget -O /opt/popcorntime/popcorn.png https://upload.wikimedia.org/wikipedia/commons/d/df/Pctlogo.png" }, { "code": null, "e": 29098, "s": 29089, "text": "Add icon" }, { "code": null, "e": 29138, "s": 29098, "text": "Step 6: Set Desktop shortcut executable" }, { "code": null, "e": 29183, "s": 29138, "text": "Run the below command to make it executable:" }, { "code": null, "e": 29243, "s": 29183, "text": "$ sudo chmod +x /usr/share/applications/popcorntime.desktop" }, { "code": null, "e": 29259, "s": 29243, "text": "Make executable" }, { "code": null, "e": 29299, "s": 29259, "text": "Step 7: Install dependencies (optional)" }, { "code": null, "e": 29505, "s": 29299, "text": "Install the following dependencies if you get an error showing ‘Error loading shared libraries: libgconf-2.so.4: Unable to open shared object file: No such file or directory’ when loading shared libraries." }, { "code": null, "e": 29538, "s": 29505, "text": "First update your system source:" }, { "code": null, "e": 29560, "s": 29538, "text": "$ sudo apt-get update" }, { "code": null, "e": 29581, "s": 29560, "text": "Update system source" }, { "code": null, "e": 29632, "s": 29581, "text": "Then install dependencies using the below command:" }, { "code": null, "e": 29700, "s": 29632, "text": "sudo apt-get install libcanberra-gtk-module libgconf-2-4 libatomic1" }, { "code": null, "e": 29721, "s": 29700, "text": "Install dependencies" }, { "code": null, "e": 29814, "s": 29721, "text": "Now Popcorn Time successfully installed on Linux. Now search Popcorn Time on the search bar." }, { "code": null, "e": 29821, "s": 29814, "text": "Search" }, { "code": null, "e": 29847, "s": 29821, "text": "Accept license Agreement:" }, { "code": null, "e": 29872, "s": 29847, "text": "Accept license Agreement" }, { "code": null, "e": 29883, "s": 29872, "text": "Kali-Linux" }, { "code": null, "e": 29890, "s": 29883, "text": "Picked" }, { "code": null, "e": 29914, "s": 29890, "text": "Technical Scripter 2020" }, { "code": null, "e": 29921, "s": 29914, "text": "How To" }, { "code": null, "e": 29932, "s": 29921, "text": "Linux-Unix" }, { "code": null, "e": 29951, "s": 29932, "text": "Technical Scripter" }, { "code": null, "e": 30049, "s": 29951, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30083, "s": 30049, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 30141, "s": 30083, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 30190, "s": 30141, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 30232, "s": 30190, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 30292, "s": 30232, "text": "How to Create and Setup Spring Boot Project in Eclipse IDE?" }, { "code": null, "e": 30332, "s": 30292, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 30372, "s": 30332, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 30399, "s": 30372, "text": "grep command in Unix/Linux" }, { "code": null, "e": 30434, "s": 30399, "text": "cut command in Linux with examples" } ]
PrintWriter write(String) method in Java with Examples - GeeksforGeeks
29 Jan, 2019 The write(String) method of PrintWriter Class in Java is used to write the specified String on the stream. This String value is taken as a parameter. Syntax: public void write(String string) Parameters: This method accepts a mandatory parameter string which is the String to be written in the Stream. Return Value: This method do not returns any value. Below methods illustrates the working of write(String) method: Program 1: // Java program to demonstrate// PrintWriter write(String) method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a PrintWriter instance PrintWriter writer = new PrintWriter(System.out); // Write the String 'GeeksForGeeks' // to this writer using write() method // This will put the string in the stream // till it is printed on the console writer.write("GeeksForGeeks"); writer.flush(); } catch (Exception e) { System.out.println(e); } }} GeeksForGeeks Program 2: // Java program to demonstrate// PrintWriter write(String) method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a PrintWriter instance PrintWriter writer = new PrintWriter(System.out); // Write the String 'GFG' // to this writer using write() method // This will put the string in the stream // till it is printed on the console writer.write("GFG"); writer.flush(); } catch (Exception e) { System.out.println(e); } }} GFG Java-Functions Java-IO package Java-PrintWriter Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java
[ { "code": null, "e": 25961, "s": 25933, "text": "\n29 Jan, 2019" }, { "code": null, "e": 26111, "s": 25961, "text": "The write(String) method of PrintWriter Class in Java is used to write the specified String on the stream. This String value is taken as a parameter." }, { "code": null, "e": 26119, "s": 26111, "text": "Syntax:" }, { "code": null, "e": 26152, "s": 26119, "text": "public void write(String string)" }, { "code": null, "e": 26262, "s": 26152, "text": "Parameters: This method accepts a mandatory parameter string which is the String to be written in the Stream." }, { "code": null, "e": 26314, "s": 26262, "text": "Return Value: This method do not returns any value." }, { "code": null, "e": 26377, "s": 26314, "text": "Below methods illustrates the working of write(String) method:" }, { "code": null, "e": 26388, "s": 26377, "text": "Program 1:" }, { "code": "// Java program to demonstrate// PrintWriter write(String) method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a PrintWriter instance PrintWriter writer = new PrintWriter(System.out); // Write the String 'GeeksForGeeks' // to this writer using write() method // This will put the string in the stream // till it is printed on the console writer.write(\"GeeksForGeeks\"); writer.flush(); } catch (Exception e) { System.out.println(e); } }}", "e": 27028, "s": 26388, "text": null }, { "code": null, "e": 27043, "s": 27028, "text": "GeeksForGeeks\n" }, { "code": null, "e": 27054, "s": 27043, "text": "Program 2:" }, { "code": "// Java program to demonstrate// PrintWriter write(String) method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a PrintWriter instance PrintWriter writer = new PrintWriter(System.out); // Write the String 'GFG' // to this writer using write() method // This will put the string in the stream // till it is printed on the console writer.write(\"GFG\"); writer.flush(); } catch (Exception e) { System.out.println(e); } }}", "e": 27674, "s": 27054, "text": null }, { "code": null, "e": 27679, "s": 27674, "text": "GFG\n" }, { "code": null, "e": 27694, "s": 27679, "text": "Java-Functions" }, { "code": null, "e": 27710, "s": 27694, "text": "Java-IO package" }, { "code": null, "e": 27727, "s": 27710, "text": "Java-PrintWriter" }, { "code": null, "e": 27732, "s": 27727, "text": "Java" }, { "code": null, "e": 27737, "s": 27732, "text": "Java" }, { "code": null, "e": 27835, "s": 27737, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27886, "s": 27835, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27916, "s": 27886, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27931, "s": 27916, "text": "Stream In Java" }, { "code": null, "e": 27950, "s": 27931, "text": "Interfaces in Java" }, { "code": null, "e": 27981, "s": 27950, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27999, "s": 27981, "text": "ArrayList in Java" }, { "code": null, "e": 28031, "s": 27999, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28051, "s": 28031, "text": "Stack Class in Java" }, { "code": null, "e": 28075, "s": 28051, "text": "Singleton Class in Java" } ]
When is copy constructor called in C++?
The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to − Initialize one object from another of the same type. Copy an object to pass it as an argument to a function. Copy an object to return it from a function. If a copy constructor is not defined in a class, the compiler itself defines one. If the class has pointer variables and has some dynamic memory allocations, then it is a must to have a copy constructor. The most common form of copy constructor is shown here − classname (const classname &obj) { // body of constructor } Here, obj is a reference to an object that is being used to initialize another object. Live Demo #include <iostream> using namespace std; class Line { public: int getLength( void ); Line( int len ); // simple constructor Line( const Line &obj); // copy constructor ~Line(); // destructor private: int *ptr; }; // Member functions definitions including constructor Line::Line(int len) { cout << "Normal constructor allocating ptr" << endl; // allocate memory for the pointer; ptr = new int; *ptr = len; } Line::Line(const Line &obj) { cout << "Copy constructor allocating ptr." << endl; ptr = new int; *ptr = *obj.ptr; // copy the value } Line::~Line(void) { cout << "Freeing memory!" << endl; delete ptr; } int Line::getLength( void ) { return *ptr; } void display(Line obj) { cout << "Length of line : " << obj.getLength() <<endl; } // Main function for the program int main() { Line line(10); display(line); return 0; } Normal constructor allocating ptr Copy constructor allocating ptr. Length of line : 10 Freeing memory! Freeing memory! Let us see the same example but with a small change to create another object using an existing object of the same type − Live Demo #include <iostream> using namespace std; class Line { public: int getLength( void ); Line( int len ); // simple constructor Line( const Line &obj); // copy constructor ~Line(); // destructor private: int *ptr; }; // Member functions definitions including constructor Line::Line(int len) { cout << "Normal constructor allocating ptr" << endl; // allocate memory for the pointer; ptr = new int; *ptr = len; } Line::Line(const Line &obj) { cout << "Copy constructor allocating ptr." << endl; ptr = new int; *ptr = *obj.ptr; // copy the value } Line::~Line(void) { cout << "Freeing memory!" << endl; delete ptr; } int Line::getLength( void ) { return *ptr; } void display(Line obj) { cout << "Length of line : " << obj.getLength() <<endl; } // Main function for the program int main() { Line line1(10); Line line2 = line1; // This also calls copy constructor display(line1); display(line2); return 0; } Normal constructor allocating ptr Copy constructor allocating ptr. Copy constructor allocating ptr. Length of line : 10 Freeing memory! Copy constructor allocating ptr. Length of line : 10 Freeing memory! Freeing memory! Freeing memory!
[ { "code": null, "e": 1246, "s": 1062, "text": "The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to −" }, { "code": null, "e": 1299, "s": 1246, "text": "Initialize one object from another of the same type." }, { "code": null, "e": 1355, "s": 1299, "text": "Copy an object to pass it as an argument to a function." }, { "code": null, "e": 1400, "s": 1355, "text": "Copy an object to return it from a function." }, { "code": null, "e": 1661, "s": 1400, "text": "If a copy constructor is not defined in a class, the compiler itself defines one. If the class has pointer variables and has some dynamic memory allocations, then it is a must to have a copy constructor. The most common form of copy constructor is shown here −" }, { "code": null, "e": 1724, "s": 1661, "text": "classname (const classname &obj) {\n // body of constructor\n}" }, { "code": null, "e": 1811, "s": 1724, "text": "Here, obj is a reference to an object that is being used to initialize another object." }, { "code": null, "e": 1822, "s": 1811, "text": " Live Demo" }, { "code": null, "e": 2734, "s": 1822, "text": "#include <iostream>\nusing namespace std;\n\nclass Line {\n public:\n int getLength( void );\n Line( int len ); // simple constructor\n Line( const Line &obj); // copy constructor\n ~Line(); // destructor\n\n private:\n int *ptr;\n};\n\n// Member functions definitions including constructor\nLine::Line(int len) {\n cout << \"Normal constructor allocating ptr\" << endl;\n\n // allocate memory for the pointer;\n ptr = new int;\n *ptr = len;\n}\n\nLine::Line(const Line &obj) {\n cout << \"Copy constructor allocating ptr.\" << endl;\n ptr = new int;\n *ptr = *obj.ptr; // copy the value\n}\n\nLine::~Line(void) {\n cout << \"Freeing memory!\" << endl;\n delete ptr;\n}\n\nint Line::getLength( void ) {\n return *ptr;\n}\n\nvoid display(Line obj) {\n cout << \"Length of line : \" << obj.getLength() <<endl;\n}\n\n// Main function for the program\nint main() {\n Line line(10);\n display(line);\n return 0;\n}" }, { "code": null, "e": 2853, "s": 2734, "text": "Normal constructor allocating ptr\nCopy constructor allocating ptr.\nLength of line : 10\nFreeing memory!\nFreeing memory!" }, { "code": null, "e": 2974, "s": 2853, "text": "Let us see the same example but with a small change to create another object using an existing object of the same type −" }, { "code": null, "e": 2985, "s": 2974, "text": " Live Demo" }, { "code": null, "e": 3981, "s": 2985, "text": "#include <iostream>\nusing namespace std;\n\nclass Line {\n public:\n int getLength( void );\n Line( int len ); // simple constructor\n Line( const Line &obj); // copy constructor\n ~Line(); // destructor\n\n private:\n int *ptr;\n};\n\n// Member functions definitions including constructor\nLine::Line(int len) {\n cout << \"Normal constructor allocating ptr\" << endl;\n\n // allocate memory for the pointer;\n ptr = new int;\n *ptr = len;\n}\n\nLine::Line(const Line &obj) {\n cout << \"Copy constructor allocating ptr.\" << endl;\n ptr = new int;\n *ptr = *obj.ptr; // copy the value\n}\n\nLine::~Line(void) {\n cout << \"Freeing memory!\" << endl;\n delete ptr;\n}\n\nint Line::getLength( void ) {\n return *ptr;\n}\n\nvoid display(Line obj) {\n cout << \"Length of line : \" << obj.getLength() <<endl;\n}\n\n// Main function for the program\n int main() {\n Line line1(10);\n Line line2 = line1; // This also calls copy constructor\n\n display(line1);\n display(line2);\n return 0;\n}" }, { "code": null, "e": 4218, "s": 3981, "text": "Normal constructor allocating ptr\nCopy constructor allocating ptr.\nCopy constructor allocating ptr.\nLength of line : 10\nFreeing memory!\nCopy constructor allocating ptr.\nLength of line : 10\nFreeing memory!\nFreeing memory!\nFreeing memory!" } ]
How to set same scale for subplots in Python using Matplotlib?
To set the same scale for subplot in Python using Matplotlib, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Create a new figure or activate an existing figure. Add an 'ax1' to the figure as part of a subplot arrangement with nrows=2, ncols=1 and index=1. Add another axis 'ax2' to the figure as part of a subplot arrangement with nrows=2, ncols=1 and index=2, with shared X-axis (to set same scale for subplots) Create "t" data points to plot sine and cosine curves on axes ax1 and ax2. To display the figure, use show() method. import matplotlib.pyplot as plt import numpy as np # Set the figure size plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True # Plot the figure fig = plt.figure() # Add the axes ax1 = fig.add_subplot(2, 1, 1) ax2 = fig.add_subplot(2, 1, 2, sharex=ax1) # Create data points t = np.linspace(-5, 5, 100) # Plot sine and cosine curves on ax1 and ax2 ax1.plot(t, np.sin(2 * np.pi * t), color='red', lw=4) ax2.plot(t, np.cos(2 * np.pi * t), color='orange', lw=4) plt.show() It will produce the following output
[ { "code": null, "e": 1158, "s": 1062, "text": "To set the same scale for subplot in Python using Matplotlib, we can take the following steps −" }, { "code": null, "e": 1234, "s": 1158, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1286, "s": 1234, "text": "Create a new figure or activate an existing figure." }, { "code": null, "e": 1381, "s": 1286, "text": "Add an 'ax1' to the figure as part of a subplot arrangement with nrows=2, ncols=1 and index=1." }, { "code": null, "e": 1538, "s": 1381, "text": "Add another axis 'ax2' to the figure as part of a subplot arrangement with nrows=2, ncols=1 and index=2, with shared X-axis (to set same scale for subplots)" }, { "code": null, "e": 1613, "s": 1538, "text": "Create \"t\" data points to plot sine and cosine curves on axes ax1 and ax2." }, { "code": null, "e": 1655, "s": 1613, "text": "To display the figure, use show() method." }, { "code": null, "e": 2163, "s": 1655, "text": "import matplotlib.pyplot as plt\nimport numpy as np\n\n# Set the figure size\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\n# Plot the figure\nfig = plt.figure()\n\n# Add the axes\nax1 = fig.add_subplot(2, 1, 1)\nax2 = fig.add_subplot(2, 1, 2, sharex=ax1)\n\n# Create data points\nt = np.linspace(-5, 5, 100)\n\n# Plot sine and cosine curves on ax1 and ax2\nax1.plot(t, np.sin(2 * np.pi * t), color='red', lw=4)\nax2.plot(t, np.cos(2 * np.pi * t), color='orange', lw=4)\n\nplt.show()" }, { "code": null, "e": 2200, "s": 2163, "text": "It will produce the following output" } ]
How to access child's state in React? - GeeksforGeeks
01 Feb, 2021 In React we can access the child’s state using Refs. we will assign a Refs for the child component in the parent component. then using Refs we can access the child’s state. Creating Refs Refs are created using React.createRef() and attached to React elements via the ref attribute. class App extends React.Component { constructor(props) { super(props); //creating ref this.childRef= React.createRef(); } render() { return ( //assigning the ref to child component <Child ref= {this.myRef } /> ) } } Accessing Refs When we assign a ref to an element or child component in the render, then we can access the element using the current attribute of the ref. const element = this.myRef.current; in the same way, we can access the state using element.state.state_name from the parent component. Create a react app and edit the App.js file as: Filepath- src/App.js Javascript import React from "react";import Child from './Child' class App extends React.Component { constructor(props) { super(props); this.ChildElement = React.createRef(); } handleClick = () => { const childelement = this.ChildElement.current; alert("current state of child is : "+ childelement.state.name); childelement.changeName("Aakash"); }; render() { return ( <div > <Child ref={this.ChildElement} /> <button onClick={this.handleClick}>Show real name</button> </div> ); }}export default App Create a new Child.js component in src folder and edit it as follow: Filepath- src/Child.js: Javascript import React from 'react'class Child extends React.Component { state = { name: "Batman" }; changeName = (newname ) => { this.setState({ name:newname }); }; render() { return <div>{this.state.name}</div>; }}export default Child Output: Picked ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments ReactJS useNavigate() Hook How to set background images in ReactJS ? How to navigate on path by button click in react router ? How to create a table in ReactJS ? How to parse JSON Data into React Table Component ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? Top 10 Angular Libraries For Web Developers
[ { "code": null, "e": 24708, "s": 24680, "text": "\n01 Feb, 2021" }, { "code": null, "e": 24882, "s": 24708, "text": "In React we can access the child’s state using Refs. we will assign a Refs for the child component in the parent component. then using Refs we can access the child’s state." }, { "code": null, "e": 24991, "s": 24882, "text": "Creating Refs Refs are created using React.createRef() and attached to React elements via the ref attribute." }, { "code": null, "e": 25214, "s": 24991, "text": "class App extends React.Component {\nconstructor(props) {\n super(props);\n //creating ref\n this.childRef= React.createRef();\n}\nrender() {\n return (\n //assigning the ref to child component\n <Child ref= {this.myRef } />\n )\n}\n}" }, { "code": null, "e": 25369, "s": 25214, "text": "Accessing Refs When we assign a ref to an element or child component in the render, then we can access the element using the current attribute of the ref." }, { "code": null, "e": 25405, "s": 25369, "text": "const element = this.myRef.current;" }, { "code": null, "e": 25504, "s": 25405, "text": "in the same way, we can access the state using element.state.state_name from the parent component." }, { "code": null, "e": 25552, "s": 25504, "text": "Create a react app and edit the App.js file as:" }, { "code": null, "e": 25573, "s": 25552, "text": "Filepath- src/App.js" }, { "code": null, "e": 25584, "s": 25573, "text": "Javascript" }, { "code": "import React from \"react\";import Child from './Child' class App extends React.Component { constructor(props) { super(props); this.ChildElement = React.createRef(); } handleClick = () => { const childelement = this.ChildElement.current; alert(\"current state of child is : \"+ childelement.state.name); childelement.changeName(\"Aakash\"); }; render() { return ( <div > <Child ref={this.ChildElement} /> <button onClick={this.handleClick}>Show real name</button> </div> ); }}export default App", "e": 26140, "s": 25584, "text": null }, { "code": null, "e": 26209, "s": 26140, "text": "Create a new Child.js component in src folder and edit it as follow:" }, { "code": null, "e": 26233, "s": 26209, "text": "Filepath- src/Child.js:" }, { "code": null, "e": 26244, "s": 26233, "text": "Javascript" }, { "code": "import React from 'react'class Child extends React.Component { state = { name: \"Batman\" }; changeName = (newname ) => { this.setState({ name:newname }); }; render() { return <div>{this.state.name}</div>; }}export default Child", "e": 26494, "s": 26244, "text": null }, { "code": null, "e": 26502, "s": 26494, "text": "Output:" }, { "code": null, "e": 26509, "s": 26502, "text": "Picked" }, { "code": null, "e": 26517, "s": 26509, "text": "ReactJS" }, { "code": null, "e": 26534, "s": 26517, "text": "Web Technologies" }, { "code": null, "e": 26632, "s": 26534, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26641, "s": 26632, "text": "Comments" }, { "code": null, "e": 26654, "s": 26641, "text": "Old Comments" }, { "code": null, "e": 26681, "s": 26654, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 26723, "s": 26681, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 26781, "s": 26723, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 26816, "s": 26781, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 26868, "s": 26816, "text": "How to parse JSON Data into React Table Component ?" }, { "code": null, "e": 26910, "s": 26868, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26943, "s": 26910, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27005, "s": 26943, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27055, "s": 27005, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Keras vs PyTorch for Deep Learning | by George Seif | Towards Data Science
Want to be inspired? Come join my Super Quotes newsletter. 😎 For many Scientists, Engineers, and Developers, TensorFlow was their first Deep Learning framework. TensorFlow 1.0 was released back February 2017; to say the least, it wasn’t very user friendly. Over the past couple of years, two major Deep Learning libraries have gained massive popularity, mainly due to how much easier to use they are over TensorFlow: Keras and PyTorch. The article will cover a list of 4 different aspects of Keras vs. PyTorch and why you might pick one library over the other. Keras is not a framework on it’s own, but actually a high-level API that sits on top of other Deep Learning frameworks. Currently it supports TensorFlow, Theano, and CNTK. The beauty of Keras lies in its easy of use. It’s by far the easiest framework to get up and running fast. Defining neural networks is intuitive, where using the functional API allows one to define layers as functions. Pyorch is a Deep Learning framework (like TensorFlow) developed by Facebook’s AI research group. Like Keras, it also abstracts away much of the messy parts of programming deep networks. In terms of high vs low level coding style, Pytorch lies somewhere in between Keras and TensorFlow. You have more flexibility and control than Keras, but at the same time you’re not having to do any crazy declarative programming. Deep Learning practitioners wrestle back and forth all day about which framework one should use. Generally, it’s up to personal preference. But there are a few aspects of Keras and Pytorch that you should keep in mind when making your pick. To define Deep Learning models, Keras offers the Functional API. With the Functional API, neural networks are defined as a set of sequential functions, applied one after the other. For example, the output of the function defining layer 1 is the input of the function defining layer 2. img_input = layers.Input(shape=input_shape)x = layers.Conv2D(64, (3, 3), activation='relu')(img_input) x = layers.Conv2D(64, (3, 3), activation='relu')(x) x = layers.MaxPooling2D((2, 2), strides=(2, 2))(x) In Pytorch, you set up your network as a class which extends the torch.nn.Module from the Torch library. Similar to Keras, Pytorch provides you layers as building blocks, but since they’re in a Python class they are reference in the class’s __init__() method and executed by the class’s forward() method. class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 64, 3) self.conv2 = nn.Conv2d(64, 64, 3) self.pool = nn.MaxPool2d(2, 2) def forward(self, x): x = F.relu(self.conv1(x)) x = self.pool(F.relu(self.conv2(x))) return xmodel = Net() Because Pytorch gives you access to all of Python’s class features as opposed to simple function calls, defining the networks can be a lot clearer and more elegantly contained. There’s really not much downside to this, unless you really feel that writing your network code as quickly as possible is most important to you, then Keras will be a bit easier to work with. The Keras API hides a lot of the messy details from the casual coder. Defining the network layers is intuitive and the default settings are often enough to get you started. The only time you really have to get down to low-level, nitty-gritty TensorFlow is when you’re implementing a fairly cutting-edge or “exotic” model. The tricky part is that when you do actually go down to the lower-level TensorFlow code, you get all the challenging parts that come along with it! You’ll need to make sure that all of your matrix multiplications line up. Oh and don’t even think about trying to print out one of the outputs of your layers, as you’ll just get a nice Tensor definition printed out on your terminal. Pytorch tends to be a little more forgiving in these aspects. You are required to know the input and output sizes of each of the layers, but this is one of the easier aspects which one can get the hang of quite quickly. You don’t have to deal with building an abstract computational graph which you can’t see inside of for debugging. Another plus for Pytorch is the smoothness in which you can go back and forth between Torch Tensors and Numpy arrays. If you need to implement something custom, then going back and forth between TF tensors and Numpy arrays can be a pain, requiring the developer to have a solid understanding of TensorFlow sessions. Pytorch interop is actually much simpler. There’s just two operations you need to know: one to switch a Torch Tensor (a Variable object) to Numpy and another one to go in the opposite direction. Of course, if you never have to implement anything fancy, then Keras will do just fine as you won’t run into any TensorFlow road blocks. But if you do, then Pytorch will probably be a lot smoother of a ride. Training a model in Keras is super easy! Just a simple .fit() and you can kick your feet up and enjoy the ride! history = model.fit_generator( generator=train_generator, epochs=10, validation_data=validation_generator) Training a model in Pytorch consists of a few steps: Initialise gradients at the start of each batch of trainingRun the forward pass through the mode;Run the backward passCompute the loss and update the weights Initialise gradients at the start of each batch of training Run the forward pass through the mode; Run the backward pass Compute the loss and update the weights for epoch in range(2): # loop over the dataset multiple times running_loss = 0.0 for i, data in enumerate(trainloader, 0): # Get the inputs; data is a list of [inputs, labels] inputs, labels = data # (1) Initialise gradients optimizer.zero_grad() # (2) Forward pass outputs = net(inputs) loss = criterion(outputs, labels) # (3) Backward loss.backward() # (4) Compute the loss and update the weights optimizer.step() That’s a lot of steps just to run the training! I suppose this way you’re always aware of what’s happening. At the same time, it’s quite unnecessary since these model training steps essentially remain unchanged for training different models. If you have tensorflow-gpu installed, then using the GPU is enabled and done by default in Keras. Then, if you wish to move certain operations to CPU, you can do so with a one-liner. with tf.device('/cpu:0'): y = apply_non_max_suppression(x) For Pytorch, you’ll have to enable the GPU explicitly for every torch tensor and numpy variable. This clutters up the code and can be a bit error prone if you move back and forth between CPU and GPU for different operation. For example, to transfer our previous model to run on GPU we have to do the following: # Get the GPU devicedevice = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")# Transfer the network to GPUnet.to(device)# Transfer the inputs and labels to GPUinputs, labels = data[0].to(device), data[1].to(device) Keras wins here on its simplicity and nice default setup The advice I usually give is to start with Keras. Keras is definitely the easiest framework to use, understand, and quickly get up and running with. You don’t have to worry about GPU setup, fiddling with abstract code, or in general doing anything complicated. You can even do things like implementing custom layers and loss functions without ever touching a single line of TensorFlow. If you do start to get down to the more fine-grained aspects of deep networks or are implementing something that’s non-standard, then Pytorch is your go-to library. It’ll be a bit of extra work over Keras, but not so much so that it slows you down. You’ll still be able to rapidly implement, train, and test your networks, with the added bonus of easy debugging! Follow me on twitter where I post all about the latest and greatest AI, Technology, and Science! Connect with me on LinkedIn too!
[ { "code": null, "e": 233, "s": 172, "text": "Want to be inspired? Come join my Super Quotes newsletter. 😎" }, { "code": null, "e": 429, "s": 233, "text": "For many Scientists, Engineers, and Developers, TensorFlow was their first Deep Learning framework. TensorFlow 1.0 was released back February 2017; to say the least, it wasn’t very user friendly." }, { "code": null, "e": 608, "s": 429, "text": "Over the past couple of years, two major Deep Learning libraries have gained massive popularity, mainly due to how much easier to use they are over TensorFlow: Keras and PyTorch." }, { "code": null, "e": 733, "s": 608, "text": "The article will cover a list of 4 different aspects of Keras vs. PyTorch and why you might pick one library over the other." }, { "code": null, "e": 905, "s": 733, "text": "Keras is not a framework on it’s own, but actually a high-level API that sits on top of other Deep Learning frameworks. Currently it supports TensorFlow, Theano, and CNTK." }, { "code": null, "e": 1124, "s": 905, "text": "The beauty of Keras lies in its easy of use. It’s by far the easiest framework to get up and running fast. Defining neural networks is intuitive, where using the functional API allows one to define layers as functions." }, { "code": null, "e": 1310, "s": 1124, "text": "Pyorch is a Deep Learning framework (like TensorFlow) developed by Facebook’s AI research group. Like Keras, it also abstracts away much of the messy parts of programming deep networks." }, { "code": null, "e": 1540, "s": 1310, "text": "In terms of high vs low level coding style, Pytorch lies somewhere in between Keras and TensorFlow. You have more flexibility and control than Keras, but at the same time you’re not having to do any crazy declarative programming." }, { "code": null, "e": 1781, "s": 1540, "text": "Deep Learning practitioners wrestle back and forth all day about which framework one should use. Generally, it’s up to personal preference. But there are a few aspects of Keras and Pytorch that you should keep in mind when making your pick." }, { "code": null, "e": 2066, "s": 1781, "text": "To define Deep Learning models, Keras offers the Functional API. With the Functional API, neural networks are defined as a set of sequential functions, applied one after the other. For example, the output of the function defining layer 1 is the input of the function defining layer 2." }, { "code": null, "e": 2278, "s": 2066, "text": "img_input = layers.Input(shape=input_shape)x = layers.Conv2D(64, (3, 3), activation='relu')(img_input) x = layers.Conv2D(64, (3, 3), activation='relu')(x) x = layers.MaxPooling2D((2, 2), strides=(2, 2))(x)" }, { "code": null, "e": 2583, "s": 2278, "text": "In Pytorch, you set up your network as a class which extends the torch.nn.Module from the Torch library. Similar to Keras, Pytorch provides you layers as building blocks, but since they’re in a Python class they are reference in the class’s __init__() method and executed by the class’s forward() method." }, { "code": null, "e": 2913, "s": 2583, "text": "class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 64, 3) self.conv2 = nn.Conv2d(64, 64, 3) self.pool = nn.MaxPool2d(2, 2) def forward(self, x): x = F.relu(self.conv1(x)) x = self.pool(F.relu(self.conv2(x))) return xmodel = Net()" }, { "code": null, "e": 3281, "s": 2913, "text": "Because Pytorch gives you access to all of Python’s class features as opposed to simple function calls, defining the networks can be a lot clearer and more elegantly contained. There’s really not much downside to this, unless you really feel that writing your network code as quickly as possible is most important to you, then Keras will be a bit easier to work with." }, { "code": null, "e": 3454, "s": 3281, "text": "The Keras API hides a lot of the messy details from the casual coder. Defining the network layers is intuitive and the default settings are often enough to get you started." }, { "code": null, "e": 3603, "s": 3454, "text": "The only time you really have to get down to low-level, nitty-gritty TensorFlow is when you’re implementing a fairly cutting-edge or “exotic” model." }, { "code": null, "e": 3984, "s": 3603, "text": "The tricky part is that when you do actually go down to the lower-level TensorFlow code, you get all the challenging parts that come along with it! You’ll need to make sure that all of your matrix multiplications line up. Oh and don’t even think about trying to print out one of the outputs of your layers, as you’ll just get a nice Tensor definition printed out on your terminal." }, { "code": null, "e": 4318, "s": 3984, "text": "Pytorch tends to be a little more forgiving in these aspects. You are required to know the input and output sizes of each of the layers, but this is one of the easier aspects which one can get the hang of quite quickly. You don’t have to deal with building an abstract computational graph which you can’t see inside of for debugging." }, { "code": null, "e": 4634, "s": 4318, "text": "Another plus for Pytorch is the smoothness in which you can go back and forth between Torch Tensors and Numpy arrays. If you need to implement something custom, then going back and forth between TF tensors and Numpy arrays can be a pain, requiring the developer to have a solid understanding of TensorFlow sessions." }, { "code": null, "e": 4829, "s": 4634, "text": "Pytorch interop is actually much simpler. There’s just two operations you need to know: one to switch a Torch Tensor (a Variable object) to Numpy and another one to go in the opposite direction." }, { "code": null, "e": 5037, "s": 4829, "text": "Of course, if you never have to implement anything fancy, then Keras will do just fine as you won’t run into any TensorFlow road blocks. But if you do, then Pytorch will probably be a lot smoother of a ride." }, { "code": null, "e": 5149, "s": 5037, "text": "Training a model in Keras is super easy! Just a simple .fit() and you can kick your feet up and enjoy the ride!" }, { "code": null, "e": 5265, "s": 5149, "text": "history = model.fit_generator( generator=train_generator, epochs=10, validation_data=validation_generator)" }, { "code": null, "e": 5318, "s": 5265, "text": "Training a model in Pytorch consists of a few steps:" }, { "code": null, "e": 5476, "s": 5318, "text": "Initialise gradients at the start of each batch of trainingRun the forward pass through the mode;Run the backward passCompute the loss and update the weights" }, { "code": null, "e": 5536, "s": 5476, "text": "Initialise gradients at the start of each batch of training" }, { "code": null, "e": 5575, "s": 5536, "text": "Run the forward pass through the mode;" }, { "code": null, "e": 5597, "s": 5575, "text": "Run the backward pass" }, { "code": null, "e": 5637, "s": 5597, "text": "Compute the loss and update the weights" }, { "code": null, "e": 6137, "s": 5637, "text": "for epoch in range(2): # loop over the dataset multiple times running_loss = 0.0 for i, data in enumerate(trainloader, 0): # Get the inputs; data is a list of [inputs, labels] inputs, labels = data # (1) Initialise gradients optimizer.zero_grad() # (2) Forward pass outputs = net(inputs) loss = criterion(outputs, labels) # (3) Backward loss.backward() # (4) Compute the loss and update the weights optimizer.step()" }, { "code": null, "e": 6185, "s": 6137, "text": "That’s a lot of steps just to run the training!" }, { "code": null, "e": 6379, "s": 6185, "text": "I suppose this way you’re always aware of what’s happening. At the same time, it’s quite unnecessary since these model training steps essentially remain unchanged for training different models." }, { "code": null, "e": 6562, "s": 6379, "text": "If you have tensorflow-gpu installed, then using the GPU is enabled and done by default in Keras. Then, if you wish to move certain operations to CPU, you can do so with a one-liner." }, { "code": null, "e": 6624, "s": 6562, "text": "with tf.device('/cpu:0'): y = apply_non_max_suppression(x)" }, { "code": null, "e": 6848, "s": 6624, "text": "For Pytorch, you’ll have to enable the GPU explicitly for every torch tensor and numpy variable. This clutters up the code and can be a bit error prone if you move back and forth between CPU and GPU for different operation." }, { "code": null, "e": 6935, "s": 6848, "text": "For example, to transfer our previous model to run on GPU we have to do the following:" }, { "code": null, "e": 7164, "s": 6935, "text": "# Get the GPU devicedevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")# Transfer the network to GPUnet.to(device)# Transfer the inputs and labels to GPUinputs, labels = data[0].to(device), data[1].to(device)" }, { "code": null, "e": 7221, "s": 7164, "text": "Keras wins here on its simplicity and nice default setup" }, { "code": null, "e": 7271, "s": 7221, "text": "The advice I usually give is to start with Keras." }, { "code": null, "e": 7607, "s": 7271, "text": "Keras is definitely the easiest framework to use, understand, and quickly get up and running with. You don’t have to worry about GPU setup, fiddling with abstract code, or in general doing anything complicated. You can even do things like implementing custom layers and loss functions without ever touching a single line of TensorFlow." }, { "code": null, "e": 7970, "s": 7607, "text": "If you do start to get down to the more fine-grained aspects of deep networks or are implementing something that’s non-standard, then Pytorch is your go-to library. It’ll be a bit of extra work over Keras, but not so much so that it slows you down. You’ll still be able to rapidly implement, train, and test your networks, with the added bonus of easy debugging!" } ]
Ionic - Icons
There are more than 700 premium icons provided by Ionic. There are also different sets of icons provided for Android and IOS. You can find almost anything you need but you are not bound to use them, if you do not want to. You can use your own custom icons or any other icon set instead. You can check all the Ionic icons here. If you want to use Ionic icons find the icon you need on the page (https://ionicons.com/). When you are adding Ionic elements, you always add the main class first and then you add the subclass you want. The main class for all icons is icon. The Subclass is the name of the icon you want. We will add six icons in our example that is given below − <i class = "icon icon ion-happy-outline"></i> <i class = "icon icon ion-star"></i> <i class = "icon icon ion-compass"></i> <i class = "icon icon ion-planet"></i> <i class = "icon icon ion-ios-analytics"></i> <i class = "icon icon ion-ios-eye"></i> The above code will produce the following screen − The size of these icons can be changed with the font-size property in your Ionic CSS file. .icon { font-size: 50px; } Once the icon size is setup, the same code will produce the following screenshot as the output − 16 Lectures 2.5 hours Frahaan Hussain 185 Lectures 46.5 hours Nikhil Agarwal Print Add Notes Bookmark this page
[ { "code": null, "e": 2790, "s": 2463, "text": "There are more than 700 premium icons provided by Ionic. There are also different sets of icons provided for Android and IOS. You can find almost anything you need but you are not bound to use them, if you do not want to. You can use your own custom icons or any other icon set instead. You can check all the Ionic icons here." }, { "code": null, "e": 3137, "s": 2790, "text": "If you want to use Ionic icons find the icon you need on the page (https://ionicons.com/). When you are adding Ionic elements, you always add the main class first and then you add the subclass you want. The main class for all icons is icon. The Subclass is the name of the icon you want. We will add six icons in our example that is given below −" }, { "code": null, "e": 3385, "s": 3137, "text": "<i class = \"icon icon ion-happy-outline\"></i>\n<i class = \"icon icon ion-star\"></i>\n<i class = \"icon icon ion-compass\"></i>\n<i class = \"icon icon ion-planet\"></i>\n<i class = \"icon icon ion-ios-analytics\"></i>\n<i class = \"icon icon ion-ios-eye\"></i>" }, { "code": null, "e": 3436, "s": 3385, "text": "The above code will produce the following screen −" }, { "code": null, "e": 3527, "s": 3436, "text": "The size of these icons can be changed with the font-size property in your Ionic CSS file." }, { "code": null, "e": 3557, "s": 3527, "text": ".icon {\n font-size: 50px;\n}" }, { "code": null, "e": 3654, "s": 3557, "text": "Once the icon size is setup, the same code will produce the following screenshot as the output −" }, { "code": null, "e": 3689, "s": 3654, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3706, "s": 3689, "text": " Frahaan Hussain" }, { "code": null, "e": 3743, "s": 3706, "text": "\n 185 Lectures \n 46.5 hours \n" }, { "code": null, "e": 3759, "s": 3743, "text": " Nikhil Agarwal" }, { "code": null, "e": 3766, "s": 3759, "text": " Print" }, { "code": null, "e": 3777, "s": 3766, "text": " Add Notes" } ]
Image Processing Class #3 — Point Operation | by Pitchaya Thipkham | Towards Data Science
This article is for sum up the lesson that I have learned in medical image processing class (EGBE443). This article is about basic image processing. If you are new in this field, you can read my first post by clicking the link below. :) towardsdatascience.com Sometimes, pictures taken from the camera may provide poor quality. They were the result of the terrible light at that moment. So, A basic way in image processing to enhance image quality is the point operation. Point Operation Auto-contrast Adjustment Modified Auto-Contrast Histogram Equalization Histogram Specification Point Operation is the modification of the pixel value without changing in the size, geometry and local structure of the image. The new pixel value depends only on the previous value. They are mapped by a function f(a) if the function f() not depend on the coordinate, it is called “global” or “homogeneous” operation. Another one is called “nonhomogeneous” point operation if it depends on the coordinate. Nonhomogeneous point operation is used to compensate for uneven lighting during image acquisition. The common examples of homogeneous operation include: Modifying contrast and brightness Limiting the Result by Clamping Inverting Image Threshold Operation The implement of the point operation affects on the histogram. Raising the brightness shift the histogram to right and increasing the contrast of the image expand the histogram. These point operations map the intensity by the mapping function contained the constant which is image content such as the highest intensity and the lowest intensity. Auto-contrast modification is the method to map the lowest intensity and highest intensity which found in the image to the minimum and maximum intensity of the full intensity range respectively (in case of 8 bits gray-scale image, the full range is 0–255). The mapping function of Auto-contrast adjustment is defined as From the equation, a min, a max, a low and a high are minimum value intensity, maximum value intensity in the range, lowest intensity and highest intensity respectively. In case of 8-bit image, a min=0 and a max=255 so the mapping function is defined as The highest intensity and the lowest intensity may be the noise of the image, We exclude these noise by saturating intensity of the image using quantile. And it can be calculated from the equation below. And the mapping equation is defined as This task performs in order to make the difference of two images easier to compare and to use in print publication. The principle is mapping image histogram to an approximate uniform distribution. The mapping function is defined as: Where H(a) is the cumulative histogram of pixel value a, K is maximum intensity value and MN is the lastest cumulative intensity. You can apply it to your python code using OpenCV module equ = cv2.equalizeHist(img) And here is the result of histogram equalization process. This task is similar to histogram equalization but the aim of this process is mapping distribution function of histogram to the reference distribution. To be independent of image size, the image intensity needs to be normalized into range 0–1. Normalized histogram is interpreted as a probability density function (pdf) of random process. Where p(i) is probability for the pixel value i and h(i) is the summation of all intensity value. So the summation of all probability function is equal 1. H(i) defined as cumulative histogram and the statistical counterpart of H(i) is discrete distribution function P(). This is also called cumulative distribution function (cdf). Principle of histogram specification As shown in the figure, we need to map the pdf of image A to the reference image R. We obtain the new pixel value a’ as So, the mapping function is defined as Make sure that pdf of reference image R is invertible (have exiting value for b =[0,1]). However, there is not only point operation which is the method to modify image but there is another method and it was called ‘Filter’. I will introduce you more information in the next chapter. See you soon! Now, the next chapter is published. You can click the link below to read it. :D
[ { "code": null, "e": 274, "s": 171, "text": "This article is for sum up the lesson that I have learned in medical image processing class (EGBE443)." }, { "code": null, "e": 408, "s": 274, "text": "This article is about basic image processing. If you are new in this field, you can read my first post by clicking the link below. :)" }, { "code": null, "e": 431, "s": 408, "text": "towardsdatascience.com" }, { "code": null, "e": 643, "s": 431, "text": "Sometimes, pictures taken from the camera may provide poor quality. They were the result of the terrible light at that moment. So, A basic way in image processing to enhance image quality is the point operation." }, { "code": null, "e": 659, "s": 643, "text": "Point Operation" }, { "code": null, "e": 684, "s": 659, "text": "Auto-contrast Adjustment" }, { "code": null, "e": 707, "s": 684, "text": "Modified Auto-Contrast" }, { "code": null, "e": 730, "s": 707, "text": "Histogram Equalization" }, { "code": null, "e": 754, "s": 730, "text": "Histogram Specification" }, { "code": null, "e": 973, "s": 754, "text": "Point Operation is the modification of the pixel value without changing in the size, geometry and local structure of the image. The new pixel value depends only on the previous value. They are mapped by a function f(a)" }, { "code": null, "e": 1260, "s": 973, "text": "if the function f() not depend on the coordinate, it is called “global” or “homogeneous” operation. Another one is called “nonhomogeneous” point operation if it depends on the coordinate. Nonhomogeneous point operation is used to compensate for uneven lighting during image acquisition." }, { "code": null, "e": 1314, "s": 1260, "text": "The common examples of homogeneous operation include:" }, { "code": null, "e": 1348, "s": 1314, "text": "Modifying contrast and brightness" }, { "code": null, "e": 1380, "s": 1348, "text": "Limiting the Result by Clamping" }, { "code": null, "e": 1396, "s": 1380, "text": "Inverting Image" }, { "code": null, "e": 1416, "s": 1396, "text": "Threshold Operation" }, { "code": null, "e": 1761, "s": 1416, "text": "The implement of the point operation affects on the histogram. Raising the brightness shift the histogram to right and increasing the contrast of the image expand the histogram. These point operations map the intensity by the mapping function contained the constant which is image content such as the highest intensity and the lowest intensity." }, { "code": null, "e": 2081, "s": 1761, "text": "Auto-contrast modification is the method to map the lowest intensity and highest intensity which found in the image to the minimum and maximum intensity of the full intensity range respectively (in case of 8 bits gray-scale image, the full range is 0–255). The mapping function of Auto-contrast adjustment is defined as" }, { "code": null, "e": 2335, "s": 2081, "text": "From the equation, a min, a max, a low and a high are minimum value intensity, maximum value intensity in the range, lowest intensity and highest intensity respectively. In case of 8-bit image, a min=0 and a max=255 so the mapping function is defined as" }, { "code": null, "e": 2539, "s": 2335, "text": "The highest intensity and the lowest intensity may be the noise of the image, We exclude these noise by saturating intensity of the image using quantile. And it can be calculated from the equation below." }, { "code": null, "e": 2578, "s": 2539, "text": "And the mapping equation is defined as" }, { "code": null, "e": 2811, "s": 2578, "text": "This task performs in order to make the difference of two images easier to compare and to use in print publication. The principle is mapping image histogram to an approximate uniform distribution. The mapping function is defined as:" }, { "code": null, "e": 2941, "s": 2811, "text": "Where H(a) is the cumulative histogram of pixel value a, K is maximum intensity value and MN is the lastest cumulative intensity." }, { "code": null, "e": 2998, "s": 2941, "text": "You can apply it to your python code using OpenCV module" }, { "code": null, "e": 3026, "s": 2998, "text": "equ = cv2.equalizeHist(img)" }, { "code": null, "e": 3084, "s": 3026, "text": "And here is the result of histogram equalization process." }, { "code": null, "e": 3578, "s": 3084, "text": "This task is similar to histogram equalization but the aim of this process is mapping distribution function of histogram to the reference distribution. To be independent of image size, the image intensity needs to be normalized into range 0–1. Normalized histogram is interpreted as a probability density function (pdf) of random process. Where p(i) is probability for the pixel value i and h(i) is the summation of all intensity value. So the summation of all probability function is equal 1." }, { "code": null, "e": 3754, "s": 3578, "text": "H(i) defined as cumulative histogram and the statistical counterpart of H(i) is discrete distribution function P(). This is also called cumulative distribution function (cdf)." }, { "code": null, "e": 3791, "s": 3754, "text": "Principle of histogram specification" }, { "code": null, "e": 3911, "s": 3791, "text": "As shown in the figure, we need to map the pdf of image A to the reference image R. We obtain the new pixel value a’ as" }, { "code": null, "e": 3950, "s": 3911, "text": "So, the mapping function is defined as" }, { "code": null, "e": 4039, "s": 3950, "text": "Make sure that pdf of reference image R is invertible (have exiting value for b =[0,1])." }, { "code": null, "e": 4247, "s": 4039, "text": "However, there is not only point operation which is the method to modify image but there is another method and it was called ‘Filter’. I will introduce you more information in the next chapter. See you soon!" } ]
Sorting an array of binary values - JavaScript
Let’s say, we have an array of Numbers that contains only 0, 1 and we are required to write a JavaScript function that takes in this array and brings all 1s to the start and 0s to the end. For example − If the input array is − const arr = [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1]; Then the output should be − const output = [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]; Following is the code − const arr = [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1]; const sortBinary = arr => { const copy = []; for(let i = 0; i − arr.length; i++){ if(arr[i] === 0){ copy.push(0); }else{ copy.unshift(1); }; continue; }; return copy; }; console.log(sortBinary(arr)); Following is the output in the console − [ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 ]
[ { "code": null, "e": 1251, "s": 1062, "text": "Let’s say, we have an array of Numbers that contains only 0, 1 and we are required to write a JavaScript function that takes in this array and brings all 1s to the start and 0s to the end." }, { "code": null, "e": 1289, "s": 1251, "text": "For example − If the input array is −" }, { "code": null, "e": 1336, "s": 1289, "text": "const arr = [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1];" }, { "code": null, "e": 1364, "s": 1336, "text": "Then the output should be −" }, { "code": null, "e": 1414, "s": 1364, "text": "const output = [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];" }, { "code": null, "e": 1438, "s": 1414, "text": "Following is the code −" }, { "code": null, "e": 1739, "s": 1438, "text": "const arr = [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1];\nconst sortBinary = arr => {\n const copy = [];\n for(let i = 0; i − arr.length; i++){\n if(arr[i] === 0){\n copy.push(0);\n }else{\n copy.unshift(1);\n };\n continue;\n };\n return copy;\n};\nconsole.log(sortBinary(arr));" }, { "code": null, "e": 1780, "s": 1739, "text": "Following is the output in the console −" }, { "code": null, "e": 1825, "s": 1780, "text": "[\n 1, 1, 1, 1, 1,\n 1, 0, 0, 0, 0,\n 0\n]" } ]
Menu-Driven program to implement Travel Agency - GeeksforGeeks
11 Feb, 2022 Prerequisites: Classes and Objects in Java, Switch Case statement in Java Problem Statement:Write a program to build a simple application for the bus travelling service using JAVA 8, MYSQL Database and JDBC which can perform the following operations: Book ticket for users/passengers on given routes via the various payment method.Cancel the ticket booked by the users/passengers using the ticket details and the user credentialsPrint the ticket via ticket details and the user credentials.Update the passenger details on the booked ticket via ticket ID or E-mail ID and user credentials which are registered. Book ticket for users/passengers on given routes via the various payment method. Cancel the ticket booked by the users/passengers using the ticket details and the user credentials Print the ticket via ticket details and the user credentials. Update the passenger details on the booked ticket via ticket ID or E-mail ID and user credentials which are registered. Approach: Initially, we need to set up a database in order to store the information of the buses and the booking. Here, the MySQL database is used. Initially, we need to set up the database. So, the following steps are followed to set up the database: Initially, a database is created in MySQL database using the workbench.After creating the database, multiple tables are created signifying multiple travel services where each table contains details of the passenger. The tables are created in the following way:Now, since each table must contain the details of the passengers, each table has the following attributes: Initially, a database is created in MySQL database using the workbench. After creating the database, multiple tables are created signifying multiple travel services where each table contains details of the passenger. The tables are created in the following way: Now, since each table must contain the details of the passengers, each table has the following attributes: Now, we need to create a connection between the database created above and the java program. In order to do this, the following steps are followed: Initially, we need to collect the database and driver info in the class which we would be developing the application. The syntax for doing this is:String driverClassName = “com.mysql.jdbc.Driver”;String url=”jdbc:mysql://localhost/jdbc”;String user=”root”;// The default password is root.// But we can set up any password// for MYSQL databaseString pwd= “root”;Now, we need to load the JDBC driver. This is performed by the following statement:// Class.forName method returns the// Class object associated with the// class or the interfaceClass.forName(driverClassName).newInstance();After initializing the database, we need to connect to it. So, we need to create a connection. The connection is created as:Connection con = DriverManager.getConnection(url, user, pwd);System.out.println(“con—->”+con);After connecting, we should be able to execute SQL statements in order to get the data or update it or post it on the database. In order to execute the statements, the following syntax is used:Statement st = con.createStatement();// Creating SQL queryString sql= “” ;// Executing the queryst.executeUpdate(sql);Finally, after completing the execution, we need to close the connection. The connection to the database is closed as:st.close();con.close(); Initially, we need to collect the database and driver info in the class which we would be developing the application. The syntax for doing this is:String driverClassName = “com.mysql.jdbc.Driver”;String url=”jdbc:mysql://localhost/jdbc”;String user=”root”;// The default password is root.// But we can set up any password// for MYSQL databaseString pwd= “root”; String driverClassName = “com.mysql.jdbc.Driver”;String url=”jdbc:mysql://localhost/jdbc”;String user=”root”; // The default password is root.// But we can set up any password// for MYSQL databaseString pwd= “root”; Now, we need to load the JDBC driver. This is performed by the following statement:// Class.forName method returns the// Class object associated with the// class or the interfaceClass.forName(driverClassName).newInstance(); // Class.forName method returns the// Class object associated with the// class or the interfaceClass.forName(driverClassName).newInstance(); After initializing the database, we need to connect to it. So, we need to create a connection. The connection is created as:Connection con = DriverManager.getConnection(url, user, pwd);System.out.println(“con—->”+con); Connection con = DriverManager.getConnection(url, user, pwd);System.out.println(“con—->”+con); After connecting, we should be able to execute SQL statements in order to get the data or update it or post it on the database. In order to execute the statements, the following syntax is used:Statement st = con.createStatement();// Creating SQL queryString sql= “” ;// Executing the queryst.executeUpdate(sql); Statement st = con.createStatement(); // Creating SQL queryString sql= “” ; // Executing the queryst.executeUpdate(sql); Finally, after completing the execution, we need to close the connection. The connection to the database is closed as:st.close();con.close(); st.close();con.close(); Till now, we have initialized the database and created a connection between the database and the Java program. Now, we need to define all the methods based on functionality. The methods in the program are as follows: Book ticket: In order to book a ticket, we first need to choose the route. This option is given to the user to choose a route among the set of predefined routes. For all the routes, users have to enter his details like name, age, mobile number, email, etc. Now, the user gets a list of available travels in the particular route. Based on the users choice, the data is stored in that respective table of the database created above. In order to do this, switch-case is used where every case is the choice of the travel provider.Cancel Ticket: Similar to the above method, we need to implement the cancel functionality where users will be able to cancel the booked ticket. In order to do this, we need to first get the details of the users whose tickets need to be cancelled and this is validated with the mobile number and email ID of the user which is given during the input.Print Ticket: Now, the print function is implemented. In order to print the ticket, the user details are taken, like the bus in which the ticket has been booked and the email ID is taken as the input to find the ticket details and print the details.Update Ticket: In order to update the ticket, the user must have a booked ticket in the first place. Therefore, the email id of the user is taken as the input to verify if the ticket exists or not. After the email id is obtained, the search operation is performed on the database to search the ticket and then the new updated details are taken as the input which is then updated in the database. Book ticket: In order to book a ticket, we first need to choose the route. This option is given to the user to choose a route among the set of predefined routes. For all the routes, users have to enter his details like name, age, mobile number, email, etc. Now, the user gets a list of available travels in the particular route. Based on the users choice, the data is stored in that respective table of the database created above. In order to do this, switch-case is used where every case is the choice of the travel provider. Cancel Ticket: Similar to the above method, we need to implement the cancel functionality where users will be able to cancel the booked ticket. In order to do this, we need to first get the details of the users whose tickets need to be cancelled and this is validated with the mobile number and email ID of the user which is given during the input. Print Ticket: Now, the print function is implemented. In order to print the ticket, the user details are taken, like the bus in which the ticket has been booked and the email ID is taken as the input to find the ticket details and print the details. Update Ticket: In order to update the ticket, the user must have a booked ticket in the first place. Therefore, the email id of the user is taken as the input to verify if the ticket exists or not. After the email id is obtained, the search operation is performed on the database to search the ticket and then the new updated details are taken as the input which is then updated in the database. Below is the complete implementation of the above functions along with the database connection: // Java program to implement CLI// based application of travel agency import java.sql.*;import java.util.*;import javax.swing.JOptionPane; // Travel classclass My_Travels { public static void main(String[] args) throws Exception { String driverClassName = "com.mysql.jdbc.Driver"; String URL = "jdbc:mysql:// localhost/" + "My_Travels_travel_service"; String user = "root"; String pwd = "mysql"; Class.forName(driverClassName) .newInstance(); Connection con = DriverManager.getConnection( url, user, pwd); System.out.println("con---->" + con); Statement st = con.createStatement(); Scanner zz = new Scanner(System.in); System.out.println( "\n" + "\n" + "*********************" + "******************** "); System.out.println( "** WELCOME TO My_Travels" + " TRAVELS SERVICES ** "); System.out.println( "*********************" + "******************** "); System.out.println( "Here you have several" + " tasks to perform -- " + "\n" + "\n"); System.out.println( "Press 1 for ticket booking " + "\n" + "\n" + "Press 2 for " + "ticket cancellation" + "\n" + "\n" + "Press 3 for updating " + "Passenger detail" + "\n" + "\n" + "Press 4 to print " + "ticket details"); int mainCH = zz.nextInt(); switch (mainCH) { case 1: System.out.println( " Please choice the route : "); System.out.println( "For DEHRADUN <---> KANPUR " + "via Haridwar, press 1" + "\n" + "\n" + "For DEHRADUN <---> DELHI " + "via Roorkee, press 2"); int route_ch = zz.nextInt(); switch (route_ch) { case 1: System.out.println( " Welcome <--> DEHRADUN" + " - KANPUR route " + "via Haridwar "); System.out.println( "Please enter your detail" + " so we can book " + "your ticket"); String w = JOptionPane .showInputDialog( "Enter the Journey Date:"); String x = JOptionPane .showInputDialog( "Enter Passenger Name:"); String y = JOptionPane.showInputDialog( "Enter Passenger Age:"); String z = JOptionPane.showInputDialog( "Enter Bus Type:"); String a = JOptionPane.showInputDialog( "Enter Source City:"); String b = JOptionPane.showInputDialog( "Enter Destination City:"); String c = JOptionPane.showInputDialog( "Enter Seat Type:"); String cc = JOptionPane.showInputDialog( "Enter Email address:"); System.out.println( " In this route, we have " + "type of bushes for you " + "(Both AC and Non-AC " + "buses available " + "in this route "); System.out.println( "For Shatbdi Travels " + "Departure: 5 PM " + "Arrival: 6:15 AM " + "Journey time: 13Hr. 15 Min., " + "press 1" + "\n" + "\n" + "For Mahalaxmi Travels, " + "Departure: 6 PM " + "Arrival: 7:30 AM " + " Journey time: 13Hr. 30 " + "Min.press 2" + "\n" + "\n" + "For Blueworld Travels, " + "Departure: 8 PM " + "Arrival: 10:15 AM " + "Journey time: 14Hr. 15 " + "Min. press 3" + "\n" + "\n" + "For UP Govt. UPSRTC bushes, " + "Departure: 10:15 PM " + "Arrival: 12:45 AM " + "Journey time: 14Hr. 30 " + "Min. press 4"); int Bus_ch_r1 = zz.nextInt(); switch (Bus_ch_r1) { case 1: String sql1 = "INSERT INTO " + "shatabdi_travels_bus" + "(JourneyDate, P_Name, " + "P_Age, BusType, Source, " + " Destination, SeatType, " + "Email) VALUE(?, ?, ?, ?, " + "?, ?, ?, ?)"; PreparedStatement ps1 = con.prepareStatement(sql1); ps1.setString(1, w); ps1.setString(2, x); ps1.setString(3, y); ps1.setString(4, z); ps1.setString(5, a); ps1.setString(6, b); ps1.setString(7, c); ps1.setString(8, cc); ps1.executeUpdate(); System.out.println( "\n" + "\n" + "\n" + "Thanks for choosing " + "Shatabdi Travels. " + "Happy and safe Journey" + "\n" + "\n" + "\n" + "\n"); break; case 2: String sql2 = "INSERT INTO " + "mahalaxmi_travels_bus(" + "JourneyDate, P_Name, " + "P_Age, BusType, Source, " + " Destination, SeatType, " + "Email) VALUE(?, ?, ?, ?, " + "?, ?, ?, ?)"; PreparedStatement ps2 = con.prepareStatement(sql2); ps2.setString(1, w); ps2.setString(2, x); ps2.setString(3, y); ps2.setString(4, z); ps2.setString(5, a); ps2.setString(6, b); ps2.setString(7, c); ps2.setString(8, cc); ps2.executeUpdate(); System.out.println( "Your ticket " + "is booked successfully " + "in Mahalaxmi Travels. " + "This operator accept " + "m-ticket, please show " + "ticket to bus staff " + "during journey. " + "Have a nice day !"); System.out.println( "Thanks for choosing " + "Mahalaxmi Travels. " + "Happy and safe Journey"); break; case 3: String sql3 = "INSERT INTO " + "blueworld_travels_bus(" + "JourneyDate, P_Name, " + "P_Age, BusType, Source, " + " Destination, SeatType, " + " Email) VALUE(?, ?, ?, ?, " + " ?, ?, ?, ?)"; PreparedStatement ps3 = con.prepareStatement(sql3); ps3.setString(1, w); ps3.setString(2, x); ps3.setString(3, y); ps3.setString(4, z); ps3.setString(5, a); ps3.setString(6, b); ps3.setString(7, c); ps3.setString(8, cc); ps3.executeUpdate(); System.out.println( "Your ticket " + "is booked successfully " + "in Blueworld Travels. " + "This operator accept " + "m-ticket, please show " + "ticket to bus staff during " + "journey. Have a nice day !"); System.out.println( "Thanks for choosing " + "Blueworld Travels. " + "Happy and safe Journey"); break; case 4: String sql4 = "INSERT INTO " + "upsrtc_bus(JourneyDate, " + " P_Name, P_Age, BusType, " + " Source, Destination, " + "SeatType, Email)" + " VALUE(?, ?, " + "?, ?, ?, ?, ?, ?)"; PreparedStatement ps4 = con.prepareStatement(sql4); ps4.setString(1, w); ps4.setString(2, x); ps4.setString(3, y); ps4.setString(4, z); ps4.setString(5, a); ps4.setString(6, b); ps4.setString(7, c); ps4.setString(8, cc); ps4.executeUpdate(); System.out.println( "Your ticket " + "is booked successfully " + "in UP govt. UPSRTC Bus." + " This operator does not " + "accept m-ticket, please " + "take a print of ticket & " + "show bus staff during " + "journey. Have a nice day !"); System.out.println( "Thanks for " + "choosing UPSRTC." + " Happy and safe Journey"); break; default: System.out.println( "Invalid Bus choice." + " Try again Dear !"); break; } break; case 2: System.out.println( " Welcome to DEHRADUN" + " <---> DELHI route" + " via Roorkee "); System.out.println( "Please enter your detail, " + " so we can book" + " your ticket"); String n = JOptionPane.showInputDialog( "Enter the Journey Date:"); String s = JOptionPane.showInputDialog( "Enter Passenger Name:"); String m = JOptionPane.showInputDialog( "Enter Passenger Age:"); String o = JOptionPane.showInputDialog( "Enter Bus Type:"); String p = JOptionPane.showInputDialog( "Enter Source City:"); String q = JOptionPane.showInputDialog( "Enter Destination City:"); String r = JOptionPane.showInputDialog( "Enter Seat Type:"); String cd = JOptionPane.showInputDialog( "Enter Email address:"); System.out.println( " In this route, " + "we have 5 type of " + "bushes for you " + "(Both AC and " + "Non-AC buses available " + "in this route "); System.out.println( "For Shreenath Travels, " + " Departure: 5 PM " + "Arrival: 11:15 PM " + "Journey time: " + "6 Hr. 15 Min.press 1" + "\n" + "\n" + "For Shatabdi Travels, " + " Departure: 8:5 PM " + "Arrival: 2:10 AM " + "Journey time: 6 Hr. 10 " + "Min.press 2" + "\n" + "\n" + "For Mahalaxmi Travels, " + "Departure: 11 PM " + "Arrival: 6:15 AM " + "Journey time: 7Hr." + " 15 Min. press 3" + "\n" + "\n" + "For UP Govt. " + "UPSRTC bushes, " + "Departure: 9:30 PM " + "Arrival: 4 AM " + "Journey time: 6 Hr. 30 " + "Min. press 4" + "\n" + "\n" + "For Royal Travels Pvt. Ltd." + ", Departure: 12 PM " + "Arrival: 6:15 PM " + "Journey time: 6 Hr. 15 " + "Min. press 5"); int Bus_ch_r2 = zz.nextInt(); switch (Bus_ch_r2) { case 2: String sql5 = "INSERT INTO " + "shatabdi_travels_bus" + "(JourneyDate, P_Name, " + " P_Age, BusType, Source, " + "Destination, SeatType, " + "Email) VALUE(?, ?, ?, ?, " + " ?, ?, ?, ?)"; PreparedStatement ps5 = con.prepareStatement(sql5); ps5.setString(1, n); ps5.setString(2, s); ps5.setString(3, m); ps5.setString(4, o); ps5.setString(5, p); ps5.setString(6, q); ps5.setString(7, r); ps5.setString(8, cd); ps5.executeUpdate(); System.out.println( "Your ticket is " + "booked successfully in " + "Statabdi Travels. " + "This operator accept " + "m-ticket, please show " + "ticket to bus staff " + "during the journey. " + "Have a nice day !"); System.out.println( "\n" + "\n" + "\n" + "Thanks for choosing " + "Shatabdi Travels." + " Happy and safe Journey" + "\n" + "\n" + "\n" + "\n"); break; case 3: String sql6 = "INSERT INTO " + "mahalaxmi_travels_bus(" + "JourneyDate, P_Name, " + "P_Age, BusType, Source, " + " Destination, SeatType, " + "Email) VALUE(?, ?, ?, ?, " + " ?, ?, ?, ?)"; PreparedStatement ps6 = con.prepareStatement(sql6); ps6.setString(1, n); ps6.setString(2, s); ps6.setString(3, m); ps6.setString(4, o); ps6.setString(5, p); ps6.setString(6, q); ps6.setString(7, r); ps6.setString(8, cd); ps6.executeUpdate(); System.out.println( "Your ticket is booked " + "successfully in Mahalaxmi " + "Travels. This operator accept " + "m-ticket, please show ticket " + "to bus staf during journey. " + "Have a nice day !"); System.out.println( "Thanks for choosing " + "Mahalaxmi Travels. " + "Happy and safe Journey"); break; case 1: String sql7 = "INSERT INTO " + "shreenath_travels_bus" + "(JourneyDate, P_Name, " + " P_Age, BusType, Source, " + " Destination, SeatType, " + "Email) VALUE(?, ?, ?, ?, " + "?, ?, ?, ?)"; PreparedStatement ps17 = con.prepareStatement(sql7); ps17.setString(1, n); ps17.setString(2, s); ps17.setString(3, m); ps17.setString(4, o); ps17.setString(5, p); ps17.setString(6, q); ps17.setString(7, r); ps17.setString(8, cd); ps17.executeUpdate(); System.out.println( "Your ticket is booked " + "successfully in " + "Shreenath Travels. " + "This operator accept " + "m-ticket, please show " + "ticket to bus staff " + "during journey. " + "Have a nice day !"); System.out.println( "Thanks for choosing " + "Shreenath Travels. " + "Happy and safe Journey"); break; case 4: String sql8 = "INSERT INTO " + "upsrtc_bus(" + "JourneyDate, P_Name, " + " P_Age, BusType, " + "Source, Destination, " + "SeatType, Email) " + "VALUE(?, ?, ?, ?, " + "?, ?, ?, ?)"; PreparedStatement ps8 = con.prepareStatement(sql8); ps8.setString(1, n); ps8.setString(2, s); ps8.setString(3, m); ps8.setString(4, o); ps8.setString(5, p); ps8.setString(6, q); ps8.setString(7, r); ps8.setString(8, cd); ps8.executeUpdate(); System.out.println( "Your ticket is booked " + "successfully in UP govt. " + "UPSRTC Bus. This operator " + "does not accept m-ticket, " + "please take a print of ticket " + "& show bus staf during journey." + " Have a nice day !"); System.out.println( "Thanks for choosing " + "UPSRTC. Happy " + "and safe Journey"); break; case 5: String sql9 = "INSERT INTO " + "royal_travels_bus(" + "JourneyDate, P_Name, " + "P_Age, BusType, Source, " + " Destination, SeatType, " + " Email) VALUE(?, ?, ?, ?, " + " ?, ?, ?, ?)"; PreparedStatement ps9 = con.prepareStatement(sql9); ps9.setString(1, n); ps9.setString(2, s); ps9.setString(3, m); ps9.setString(4, o); ps9.setString(5, p); ps9.setString(6, q); ps9.setString(7, r); ps9.setString(8, cd); ps9.executeUpdate(); System.out.println( "Your ticket is booked " + "successfully in Royal " + "Travels Bus. This operator " + "does not accept m-ticket, " + " please take a print of ticket " + "& show bus staff during journey." + " Have a nice day !"); System.out.println( "Thanks for choosing " + "UPSRTC. " + "Happy and safe Journey"); break; default: System.out.println( "Invalid Bus choice. " + "Try again Dear !"); break; } break; } System.out.println( "Proceed to payment ---- " + "don't refresh the page :" + "\n" + "\n" + "You have 3 options -->"); System.out.println( "1 : By Net Banking" + "\n" + "\n" + "2 : By Debit Card" + "\n" + "\n" + "3 : By Paytm Account"); int pay_ch = zz.nextInt(); switch (pay_ch) { case 1: System.out.println( "Enter your Net Banking " + "ID and Password"); String id = zz.next(); String pass = zz.next(); break; case 2: System.out.println( "Enter your 16 digit " + "debit card number, " + "cvv and OTP which " + "is sent to your " + "linked mobile number"); String dc = zz.next(); String cvv = zz.next(); String OTP = zz.next(); break; case 3: System.out.println( "Enter your PAYTM " + "mobile number, " + "password and OTP"); String PaytmNo = zz.next(); String PtmPass = zz.next(); String PtmOTP = zz.next(); break; default: System.out.println( "Invalid Payment choice, " + " try again !"); break; } System.out.println( "Your ticket is booked " + "successfully. This " + "operator accept m-ticket, " + "please show ticket to " + "bus staff during journey. " + "Have a nice day !"); break; case 2: System.out.println( "Select bus in which you " + "want to cancel your ticket"); System.out.println( " 1: Shatabdi Travels" + "\n" + "\n" + " 2: Blueworld Travels" + "\n" + "\n" + " 3: Mahalaxmi Travels" + "\n" + "\n" + " 4: Shreenath Travels" + "\n" + "\n" + " 5: UP govt. upsrtc bus" + "\n" + "\n" + " 6: Royal Travels" + "\n" + "\n" + " Select any one"); int cnclCH = zz.nextInt(); String P_name = JOptionPane.showInputDialog( "Enter the Passenger name " + "who want to delete ticket"); String Email = JOptionPane.showInputDialog( "Enter the Passenger's" + " Email want to delete ticket"); switch (cnclCH) { case 1: String sql12 = "DELETE FROM " + "shatabdi_travels_bus " + "where P_name=? and Email=?"; PreparedStatement ps12 = con.prepareStatement(sql12); ps12.setString(1, P_name); ps12.setString(2, Email); ps12.executeUpdate(); System.out.println( "Your ticket is cancelled " + "successfully from " + "Shatabdi Travels"); System.out.println( "\n" + "\n" + "\n" + "Thanks for choosing " + "Shatabdi Travels.... " + "Happy and safe Journey" + "\n" + "\n" + "\n" + "\n"); break; case 2: String sql13 = "DELETE FROM " + "blueworld_travels_bus " + "where P_name=? and Email=?"; PreparedStatement ps13 = con.prepareStatement(sql13); ps13.setString(1, P_name); ps13.setString(2, Email); ps13.executeUpdate(); System.out.println( "Your ticket is " + "cancelled successfully " + "from Blueworld Travels"); System.out.println( "Thanks for choosing" + "Blueworld Travels.... " + "Happy and safe Journey"); break; case 3: String sql14 = "DELETE FROM " + "mahalaxmi_travels_bus" + " where P_name=? and Email=?"; PreparedStatement ps14 = con.prepareStatement(sql14); ps14.setString(1, P_name); ps14.setString(2, Email); ps14.executeUpdate(); System.out.println( "Your ticket is " + "cancelled successfully " + "from Mahalaxmi Travels"); System.out.println( "Thanks for choosing " + "Mahalaxmi Travels. " + "Happy and safe Journey"); break; case 4: String sql15 = "DELETE FROM " + "shreenath_travels_bus " + "where P_name=? and " + "Email=?"; PreparedStatement ps15 = con.prepareStatement(sql15); ps15.setString(1, P_name); ps15.setString(2, Email); ps15.executeUpdate(); System.out.println( "Your ticket is " + "cancelled successfully " + "from Royal Travels"); System.out.println( "Thanks for choosing " + "Shreenath Travels.... " + "Happy and safe Journey"); break; case 5: String sql16 = "DELETE FROM " + "upsrtc_bus where " + "P_name=? and Email=?"; PreparedStatement ps16 = con.prepareStatement(sql16); ps16.setString(1, P_name); ps16.setString(2, Email); ps16.executeUpdate(); System.out.println( "Your ticket is cancelled " + "successfully from UP " + "govt. UPSRTC bus"); System.out.println( "Thanks for choosing " + "UP govt. UPSRTC bus." + " Happy and safe Journey"); break; case 6: String sql11 = "DELETE FROM " + "royal_travels_bus " + "where P_name=? and Email=?"; PreparedStatement ps11 = con.prepareStatement(sql11); ps11.setString(1, P_name); ps11.setString(2, Email); ps11.executeUpdate(); System.out.println( "Your ticket is " + "cancelled successfully " + "from Royal Travels"); System.out.println( "Thanks for choosing " + "Royal Travels.... " + "Happy and safe Journey"); break; default: System.out.println( "Invalid cancellation choise"); break; } break; case 3: System.out.println( "Select bus in which you " + "want to update your detail"); System.out.println( " 1: Shatabdi Travels" + "\n" + "\n" + " 2: Blueworld Travels" + "\n" + "\n" + " 3: Mahalaxmi Travels" + "\n" + "\n" + " 4: Shreenath Travels" + "\n" + "\n" + " 5: UP govt. upsrtc bus" + "\n" + "\n" + " 6: Royal Travels" + "\n" + "\n" + " Select any one"); int udtCH = zz.nextInt(); String Email1 = JOptionPane.showInputDialog( "Enter the Passenger's Email" + " who want to delete ticket"); String P_name1 = JOptionPane.showInputDialog( "Enter the correct " + "name to update ticket"); String age1 = JOptionPane.showInputDialog( "Enter the correct " + "age to update ticket"); switch (udtCH) { case 1: String sql12 = "UPDATE shatabdi_travels_bus " + "SET P_Name=?, P_Age=? where Email=?"; PreparedStatement ps12 = con.prepareStatement(sql12); ps12.setString(1, P_name1); ps12.setString(2, age1); ps12.setString(3, Email1); ps12.executeUpdate(); System.out.println( "Your ticket is updated " + "successfully from " + "Shatabdi Travels"); System.out.println("\n" + "\n" + "\n" + "Thanks for choosing " + "Shatabdi Travels.... " + "Happy and safe Journey" + "\n" + "\n" + "\n" + "\n"); break; case 2: String sql13 = "UPDATE blueworld_travels_bus" + " SET P_Name=?, P_age=? where Email=?"; PreparedStatement ps13 = con.prepareStatement(sql13); ps13.setString(1, P_name1); ps13.setString(2, age1); ps13.setString(3, Email1); ps13.executeUpdate(); System.out.println( "Your ticket is updated " + "successfully from " + "Blueworld Travels"); System.out.println( "Thanks for choosing " + "Blueworld Travels.... " + "Happy and safe Journey"); break; case 3: String sql14 = "UPDATE mahalaxmi_travels_bus " + "SET P_Name=?, P_Age=? where Email=?"; PreparedStatement ps14 = con.prepareStatement(sql14); ps14.setString(1, P_name1); ps14.setString(2, age1); ps14.setString(3, Email1); ps14.executeUpdate(); System.out.println( "Your ticket is updated " + "successfully from " + "Mahalaxmi Travels"); System.out.println( "Thanks for choosing " + "Mahalaxmi Travels.... " + "Happy and safe Journey"); break; case 4: String sql15 = "UPDATE shreenath_travels_bus " + "SET P_Name=?, P_Age=? where Email=?"; PreparedStatement ps15 = con.prepareStatement(sql15); ps15.setString(1, P_name1); ps15.setString(2, age1); ps15.setString(3, Email1); ps15.executeUpdate(); System.out.println( "Your ticket is updated " + "successfully from " + "Royal Travels"); System.out.println( "Thanks for choosing " + "Shreenath Travels.... " + "Happy and safe Journey"); break; case 5: String sql16 = "UPDATE upsrtc_bus " + "SET P_Name=?, P_Age=? " + "where Email=?"; PreparedStatement ps16 = con.prepareStatement(sql16); ps16.setString(1, P_name1); ps16.setString(2, age1); ps16.setString(3, Email1); ps16.executeUpdate(); System.out.println( "Your ticket is updated " + "successfully from UP " + "govt. UPSRTC bus"); System.out.println( "Thanks for choosing " + "UP govt. UPSRTC bus...." + " Happy and safe Journey"); break; case 6: String sql11 = "UPDATE royal_travels_bus" + " SET P_Name=?, P_Age=? " + "where Email=?"; PreparedStatement ps11 = con.prepareStatement(sql11); ps11.setString(1, P_name1); ps11.setString(2, age1); ps11.setString(3, age1); ps11.executeUpdate(); System.out.println( "Your ticket is updated " + "successfully from " + "Royal Travels"); System.out.println( "Thanks for choosing " + "Royal Travels.... " + "Happy and safe Journey"); break; default: System.out.println( "Invalid cancellation choise"); break; } break; case 4: System.out.println( "Select bus in which " + "you want to print your ticket"); System.out.println( " 1: Shatabdi Travels" + "\n" + "\n" + " 2: Blueworld Travels" + "\n" + "\n" + " 3: Mahalaxmi Travels" + "\n" + "\n" + " 4: Shreenath Travels" + "\n" + "\n" + " 5: UP govt. upsrtc bus" + "\n" + "\n" + " 6: Royal Travels" + "\n" + "\n" + " Select any one"); int PrntCH = zz.nextInt(); String PEmail = JOptionPane.showInputDialog( "Enter the Email to print ticket"); switch (PrntCH) { case 1: String sql21 = "SELECT JourneyDate, " + "P_Name, P_Age, Source, " + "Destination, BusType, " + "Email, SeatType FROM " + "shatabdi_travels_bus " + "WHERE Email= ?"; PreparedStatement ps21 = con.prepareStatement(sql21); ps21.setString(1, PEmail); ResultSet rs1 = ps21.executeQuery(); while (rs1.next()) { System.out.println( "Journey Date : " + rs1.getString("JourneyDate") + "\n" + "\n" + "Passenger Name : " + rs1.getString("P_Name") + "\n" + "\n" + "Passenger Age : " + rs1.getInt("P_Age") + "\n" + "\n" + "Source City : " + rs1.getString("Source") + "\n" + "\n" + "Destination City : " + rs1.getString("Destination") + "\n" + "\n" + "Bus Type : " + rs1.getString("BusType") + "\n" + "\n" + "Passenger's Email : " + rs1.getString("Email") + "\n" + "\n" + "Seat Type : " + rs1.getString("SeatType")); } rs1.close(); System.out.println( "\n" + "\n" + "\n" + "Thanks for choosing " + "Shatabdi Travels.... " + "Happy and safe Journey" + "\n" + "\n" + "\n" + "\n"); break; case 2: String sql22 = "SELECT JourneyDate, " + "P_Name, P_Age, Source, " + " Destination, BusType, " + "Email, SeatType FROM " + "blueworld_travels_bus " + "WHERE Email= ?"; PreparedStatement ps22 = con.prepareStatement(sql22); ps22.setString(1, PEmail); ResultSet rs2 = ps22.executeQuery(); while (rs2.next()) { System.out.println( "Journey Date : " + rs2.getString("JourneyDate") + "\n" + "\n" + "Passenger Name : " + rs2.getString("P_Name") + "\n" + "\n" + "Passenger Age : " + rs2.getInt("P_Age") + "\n" + "\n" + "Source City : " + rs2.getString("Source") + "\n" + "\n" + "Destination City : " + rs2.getString("Destination") + "\n" + "\n" + "Bus Type : " + rs2.getString("BusType") + "\n" + "\n" + "Passenger's Email : " + rs2.getString("Email") + "\n" + "\n" + "Seat Type : " + rs2.getString("SeatType")); } rs2.close(); System.out.println( "\n" + "\n" + "\n" + "Thanks for choosing " + "Blueworld Travels.... " + "Happy and safe Journey" + "\n" + "\n" + "\n" + "\n"); break; case 3: String sql23 = "SELECT JourneyDate, P_Name, " + "P_Age, Source, Destination, " + " BusType, Email, " + "SeatType FROM " + "mahalaxmi_travels_bus " + "WHERE Email= ?"; PreparedStatement ps23 = con.prepareStatement(sql23); ps23.setString(1, PEmail); ResultSet rs3 = ps23.executeQuery(); while (rs3.next()) { System.out.println( "Journey Date : " + rs3.getString("JourneyDate") + "\n" + "\n" + "Passenger Name : " + rs3.getString("P_Name") + "\n" + "\n" + "Passenger Age : " + rs3.getInt("P_Age") + "\n" + "\n" + "Source City : " + rs3.getString("Source") + "\n" + "\n" + "Destination City : " + rs3.getString("Destination") + "\n" + "\n" + "Bus Type : " + rs3.getString("BusType") + "\n" + "\n" + "Passenger's Email : " + rs3.getString("Email") + "\n" + "\n" + "Seat Type : " + rs3.getString("SeatType")); } rs3.close(); System.out.println( "\n" + "\n" + "\n" + "Thanks for choosing " + "Mahalaxmi Travels.... " + "Happy and safe Journey" + "\n" + "\n" + "\n" + "\n"); break; case 4: String sql24 = "SELECT JourneyDate, P_Name, " + "P_Age, Source, Destination, " + "BusType, Email, SeatType " + "FROM shreenath_travels_bus " + "WHERE Email= ?"; PreparedStatement ps24 = con.prepareStatement(sql24); ps24.setString(1, PEmail); ResultSet rs4 = ps24.executeQuery(); while (rs4.next()) { System.out.println( "Journey Date : " + rs4.getString("JourneyDate") + "\n" + "\n" + "Passenger Name : " + rs4.getString("P_Name") + "\n" + "\n" + "Passenger Age : " + rs4.getInt("P_Age") + "\n" + "\n" + "Source City : " + rs4.getString("Source") + "\n" + "\n" + "Destination City : " + rs4.getString("Destination") + "\n" + "\n" + "Bus Type : " + rs4.getString("BusType") + "\n" + "\n" + "Passenger's Email : " + rs4.getString("Email") + "\n" + "\n" + "Seat Type : " + rs4.getString("SeatType")); } rs4.close(); System.out.println( "\n" + "\n" + "\n" + "Thanks for choosing " + "Shreenath Travels.... " + "Happy and safe Journey" + "\n" + "\n" + "\n" + "\n"); break; case 6: String sql25 = "SELECT JourneyDate, P_Name, " + "P_Age, Source, Destination, " + "BusType, Email, SeatType " + "FROM royal_travels_bus " + "WHERE Email= ?"; PreparedStatement ps25 = con.prepareStatement(sql25); ps25.setString(1, PEmail); ResultSet rs5 = ps25.executeQuery(); while (rs5.next()) { System.out.println( "Journey Date : " + rs5.getString("JourneyDate") + "\n" + "\n" + "Passenger Name : " + rs5.getString("P_Name") + "\n" + "\n" + "Passenger Age : " + rs5.getInt("P_Age") + "\n" + "\n" + "Source City : " + rs5.getString("Source") + "\n" + "\n" + "Destination City : " + rs5.getString("Destination") + "\n" + "\n" + "Bus Type : " + rs5.getString("BusType") + "\n" + "\n" + "Passenger's Email : " + rs5.getString("Email") + "\n" + "\n" + "Seat Type : " + rs5.getString("SeatType")); } rs5.close(); System.out.println( "\n" + "\n" + "\n" + "Thanks for choosing " + "Royal Travels.... " + "Happy and safe Journey" + "\n" + "\n" + "\n" + "\n"); break; case 5: String sql26 = "SELECT JourneyDate, P_Name, " + " P_Age, Source, Destination, " + "BusType, Email, SeatType " + "FROM upsrtc_bus WHERE " + "Email= ?"; PreparedStatement ps26 = con.prepareStatement(sql26); ps26.setString(1, PEmail); ResultSet rs6 = ps26.executeQuery(); while (rs6.next()) { System.out.println( "Journey Date : " + rs6.getString("JourneyDate") + "\n" + "\n" + "Passenger Name : " + rs6.getString("P_Name") + "\n" + "\n" + "Passenger Age : " + rs6.getInt("P_Age") + "\n" + "\n" + "Source City : " + rs6.getString("Source") + "\n" + "\n" + "Destination City : " + rs6.getString("Destination") + "\n" + "\n" + "Bus Type : " + rs6.getString("BusType") + "\n" + "\n" + "Passenger's Email : " + rs6.getString("Email") + "\n" + "\n" + "Seat Type : " + rs6.getString("SeatType")); } rs6.close(); System.out.println( "\n" + "\n" + "\n" + "Thanks for choosing UP govt. " + "UPSRTC.... " + "Happy and safe Journey" + "\n" + "\n" + "\n" + "\n"); break; } break; } st.close(); con.close(); System.out.println("---SQL executed successfully---"); System.out.println("Adars11h Shukla " + "R134218010"); }} Note: The above code does not work on the online IDE. Please use an offline IDE to run the above code. Output: The following two videos explain the working of the above code. sumitgumber28 kk9826225 nnr223442 rkbhola5 Java 8 JDBC mysql Java Java Programs Project Write From Home Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Constructors in Java Exceptions in Java Functional Interfaces in Java Stream In Java Different ways of Reading a text file in Java Convert a String to Character array in Java Java Programming Examples How to Iterate HashMap in Java? Implementing a Linked List in Java using Class Min Heap in Java
[ { "code": null, "e": 23583, "s": 23555, "text": "\n11 Feb, 2022" }, { "code": null, "e": 23657, "s": 23583, "text": "Prerequisites: Classes and Objects in Java, Switch Case statement in Java" }, { "code": null, "e": 23834, "s": 23657, "text": "Problem Statement:Write a program to build a simple application for the bus travelling service using JAVA 8, MYSQL Database and JDBC which can perform the following operations:" }, { "code": null, "e": 24193, "s": 23834, "text": "Book ticket for users/passengers on given routes via the various payment method.Cancel the ticket booked by the users/passengers using the ticket details and the user credentialsPrint the ticket via ticket details and the user credentials.Update the passenger details on the booked ticket via ticket ID or E-mail ID and user credentials which are registered." }, { "code": null, "e": 24274, "s": 24193, "text": "Book ticket for users/passengers on given routes via the various payment method." }, { "code": null, "e": 24373, "s": 24274, "text": "Cancel the ticket booked by the users/passengers using the ticket details and the user credentials" }, { "code": null, "e": 24435, "s": 24373, "text": "Print the ticket via ticket details and the user credentials." }, { "code": null, "e": 24555, "s": 24435, "text": "Update the passenger details on the booked ticket via ticket ID or E-mail ID and user credentials which are registered." }, { "code": null, "e": 24807, "s": 24555, "text": "Approach: Initially, we need to set up a database in order to store the information of the buses and the booking. Here, the MySQL database is used. Initially, we need to set up the database. So, the following steps are followed to set up the database:" }, { "code": null, "e": 25174, "s": 24807, "text": "Initially, a database is created in MySQL database using the workbench.After creating the database, multiple tables are created signifying multiple travel services where each table contains details of the passenger. The tables are created in the following way:Now, since each table must contain the details of the passengers, each table has the following attributes:" }, { "code": null, "e": 25246, "s": 25174, "text": "Initially, a database is created in MySQL database using the workbench." }, { "code": null, "e": 25436, "s": 25246, "text": "After creating the database, multiple tables are created signifying multiple travel services where each table contains details of the passenger. The tables are created in the following way:" }, { "code": null, "e": 25543, "s": 25436, "text": "Now, since each table must contain the details of the passengers, each table has the following attributes:" }, { "code": null, "e": 25691, "s": 25543, "text": "Now, we need to create a connection between the database created above and the java program. In order to do this, the following steps are followed:" }, { "code": null, "e": 26946, "s": 25691, "text": "Initially, we need to collect the database and driver info in the class which we would be developing the application. The syntax for doing this is:String driverClassName = “com.mysql.jdbc.Driver”;String url=”jdbc:mysql://localhost/jdbc”;String user=”root”;// The default password is root.// But we can set up any password// for MYSQL databaseString pwd= “root”;Now, we need to load the JDBC driver. This is performed by the following statement:// Class.forName method returns the// Class object associated with the// class or the interfaceClass.forName(driverClassName).newInstance();After initializing the database, we need to connect to it. So, we need to create a connection. The connection is created as:Connection con = DriverManager.getConnection(url, user, pwd);System.out.println(“con—->”+con);After connecting, we should be able to execute SQL statements in order to get the data or update it or post it on the database. In order to execute the statements, the following syntax is used:Statement st = con.createStatement();// Creating SQL queryString sql= “” ;// Executing the queryst.executeUpdate(sql);Finally, after completing the execution, we need to close the connection. The connection to the database is closed as:st.close();con.close();" }, { "code": null, "e": 27308, "s": 26946, "text": "Initially, we need to collect the database and driver info in the class which we would be developing the application. The syntax for doing this is:String driverClassName = “com.mysql.jdbc.Driver”;String url=”jdbc:mysql://localhost/jdbc”;String user=”root”;// The default password is root.// But we can set up any password// for MYSQL databaseString pwd= “root”;" }, { "code": null, "e": 27418, "s": 27308, "text": "String driverClassName = “com.mysql.jdbc.Driver”;String url=”jdbc:mysql://localhost/jdbc”;String user=”root”;" }, { "code": null, "e": 27524, "s": 27418, "text": "// The default password is root.// But we can set up any password// for MYSQL databaseString pwd= “root”;" }, { "code": null, "e": 27748, "s": 27524, "text": "Now, we need to load the JDBC driver. This is performed by the following statement:// Class.forName method returns the// Class object associated with the// class or the interfaceClass.forName(driverClassName).newInstance();" }, { "code": null, "e": 27889, "s": 27748, "text": "// Class.forName method returns the// Class object associated with the// class or the interfaceClass.forName(driverClassName).newInstance();" }, { "code": null, "e": 28108, "s": 27889, "text": "After initializing the database, we need to connect to it. So, we need to create a connection. The connection is created as:Connection con = DriverManager.getConnection(url, user, pwd);System.out.println(“con—->”+con);" }, { "code": null, "e": 28203, "s": 28108, "text": "Connection con = DriverManager.getConnection(url, user, pwd);System.out.println(“con—->”+con);" }, { "code": null, "e": 28515, "s": 28203, "text": "After connecting, we should be able to execute SQL statements in order to get the data or update it or post it on the database. In order to execute the statements, the following syntax is used:Statement st = con.createStatement();// Creating SQL queryString sql= “” ;// Executing the queryst.executeUpdate(sql);" }, { "code": null, "e": 28553, "s": 28515, "text": "Statement st = con.createStatement();" }, { "code": null, "e": 28591, "s": 28553, "text": "// Creating SQL queryString sql= “” ;" }, { "code": null, "e": 28636, "s": 28591, "text": "// Executing the queryst.executeUpdate(sql);" }, { "code": null, "e": 28778, "s": 28636, "text": "Finally, after completing the execution, we need to close the connection. The connection to the database is closed as:st.close();con.close();" }, { "code": null, "e": 28802, "s": 28778, "text": "st.close();con.close();" }, { "code": null, "e": 29019, "s": 28802, "text": "Till now, we have initialized the database and created a connection between the database and the Java program. Now, we need to define all the methods based on functionality. The methods in the program are as follows:" }, { "code": null, "e": 30538, "s": 29019, "text": "Book ticket: In order to book a ticket, we first need to choose the route. This option is given to the user to choose a route among the set of predefined routes. For all the routes, users have to enter his details like name, age, mobile number, email, etc. Now, the user gets a list of available travels in the particular route. Based on the users choice, the data is stored in that respective table of the database created above. In order to do this, switch-case is used where every case is the choice of the travel provider.Cancel Ticket: Similar to the above method, we need to implement the cancel functionality where users will be able to cancel the booked ticket. In order to do this, we need to first get the details of the users whose tickets need to be cancelled and this is validated with the mobile number and email ID of the user which is given during the input.Print Ticket: Now, the print function is implemented. In order to print the ticket, the user details are taken, like the bus in which the ticket has been booked and the email ID is taken as the input to find the ticket details and print the details.Update Ticket: In order to update the ticket, the user must have a booked ticket in the first place. Therefore, the email id of the user is taken as the input to verify if the ticket exists or not. After the email id is obtained, the search operation is performed on the database to search the ticket and then the new updated details are taken as the input which is then updated in the database." }, { "code": null, "e": 31065, "s": 30538, "text": "Book ticket: In order to book a ticket, we first need to choose the route. This option is given to the user to choose a route among the set of predefined routes. For all the routes, users have to enter his details like name, age, mobile number, email, etc. Now, the user gets a list of available travels in the particular route. Based on the users choice, the data is stored in that respective table of the database created above. In order to do this, switch-case is used where every case is the choice of the travel provider." }, { "code": null, "e": 31414, "s": 31065, "text": "Cancel Ticket: Similar to the above method, we need to implement the cancel functionality where users will be able to cancel the booked ticket. In order to do this, we need to first get the details of the users whose tickets need to be cancelled and this is validated with the mobile number and email ID of the user which is given during the input." }, { "code": null, "e": 31664, "s": 31414, "text": "Print Ticket: Now, the print function is implemented. In order to print the ticket, the user details are taken, like the bus in which the ticket has been booked and the email ID is taken as the input to find the ticket details and print the details." }, { "code": null, "e": 32060, "s": 31664, "text": "Update Ticket: In order to update the ticket, the user must have a booked ticket in the first place. Therefore, the email id of the user is taken as the input to verify if the ticket exists or not. After the email id is obtained, the search operation is performed on the database to search the ticket and then the new updated details are taken as the input which is then updated in the database." }, { "code": null, "e": 32156, "s": 32060, "text": "Below is the complete implementation of the above functions along with the database connection:" }, { "code": "// Java program to implement CLI// based application of travel agency import java.sql.*;import java.util.*;import javax.swing.JOptionPane; // Travel classclass My_Travels { public static void main(String[] args) throws Exception { String driverClassName = \"com.mysql.jdbc.Driver\"; String URL = \"jdbc:mysql:// localhost/\" + \"My_Travels_travel_service\"; String user = \"root\"; String pwd = \"mysql\"; Class.forName(driverClassName) .newInstance(); Connection con = DriverManager.getConnection( url, user, pwd); System.out.println(\"con---->\" + con); Statement st = con.createStatement(); Scanner zz = new Scanner(System.in); System.out.println( \"\\n\" + \"\\n\" + \"*********************\" + \"******************** \"); System.out.println( \"** WELCOME TO My_Travels\" + \" TRAVELS SERVICES ** \"); System.out.println( \"*********************\" + \"******************** \"); System.out.println( \"Here you have several\" + \" tasks to perform -- \" + \"\\n\" + \"\\n\"); System.out.println( \"Press 1 for ticket booking \" + \"\\n\" + \"\\n\" + \"Press 2 for \" + \"ticket cancellation\" + \"\\n\" + \"\\n\" + \"Press 3 for updating \" + \"Passenger detail\" + \"\\n\" + \"\\n\" + \"Press 4 to print \" + \"ticket details\"); int mainCH = zz.nextInt(); switch (mainCH) { case 1: System.out.println( \" Please choice the route : \"); System.out.println( \"For DEHRADUN <---> KANPUR \" + \"via Haridwar, press 1\" + \"\\n\" + \"\\n\" + \"For DEHRADUN <---> DELHI \" + \"via Roorkee, press 2\"); int route_ch = zz.nextInt(); switch (route_ch) { case 1: System.out.println( \" Welcome <--> DEHRADUN\" + \" - KANPUR route \" + \"via Haridwar \"); System.out.println( \"Please enter your detail\" + \" so we can book \" + \"your ticket\"); String w = JOptionPane .showInputDialog( \"Enter the Journey Date:\"); String x = JOptionPane .showInputDialog( \"Enter Passenger Name:\"); String y = JOptionPane.showInputDialog( \"Enter Passenger Age:\"); String z = JOptionPane.showInputDialog( \"Enter Bus Type:\"); String a = JOptionPane.showInputDialog( \"Enter Source City:\"); String b = JOptionPane.showInputDialog( \"Enter Destination City:\"); String c = JOptionPane.showInputDialog( \"Enter Seat Type:\"); String cc = JOptionPane.showInputDialog( \"Enter Email address:\"); System.out.println( \" In this route, we have \" + \"type of bushes for you \" + \"(Both AC and Non-AC \" + \"buses available \" + \"in this route \"); System.out.println( \"For Shatbdi Travels \" + \"Departure: 5 PM \" + \"Arrival: 6:15 AM \" + \"Journey time: 13Hr. 15 Min., \" + \"press 1\" + \"\\n\" + \"\\n\" + \"For Mahalaxmi Travels, \" + \"Departure: 6 PM \" + \"Arrival: 7:30 AM \" + \" Journey time: 13Hr. 30 \" + \"Min.press 2\" + \"\\n\" + \"\\n\" + \"For Blueworld Travels, \" + \"Departure: 8 PM \" + \"Arrival: 10:15 AM \" + \"Journey time: 14Hr. 15 \" + \"Min. press 3\" + \"\\n\" + \"\\n\" + \"For UP Govt. UPSRTC bushes, \" + \"Departure: 10:15 PM \" + \"Arrival: 12:45 AM \" + \"Journey time: 14Hr. 30 \" + \"Min. press 4\"); int Bus_ch_r1 = zz.nextInt(); switch (Bus_ch_r1) { case 1: String sql1 = \"INSERT INTO \" + \"shatabdi_travels_bus\" + \"(JourneyDate, P_Name, \" + \"P_Age, BusType, Source, \" + \" Destination, SeatType, \" + \"Email) VALUE(?, ?, ?, ?, \" + \"?, ?, ?, ?)\"; PreparedStatement ps1 = con.prepareStatement(sql1); ps1.setString(1, w); ps1.setString(2, x); ps1.setString(3, y); ps1.setString(4, z); ps1.setString(5, a); ps1.setString(6, b); ps1.setString(7, c); ps1.setString(8, cc); ps1.executeUpdate(); System.out.println( \"\\n\" + \"\\n\" + \"\\n\" + \"Thanks for choosing \" + \"Shatabdi Travels. \" + \"Happy and safe Journey\" + \"\\n\" + \"\\n\" + \"\\n\" + \"\\n\"); break; case 2: String sql2 = \"INSERT INTO \" + \"mahalaxmi_travels_bus(\" + \"JourneyDate, P_Name, \" + \"P_Age, BusType, Source, \" + \" Destination, SeatType, \" + \"Email) VALUE(?, ?, ?, ?, \" + \"?, ?, ?, ?)\"; PreparedStatement ps2 = con.prepareStatement(sql2); ps2.setString(1, w); ps2.setString(2, x); ps2.setString(3, y); ps2.setString(4, z); ps2.setString(5, a); ps2.setString(6, b); ps2.setString(7, c); ps2.setString(8, cc); ps2.executeUpdate(); System.out.println( \"Your ticket \" + \"is booked successfully \" + \"in Mahalaxmi Travels. \" + \"This operator accept \" + \"m-ticket, please show \" + \"ticket to bus staff \" + \"during journey. \" + \"Have a nice day !\"); System.out.println( \"Thanks for choosing \" + \"Mahalaxmi Travels. \" + \"Happy and safe Journey\"); break; case 3: String sql3 = \"INSERT INTO \" + \"blueworld_travels_bus(\" + \"JourneyDate, P_Name, \" + \"P_Age, BusType, Source, \" + \" Destination, SeatType, \" + \" Email) VALUE(?, ?, ?, ?, \" + \" ?, ?, ?, ?)\"; PreparedStatement ps3 = con.prepareStatement(sql3); ps3.setString(1, w); ps3.setString(2, x); ps3.setString(3, y); ps3.setString(4, z); ps3.setString(5, a); ps3.setString(6, b); ps3.setString(7, c); ps3.setString(8, cc); ps3.executeUpdate(); System.out.println( \"Your ticket \" + \"is booked successfully \" + \"in Blueworld Travels. \" + \"This operator accept \" + \"m-ticket, please show \" + \"ticket to bus staff during \" + \"journey. Have a nice day !\"); System.out.println( \"Thanks for choosing \" + \"Blueworld Travels. \" + \"Happy and safe Journey\"); break; case 4: String sql4 = \"INSERT INTO \" + \"upsrtc_bus(JourneyDate, \" + \" P_Name, P_Age, BusType, \" + \" Source, Destination, \" + \"SeatType, Email)\" + \" VALUE(?, ?, \" + \"?, ?, ?, ?, ?, ?)\"; PreparedStatement ps4 = con.prepareStatement(sql4); ps4.setString(1, w); ps4.setString(2, x); ps4.setString(3, y); ps4.setString(4, z); ps4.setString(5, a); ps4.setString(6, b); ps4.setString(7, c); ps4.setString(8, cc); ps4.executeUpdate(); System.out.println( \"Your ticket \" + \"is booked successfully \" + \"in UP govt. UPSRTC Bus.\" + \" This operator does not \" + \"accept m-ticket, please \" + \"take a print of ticket & \" + \"show bus staff during \" + \"journey. Have a nice day !\"); System.out.println( \"Thanks for \" + \"choosing UPSRTC.\" + \" Happy and safe Journey\"); break; default: System.out.println( \"Invalid Bus choice.\" + \" Try again Dear !\"); break; } break; case 2: System.out.println( \" Welcome to DEHRADUN\" + \" <---> DELHI route\" + \" via Roorkee \"); System.out.println( \"Please enter your detail, \" + \" so we can book\" + \" your ticket\"); String n = JOptionPane.showInputDialog( \"Enter the Journey Date:\"); String s = JOptionPane.showInputDialog( \"Enter Passenger Name:\"); String m = JOptionPane.showInputDialog( \"Enter Passenger Age:\"); String o = JOptionPane.showInputDialog( \"Enter Bus Type:\"); String p = JOptionPane.showInputDialog( \"Enter Source City:\"); String q = JOptionPane.showInputDialog( \"Enter Destination City:\"); String r = JOptionPane.showInputDialog( \"Enter Seat Type:\"); String cd = JOptionPane.showInputDialog( \"Enter Email address:\"); System.out.println( \" In this route, \" + \"we have 5 type of \" + \"bushes for you \" + \"(Both AC and \" + \"Non-AC buses available \" + \"in this route \"); System.out.println( \"For Shreenath Travels, \" + \" Departure: 5 PM \" + \"Arrival: 11:15 PM \" + \"Journey time: \" + \"6 Hr. 15 Min.press 1\" + \"\\n\" + \"\\n\" + \"For Shatabdi Travels, \" + \" Departure: 8:5 PM \" + \"Arrival: 2:10 AM \" + \"Journey time: 6 Hr. 10 \" + \"Min.press 2\" + \"\\n\" + \"\\n\" + \"For Mahalaxmi Travels, \" + \"Departure: 11 PM \" + \"Arrival: 6:15 AM \" + \"Journey time: 7Hr.\" + \" 15 Min. press 3\" + \"\\n\" + \"\\n\" + \"For UP Govt. \" + \"UPSRTC bushes, \" + \"Departure: 9:30 PM \" + \"Arrival: 4 AM \" + \"Journey time: 6 Hr. 30 \" + \"Min. press 4\" + \"\\n\" + \"\\n\" + \"For Royal Travels Pvt. Ltd.\" + \", Departure: 12 PM \" + \"Arrival: 6:15 PM \" + \"Journey time: 6 Hr. 15 \" + \"Min. press 5\"); int Bus_ch_r2 = zz.nextInt(); switch (Bus_ch_r2) { case 2: String sql5 = \"INSERT INTO \" + \"shatabdi_travels_bus\" + \"(JourneyDate, P_Name, \" + \" P_Age, BusType, Source, \" + \"Destination, SeatType, \" + \"Email) VALUE(?, ?, ?, ?, \" + \" ?, ?, ?, ?)\"; PreparedStatement ps5 = con.prepareStatement(sql5); ps5.setString(1, n); ps5.setString(2, s); ps5.setString(3, m); ps5.setString(4, o); ps5.setString(5, p); ps5.setString(6, q); ps5.setString(7, r); ps5.setString(8, cd); ps5.executeUpdate(); System.out.println( \"Your ticket is \" + \"booked successfully in \" + \"Statabdi Travels. \" + \"This operator accept \" + \"m-ticket, please show \" + \"ticket to bus staff \" + \"during the journey. \" + \"Have a nice day !\"); System.out.println( \"\\n\" + \"\\n\" + \"\\n\" + \"Thanks for choosing \" + \"Shatabdi Travels.\" + \" Happy and safe Journey\" + \"\\n\" + \"\\n\" + \"\\n\" + \"\\n\"); break; case 3: String sql6 = \"INSERT INTO \" + \"mahalaxmi_travels_bus(\" + \"JourneyDate, P_Name, \" + \"P_Age, BusType, Source, \" + \" Destination, SeatType, \" + \"Email) VALUE(?, ?, ?, ?, \" + \" ?, ?, ?, ?)\"; PreparedStatement ps6 = con.prepareStatement(sql6); ps6.setString(1, n); ps6.setString(2, s); ps6.setString(3, m); ps6.setString(4, o); ps6.setString(5, p); ps6.setString(6, q); ps6.setString(7, r); ps6.setString(8, cd); ps6.executeUpdate(); System.out.println( \"Your ticket is booked \" + \"successfully in Mahalaxmi \" + \"Travels. This operator accept \" + \"m-ticket, please show ticket \" + \"to bus staf during journey. \" + \"Have a nice day !\"); System.out.println( \"Thanks for choosing \" + \"Mahalaxmi Travels. \" + \"Happy and safe Journey\"); break; case 1: String sql7 = \"INSERT INTO \" + \"shreenath_travels_bus\" + \"(JourneyDate, P_Name, \" + \" P_Age, BusType, Source, \" + \" Destination, SeatType, \" + \"Email) VALUE(?, ?, ?, ?, \" + \"?, ?, ?, ?)\"; PreparedStatement ps17 = con.prepareStatement(sql7); ps17.setString(1, n); ps17.setString(2, s); ps17.setString(3, m); ps17.setString(4, o); ps17.setString(5, p); ps17.setString(6, q); ps17.setString(7, r); ps17.setString(8, cd); ps17.executeUpdate(); System.out.println( \"Your ticket is booked \" + \"successfully in \" + \"Shreenath Travels. \" + \"This operator accept \" + \"m-ticket, please show \" + \"ticket to bus staff \" + \"during journey. \" + \"Have a nice day !\"); System.out.println( \"Thanks for choosing \" + \"Shreenath Travels. \" + \"Happy and safe Journey\"); break; case 4: String sql8 = \"INSERT INTO \" + \"upsrtc_bus(\" + \"JourneyDate, P_Name, \" + \" P_Age, BusType, \" + \"Source, Destination, \" + \"SeatType, Email) \" + \"VALUE(?, ?, ?, ?, \" + \"?, ?, ?, ?)\"; PreparedStatement ps8 = con.prepareStatement(sql8); ps8.setString(1, n); ps8.setString(2, s); ps8.setString(3, m); ps8.setString(4, o); ps8.setString(5, p); ps8.setString(6, q); ps8.setString(7, r); ps8.setString(8, cd); ps8.executeUpdate(); System.out.println( \"Your ticket is booked \" + \"successfully in UP govt. \" + \"UPSRTC Bus. This operator \" + \"does not accept m-ticket, \" + \"please take a print of ticket \" + \"& show bus staf during journey.\" + \" Have a nice day !\"); System.out.println( \"Thanks for choosing \" + \"UPSRTC. Happy \" + \"and safe Journey\"); break; case 5: String sql9 = \"INSERT INTO \" + \"royal_travels_bus(\" + \"JourneyDate, P_Name, \" + \"P_Age, BusType, Source, \" + \" Destination, SeatType, \" + \" Email) VALUE(?, ?, ?, ?, \" + \" ?, ?, ?, ?)\"; PreparedStatement ps9 = con.prepareStatement(sql9); ps9.setString(1, n); ps9.setString(2, s); ps9.setString(3, m); ps9.setString(4, o); ps9.setString(5, p); ps9.setString(6, q); ps9.setString(7, r); ps9.setString(8, cd); ps9.executeUpdate(); System.out.println( \"Your ticket is booked \" + \"successfully in Royal \" + \"Travels Bus. This operator \" + \"does not accept m-ticket, \" + \" please take a print of ticket \" + \"& show bus staff during journey.\" + \" Have a nice day !\"); System.out.println( \"Thanks for choosing \" + \"UPSRTC. \" + \"Happy and safe Journey\"); break; default: System.out.println( \"Invalid Bus choice. \" + \"Try again Dear !\"); break; } break; } System.out.println( \"Proceed to payment ---- \" + \"don't refresh the page :\" + \"\\n\" + \"\\n\" + \"You have 3 options -->\"); System.out.println( \"1 : By Net Banking\" + \"\\n\" + \"\\n\" + \"2 : By Debit Card\" + \"\\n\" + \"\\n\" + \"3 : By Paytm Account\"); int pay_ch = zz.nextInt(); switch (pay_ch) { case 1: System.out.println( \"Enter your Net Banking \" + \"ID and Password\"); String id = zz.next(); String pass = zz.next(); break; case 2: System.out.println( \"Enter your 16 digit \" + \"debit card number, \" + \"cvv and OTP which \" + \"is sent to your \" + \"linked mobile number\"); String dc = zz.next(); String cvv = zz.next(); String OTP = zz.next(); break; case 3: System.out.println( \"Enter your PAYTM \" + \"mobile number, \" + \"password and OTP\"); String PaytmNo = zz.next(); String PtmPass = zz.next(); String PtmOTP = zz.next(); break; default: System.out.println( \"Invalid Payment choice, \" + \" try again !\"); break; } System.out.println( \"Your ticket is booked \" + \"successfully. This \" + \"operator accept m-ticket, \" + \"please show ticket to \" + \"bus staff during journey. \" + \"Have a nice day !\"); break; case 2: System.out.println( \"Select bus in which you \" + \"want to cancel your ticket\"); System.out.println( \" 1: Shatabdi Travels\" + \"\\n\" + \"\\n\" + \" 2: Blueworld Travels\" + \"\\n\" + \"\\n\" + \" 3: Mahalaxmi Travels\" + \"\\n\" + \"\\n\" + \" 4: Shreenath Travels\" + \"\\n\" + \"\\n\" + \" 5: UP govt. upsrtc bus\" + \"\\n\" + \"\\n\" + \" 6: Royal Travels\" + \"\\n\" + \"\\n\" + \" Select any one\"); int cnclCH = zz.nextInt(); String P_name = JOptionPane.showInputDialog( \"Enter the Passenger name \" + \"who want to delete ticket\"); String Email = JOptionPane.showInputDialog( \"Enter the Passenger's\" + \" Email want to delete ticket\"); switch (cnclCH) { case 1: String sql12 = \"DELETE FROM \" + \"shatabdi_travels_bus \" + \"where P_name=? and Email=?\"; PreparedStatement ps12 = con.prepareStatement(sql12); ps12.setString(1, P_name); ps12.setString(2, Email); ps12.executeUpdate(); System.out.println( \"Your ticket is cancelled \" + \"successfully from \" + \"Shatabdi Travels\"); System.out.println( \"\\n\" + \"\\n\" + \"\\n\" + \"Thanks for choosing \" + \"Shatabdi Travels.... \" + \"Happy and safe Journey\" + \"\\n\" + \"\\n\" + \"\\n\" + \"\\n\"); break; case 2: String sql13 = \"DELETE FROM \" + \"blueworld_travels_bus \" + \"where P_name=? and Email=?\"; PreparedStatement ps13 = con.prepareStatement(sql13); ps13.setString(1, P_name); ps13.setString(2, Email); ps13.executeUpdate(); System.out.println( \"Your ticket is \" + \"cancelled successfully \" + \"from Blueworld Travels\"); System.out.println( \"Thanks for choosing\" + \"Blueworld Travels.... \" + \"Happy and safe Journey\"); break; case 3: String sql14 = \"DELETE FROM \" + \"mahalaxmi_travels_bus\" + \" where P_name=? and Email=?\"; PreparedStatement ps14 = con.prepareStatement(sql14); ps14.setString(1, P_name); ps14.setString(2, Email); ps14.executeUpdate(); System.out.println( \"Your ticket is \" + \"cancelled successfully \" + \"from Mahalaxmi Travels\"); System.out.println( \"Thanks for choosing \" + \"Mahalaxmi Travels. \" + \"Happy and safe Journey\"); break; case 4: String sql15 = \"DELETE FROM \" + \"shreenath_travels_bus \" + \"where P_name=? and \" + \"Email=?\"; PreparedStatement ps15 = con.prepareStatement(sql15); ps15.setString(1, P_name); ps15.setString(2, Email); ps15.executeUpdate(); System.out.println( \"Your ticket is \" + \"cancelled successfully \" + \"from Royal Travels\"); System.out.println( \"Thanks for choosing \" + \"Shreenath Travels.... \" + \"Happy and safe Journey\"); break; case 5: String sql16 = \"DELETE FROM \" + \"upsrtc_bus where \" + \"P_name=? and Email=?\"; PreparedStatement ps16 = con.prepareStatement(sql16); ps16.setString(1, P_name); ps16.setString(2, Email); ps16.executeUpdate(); System.out.println( \"Your ticket is cancelled \" + \"successfully from UP \" + \"govt. UPSRTC bus\"); System.out.println( \"Thanks for choosing \" + \"UP govt. UPSRTC bus.\" + \" Happy and safe Journey\"); break; case 6: String sql11 = \"DELETE FROM \" + \"royal_travels_bus \" + \"where P_name=? and Email=?\"; PreparedStatement ps11 = con.prepareStatement(sql11); ps11.setString(1, P_name); ps11.setString(2, Email); ps11.executeUpdate(); System.out.println( \"Your ticket is \" + \"cancelled successfully \" + \"from Royal Travels\"); System.out.println( \"Thanks for choosing \" + \"Royal Travels.... \" + \"Happy and safe Journey\"); break; default: System.out.println( \"Invalid cancellation choise\"); break; } break; case 3: System.out.println( \"Select bus in which you \" + \"want to update your detail\"); System.out.println( \" 1: Shatabdi Travels\" + \"\\n\" + \"\\n\" + \" 2: Blueworld Travels\" + \"\\n\" + \"\\n\" + \" 3: Mahalaxmi Travels\" + \"\\n\" + \"\\n\" + \" 4: Shreenath Travels\" + \"\\n\" + \"\\n\" + \" 5: UP govt. upsrtc bus\" + \"\\n\" + \"\\n\" + \" 6: Royal Travels\" + \"\\n\" + \"\\n\" + \" Select any one\"); int udtCH = zz.nextInt(); String Email1 = JOptionPane.showInputDialog( \"Enter the Passenger's Email\" + \" who want to delete ticket\"); String P_name1 = JOptionPane.showInputDialog( \"Enter the correct \" + \"name to update ticket\"); String age1 = JOptionPane.showInputDialog( \"Enter the correct \" + \"age to update ticket\"); switch (udtCH) { case 1: String sql12 = \"UPDATE shatabdi_travels_bus \" + \"SET P_Name=?, P_Age=? where Email=?\"; PreparedStatement ps12 = con.prepareStatement(sql12); ps12.setString(1, P_name1); ps12.setString(2, age1); ps12.setString(3, Email1); ps12.executeUpdate(); System.out.println( \"Your ticket is updated \" + \"successfully from \" + \"Shatabdi Travels\"); System.out.println(\"\\n\" + \"\\n\" + \"\\n\" + \"Thanks for choosing \" + \"Shatabdi Travels.... \" + \"Happy and safe Journey\" + \"\\n\" + \"\\n\" + \"\\n\" + \"\\n\"); break; case 2: String sql13 = \"UPDATE blueworld_travels_bus\" + \" SET P_Name=?, P_age=? where Email=?\"; PreparedStatement ps13 = con.prepareStatement(sql13); ps13.setString(1, P_name1); ps13.setString(2, age1); ps13.setString(3, Email1); ps13.executeUpdate(); System.out.println( \"Your ticket is updated \" + \"successfully from \" + \"Blueworld Travels\"); System.out.println( \"Thanks for choosing \" + \"Blueworld Travels.... \" + \"Happy and safe Journey\"); break; case 3: String sql14 = \"UPDATE mahalaxmi_travels_bus \" + \"SET P_Name=?, P_Age=? where Email=?\"; PreparedStatement ps14 = con.prepareStatement(sql14); ps14.setString(1, P_name1); ps14.setString(2, age1); ps14.setString(3, Email1); ps14.executeUpdate(); System.out.println( \"Your ticket is updated \" + \"successfully from \" + \"Mahalaxmi Travels\"); System.out.println( \"Thanks for choosing \" + \"Mahalaxmi Travels.... \" + \"Happy and safe Journey\"); break; case 4: String sql15 = \"UPDATE shreenath_travels_bus \" + \"SET P_Name=?, P_Age=? where Email=?\"; PreparedStatement ps15 = con.prepareStatement(sql15); ps15.setString(1, P_name1); ps15.setString(2, age1); ps15.setString(3, Email1); ps15.executeUpdate(); System.out.println( \"Your ticket is updated \" + \"successfully from \" + \"Royal Travels\"); System.out.println( \"Thanks for choosing \" + \"Shreenath Travels.... \" + \"Happy and safe Journey\"); break; case 5: String sql16 = \"UPDATE upsrtc_bus \" + \"SET P_Name=?, P_Age=? \" + \"where Email=?\"; PreparedStatement ps16 = con.prepareStatement(sql16); ps16.setString(1, P_name1); ps16.setString(2, age1); ps16.setString(3, Email1); ps16.executeUpdate(); System.out.println( \"Your ticket is updated \" + \"successfully from UP \" + \"govt. UPSRTC bus\"); System.out.println( \"Thanks for choosing \" + \"UP govt. UPSRTC bus....\" + \" Happy and safe Journey\"); break; case 6: String sql11 = \"UPDATE royal_travels_bus\" + \" SET P_Name=?, P_Age=? \" + \"where Email=?\"; PreparedStatement ps11 = con.prepareStatement(sql11); ps11.setString(1, P_name1); ps11.setString(2, age1); ps11.setString(3, age1); ps11.executeUpdate(); System.out.println( \"Your ticket is updated \" + \"successfully from \" + \"Royal Travels\"); System.out.println( \"Thanks for choosing \" + \"Royal Travels.... \" + \"Happy and safe Journey\"); break; default: System.out.println( \"Invalid cancellation choise\"); break; } break; case 4: System.out.println( \"Select bus in which \" + \"you want to print your ticket\"); System.out.println( \" 1: Shatabdi Travels\" + \"\\n\" + \"\\n\" + \" 2: Blueworld Travels\" + \"\\n\" + \"\\n\" + \" 3: Mahalaxmi Travels\" + \"\\n\" + \"\\n\" + \" 4: Shreenath Travels\" + \"\\n\" + \"\\n\" + \" 5: UP govt. upsrtc bus\" + \"\\n\" + \"\\n\" + \" 6: Royal Travels\" + \"\\n\" + \"\\n\" + \" Select any one\"); int PrntCH = zz.nextInt(); String PEmail = JOptionPane.showInputDialog( \"Enter the Email to print ticket\"); switch (PrntCH) { case 1: String sql21 = \"SELECT JourneyDate, \" + \"P_Name, P_Age, Source, \" + \"Destination, BusType, \" + \"Email, SeatType FROM \" + \"shatabdi_travels_bus \" + \"WHERE Email= ?\"; PreparedStatement ps21 = con.prepareStatement(sql21); ps21.setString(1, PEmail); ResultSet rs1 = ps21.executeQuery(); while (rs1.next()) { System.out.println( \"Journey Date : \" + rs1.getString(\"JourneyDate\") + \"\\n\" + \"\\n\" + \"Passenger Name : \" + rs1.getString(\"P_Name\") + \"\\n\" + \"\\n\" + \"Passenger Age : \" + rs1.getInt(\"P_Age\") + \"\\n\" + \"\\n\" + \"Source City : \" + rs1.getString(\"Source\") + \"\\n\" + \"\\n\" + \"Destination City : \" + rs1.getString(\"Destination\") + \"\\n\" + \"\\n\" + \"Bus Type : \" + rs1.getString(\"BusType\") + \"\\n\" + \"\\n\" + \"Passenger's Email : \" + rs1.getString(\"Email\") + \"\\n\" + \"\\n\" + \"Seat Type : \" + rs1.getString(\"SeatType\")); } rs1.close(); System.out.println( \"\\n\" + \"\\n\" + \"\\n\" + \"Thanks for choosing \" + \"Shatabdi Travels.... \" + \"Happy and safe Journey\" + \"\\n\" + \"\\n\" + \"\\n\" + \"\\n\"); break; case 2: String sql22 = \"SELECT JourneyDate, \" + \"P_Name, P_Age, Source, \" + \" Destination, BusType, \" + \"Email, SeatType FROM \" + \"blueworld_travels_bus \" + \"WHERE Email= ?\"; PreparedStatement ps22 = con.prepareStatement(sql22); ps22.setString(1, PEmail); ResultSet rs2 = ps22.executeQuery(); while (rs2.next()) { System.out.println( \"Journey Date : \" + rs2.getString(\"JourneyDate\") + \"\\n\" + \"\\n\" + \"Passenger Name : \" + rs2.getString(\"P_Name\") + \"\\n\" + \"\\n\" + \"Passenger Age : \" + rs2.getInt(\"P_Age\") + \"\\n\" + \"\\n\" + \"Source City : \" + rs2.getString(\"Source\") + \"\\n\" + \"\\n\" + \"Destination City : \" + rs2.getString(\"Destination\") + \"\\n\" + \"\\n\" + \"Bus Type : \" + rs2.getString(\"BusType\") + \"\\n\" + \"\\n\" + \"Passenger's Email : \" + rs2.getString(\"Email\") + \"\\n\" + \"\\n\" + \"Seat Type : \" + rs2.getString(\"SeatType\")); } rs2.close(); System.out.println( \"\\n\" + \"\\n\" + \"\\n\" + \"Thanks for choosing \" + \"Blueworld Travels.... \" + \"Happy and safe Journey\" + \"\\n\" + \"\\n\" + \"\\n\" + \"\\n\"); break; case 3: String sql23 = \"SELECT JourneyDate, P_Name, \" + \"P_Age, Source, Destination, \" + \" BusType, Email, \" + \"SeatType FROM \" + \"mahalaxmi_travels_bus \" + \"WHERE Email= ?\"; PreparedStatement ps23 = con.prepareStatement(sql23); ps23.setString(1, PEmail); ResultSet rs3 = ps23.executeQuery(); while (rs3.next()) { System.out.println( \"Journey Date : \" + rs3.getString(\"JourneyDate\") + \"\\n\" + \"\\n\" + \"Passenger Name : \" + rs3.getString(\"P_Name\") + \"\\n\" + \"\\n\" + \"Passenger Age : \" + rs3.getInt(\"P_Age\") + \"\\n\" + \"\\n\" + \"Source City : \" + rs3.getString(\"Source\") + \"\\n\" + \"\\n\" + \"Destination City : \" + rs3.getString(\"Destination\") + \"\\n\" + \"\\n\" + \"Bus Type : \" + rs3.getString(\"BusType\") + \"\\n\" + \"\\n\" + \"Passenger's Email : \" + rs3.getString(\"Email\") + \"\\n\" + \"\\n\" + \"Seat Type : \" + rs3.getString(\"SeatType\")); } rs3.close(); System.out.println( \"\\n\" + \"\\n\" + \"\\n\" + \"Thanks for choosing \" + \"Mahalaxmi Travels.... \" + \"Happy and safe Journey\" + \"\\n\" + \"\\n\" + \"\\n\" + \"\\n\"); break; case 4: String sql24 = \"SELECT JourneyDate, P_Name, \" + \"P_Age, Source, Destination, \" + \"BusType, Email, SeatType \" + \"FROM shreenath_travels_bus \" + \"WHERE Email= ?\"; PreparedStatement ps24 = con.prepareStatement(sql24); ps24.setString(1, PEmail); ResultSet rs4 = ps24.executeQuery(); while (rs4.next()) { System.out.println( \"Journey Date : \" + rs4.getString(\"JourneyDate\") + \"\\n\" + \"\\n\" + \"Passenger Name : \" + rs4.getString(\"P_Name\") + \"\\n\" + \"\\n\" + \"Passenger Age : \" + rs4.getInt(\"P_Age\") + \"\\n\" + \"\\n\" + \"Source City : \" + rs4.getString(\"Source\") + \"\\n\" + \"\\n\" + \"Destination City : \" + rs4.getString(\"Destination\") + \"\\n\" + \"\\n\" + \"Bus Type : \" + rs4.getString(\"BusType\") + \"\\n\" + \"\\n\" + \"Passenger's Email : \" + rs4.getString(\"Email\") + \"\\n\" + \"\\n\" + \"Seat Type : \" + rs4.getString(\"SeatType\")); } rs4.close(); System.out.println( \"\\n\" + \"\\n\" + \"\\n\" + \"Thanks for choosing \" + \"Shreenath Travels.... \" + \"Happy and safe Journey\" + \"\\n\" + \"\\n\" + \"\\n\" + \"\\n\"); break; case 6: String sql25 = \"SELECT JourneyDate, P_Name, \" + \"P_Age, Source, Destination, \" + \"BusType, Email, SeatType \" + \"FROM royal_travels_bus \" + \"WHERE Email= ?\"; PreparedStatement ps25 = con.prepareStatement(sql25); ps25.setString(1, PEmail); ResultSet rs5 = ps25.executeQuery(); while (rs5.next()) { System.out.println( \"Journey Date : \" + rs5.getString(\"JourneyDate\") + \"\\n\" + \"\\n\" + \"Passenger Name : \" + rs5.getString(\"P_Name\") + \"\\n\" + \"\\n\" + \"Passenger Age : \" + rs5.getInt(\"P_Age\") + \"\\n\" + \"\\n\" + \"Source City : \" + rs5.getString(\"Source\") + \"\\n\" + \"\\n\" + \"Destination City : \" + rs5.getString(\"Destination\") + \"\\n\" + \"\\n\" + \"Bus Type : \" + rs5.getString(\"BusType\") + \"\\n\" + \"\\n\" + \"Passenger's Email : \" + rs5.getString(\"Email\") + \"\\n\" + \"\\n\" + \"Seat Type : \" + rs5.getString(\"SeatType\")); } rs5.close(); System.out.println( \"\\n\" + \"\\n\" + \"\\n\" + \"Thanks for choosing \" + \"Royal Travels.... \" + \"Happy and safe Journey\" + \"\\n\" + \"\\n\" + \"\\n\" + \"\\n\"); break; case 5: String sql26 = \"SELECT JourneyDate, P_Name, \" + \" P_Age, Source, Destination, \" + \"BusType, Email, SeatType \" + \"FROM upsrtc_bus WHERE \" + \"Email= ?\"; PreparedStatement ps26 = con.prepareStatement(sql26); ps26.setString(1, PEmail); ResultSet rs6 = ps26.executeQuery(); while (rs6.next()) { System.out.println( \"Journey Date : \" + rs6.getString(\"JourneyDate\") + \"\\n\" + \"\\n\" + \"Passenger Name : \" + rs6.getString(\"P_Name\") + \"\\n\" + \"\\n\" + \"Passenger Age : \" + rs6.getInt(\"P_Age\") + \"\\n\" + \"\\n\" + \"Source City : \" + rs6.getString(\"Source\") + \"\\n\" + \"\\n\" + \"Destination City : \" + rs6.getString(\"Destination\") + \"\\n\" + \"\\n\" + \"Bus Type : \" + rs6.getString(\"BusType\") + \"\\n\" + \"\\n\" + \"Passenger's Email : \" + rs6.getString(\"Email\") + \"\\n\" + \"\\n\" + \"Seat Type : \" + rs6.getString(\"SeatType\")); } rs6.close(); System.out.println( \"\\n\" + \"\\n\" + \"\\n\" + \"Thanks for choosing UP govt. \" + \"UPSRTC.... \" + \"Happy and safe Journey\" + \"\\n\" + \"\\n\" + \"\\n\" + \"\\n\"); break; } break; } st.close(); con.close(); System.out.println(\"---SQL executed successfully---\"); System.out.println(\"Adars11h Shukla \" + \"R134218010\"); }}", "e": 81298, "s": 32156, "text": null }, { "code": null, "e": 81401, "s": 81298, "text": "Note: The above code does not work on the online IDE. Please use an offline IDE to run the above code." }, { "code": null, "e": 81473, "s": 81401, "text": "Output: The following two videos explain the working of the above code." }, { "code": null, "e": 81487, "s": 81473, "text": "sumitgumber28" }, { "code": null, "e": 81497, "s": 81487, "text": "kk9826225" }, { "code": null, "e": 81507, "s": 81497, "text": "nnr223442" }, { "code": null, "e": 81516, "s": 81507, "text": "rkbhola5" }, { "code": null, "e": 81523, "s": 81516, "text": "Java 8" }, { "code": null, "e": 81528, "s": 81523, "text": "JDBC" }, { "code": null, "e": 81534, "s": 81528, "text": "mysql" }, { "code": null, "e": 81539, "s": 81534, "text": "Java" }, { "code": null, "e": 81553, "s": 81539, "text": "Java Programs" }, { "code": null, "e": 81561, "s": 81553, "text": "Project" }, { "code": null, "e": 81577, "s": 81561, "text": "Write From Home" }, { "code": null, "e": 81582, "s": 81577, "text": "Java" }, { "code": null, "e": 81680, "s": 81582, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 81689, "s": 81680, "text": "Comments" }, { "code": null, "e": 81702, "s": 81689, "text": "Old Comments" }, { "code": null, "e": 81723, "s": 81702, "text": "Constructors in Java" }, { "code": null, "e": 81742, "s": 81723, "text": "Exceptions in Java" }, { "code": null, "e": 81772, "s": 81742, "text": "Functional Interfaces in Java" }, { "code": null, "e": 81787, "s": 81772, "text": "Stream In Java" }, { "code": null, "e": 81833, "s": 81787, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 81877, "s": 81833, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 81903, "s": 81877, "text": "Java Programming Examples" }, { "code": null, "e": 81935, "s": 81903, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 81982, "s": 81935, "text": "Implementing a Linked List in Java using Class" } ]
Remove spaces from std::string in C++
In this program we will see how to remove the spaces from a std::string in C++. To remove this we will use the remove() function. With this remove() function it takes the beginning and end of the iterator, then takes the third argument that will be deleted from that iterator object. Input: A string "This is C++ Programming Language" Output: "ThisisC++ProgrammingLanguage" Step 1: Get the string Step 2: Remove spaces from the given string using remove() function. Step 3: Return string. Live Demo #include<iostream> #include<algorithm> using namespace std; main() { string my_str = "This is C++ Programming Language"; cout << "String with Spaces :" << my_str << endl; remove(my_str.begin(), my_str.end(), ' '); cout << "String without Spaces :" << my_str; } String with Spaces :This is C++ Programming Language String without Spaces :ThisisC++ProgrammingLanguage
[ { "code": null, "e": 1346, "s": 1062, "text": "In this program we will see how to remove the spaces from a std::string in C++. To remove this we will use the remove() function. With this remove() function it takes the beginning and end of the iterator, then takes the third argument that will be deleted from that iterator object." }, { "code": null, "e": 1436, "s": 1346, "text": "Input: A string \"This is C++ Programming Language\"\nOutput: \"ThisisC++ProgrammingLanguage\"" }, { "code": null, "e": 1551, "s": 1436, "text": "Step 1: Get the string\nStep 2: Remove spaces from the given string using remove() function.\nStep 3: Return string." }, { "code": null, "e": 1562, "s": 1551, "text": " Live Demo" }, { "code": null, "e": 1835, "s": 1562, "text": "#include<iostream>\n#include<algorithm>\nusing namespace std;\nmain() {\n string my_str = \"This is C++ Programming Language\";\n cout << \"String with Spaces :\" << my_str << endl;\n remove(my_str.begin(), my_str.end(), ' ');\n cout << \"String without Spaces :\" << my_str;\n}" }, { "code": null, "e": 1940, "s": 1835, "text": "String with Spaces :This is C++ Programming Language\nString without Spaces :ThisisC++ProgrammingLanguage" } ]
A Complete Guide to Time Series Data Visualization in Python | by Rashida Nasrin Sucky | Towards Data Science
Time series data is very important in so many different industries. It is especially important in research, financial industries, pharmaceuticals, social media, web services, and many more. Analysis of time series data is also becoming more and more essential. What is better than some good visualizations in the analysis. Any type of data analysis is not complete without some visuals. Because one good plot can provide you with a better understanding than a 20-page report. So, this article is all about time-series data visualization. I will start with some very simple visualization and slowly will move to some advanced visualization techniques and tools I need to make one more thing clear before starting. ‘The complete guide” in the title does not mean, it has all the visualization. There are so many visualizations available in so many different libraries that it is even not practical to have all of them in one article. But this article should provide you with enough tools and techniques to tell a story or understand and visualize a time series data clearly. I tried to explain some simple and easy ones and some advanced techniques. If you are reading this for learning, the best way is to follow along and run all the code by yourself. Please feel free to download the dataset from this link: github.com This is a stock dataset. Let’s import some necessary packages and the dataset: import pandas as pdimport numpy as npimport matplotlib.pyplot as pltdf = pd.read_csv("stock_data.csv", parse_dates=True, index_col = "Date")df.head() I used the ‘parse_dates’ parameter in the read_csv function to convert the ‘Date’ column to the DatetimeIndex format. Most of the time, Dates are stored in string format which is not the right format for time series data analysis. When it is in the DatetimeIndex format, it is a lot helpful to deal with as a time series data. You will see it soon. I have a detailed article on Time-series data analysis. If you are new to time series data, it will be helpful if you have a look at this article first: towardsdatascience.com I explained some important Pandas function in the article above that will be used in this article. Though I will provide a brief idea here as well. But if you need an example to understand better, please feel free to have a look at that previous article. As I said before, I want to start with some basic plots. The most basic plot should be a line plot using Pandas. I will plot the ‘Volume’ data here. See how it looks: df['Volume'].plot() This is our plot of ‘Volume’ data that looks pretty busy with some big spikes. It will be a good idea to plot all the other columns as well in a plot to examine the curves of all of them at the same time. df.plot(subplots=True, figsize=(10,12)) The shape of the curve for ‘Open’, ‘Close’, ‘High’ and ‘Low’ data have the same shape. Only the ‘Volume’ has a different shape. Seasonality The line plot I used above is great for showing seasonality. Resampling for months or weeks and making bar plots is another very simple and widely used method of finding seasonality. Here I am making a bar plot of month data for 2016 and 2017. For the index, I will use [2016:]. Because our dataset contains data until 2017. So, 2016 to end should bring 2016 and 2017. df_month = df.resample("M").mean()fig, ax = plt.subplots(figsize=(10, 6))ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))ax.bar(df_month['2016':].index, df_month.loc['2016':, "Volume"], width=25, align='center' There are 24 bars. Each bar represents a month. A huge spike in July 2017. Otherwise, there is no monthly seasonality here. One way to find seasonality is by using a set of boxplots. Here I am going to make boxplots for each month. I will use ‘Open’, ‘Close’, ‘High’ and ‘Low’ data to make this plot. import seaborn as sns#start, end = '2016-01', '2016-12'fig, axes = plt.subplots(4, 1, figsize=(10, 16), sharex=True)for name, ax in zip(['Open', 'Close', 'High', 'Low'], axes): sns.boxplot(data = df, x='Month', y=name, ax=ax) ax.set_ylabel("") ax.set_title(name) if ax != axes[-1]: ax.set_xlabel('') It shows the monthly difference in values clearly. There are more ways to show seasonality. I discussed it one more way at the end. Remember that first line plot of ‘Volume’ data above. As we discussed before, it was too busy. It can be fixed by resampling. Instead of plotting daily data, plotting monthly average will fix this issue to a large extent. I will use the df_month dataset I prepared already for the bar plot and box plots above for this. df_month['Volume'].plot(figsize=(8, 6)) Much more understandable and clearer! It gives a better idea about a trend in long term. Resampling is very common in time-series data. Most of the time resampling is done to a lower frequency. So, this article will only deal with the resampling of lower frequencies. Though resampling of higher frequency is also necessary especially for modeling purposes. Not so much in data analysis purpose. In the ‘Volume’ data we are working on right now, we can observe some big spikes here and there. These types of spikes are not helpful for data analysis or for modeling. normally to smooth out the spikes, resampling to a lower frequency and rolling is very helpful. Now, plot the daily data and weekly average ‘Volume’ in the same plot. First, make a weekly average dataset using the resampling method. df_week = df.resample("W").mean() This ‘df_week’ and ‘df_month’ will be useful for us in later visualization as well. Let’s plot the daily and weekly data in the same plot. start, end = '2015-01', '2015-08'fig, ax = plt.subplots()ax.plot(df.loc[start:end, 'Volume'], marker='.', linestyle='-', linewidth = 0.5, label='Daily', color='black')ax.plot(df_week.loc[start:end, 'Volume'], marker='o', markersize=8, linestyle='-', label='Weekly', color='coral')label='Monthly', color='violet')ax.set_ylabel("Open")ax.legend() Look, the weekly average plot has smaller spikes than daily data. Rolling is another very helpful way of smoothing out the curve. It takes the average of a specified amount of data. If I want a 7-day rolling, it gives us the 7-d average data. Let’s include the 7-d rolling data in the above plot. df_7d_rolling = df.rolling(7, center=True).mean()start, end = '2016-06', '2017-05'fig, ax = plt.subplots()ax.plot(df.loc[start:end, 'Volume'], marker='.', linestyle='-', linewidth=0.5, label='Daily')ax.plot(df_week.loc[start:end, 'Volume'], marker='o', markersize=5, linestyle='-', label = 'Weekly mean volume')ax.plot(df_7d_rolling.loc[start:end, 'Volume'], marker='.', linestyle='-', label='7d Rolling Average')ax.set_ylabel('Stock Volume')ax.legend() A lot going on in this one plot. But If you look at it carefully it is still understandable. If you notice 7-d rolling average is a bit smoother than the weekly average. It is also common to take a 30-d or 365-d rolling average to make the curve smoother. Please try it yourself. Lots of time it is more useful to see how the data change over time instead of just everyday data. There are a few different ways to calculate and visualize the change in data. Shift The shift function shifts the data before or after the specified amount of time. If I do not specify the time it will shift the data by one day by default. That means you will get the previous day's data. In financial data like this one, it is helpful to see previous day data and today's data side by side. As this article is dedicated to visualization only, I will only plot the previous day data: df['Change'] = df.Close.div(df.Close.shift())df['Change'].plot(figsize=(20, 8), fontsize = 16) In the code above, .div() helps to fill up the missing data. Actually, div() means division. df. div(6) will divide each element in df by 6. But here I used ‘df.Close.shift()’. So, Each element of df will be divided by each element of ‘df.Close.shift()’. We do this to avoid the null values that are created by the ‘shift()’ operation. If it is not yet clear to you, please look at the article I mentioned in the beginning. Here is the output: You can simply take a specific period and plot to have a clearer look. This is the plot of 2017 only. df['2017']['Change'].plot(figsize=(10, 6)) Though the shift is useful in many ways. But I find percent change useful on many occasions. Percent_Change I will use the monthly data that was calculated in the beginning. This time I chose bar plots. It shows the percent change clearly. There is a percent change function available to get the percent_change data. df_month.loc[:, 'pct_change'] = df.Close.pct_change()*100fig, ax = plt.subplots()df_month['pct_change' ].plot(kind='bar', color='coral', ax=ax)ax.xaxis.set_major_locator(mdates.WeekdayLocator())ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))plt.xticks(rotation=45)ax.legend() I plotted the percent change in closing data here. I used monthly percent change here. Differencing Differencing takes the difference in values of a specified distance. By default, it’s one. If you specify 2 like “df.High.diff(2)’, it will take the difference of first and third element of ‘High’ column, second and fourth element, and so on. It is a popular method to remove the trend in the data. The trend is not good for forecasting or modeling. df.High.diff().plot(figsize=(10, 6)) Expanding Window Another way of transformation. It keeps adding the cumulative. For example, if you add an expanding function to the ‘High’ column first element remains the same. The second element becomes cumulative of the first and second element, the third element becomes cumulative of the first, second, and third element, and so on. You can use aggregate functions like mean, median, standard deviation, etc. on it too. In that way, it will provide you with the changing mean, median, sum, or standard deviation with time. Isn’t it really useful for financial data or business sales or profit data? fig, ax = plt.subplots()ax = df.High.plot(label='High')ax = df.High.expanding().mean().plot(label='High expanding mean')ax = df.High.expanding().std().plot(label='High expanding std')ax.legend() Here I added expanding mean and standard deviation. Look at the daily data and the mean. At the end of 2017, daily data shows a huge spike. But it doesn’t show a spike in the average. Probably if you take the 2017 data only, the expanding average will look different. Please feel free to try it. A heat map is generally a common type of data visualization that is used everywhere. In time-series data also heat maps can be very useful. But before diving into the heat map, we need to develop a calendar that will represent each year and month data of our dataset. Let’s see it in an example. For this demonstration, I will import a calendar package and use the pivot table function to generate the values. import calendarall_month_year_df = pd.pivot_table(df, values="Open", index=["month"], columns=["year"], fill_value=0, margins=True)named_index = [[calendar.month_abbr[i] if isinstance(i, int) else i for i in list(all_month_year_df.index)]] # name monthsall_month_year_df = all_month_year_df.set_index(named_index)all_month_year_df The calendar is ready with monthly average ‘Open’ data. Now, generate the heat map with it. ax = sns.heatmap(all_month_year_df, cmap='RdYlGn_r', robust=True, fmt='.2f', annot=True, linewidths=.5, annot_kws={'size':11}, cbar_kws={'shrink':.8, 'label':'Open'}) ax.set_yticklabels(ax.get_yticklabels(), rotation=0, fontsize=10)ax.set_xticklabels(ax.get_xticklabels(), rotation=0, fontsize=10)plt.title('Average Opening', fontdict={'fontsize':18}, pad=14); The heat map is ready! Darker red means very high opening and dark green mean very low opening. Decomposition will show the observations and these three elements in the same plot: Trend: Consistent upward or downward slope of a time series. Seasonality: Clear periodic pattern of a time series Noise: Outliers or missing values Using the stats model library, it is easy to do it: from pylab import rcParamsimport statsmodels.api as smrcParams['figure.figsize'] = 11, 9decomposition = sm.tsa.seasonal_decompose(df_month['Volume'], model='Additive')fig = decomposition.plot()plt.show() Here the trend is the moving average. To give you a high-level idea of residuals in the last row, here is the general formula: Original observations = Trend + Seasonality + Residuals Though the documentation for decomposition itself says that it’s a very naive representation but it is still popular. If you could run all the code above, Congratulation! You learned enough today to make a great level of time series of data visualization. As I mentioned in the beginning, there are a lot of cool visualization techniques available. I will write more in the future. Feel free to follow me on Twitter and like my Facebook page.
[ { "code": null, "e": 710, "s": 172, "text": "Time series data is very important in so many different industries. It is especially important in research, financial industries, pharmaceuticals, social media, web services, and many more. Analysis of time series data is also becoming more and more essential. What is better than some good visualizations in the analysis. Any type of data analysis is not complete without some visuals. Because one good plot can provide you with a better understanding than a 20-page report. So, this article is all about time-series data visualization." }, { "code": null, "e": 832, "s": 710, "text": "I will start with some very simple visualization and slowly will move to some advanced visualization techniques and tools" }, { "code": null, "e": 885, "s": 832, "text": "I need to make one more thing clear before starting." }, { "code": null, "e": 1104, "s": 885, "text": "‘The complete guide” in the title does not mean, it has all the visualization. There are so many visualizations available in so many different libraries that it is even not practical to have all of them in one article." }, { "code": null, "e": 1320, "s": 1104, "text": "But this article should provide you with enough tools and techniques to tell a story or understand and visualize a time series data clearly. I tried to explain some simple and easy ones and some advanced techniques." }, { "code": null, "e": 1481, "s": 1320, "text": "If you are reading this for learning, the best way is to follow along and run all the code by yourself. Please feel free to download the dataset from this link:" }, { "code": null, "e": 1492, "s": 1481, "text": "github.com" }, { "code": null, "e": 1571, "s": 1492, "text": "This is a stock dataset. Let’s import some necessary packages and the dataset:" }, { "code": null, "e": 1721, "s": 1571, "text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltdf = pd.read_csv(\"stock_data.csv\", parse_dates=True, index_col = \"Date\")df.head()" }, { "code": null, "e": 2070, "s": 1721, "text": "I used the ‘parse_dates’ parameter in the read_csv function to convert the ‘Date’ column to the DatetimeIndex format. Most of the time, Dates are stored in string format which is not the right format for time series data analysis. When it is in the DatetimeIndex format, it is a lot helpful to deal with as a time series data. You will see it soon." }, { "code": null, "e": 2223, "s": 2070, "text": "I have a detailed article on Time-series data analysis. If you are new to time series data, it will be helpful if you have a look at this article first:" }, { "code": null, "e": 2246, "s": 2223, "text": "towardsdatascience.com" }, { "code": null, "e": 2501, "s": 2246, "text": "I explained some important Pandas function in the article above that will be used in this article. Though I will provide a brief idea here as well. But if you need an example to understand better, please feel free to have a look at that previous article." }, { "code": null, "e": 2668, "s": 2501, "text": "As I said before, I want to start with some basic plots. The most basic plot should be a line plot using Pandas. I will plot the ‘Volume’ data here. See how it looks:" }, { "code": null, "e": 2688, "s": 2668, "text": "df['Volume'].plot()" }, { "code": null, "e": 2893, "s": 2688, "text": "This is our plot of ‘Volume’ data that looks pretty busy with some big spikes. It will be a good idea to plot all the other columns as well in a plot to examine the curves of all of them at the same time." }, { "code": null, "e": 2933, "s": 2893, "text": "df.plot(subplots=True, figsize=(10,12))" }, { "code": null, "e": 3061, "s": 2933, "text": "The shape of the curve for ‘Open’, ‘Close’, ‘High’ and ‘Low’ data have the same shape. Only the ‘Volume’ has a different shape." }, { "code": null, "e": 3073, "s": 3061, "text": "Seasonality" }, { "code": null, "e": 3442, "s": 3073, "text": "The line plot I used above is great for showing seasonality. Resampling for months or weeks and making bar plots is another very simple and widely used method of finding seasonality. Here I am making a bar plot of month data for 2016 and 2017. For the index, I will use [2016:]. Because our dataset contains data until 2017. So, 2016 to end should bring 2016 and 2017." }, { "code": null, "e": 3664, "s": 3442, "text": "df_month = df.resample(\"M\").mean()fig, ax = plt.subplots(figsize=(10, 6))ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))ax.bar(df_month['2016':].index, df_month.loc['2016':, \"Volume\"], width=25, align='center'" }, { "code": null, "e": 3788, "s": 3664, "text": "There are 24 bars. Each bar represents a month. A huge spike in July 2017. Otherwise, there is no monthly seasonality here." }, { "code": null, "e": 3965, "s": 3788, "text": "One way to find seasonality is by using a set of boxplots. Here I am going to make boxplots for each month. I will use ‘Open’, ‘Close’, ‘High’ and ‘Low’ data to make this plot." }, { "code": null, "e": 4284, "s": 3965, "text": "import seaborn as sns#start, end = '2016-01', '2016-12'fig, axes = plt.subplots(4, 1, figsize=(10, 16), sharex=True)for name, ax in zip(['Open', 'Close', 'High', 'Low'], axes): sns.boxplot(data = df, x='Month', y=name, ax=ax) ax.set_ylabel(\"\") ax.set_title(name) if ax != axes[-1]: ax.set_xlabel('')" }, { "code": null, "e": 4335, "s": 4284, "text": "It shows the monthly difference in values clearly." }, { "code": null, "e": 4416, "s": 4335, "text": "There are more ways to show seasonality. I discussed it one more way at the end." }, { "code": null, "e": 4736, "s": 4416, "text": "Remember that first line plot of ‘Volume’ data above. As we discussed before, it was too busy. It can be fixed by resampling. Instead of plotting daily data, plotting monthly average will fix this issue to a large extent. I will use the df_month dataset I prepared already for the bar plot and box plots above for this." }, { "code": null, "e": 4776, "s": 4736, "text": "df_month['Volume'].plot(figsize=(8, 6))" }, { "code": null, "e": 4865, "s": 4776, "text": "Much more understandable and clearer! It gives a better idea about a trend in long term." }, { "code": null, "e": 4970, "s": 4865, "text": "Resampling is very common in time-series data. Most of the time resampling is done to a lower frequency." }, { "code": null, "e": 5172, "s": 4970, "text": "So, this article will only deal with the resampling of lower frequencies. Though resampling of higher frequency is also necessary especially for modeling purposes. Not so much in data analysis purpose." }, { "code": null, "e": 5438, "s": 5172, "text": "In the ‘Volume’ data we are working on right now, we can observe some big spikes here and there. These types of spikes are not helpful for data analysis or for modeling. normally to smooth out the spikes, resampling to a lower frequency and rolling is very helpful." }, { "code": null, "e": 5575, "s": 5438, "text": "Now, plot the daily data and weekly average ‘Volume’ in the same plot. First, make a weekly average dataset using the resampling method." }, { "code": null, "e": 5609, "s": 5575, "text": "df_week = df.resample(\"W\").mean()" }, { "code": null, "e": 5693, "s": 5609, "text": "This ‘df_week’ and ‘df_month’ will be useful for us in later visualization as well." }, { "code": null, "e": 5748, "s": 5693, "text": "Let’s plot the daily and weekly data in the same plot." }, { "code": null, "e": 6093, "s": 5748, "text": "start, end = '2015-01', '2015-08'fig, ax = plt.subplots()ax.plot(df.loc[start:end, 'Volume'], marker='.', linestyle='-', linewidth = 0.5, label='Daily', color='black')ax.plot(df_week.loc[start:end, 'Volume'], marker='o', markersize=8, linestyle='-', label='Weekly', color='coral')label='Monthly', color='violet')ax.set_ylabel(\"Open\")ax.legend()" }, { "code": null, "e": 6159, "s": 6093, "text": "Look, the weekly average plot has smaller spikes than daily data." }, { "code": null, "e": 6336, "s": 6159, "text": "Rolling is another very helpful way of smoothing out the curve. It takes the average of a specified amount of data. If I want a 7-day rolling, it gives us the 7-d average data." }, { "code": null, "e": 6390, "s": 6336, "text": "Let’s include the 7-d rolling data in the above plot." }, { "code": null, "e": 6860, "s": 6390, "text": "df_7d_rolling = df.rolling(7, center=True).mean()start, end = '2016-06', '2017-05'fig, ax = plt.subplots()ax.plot(df.loc[start:end, 'Volume'], marker='.', linestyle='-', linewidth=0.5, label='Daily')ax.plot(df_week.loc[start:end, 'Volume'], marker='o', markersize=5, linestyle='-', label = 'Weekly mean volume')ax.plot(df_7d_rolling.loc[start:end, 'Volume'], marker='.', linestyle='-', label='7d Rolling Average')ax.set_ylabel('Stock Volume')ax.legend()" }, { "code": null, "e": 7030, "s": 6860, "text": "A lot going on in this one plot. But If you look at it carefully it is still understandable. If you notice 7-d rolling average is a bit smoother than the weekly average." }, { "code": null, "e": 7140, "s": 7030, "text": "It is also common to take a 30-d or 365-d rolling average to make the curve smoother. Please try it yourself." }, { "code": null, "e": 7239, "s": 7140, "text": "Lots of time it is more useful to see how the data change over time instead of just everyday data." }, { "code": null, "e": 7317, "s": 7239, "text": "There are a few different ways to calculate and visualize the change in data." }, { "code": null, "e": 7323, "s": 7317, "text": "Shift" }, { "code": null, "e": 7631, "s": 7323, "text": "The shift function shifts the data before or after the specified amount of time. If I do not specify the time it will shift the data by one day by default. That means you will get the previous day's data. In financial data like this one, it is helpful to see previous day data and today's data side by side." }, { "code": null, "e": 7723, "s": 7631, "text": "As this article is dedicated to visualization only, I will only plot the previous day data:" }, { "code": null, "e": 7818, "s": 7723, "text": "df['Change'] = df.Close.div(df.Close.shift())df['Change'].plot(figsize=(20, 8), fontsize = 16)" }, { "code": null, "e": 8154, "s": 7818, "text": "In the code above, .div() helps to fill up the missing data. Actually, div() means division. df. div(6) will divide each element in df by 6. But here I used ‘df.Close.shift()’. So, Each element of df will be divided by each element of ‘df.Close.shift()’. We do this to avoid the null values that are created by the ‘shift()’ operation." }, { "code": null, "e": 8242, "s": 8154, "text": "If it is not yet clear to you, please look at the article I mentioned in the beginning." }, { "code": null, "e": 8262, "s": 8242, "text": "Here is the output:" }, { "code": null, "e": 8364, "s": 8262, "text": "You can simply take a specific period and plot to have a clearer look. This is the plot of 2017 only." }, { "code": null, "e": 8407, "s": 8364, "text": "df['2017']['Change'].plot(figsize=(10, 6))" }, { "code": null, "e": 8500, "s": 8407, "text": "Though the shift is useful in many ways. But I find percent change useful on many occasions." }, { "code": null, "e": 8515, "s": 8500, "text": "Percent_Change" }, { "code": null, "e": 8724, "s": 8515, "text": "I will use the monthly data that was calculated in the beginning. This time I chose bar plots. It shows the percent change clearly. There is a percent change function available to get the percent_change data." }, { "code": null, "e": 9012, "s": 8724, "text": "df_month.loc[:, 'pct_change'] = df.Close.pct_change()*100fig, ax = plt.subplots()df_month['pct_change' ].plot(kind='bar', color='coral', ax=ax)ax.xaxis.set_major_locator(mdates.WeekdayLocator())ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))plt.xticks(rotation=45)ax.legend()" }, { "code": null, "e": 9099, "s": 9012, "text": "I plotted the percent change in closing data here. I used monthly percent change here." }, { "code": null, "e": 9112, "s": 9099, "text": "Differencing" }, { "code": null, "e": 9355, "s": 9112, "text": "Differencing takes the difference in values of a specified distance. By default, it’s one. If you specify 2 like “df.High.diff(2)’, it will take the difference of first and third element of ‘High’ column, second and fourth element, and so on." }, { "code": null, "e": 9462, "s": 9355, "text": "It is a popular method to remove the trend in the data. The trend is not good for forecasting or modeling." }, { "code": null, "e": 9499, "s": 9462, "text": "df.High.diff().plot(figsize=(10, 6))" }, { "code": null, "e": 9516, "s": 9499, "text": "Expanding Window" }, { "code": null, "e": 9925, "s": 9516, "text": "Another way of transformation. It keeps adding the cumulative. For example, if you add an expanding function to the ‘High’ column first element remains the same. The second element becomes cumulative of the first and second element, the third element becomes cumulative of the first, second, and third element, and so on. You can use aggregate functions like mean, median, standard deviation, etc. on it too." }, { "code": null, "e": 10104, "s": 9925, "text": "In that way, it will provide you with the changing mean, median, sum, or standard deviation with time. Isn’t it really useful for financial data or business sales or profit data?" }, { "code": null, "e": 10299, "s": 10104, "text": "fig, ax = plt.subplots()ax = df.High.plot(label='High')ax = df.High.expanding().mean().plot(label='High expanding mean')ax = df.High.expanding().std().plot(label='High expanding std')ax.legend()" }, { "code": null, "e": 10595, "s": 10299, "text": "Here I added expanding mean and standard deviation. Look at the daily data and the mean. At the end of 2017, daily data shows a huge spike. But it doesn’t show a spike in the average. Probably if you take the 2017 data only, the expanding average will look different. Please feel free to try it." }, { "code": null, "e": 10735, "s": 10595, "text": "A heat map is generally a common type of data visualization that is used everywhere. In time-series data also heat maps can be very useful." }, { "code": null, "e": 10891, "s": 10735, "text": "But before diving into the heat map, we need to develop a calendar that will represent each year and month data of our dataset. Let’s see it in an example." }, { "code": null, "e": 11005, "s": 10891, "text": "For this demonstration, I will import a calendar package and use the pivot table function to generate the values." }, { "code": null, "e": 11472, "s": 11005, "text": "import calendarall_month_year_df = pd.pivot_table(df, values=\"Open\", index=[\"month\"], columns=[\"year\"], fill_value=0, margins=True)named_index = [[calendar.month_abbr[i] if isinstance(i, int) else i for i in list(all_month_year_df.index)]] # name monthsall_month_year_df = all_month_year_df.set_index(named_index)all_month_year_df" }, { "code": null, "e": 11564, "s": 11472, "text": "The calendar is ready with monthly average ‘Open’ data. Now, generate the heat map with it." }, { "code": null, "e": 11988, "s": 11564, "text": "ax = sns.heatmap(all_month_year_df, cmap='RdYlGn_r', robust=True, fmt='.2f', annot=True, linewidths=.5, annot_kws={'size':11}, cbar_kws={'shrink':.8, 'label':'Open'}) ax.set_yticklabels(ax.get_yticklabels(), rotation=0, fontsize=10)ax.set_xticklabels(ax.get_xticklabels(), rotation=0, fontsize=10)plt.title('Average Opening', fontdict={'fontsize':18}, pad=14);" }, { "code": null, "e": 12084, "s": 11988, "text": "The heat map is ready! Darker red means very high opening and dark green mean very low opening." }, { "code": null, "e": 12168, "s": 12084, "text": "Decomposition will show the observations and these three elements in the same plot:" }, { "code": null, "e": 12229, "s": 12168, "text": "Trend: Consistent upward or downward slope of a time series." }, { "code": null, "e": 12282, "s": 12229, "text": "Seasonality: Clear periodic pattern of a time series" }, { "code": null, "e": 12316, "s": 12282, "text": "Noise: Outliers or missing values" }, { "code": null, "e": 12368, "s": 12316, "text": "Using the stats model library, it is easy to do it:" }, { "code": null, "e": 12572, "s": 12368, "text": "from pylab import rcParamsimport statsmodels.api as smrcParams['figure.figsize'] = 11, 9decomposition = sm.tsa.seasonal_decompose(df_month['Volume'], model='Additive')fig = decomposition.plot()plt.show()" }, { "code": null, "e": 12699, "s": 12572, "text": "Here the trend is the moving average. To give you a high-level idea of residuals in the last row, here is the general formula:" }, { "code": null, "e": 12755, "s": 12699, "text": "Original observations = Trend + Seasonality + Residuals" }, { "code": null, "e": 12873, "s": 12755, "text": "Though the documentation for decomposition itself says that it’s a very naive representation but it is still popular." }, { "code": null, "e": 13137, "s": 12873, "text": "If you could run all the code above, Congratulation! You learned enough today to make a great level of time series of data visualization. As I mentioned in the beginning, there are a lot of cool visualization techniques available. I will write more in the future." } ]
Floor in a Sorted Array | Practice | GeeksforGeeks
Given a sorted array arr[] of size N without duplicates, and given a value x. Floor of x is defined as the largest element K in arr[] such that K is smaller than or equal to x. Find the index of K(0-based indexing). Example 1: Input: N = 7, x = 0 arr[] = {1,2,8,10,11,12,19} Output: -1 Explanation: No element less than 0 is found. So output is "-1". Example 2: Input: N = 7, x = 5 arr[] = {1,2,8,10,11,12,19} Output: 1 Explanation: Largest Number less than 5 is 2 (i.e K = 2), whose index is 1(0-based indexing). Your Task: The task is to complete the function findFloor() which returns an integer denoting the index value of K or return -1 if there isn't any such number. Expected Time Complexity: O(log N). Expected Auxiliary Space: O(1). Constraints: 1 ≤ N ≤ 107 1 ≤ arr[i] ≤ 1018 0 ≤ X ≤ arr[n-1] 0 harshilrpanchal19982 days ago java solution class Solution{ // Function to find floor of x // arr: input array // n is the size of array static int findFloor(long arr[], int n, long x) { int count=0;for(int i=0;i<n;i++){ if(arr[i]<=x) { count =i; } else if(arr[0]>x) return -1;} return count; } } 0 keshridivya51 week ago //c++ solution using binary search class Solution{ public: // Function to find floor of x // n: size of vector // x: element whose floor is to find int findFloor(vector<long long> v, long long n, long long x){ long long start = 0; long long end = n - 1; while(start <= end) { long long mid = start + (end - start) / 2; if(v[mid] == x) return mid; else if(v[mid] < x) { int res = mid; start = mid + 1; } else end = mid - 1; } return end; } }; 0 tantade20022 weeks ago static int findFloor(long arr[], int n, long k) { if(k<arr[0]) { return -1; } if(k>arr[arr.length-1]) { return arr.length-1; } int low=0; int high=arr.length-1; while(low<=high) { int mid=(low+high)/2; if(arr[mid]>k && arr[mid-1]<k) { return mid-1; } if(arr[mid]>k && arr[mid-1]>k) { high=mid-1; } if(arr[mid]<k && arr[mid+1]<k) { low=mid+1; } if(arr[mid]<k && arr[mid+1]>k) { return mid; } } return -1; } } +1 hiphopsamreen2 weeks ago // > if the search ele is present then return it's index // > else return the largest ele smaller than search ele int findFloor(vector<long long> v, long long n, long long x) { // Your code here int index = lower_bound(v.begin(), v.end(), x) - v.begin(); if (index < n && v[index] == x) return index; else if (index - 1 >= 0) return --index; else return -1; } 0 1ms19me0242 weeks ago int findFloor(long long int arr[], int N, long long int K) {int count=0;for(int i=0;i<N;i++){ if(arr[i]<=K) { count++; } else if(arr[0]>K) return -1;}int res=count-1;return res;} 0 shubham211019973 weeks ago static int findFloor(long arr[], int n, long x) { int ans=-1; int low=0,high=n-1; while(low<=high){ int mid=(low+high)/2; if(arr[mid]==x) return mid; else if(arr[mid]>x)high=mid-1; else{ ans=mid; low=mid+1; } } return ans; } 0 alokkumar90194 weeks ago int findFloor(vector<long long> v, long long n, long long x){ // Your code here int a=v.size(); int l=0, h=a-1,m; if(x>v[a-1]){ return a-1; } while(l<=h){ m=l+(h-l)/2; if(v[m]==x || (x>v[m] && x<v[m+1])){ return m; }else if(v[m]==x || (x>v[m-1] && x<v[m])){ return m-1; } else if(v[m]>x){ h=m-1; } else if(v[m]<x){ l=m+1; } } return -1; } 0 vikasvasabathula1 month ago def findFloor(self,A,N,X): if X==0: return -1 else: for i in range(X,0,-1): if(i in A): return A.index(i) return -1 -7 lakshitpant7741 month ago class Solution{ // Function to find floor of x // arr: input array // n is the size of array static int findFloor(long arr[], int n, long x) { for(int i=0;i<n;i++){ if(arr[i]<=x){ return i; } } return -1; }} 0 zunjarprasad08971 month ago static int findFloor(long arr[], int n, long x) { int low =0; int high =n-1; int res =-1; while(low <= high){ int mid = (low+high)/2; if(arr[mid] == x){ return mid; } if(arr[mid] > x){ high = mid -1; }else{ low = mid +1; res = mid; } } return res; } 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": 454, "s": 238, "text": "Given a sorted array arr[] of size N without duplicates, and given a value x. Floor of x is defined as the largest element K in arr[] such that K is smaller than or equal to x. Find the index of K(0-based indexing)." }, { "code": null, "e": 465, "s": 454, "text": "Example 1:" }, { "code": null, "e": 592, "s": 465, "text": "Input:\nN = 7, x = 0 \narr[] = {1,2,8,10,11,12,19}\nOutput: -1\nExplanation: No element less \nthan 0 is found. So output \nis \"-1\"." }, { "code": null, "e": 603, "s": 592, "text": "Example 2:" }, { "code": null, "e": 758, "s": 603, "text": "Input:\nN = 7, x = 5 \narr[] = {1,2,8,10,11,12,19}\nOutput: 1\nExplanation: Largest Number less than 5 is\n2 (i.e K = 2), whose index is 1(0-based \nindexing).\n" }, { "code": null, "e": 918, "s": 758, "text": "Your Task:\nThe task is to complete the function findFloor() which returns an integer denoting the index value of K or return -1 if there isn't any such number." }, { "code": null, "e": 986, "s": 918, "text": "Expected Time Complexity: O(log N).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1046, "s": 986, "text": "Constraints:\n1 ≤ N ≤ 107\n1 ≤ arr[i] ≤ 1018\n0 ≤ X ≤ arr[n-1]" }, { "code": null, "e": 1048, "s": 1046, "text": "0" }, { "code": null, "e": 1078, "s": 1048, "text": "harshilrpanchal19982 days ago" }, { "code": null, "e": 1092, "s": 1078, "text": "java solution" }, { "code": null, "e": 1357, "s": 1094, "text": "class Solution{ // Function to find floor of x // arr: input array // n is the size of array static int findFloor(long arr[], int n, long x) { int count=0;for(int i=0;i<n;i++){ if(arr[i]<=x) { count =i; } else if(arr[0]>x) return -1;}" }, { "code": null, "e": 1380, "s": 1357, "text": "return count; } } " }, { "code": null, "e": 1382, "s": 1380, "text": "0" }, { "code": null, "e": 1405, "s": 1382, "text": "keshridivya51 week ago" }, { "code": null, "e": 2026, "s": 1405, "text": "//c++ solution using binary search\nclass Solution{\n public:\n // Function to find floor of x\n // n: size of vector\n // x: element whose floor is to find\n int findFloor(vector<long long> v, long long n, long long x){\n \n long long start = 0;\n long long end = n - 1;\n \n while(start <= end)\n {\n long long mid = start + (end - start) / 2;\n if(v[mid] == x) return mid;\n else if(v[mid] < x)\n {\n int res = mid;\n start = mid + 1;\n }\n else end = mid - 1;\n }\n return end; \n }\n};\n" }, { "code": null, "e": 2028, "s": 2026, "text": "0" }, { "code": null, "e": 2051, "s": 2028, "text": "tantade20022 weeks ago" }, { "code": null, "e": 2490, "s": 2051, "text": "static int findFloor(long arr[], int n, long k) { if(k<arr[0]) { return -1; } if(k>arr[arr.length-1]) { return arr.length-1; } int low=0; int high=arr.length-1; while(low<=high) { int mid=(low+high)/2; if(arr[mid]>k && arr[mid-1]<k) { return mid-1; } if(arr[mid]>k && arr[mid-1]>k) { high=mid-1; } if(arr[mid]<k && arr[mid+1]<k) { low=mid+1; } if(arr[mid]<k && arr[mid+1]>k) { return mid; } } return -1; } }" }, { "code": null, "e": 2493, "s": 2490, "text": "+1" }, { "code": null, "e": 2518, "s": 2493, "text": "hiphopsamreen2 weeks ago" }, { "code": null, "e": 2575, "s": 2518, "text": "// > if the search ele is present then return it's index" }, { "code": null, "e": 2632, "s": 2575, "text": "// > else return the largest ele smaller than search ele" }, { "code": null, "e": 2693, "s": 2632, "text": "int findFloor(vector<long long> v, long long n, long long x)" }, { "code": null, "e": 2695, "s": 2693, "text": "{" }, { "code": null, "e": 2717, "s": 2695, "text": " // Your code here" }, { "code": null, "e": 2781, "s": 2717, "text": " int index = lower_bound(v.begin(), v.end(), x) - v.begin();" }, { "code": null, "e": 2819, "s": 2783, "text": " if (index < n && v[index] == x)" }, { "code": null, "e": 2841, "s": 2819, "text": " return index;" }, { "code": null, "e": 2872, "s": 2843, "text": " else if (index - 1 >= 0)" }, { "code": null, "e": 2896, "s": 2872, "text": " return --index;" }, { "code": null, "e": 2907, "s": 2898, "text": " else" }, { "code": null, "e": 2926, "s": 2907, "text": " return -1;" }, { "code": null, "e": 2928, "s": 2926, "text": "}" }, { "code": null, "e": 2930, "s": 2928, "text": "0" }, { "code": null, "e": 2952, "s": 2930, "text": "1ms19me0242 weeks ago" }, { "code": null, "e": 3147, "s": 2952, "text": "int findFloor(long long int arr[], int N, long long int K) {int count=0;for(int i=0;i<N;i++){ if(arr[i]<=K) { count++; } else if(arr[0]>K) return -1;}int res=count-1;return res;}" }, { "code": null, "e": 3149, "s": 3147, "text": "0" }, { "code": null, "e": 3176, "s": 3149, "text": "shubham211019973 weeks ago" }, { "code": null, "e": 3524, "s": 3176, "text": "static int findFloor(long arr[], int n, long x) { int ans=-1; int low=0,high=n-1; while(low<=high){ int mid=(low+high)/2; if(arr[mid]==x) return mid; else if(arr[mid]>x)high=mid-1; else{ ans=mid; low=mid+1; } } return ans; }" }, { "code": null, "e": 3526, "s": 3524, "text": "0" }, { "code": null, "e": 3551, "s": 3526, "text": "alokkumar90194 weeks ago" }, { "code": null, "e": 4107, "s": 3551, "text": " int findFloor(vector<long long> v, long long n, long long x){\n \n // Your code here\n int a=v.size();\n int l=0, h=a-1,m;\n if(x>v[a-1]){\n return a-1;\n }\n while(l<=h){\n m=l+(h-l)/2;\n if(v[m]==x || (x>v[m] && x<v[m+1])){\n return m;\n }else if(v[m]==x || (x>v[m-1] && x<v[m])){\n return m-1;\n } \n else if(v[m]>x){\n h=m-1;\n } else if(v[m]<x){\n l=m+1;\n }\n }\n return -1;\n }" }, { "code": null, "e": 4109, "s": 4107, "text": "0" }, { "code": null, "e": 4137, "s": 4109, "text": "vikasvasabathula1 month ago" }, { "code": null, "e": 4337, "s": 4137, "text": "def findFloor(self,A,N,X):\n if X==0:\n return -1\n else:\n for i in range(X,0,-1):\n if(i in A):\n return A.index(i)\n return -1" }, { "code": null, "e": 4340, "s": 4337, "text": "-7" }, { "code": null, "e": 4366, "s": 4340, "text": "lakshitpant7741 month ago" }, { "code": null, "e": 4630, "s": 4366, "text": "class Solution{ // Function to find floor of x // arr: input array // n is the size of array static int findFloor(long arr[], int n, long x) { for(int i=0;i<n;i++){ if(arr[i]<=x){ return i; } } return -1; }}" }, { "code": null, "e": 4632, "s": 4630, "text": "0" }, { "code": null, "e": 4660, "s": 4632, "text": "zunjarprasad08971 month ago" }, { "code": null, "e": 5079, "s": 4660, "text": " static int findFloor(long arr[], int n, long x) { int low =0; int high =n-1; int res =-1; while(low <= high){ int mid = (low+high)/2; if(arr[mid] == x){ return mid; } if(arr[mid] > x){ high = mid -1; }else{ low = mid +1; res = mid; } } return res; }" }, { "code": null, "e": 5225, "s": 5079, "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": 5261, "s": 5225, "text": " Login to access your submissions. " }, { "code": null, "e": 5271, "s": 5261, "text": "\nProblem\n" }, { "code": null, "e": 5281, "s": 5271, "text": "\nContest\n" }, { "code": null, "e": 5344, "s": 5281, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5492, "s": 5344, "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": 5700, "s": 5492, "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": 5806, "s": 5700, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Retail Management - Business Operations
Customers remember the service a lot longer than they remember the price. − Lauren Freedman (President, E-tailing Group) The retail business operations include all the activities that the employers perform to keep the store functioning smoothly. The shopping experience of a customer is planned before the customer enters, shops, and leaves the store with a smile or with agony by carrying a perception about the store. This experience drives the customer’s decision of visiting the store in future. Let us see, what efforts retail business operations executives put in to make the shopping experience memorable for the customer. The retail store being the fundamental source of revenue and the place of customer interaction, is vital to the retailer. The store manager may not himself perform, but is responsible for the following duties − Maintaining cleanliness in the store. Maintaining cleanliness in the store. Ensuring adequate stock of merchandise in the store. Ensuring adequate stock of merchandise in the store. Appropriate planning, scheduling, and organization of staff, inventory and expenses, for short and long-term success. Appropriate planning, scheduling, and organization of staff, inventory and expenses, for short and long-term success. Monitoring the loss and taking preventive measures to protect the company’s assets and products in the store. Monitoring the loss and taking preventive measures to protect the company’s assets and products in the store. Upgrading store to reflect high profitable image. Upgrading store to reflect high profitable image. Communicating with head office/regional office when required. Communicating with head office/regional office when required. Conducting constructive meetings with staff to boost their morale and motivate the staff to achieve sales goals. Conducting constructive meetings with staff to boost their morale and motivate the staff to achieve sales goals. Communicating with customers to identify their needs, grievances, and complaints. Communicating with customers to identify their needs, grievances, and complaints. Ensuring that the store is in compliance with employment laws regarding salary, work hours, and equal employment opportunities. Ensuring that the store is in compliance with employment laws regarding salary, work hours, and equal employment opportunities. Writing performance appraisals for assisting staff. Writing performance appraisals for assisting staff. The store manager ensures that these duties are performed according to the guidelines set by the company. The store premises are as important as the retail store itself. Managing premises includes the following tasks − Determining Working Hours of Store. It majorly depends upon the target audience, retailed products, and store location. For example, a grocery store near residential area should open earlier than a fashion store. Also, a solitary store can be open as long as the owner wants to but a store in a mall has to adhere to working hours set by the mall management. Managing Store Security. It helps avoiding inventory shrinkage. It depends upon the size of store, the product, and the location of store. Some retailers attach electronic tags on products, which are sensed at store entrance and exits by sensors for theft detection. Some stores install video cameras to monitor movement and some provide separate entry and exit for personnel so that they can be checked. For example, a large departmental store needs high security than the grocery store located near residential area. Here are some basic formulae used while managing premises − Transaction per Hour = No. of Transactions/Number of Hours The retailer keeps track of the number of transactions per hour, which helps in determining store hours and staff scheduling. Sales per Transaction = Net Sales/Number of Transactions The result gives the value of the average sales and net return, which is used to study sales trends over time. Hourly Customer Traffic = Customer Traffic In/Number of Hours This measure is used to track total number of customer traffic per unit time. It is then applied to schedule hours and determine staff strength. Merchandise manager, category manager, and other staff handle the inventory. It includes the following tasks − Receiving products from the vendor. Receiving products from the vendor. Recording inward entry of the products. Recording inward entry of the products. Checking the products against quality norms laid by the retail company and for details such as colors, sizes, and styles. In case of large stores, this task is automated to a large extent. Checking the products against quality norms laid by the retail company and for details such as colors, sizes, and styles. In case of large stores, this task is automated to a large extent. Separating and documenting the faulty or damaged products for returning. Separating and documenting the faulty or damaged products for returning. Displaying the products appropriately to gain customers’ attention. Heavy products are kept at the lower level. Most accessed products are kept at the eye-level and the less accessed products are kept at high level of shelves. On-the-fly-purchased products such as chocolates, candies, etc. are placed near payment counters. Displaying the products appropriately to gain customers’ attention. Heavy products are kept at the lower level. Most accessed products are kept at the eye-level and the less accessed products are kept at high level of shelves. On-the-fly-purchased products such as chocolates, candies, etc. are placed near payment counters. Here are some formulae used for inventory control − Inventory Turnover Rate = Net Sales/Average Retail Value of Inventory It is expressed in number of times and indicates how often the inventory is sold and replaced during a given period of time. Cost of Goods Sold/Average Value of Inventory at Cost When either of these ratio declines, there is a possibility that inventory is excessive. % Inventory Carrying Cost = (Inventory Carrying Cost/Net Sales) * 100 This measure has gained importance due to rise in inventory carrying cost because of high interest rates. This prevents blockage of working capital. Gross Margin Return on Inventory (GMROI) = Gross Margin/Average Value of Inventory The GMROI compares the margin on sales on the original cost value of merchandise to yield a return on merchandise investment. Managing receipt is nothing but determining the manner in which the retailer is going to get the payment for the sold products. The basic modes of receipt are − Cash Credit card Debit card Gift card Large stores have the facility of paying by the modes listed above but small retailers generally prefer accepting cash. The retailer pays card fees depending upon the volume of transactions with the suppliers, manufacturers, or producers. The staff responsible for accepting payment needs to clearly understand the procedure for accepting payment by cards and collecting the amount from the bank. Supply Chain Management (SCM) is the management of materials, information, and finances while they move from manufacturer to wholesaler to retailer to consumer. It involves the activities of coordinating and integrating these flows within and out of a retail business. Most supply chains operate in collaboration if the suppliers and retail businesses are dealing with each other for a long time. Retailers depend upon supply chain members to a great extent. If the retailers develop a strong partnership with supply chain members, it can be beneficial for suppliers to create seamless procedures, which are difficult to imitate. The top management of a retail business decides the customer service policy. The entire retail store staff is trained for customer service. Each employer in the retail store ensures that the service starts with smile and the interacting customer is comfortable and has a pleasant shopping experience. The promptness and politeness of the retail store staff, their knowledge about the product and language, ability to overcome challenges, and rapidness at the billing counter; everything is noted by the customer. These aspects build a great deal of customer’s perception about the store. Many retail stores train staff members to handle the cash counter. They have also introduced a concept of express billing where customers buying less than 10 products can bill faster without having to stand in the regular payment queue. During festivals and markdown periods, the trend of shopping increases. Customer Conversion Ratio = (Number of Transactions/Customer Traffic) * 100 The result is the retailer’s ability to turn a potential customer into a buyer. It is also called “walk to buy ratio”. Low results mean that promotional activities are not being converted into sales and the overall sales efforts need to be assessed afresh. 20 Lectures 3.5 hours Richa Maheshwari 44 Lectures 5.5 hours Navdeep Yadav Print Add Notes Bookmark this page
[ { "code": null, "e": 2089, "s": 2015, "text": "Customers remember the service a lot longer than they remember the price." }, { "code": null, "e": 2136, "s": 2089, "text": "− Lauren Freedman (President, E-tailing Group)" }, { "code": null, "e": 2515, "s": 2136, "text": "The retail business operations include all the activities that the employers perform to keep the store functioning smoothly. The shopping experience of a customer is planned before the customer enters, shops, and leaves the store with a smile or with agony by carrying a perception about the store. This experience drives the customer’s decision of visiting the store in future." }, { "code": null, "e": 2645, "s": 2515, "text": "Let us see, what efforts retail business operations executives put in to make the shopping experience memorable for the customer." }, { "code": null, "e": 2767, "s": 2645, "text": "The retail store being the fundamental source of revenue and the place of customer\ninteraction, is vital to the retailer." }, { "code": null, "e": 2856, "s": 2767, "text": "The store manager may not himself perform, but is responsible for the following duties −" }, { "code": null, "e": 2894, "s": 2856, "text": "Maintaining cleanliness in the store." }, { "code": null, "e": 2932, "s": 2894, "text": "Maintaining cleanliness in the store." }, { "code": null, "e": 2985, "s": 2932, "text": "Ensuring adequate stock of merchandise in the store." }, { "code": null, "e": 3038, "s": 2985, "text": "Ensuring adequate stock of merchandise in the store." }, { "code": null, "e": 3156, "s": 3038, "text": "Appropriate planning, scheduling, and organization of staff, inventory and expenses, for short and long-term success." }, { "code": null, "e": 3274, "s": 3156, "text": "Appropriate planning, scheduling, and organization of staff, inventory and expenses, for short and long-term success." }, { "code": null, "e": 3384, "s": 3274, "text": "Monitoring the loss and taking preventive measures to protect the company’s assets and products in the store." }, { "code": null, "e": 3494, "s": 3384, "text": "Monitoring the loss and taking preventive measures to protect the company’s assets and products in the store." }, { "code": null, "e": 3544, "s": 3494, "text": "Upgrading store to reflect high profitable image." }, { "code": null, "e": 3594, "s": 3544, "text": "Upgrading store to reflect high profitable image." }, { "code": null, "e": 3656, "s": 3594, "text": "Communicating with head office/regional office when required." }, { "code": null, "e": 3718, "s": 3656, "text": "Communicating with head office/regional office when required." }, { "code": null, "e": 3831, "s": 3718, "text": "Conducting constructive meetings with staff to boost their morale and motivate the staff to achieve sales goals." }, { "code": null, "e": 3944, "s": 3831, "text": "Conducting constructive meetings with staff to boost their morale and motivate the staff to achieve sales goals." }, { "code": null, "e": 4026, "s": 3944, "text": "Communicating with customers to identify their needs, grievances, and complaints." }, { "code": null, "e": 4108, "s": 4026, "text": "Communicating with customers to identify their needs, grievances, and complaints." }, { "code": null, "e": 4236, "s": 4108, "text": "Ensuring that the store is in compliance with employment laws regarding salary, work hours, and equal employment opportunities." }, { "code": null, "e": 4364, "s": 4236, "text": "Ensuring that the store is in compliance with employment laws regarding salary, work hours, and equal employment opportunities." }, { "code": null, "e": 4416, "s": 4364, "text": "Writing performance appraisals for assisting staff." }, { "code": null, "e": 4468, "s": 4416, "text": "Writing performance appraisals for assisting staff." }, { "code": null, "e": 4574, "s": 4468, "text": "The store manager ensures that these duties are performed according to the guidelines\nset by the company." }, { "code": null, "e": 4687, "s": 4574, "text": "The store premises are as important as the retail store itself. Managing premises includes the following tasks −" }, { "code": null, "e": 4807, "s": 4687, "text": "Determining Working Hours of Store. It majorly depends upon the target audience, retailed products, and store location." }, { "code": null, "e": 5046, "s": 4807, "text": "For example, a grocery store near residential area should open earlier than a fashion store. Also, a solitary store can be open as long as the owner wants to but a store in a mall has to adhere to working hours set by the mall management." }, { "code": null, "e": 5451, "s": 5046, "text": "Managing Store Security. It helps avoiding inventory shrinkage. It depends upon the size of store, the product, and the location of store. Some retailers attach electronic tags on products, which are sensed at store entrance and exits by sensors for theft detection. Some stores install video cameras to monitor movement and some provide separate entry and exit for personnel so that they can be checked." }, { "code": null, "e": 5565, "s": 5451, "text": "For example, a large departmental store needs high security than the grocery store located near residential area." }, { "code": null, "e": 5625, "s": 5565, "text": "Here are some basic formulae used while managing premises −" }, { "code": null, "e": 5685, "s": 5625, "text": "Transaction per Hour = No. of Transactions/Number of Hours\n" }, { "code": null, "e": 5811, "s": 5685, "text": "The retailer keeps track of the number of transactions per hour, which helps in determining store hours and staff scheduling." }, { "code": null, "e": 5870, "s": 5811, "text": "Sales per Transaction = Net Sales/Number of Transactions \n" }, { "code": null, "e": 5981, "s": 5870, "text": "The result gives the value of the average sales and net return, which is used to study sales trends over time." }, { "code": null, "e": 6044, "s": 5981, "text": "Hourly Customer Traffic = Customer Traffic In/Number of Hours\n" }, { "code": null, "e": 6189, "s": 6044, "text": "This measure is used to track total number of customer traffic per unit time. It is then applied to schedule hours and determine staff strength." }, { "code": null, "e": 6300, "s": 6189, "text": "Merchandise manager, category manager, and other staff handle the inventory. It includes the following tasks −" }, { "code": null, "e": 6336, "s": 6300, "text": "Receiving products from the vendor." }, { "code": null, "e": 6372, "s": 6336, "text": "Receiving products from the vendor." }, { "code": null, "e": 6412, "s": 6372, "text": "Recording inward entry of the products." }, { "code": null, "e": 6452, "s": 6412, "text": "Recording inward entry of the products." }, { "code": null, "e": 6641, "s": 6452, "text": "Checking the products against quality norms laid by the retail company and for details such as colors, sizes, and styles. In case of large stores, this task is automated to a large extent." }, { "code": null, "e": 6830, "s": 6641, "text": "Checking the products against quality norms laid by the retail company and for details such as colors, sizes, and styles. In case of large stores, this task is automated to a large extent." }, { "code": null, "e": 6903, "s": 6830, "text": "Separating and documenting the faulty or damaged products for returning." }, { "code": null, "e": 6976, "s": 6903, "text": "Separating and documenting the faulty or damaged products for returning." }, { "code": null, "e": 7301, "s": 6976, "text": "Displaying the products appropriately to gain customers’ attention. Heavy products are kept at the lower level. Most accessed products are kept at the eye-level and the less accessed products are kept at high level of shelves. On-the-fly-purchased products such as chocolates, candies, etc. are placed near payment counters." }, { "code": null, "e": 7626, "s": 7301, "text": "Displaying the products appropriately to gain customers’ attention. Heavy products are kept at the lower level. Most accessed products are kept at the eye-level and the less accessed products are kept at high level of shelves. On-the-fly-purchased products such as chocolates, candies, etc. are placed near payment counters." }, { "code": null, "e": 7678, "s": 7626, "text": "Here are some formulae used for inventory control −" }, { "code": null, "e": 7749, "s": 7678, "text": "Inventory Turnover Rate = Net Sales/Average Retail Value of Inventory\n" }, { "code": null, "e": 7874, "s": 7749, "text": "It is expressed in number of times and indicates how often the inventory is sold and replaced during a given period of time." }, { "code": null, "e": 7929, "s": 7874, "text": "Cost of Goods Sold/Average Value of Inventory at Cost\n" }, { "code": null, "e": 8018, "s": 7929, "text": "When either of these ratio declines, there is a possibility that inventory is excessive." }, { "code": null, "e": 8090, "s": 8018, "text": "% Inventory Carrying Cost = (Inventory Carrying Cost/Net Sales) * 100 \n" }, { "code": null, "e": 8239, "s": 8090, "text": "This measure has gained importance due to rise in inventory carrying cost because of high interest rates. This prevents blockage of working capital." }, { "code": null, "e": 8323, "s": 8239, "text": "Gross Margin Return on Inventory (GMROI) = Gross Margin/Average Value of Inventory\n" }, { "code": null, "e": 8449, "s": 8323, "text": "The GMROI compares the margin on sales on the original cost value of merchandise to\nyield a return on merchandise investment." }, { "code": null, "e": 8610, "s": 8449, "text": "Managing receipt is nothing but determining the manner in which the retailer is going to get the payment for the sold products. The basic modes of receipt are −" }, { "code": null, "e": 8615, "s": 8610, "text": "Cash" }, { "code": null, "e": 8627, "s": 8615, "text": "Credit card" }, { "code": null, "e": 8638, "s": 8627, "text": "Debit card" }, { "code": null, "e": 8648, "s": 8638, "text": "Gift card" }, { "code": null, "e": 8887, "s": 8648, "text": "Large stores have the facility of paying by the modes listed above but small retailers generally prefer accepting cash. The retailer pays card fees depending upon the volume of transactions with the suppliers, manufacturers, or producers." }, { "code": null, "e": 9045, "s": 8887, "text": "The staff responsible for accepting payment needs to clearly understand the procedure for accepting payment by cards and collecting the amount from the bank." }, { "code": null, "e": 9314, "s": 9045, "text": "Supply Chain Management (SCM) is the management of materials, information, and finances while they move from manufacturer to wholesaler to retailer to consumer. It involves the activities of coordinating and integrating these flows within and out of a retail business." }, { "code": null, "e": 9675, "s": 9314, "text": "Most supply chains operate in collaboration if the suppliers and retail businesses are dealing with each other for a long time. Retailers depend upon supply chain members to a great extent. If the retailers develop a strong partnership with supply chain members, it can be beneficial for suppliers to create seamless procedures, which are difficult to imitate." }, { "code": null, "e": 9976, "s": 9675, "text": "The top management of a retail business decides the customer service policy. The entire\nretail store staff is trained for customer service. Each employer in the retail store ensures that the service starts with smile and the interacting customer is comfortable and has a pleasant shopping experience." }, { "code": null, "e": 10263, "s": 9976, "text": "The promptness and politeness of the retail store staff, their knowledge about the product and language, ability to overcome challenges, and rapidness at the billing counter; everything is noted by the customer. These aspects build a great deal of customer’s perception about the store." }, { "code": null, "e": 10500, "s": 10263, "text": "Many retail stores train staff members to handle the cash counter. They have also introduced a concept of express billing where customers buying less than 10 products can bill faster without having to stand in the regular payment queue." }, { "code": null, "e": 10572, "s": 10500, "text": "During festivals and markdown periods, the trend of shopping increases." }, { "code": null, "e": 10649, "s": 10572, "text": "Customer Conversion Ratio = (Number of Transactions/Customer Traffic) * 100\n" }, { "code": null, "e": 10906, "s": 10649, "text": "The result is the retailer’s ability to turn a potential customer into a buyer. It is also called “walk to buy ratio”. Low results mean that promotional activities are not being converted into sales and the overall sales efforts need to be assessed afresh." }, { "code": null, "e": 10941, "s": 10906, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 10959, "s": 10941, "text": " Richa Maheshwari" }, { "code": null, "e": 10994, "s": 10959, "text": "\n 44 Lectures \n 5.5 hours \n" }, { "code": null, "e": 11009, "s": 10994, "text": " Navdeep Yadav" }, { "code": null, "e": 11016, "s": 11009, "text": " Print" }, { "code": null, "e": 11027, "s": 11016, "text": " Add Notes" } ]
C#| How to change the size of one-dimensional array - GeeksforGeeks
28 Aug, 2019 Array.Resize(T[], Int32) Method is used to resize the number of elements present in the array. Or in other words, this method is used to change the number of elements of a one-dimensional array to the specified new size. It resizes the only 1-D array, not multidimensional array. Syntax: public static void Resize<T> (ref T[] array, int newSize); Parameters: array: It is a one-dimensional, zero-based array to resize, or null to create a new array with the specified size.newsize: It is the size of the new array. Exception:If the value of nsize is less than zero, then this method will give ArgumentOutOfRangeException. Note: This method is an O(n) operation, where n is new size. Below given are some examples to understand the implementation in a better way: Example 1: // C# program to resize the// elements of the 1-D arrayusing System; public class GFG { // Main method static public void Main() { // create and initialize array string[] myarray = {"C#", "Java", "C++", "Python", "HTML", "CSS", "JavaScript"}; // Display original array before Resize Console.WriteLine("Original Array:"); foreach(string i in myarray) { Console.WriteLine(i); } int len = myarray.Length; Console.WriteLine("Length of myarray: "+len); Console.WriteLine(); // Resize the element of myarray and // create a new array. Here new array // is smaller than the original array // so, elements are copied from the // myarray to the new array until the // new one is filled. The rest of the // elements in the old array are ignored Array.Resize(ref myarray, len - 3); Console.WriteLine("New array is less than myarray:"); foreach(string j in myarray) { Console.WriteLine(j); } }} Original Array: C# Java C++ Python HTML CSS JavaScript Length of myarray: 7 New array is less than myarray: C# Java C++ Python Example 2: // C# program to resize the // elements of the 1-D arrayusing System; public class GFG { // Main method static public void Main() { // create and initialize array string[] myarray = {"C#", "C++", "Ruby", "Java", "PHP", "Perl"}; // Display original string before Resize Console.WriteLine("Original Array:"); foreach(string i in myarray) { Console.WriteLine(i); } // Length of old array int len = myarray.Length; Console.WriteLine("Length of myarray: "+len); Console.WriteLine(); // Resize the element of myarray // and create a new array // Here new array is greater than // original array so, all the element // from myarray is copied to new array // and remaining will be null Array.Resize(ref myarray, 10); Console.WriteLine("New array is greater than myarray:"); foreach(string j in myarray) { Console.WriteLine(j); } // Length of new array int len1 = myarray.Length; Console.WriteLine("Length of New Array: "+len1); }} Original Array: C# C++ Ruby Java PHP Perl Length of myarray: 6 New array is greater than myarray: C# C++ Ruby Java PHP Perl Length of New Array: 10 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.array.resize?view=netcore-2.1 Akanksha_Rai CSharp-Arrays CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Destructors in C# Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? Partial Classes in C# C# | Inheritance C# | List Class Difference between Hashtable and Dictionary in C# Lambda Expressions in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n28 Aug, 2019" }, { "code": null, "e": 24582, "s": 24302, "text": "Array.Resize(T[], Int32) Method is used to resize the number of elements present in the array. Or in other words, this method is used to change the number of elements of a one-dimensional array to the specified new size. It resizes the only 1-D array, not multidimensional array." }, { "code": null, "e": 24590, "s": 24582, "text": "Syntax:" }, { "code": null, "e": 24649, "s": 24590, "text": "public static void Resize<T> (ref T[] array, int newSize);" }, { "code": null, "e": 24661, "s": 24649, "text": "Parameters:" }, { "code": null, "e": 24817, "s": 24661, "text": "array: It is a one-dimensional, zero-based array to resize, or null to create a new array with the specified size.newsize: It is the size of the new array." }, { "code": null, "e": 24924, "s": 24817, "text": "Exception:If the value of nsize is less than zero, then this method will give ArgumentOutOfRangeException." }, { "code": null, "e": 24985, "s": 24924, "text": "Note: This method is an O(n) operation, where n is new size." }, { "code": null, "e": 25065, "s": 24985, "text": "Below given are some examples to understand the implementation in a better way:" }, { "code": null, "e": 25076, "s": 25065, "text": "Example 1:" }, { "code": "// C# program to resize the// elements of the 1-D arrayusing System; public class GFG { // Main method static public void Main() { // create and initialize array string[] myarray = {\"C#\", \"Java\", \"C++\", \"Python\", \"HTML\", \"CSS\", \"JavaScript\"}; // Display original array before Resize Console.WriteLine(\"Original Array:\"); foreach(string i in myarray) { Console.WriteLine(i); } int len = myarray.Length; Console.WriteLine(\"Length of myarray: \"+len); Console.WriteLine(); // Resize the element of myarray and // create a new array. Here new array // is smaller than the original array // so, elements are copied from the // myarray to the new array until the // new one is filled. The rest of the // elements in the old array are ignored Array.Resize(ref myarray, len - 3); Console.WriteLine(\"New array is less than myarray:\"); foreach(string j in myarray) { Console.WriteLine(j); } }}", "e": 26233, "s": 25076, "text": null }, { "code": null, "e": 26362, "s": 26233, "text": "Original Array:\nC#\nJava\nC++\nPython\nHTML\nCSS\nJavaScript\nLength of myarray: 7\n\nNew array is less than myarray:\nC#\nJava\nC++\nPython\n" }, { "code": null, "e": 26373, "s": 26362, "text": "Example 2:" }, { "code": "// C# program to resize the // elements of the 1-D arrayusing System; public class GFG { // Main method static public void Main() { // create and initialize array string[] myarray = {\"C#\", \"C++\", \"Ruby\", \"Java\", \"PHP\", \"Perl\"}; // Display original string before Resize Console.WriteLine(\"Original Array:\"); foreach(string i in myarray) { Console.WriteLine(i); } // Length of old array int len = myarray.Length; Console.WriteLine(\"Length of myarray: \"+len); Console.WriteLine(); // Resize the element of myarray // and create a new array // Here new array is greater than // original array so, all the element // from myarray is copied to new array // and remaining will be null Array.Resize(ref myarray, 10); Console.WriteLine(\"New array is greater than myarray:\"); foreach(string j in myarray) { Console.WriteLine(j); } // Length of new array int len1 = myarray.Length; Console.WriteLine(\"Length of New Array: \"+len1); }}", "e": 27598, "s": 26373, "text": null }, { "code": null, "e": 27752, "s": 27598, "text": "Original Array:\nC#\nC++\nRuby\nJava\nPHP\nPerl\nLength of myarray: 6\n\nNew array is greater than myarray:\nC#\nC++\nRuby\nJava\nPHP\nPerl\n\n\n\n\nLength of New Array: 10\n" }, { "code": null, "e": 27844, "s": 27752, "text": "Reference: https://docs.microsoft.com/en-us/dotnet/api/system.array.resize?view=netcore-2.1" }, { "code": null, "e": 27857, "s": 27844, "text": "Akanksha_Rai" }, { "code": null, "e": 27871, "s": 27857, "text": "CSharp-Arrays" }, { "code": null, "e": 27885, "s": 27871, "text": "CSharp-method" }, { "code": null, "e": 27888, "s": 27885, "text": "C#" }, { "code": null, "e": 27986, "s": 27888, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28004, "s": 27986, "text": "Destructors in C#" }, { "code": null, "e": 28027, "s": 28004, "text": "Extension Method in C#" }, { "code": null, "e": 28055, "s": 28027, "text": "HashSet in C# with Examples" }, { "code": null, "e": 28095, "s": 28055, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28138, "s": 28095, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 28160, "s": 28138, "text": "Partial Classes in C#" }, { "code": null, "e": 28177, "s": 28160, "text": "C# | Inheritance" }, { "code": null, "e": 28193, "s": 28177, "text": "C# | List Class" }, { "code": null, "e": 28243, "s": 28193, "text": "Difference between Hashtable and Dictionary in C#" } ]
MLFlow for machine learning models | Towards Data Science
When we tune parameters of a machine learning model, we might need to train it for multiple times in order to pick the best model. If the number of trainings goes to too many, we might have two problems. How do we track the parameters and metrics of each model? Writing them manually to an excel file? That would be tedious and error-prone. How do we version each model? Save them to the disk with a different name for each? It would be hard to remember which model came from what parameters. MLFlow is what we need to solve these problems. It is a powerful MLOps tool for ML model tracking, versioning, packaging, and so on. In this blog, we will focus on tracking and versioning. Regarding tracking, MLFlow can track parameters, metrics, and models. Regarding versioning, MLFlow stores models in a model registry, and then users can easily choose a specific version. MLFlow can be run locally or from a docker container, and also can be deployed to kubernetes. It has APIs in Python, Java, R, and REST. In this blog, we will showcase how to use mlflow to track and version mnist classification models. We will first run an MNIST example with tensorflow, and then extend the code to integrate mlflow. MNIST example First, create a virtual environment, and pip install tensorflow and mlflow. # my version is 2.6.0pip install tensorflow# my version is 4.4.0pip install tensorflow_datasets# my version is 1.9.1pip install mlflow Below is the code to run mnist classification using tensorflow. Run the code, and you should see a log like below. It also saves the models in the model folder. MLFlow tracking Now, let’s track the parameters, metrics, and also artifacts (models). See the code below, (also see complete code at the bottom). First, we need to name a run. We can even name an experiment (higher level of runs) if we want. Then, we use the functions log_param , log_metric , and log_artifacts to log parameters, metrics, and artifacts. import mlflowwith mlflow.start_run(run_name=run_name): mlflow.log_param("batch_size", batch_size) mlflow.log_param("learning_rate", learning_rate) mlflow.log_param("epochs", epochs) mlflow.log_metric("train_loss", train_loss) mlflow.log_metric("train_accuracy", train_acc) mlflow.log_metric("val_loss", val_loss) mlflow.log_metric("val_accuracy", val_acc) mlflow.log_artifacts("./model") After running the mlflow code, we can see there is a new folder called mlruns in our disk. This is the place where parameters, metrics, and artifacts are stored locally. Then, we can do some parameters tuning, for example, change the batch_size and learning_rate. Each run will be logged to mlflow. Now, let’s view all runs at mlflow’s UI. Within the virtual environment, type: mlflow ui Then, browse at http://localhost:5000/. We can see all runs are logged there. The parameters, metrics, and run names can be clearly seen in one page. If we click into a run, we can see more details about this run. Apart from parameters and metrics, the section of Artifacts at bottom-left shows our artifacts (models). The url address of each run has the following format. Run ids within each experiment are unique. http://localhost:5000/#/experiments/<experiment id>/runs/<run id> MLFlow model versioning MLflow Model Registry is a central location to store and version models. With it, a model has an iterative version from (for example) v1, v2, ..., to v10. For each model and version, we can write a markdown description (for example detailed parameters) along with it, so that we know later what the model represents. In addition, we can tag a version with either Staging , Production , or Archived . To set up model registry, we need a database backend in order to store models, see here for instructions. After that, we can upload our tensorflow models to the mlflow registry. Here below is a code example. import mlflow.tensorflowfrom tensorflow.python.saved_model import signature_constantstag=[tf.saved_model.tag_constants.SERVING]key=signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEYmlflow.tensorflow.log_model(tf_saved_model_dir="./model", tf_meta_graph_tags=tag, tf_signature_def_key=key, artifact_path="model", registered_model_name="mnist") In conclusion, MLFlow is a powerful MLOps tool to track and version machine learning models. It supports APIs in python, java, R, etc. With its nice UI, we can clearly track, store, and compare different model versions. MLFlow has become a popular MLOps tool in many ML projects. Below is the complete code for mnist classification in tensorflow with mlflow tracking.
[ { "code": null, "e": 251, "s": 47, "text": "When we tune parameters of a machine learning model, we might need to train it for multiple times in order to pick the best model. If the number of trainings goes to too many, we might have two problems." }, { "code": null, "e": 388, "s": 251, "text": "How do we track the parameters and metrics of each model? Writing them manually to an excel file? That would be tedious and error-prone." }, { "code": null, "e": 540, "s": 388, "text": "How do we version each model? Save them to the disk with a different name for each? It would be hard to remember which model came from what parameters." }, { "code": null, "e": 916, "s": 540, "text": "MLFlow is what we need to solve these problems. It is a powerful MLOps tool for ML model tracking, versioning, packaging, and so on. In this blog, we will focus on tracking and versioning. Regarding tracking, MLFlow can track parameters, metrics, and models. Regarding versioning, MLFlow stores models in a model registry, and then users can easily choose a specific version." }, { "code": null, "e": 1052, "s": 916, "text": "MLFlow can be run locally or from a docker container, and also can be deployed to kubernetes. It has APIs in Python, Java, R, and REST." }, { "code": null, "e": 1249, "s": 1052, "text": "In this blog, we will showcase how to use mlflow to track and version mnist classification models. We will first run an MNIST example with tensorflow, and then extend the code to integrate mlflow." }, { "code": null, "e": 1263, "s": 1249, "text": "MNIST example" }, { "code": null, "e": 1339, "s": 1263, "text": "First, create a virtual environment, and pip install tensorflow and mlflow." }, { "code": null, "e": 1474, "s": 1339, "text": "# my version is 2.6.0pip install tensorflow# my version is 4.4.0pip install tensorflow_datasets# my version is 1.9.1pip install mlflow" }, { "code": null, "e": 1538, "s": 1474, "text": "Below is the code to run mnist classification using tensorflow." }, { "code": null, "e": 1635, "s": 1538, "text": "Run the code, and you should see a log like below. It also saves the models in the model folder." }, { "code": null, "e": 1651, "s": 1635, "text": "MLFlow tracking" }, { "code": null, "e": 1991, "s": 1651, "text": "Now, let’s track the parameters, metrics, and also artifacts (models). See the code below, (also see complete code at the bottom). First, we need to name a run. We can even name an experiment (higher level of runs) if we want. Then, we use the functions log_param , log_metric , and log_artifacts to log parameters, metrics, and artifacts." }, { "code": null, "e": 2387, "s": 1991, "text": "import mlflowwith mlflow.start_run(run_name=run_name): mlflow.log_param(\"batch_size\", batch_size) mlflow.log_param(\"learning_rate\", learning_rate) mlflow.log_param(\"epochs\", epochs) mlflow.log_metric(\"train_loss\", train_loss) mlflow.log_metric(\"train_accuracy\", train_acc) mlflow.log_metric(\"val_loss\", val_loss) mlflow.log_metric(\"val_accuracy\", val_acc) mlflow.log_artifacts(\"./model\")" }, { "code": null, "e": 2557, "s": 2387, "text": "After running the mlflow code, we can see there is a new folder called mlruns in our disk. This is the place where parameters, metrics, and artifacts are stored locally." }, { "code": null, "e": 2686, "s": 2557, "text": "Then, we can do some parameters tuning, for example, change the batch_size and learning_rate. Each run will be logged to mlflow." }, { "code": null, "e": 2765, "s": 2686, "text": "Now, let’s view all runs at mlflow’s UI. Within the virtual environment, type:" }, { "code": null, "e": 2775, "s": 2765, "text": "mlflow ui" }, { "code": null, "e": 2925, "s": 2775, "text": "Then, browse at http://localhost:5000/. We can see all runs are logged there. The parameters, metrics, and run names can be clearly seen in one page." }, { "code": null, "e": 3094, "s": 2925, "text": "If we click into a run, we can see more details about this run. Apart from parameters and metrics, the section of Artifacts at bottom-left shows our artifacts (models)." }, { "code": null, "e": 3191, "s": 3094, "text": "The url address of each run has the following format. Run ids within each experiment are unique." }, { "code": null, "e": 3257, "s": 3191, "text": "http://localhost:5000/#/experiments/<experiment id>/runs/<run id>" }, { "code": null, "e": 3281, "s": 3257, "text": "MLFlow model versioning" }, { "code": null, "e": 3681, "s": 3281, "text": "MLflow Model Registry is a central location to store and version models. With it, a model has an iterative version from (for example) v1, v2, ..., to v10. For each model and version, we can write a markdown description (for example detailed parameters) along with it, so that we know later what the model represents. In addition, we can tag a version with either Staging , Production , or Archived ." }, { "code": null, "e": 3889, "s": 3681, "text": "To set up model registry, we need a database backend in order to store models, see here for instructions. After that, we can upload our tensorflow models to the mlflow registry. Here below is a code example." }, { "code": null, "e": 4343, "s": 3889, "text": "import mlflow.tensorflowfrom tensorflow.python.saved_model import signature_constantstag=[tf.saved_model.tag_constants.SERVING]key=signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEYmlflow.tensorflow.log_model(tf_saved_model_dir=\"./model\", tf_meta_graph_tags=tag, tf_signature_def_key=key, artifact_path=\"model\", registered_model_name=\"mnist\")" }, { "code": null, "e": 4623, "s": 4343, "text": "In conclusion, MLFlow is a powerful MLOps tool to track and version machine learning models. It supports APIs in python, java, R, etc. With its nice UI, we can clearly track, store, and compare different model versions. MLFlow has become a popular MLOps tool in many ML projects." } ]
Download file through an AJAX call in PHP
Using Ajax to download files is not considered to be a good idea. Instead, window.location = or document.location should be used. The 'window.location' has the following characteristics − JavaScript enabling is required It doesn't need PHP. It helps show the content of the site, and redirects the user after a few seconds. Redirect can be dependent on any conditions such as − $success = 1 if ($success) { window.location.href = 'http://example.com'; } A variable named ‘success’ is assigned with the value of 1. When this condition is satisfied, the window.location is used. On running, the user is redirected to the website 'http://example.com'
[ { "code": null, "e": 1192, "s": 1062, "text": "Using Ajax to download files is not considered to be a good idea. Instead, window.location = or document.location should be used." }, { "code": null, "e": 1250, "s": 1192, "text": "The 'window.location' has the following characteristics −" }, { "code": null, "e": 1282, "s": 1250, "text": "JavaScript enabling is required" }, { "code": null, "e": 1303, "s": 1282, "text": "It doesn't need PHP." }, { "code": null, "e": 1386, "s": 1303, "text": "It helps show the content of the site, and redirects the user after a few seconds." }, { "code": null, "e": 1440, "s": 1386, "text": "Redirect can be dependent on any conditions such as −" }, { "code": null, "e": 1519, "s": 1440, "text": "$success = 1\nif ($success) {\n window.location.href = 'http://example.com';\n}" }, { "code": null, "e": 1642, "s": 1519, "text": "A variable named ‘success’ is assigned with the value of 1. When this condition is satisfied, the window.location is used." }, { "code": null, "e": 1713, "s": 1642, "text": "On running, the user is redirected to the website 'http://example.com'" } ]
Maven - Manage Dependencies
One of the core features of Maven is Dependency Management. Managing dependencies is a difficult task once we've to deal with multi-module projects (consisting of hundreds of modules/sub-projects). Maven provides a high degree of control to manage such scenarios. It is pretty often a case, when a library, say A, depends upon other library, say B. In case another project C wants to use A, then that project requires to use library B too. Maven helps to avoid such requirements to discover all the libraries required. Maven does so by reading project files (pom.xml) of dependencies, figure out their dependencies and so on. We only need to define direct dependency in each project pom. Maven handles the rest automatically. With transitive dependencies, the graph of included libraries can quickly grow to a large extent. Cases can arise when there are duplicate libraries. Maven provides few features to control extent of transitive dependencies. Dependency mediation Determines what version of a dependency is to be used when multiple versions of an artifact are encountered. If two dependency versions are at the same depth in the dependency tree, the first declared dependency will be used. Dependency management Directly specify the versions of artifacts to be used when they are encountered in transitive dependencies. For an example project C can include B as a dependency in its dependency Management section and directly control which version of B is to be used when it is ever referenced. Dependency scope Includes dependencies as per the current stage of the build. Excluded dependencies Any transitive dependency can be excluded using "exclusion" element. As example, A depends upon B and B depends upon C, then A can mark C as excluded. Optional dependencies Any transitive dependency can be marked as optional using "optional" element. As example, A depends upon B and B depends upon C. Now B marked C as optional. Then A will not use C. Transitive Dependencies Discovery can be restricted using various Dependency Scope as mentioned below. compile This scope indicates that dependency is available in classpath of project. It is default scope. provided This scope indicates that dependency is to be provided by JDK or web-Server/Container at runtime. runtime This scope indicates that dependency is not required for compilation, but is required during execution. test This scope indicates that the dependency is only available for the test compilation and execution phases. system This scope indicates that you have to provide the system path. import This scope is only used when dependency is of type pom. This scope indicates that the specified POM should be replaced with the dependencies in that POM's <dependencyManagement> section. Usually, we have a set of project under a common project. In such case, we can create a common pom having all the common dependencies and then make this pom, the parent of sub-project's poms. Following example will help you understand this concept. Following are the detail of the above dependency graph − App-UI-WAR depends upon App-Core-lib and App-Data-lib. Root is parent of App-Core-lib and App-Data-lib. Root defines Lib1, lib2, Lib3 as dependencies in its dependency section. App-UI-WAR <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.groupname</groupId> <artifactId>App-UI-WAR</artifactId> <version>1.0</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>com.companyname.groupname</groupId> <artifactId>App-Core-lib</artifactId> <version>1.0</version> </dependency> </dependencies> <dependencies> <dependency> <groupId>com.companyname.groupname</groupId> <artifactId>App-Data-lib</artifactId> <version>1.0</version> </dependency> </dependencies> </project> App-Core-lib <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>Root</artifactId> <groupId>com.companyname.groupname</groupId> <version>1.0</version> </parent> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.groupname</groupId> <artifactId>App-Core-lib</artifactId> <version>1.0</version> <packaging>jar</packaging> </project> App-Data-lib <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>Root</artifactId> <groupId>com.companyname.groupname</groupId> <version>1.0</version> </parent> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.groupname</groupId> <artifactId>App-Data-lib</artifactId> <version>1.0</version> <packaging>jar</packaging> </project> Root <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.groupname</groupId> <artifactId>Root</artifactId> <version>1.0</version> <packaging>pom</packaging> <dependencies> <dependency> <groupId>com.companyname.groupname1</groupId> <artifactId>Lib1</artifactId> <version>1.0</version> </dependency> </dependencies> <dependencies> <dependency> <groupId>com.companyname.groupname2</groupId> <artifactId>Lib2</artifactId> <version>2.1</version> </dependency> </dependencies> <dependencies> <dependency> <groupId>com.companyname.groupname3</groupId> <artifactId>Lib3</artifactId> <version>1.1</version> </dependency> </dependencies> </project> Now when we build App-UI-WAR project, Maven will discover all the dependencies by traversing the dependency graph and build the application. From above example, we can learn the following key concepts − Common dependencies can be placed at single place using concept of parent pom. Dependencies of App-Data-lib and App-Core-lib project are listed in Root project (See the packaging type of Root. It is POM). Common dependencies can be placed at single place using concept of parent pom. Dependencies of App-Data-lib and App-Core-lib project are listed in Root project (See the packaging type of Root. It is POM). There is no need to specify Lib1, lib2, Lib3 as dependency in App-UI-WAR. Maven use the Transitive Dependency Mechanism to manage such detail. There is no need to specify Lib1, lib2, Lib3 as dependency in App-UI-WAR. Maven use the Transitive Dependency Mechanism to manage such detail. 34 Lectures 4 hours Karthikeya T 14 Lectures 1.5 hours Quaatso Learning Print Add Notes Bookmark this page
[ { "code": null, "e": 2324, "s": 2060, "text": "One of the core features of Maven is Dependency Management. Managing dependencies is a difficult task once we've to deal with multi-module projects (consisting of hundreds of modules/sub-projects). Maven provides a high degree of control to manage such scenarios." }, { "code": null, "e": 2500, "s": 2324, "text": "It is pretty often a case, when a library, say A, depends upon other library, say B. In case another project C wants to use A, then that project requires to use library B too." }, { "code": null, "e": 2686, "s": 2500, "text": "Maven helps to avoid such requirements to discover all the libraries required. Maven does so by reading project files (pom.xml) of dependencies, figure out their dependencies and so on." }, { "code": null, "e": 2786, "s": 2686, "text": "We only need to define direct dependency in each project pom. Maven handles the rest automatically." }, { "code": null, "e": 3010, "s": 2786, "text": "With transitive dependencies, the graph of included libraries can quickly grow to a large extent. Cases can arise when there are duplicate libraries. Maven provides few features to control extent of transitive dependencies." }, { "code": null, "e": 3031, "s": 3010, "text": "Dependency mediation" }, { "code": null, "e": 3257, "s": 3031, "text": "Determines what version of a dependency is to be used when multiple versions of an artifact are encountered. If two dependency versions are at the same depth in the dependency tree, the first declared dependency will be used." }, { "code": null, "e": 3279, "s": 3257, "text": "Dependency management" }, { "code": null, "e": 3561, "s": 3279, "text": "Directly specify the versions of artifacts to be used when they are encountered in transitive dependencies. For an example project C can include B as a dependency in its dependency Management section and directly control which version of B is to be used when it is ever referenced." }, { "code": null, "e": 3578, "s": 3561, "text": "Dependency scope" }, { "code": null, "e": 3639, "s": 3578, "text": "Includes dependencies as per the current stage of the build." }, { "code": null, "e": 3661, "s": 3639, "text": "Excluded dependencies" }, { "code": null, "e": 3812, "s": 3661, "text": "Any transitive dependency can be excluded using \"exclusion\" element. As example, A depends upon B and B depends upon C, then A can mark C as excluded." }, { "code": null, "e": 3834, "s": 3812, "text": "Optional dependencies" }, { "code": null, "e": 4014, "s": 3834, "text": "Any transitive dependency can be marked as optional using \"optional\" element. As example, A depends upon B and B depends upon C. Now B marked C as optional. Then A will not use C." }, { "code": null, "e": 4117, "s": 4014, "text": "Transitive Dependencies Discovery can be restricted using various Dependency Scope as mentioned below." }, { "code": null, "e": 4125, "s": 4117, "text": "compile" }, { "code": null, "e": 4221, "s": 4125, "text": "This scope indicates that dependency is available in classpath of project. It is default scope." }, { "code": null, "e": 4230, "s": 4221, "text": "provided" }, { "code": null, "e": 4328, "s": 4230, "text": "This scope indicates that dependency is to be provided by JDK or web-Server/Container at runtime." }, { "code": null, "e": 4336, "s": 4328, "text": "runtime" }, { "code": null, "e": 4440, "s": 4336, "text": "This scope indicates that dependency is not required for compilation, but is required during execution." }, { "code": null, "e": 4445, "s": 4440, "text": "test" }, { "code": null, "e": 4551, "s": 4445, "text": "This scope indicates that the dependency is only available for the test compilation and execution phases." }, { "code": null, "e": 4558, "s": 4551, "text": "system" }, { "code": null, "e": 4621, "s": 4558, "text": "This scope indicates that you have to provide the system path." }, { "code": null, "e": 4628, "s": 4621, "text": "import" }, { "code": null, "e": 4815, "s": 4628, "text": "This scope is only used when dependency is of type pom. This scope indicates that the specified POM should be replaced with the dependencies in that POM's <dependencyManagement> section." }, { "code": null, "e": 5064, "s": 4815, "text": "Usually, we have a set of project under a common project. In such case, we can create a common pom having all the common dependencies and then make this pom, the parent of sub-project's poms. Following example will help you understand this concept." }, { "code": null, "e": 5121, "s": 5064, "text": "Following are the detail of the above dependency graph −" }, { "code": null, "e": 5176, "s": 5121, "text": "App-UI-WAR depends upon App-Core-lib and App-Data-lib." }, { "code": null, "e": 5225, "s": 5176, "text": "Root is parent of App-Core-lib and App-Data-lib." }, { "code": null, "e": 5298, "s": 5225, "text": "Root defines Lib1, lib2, Lib3 as dependencies in its dependency section." }, { "code": null, "e": 5309, "s": 5298, "text": "App-UI-WAR" }, { "code": null, "e": 6143, "s": 5309, "text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0\n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.groupname</groupId>\n <artifactId>App-UI-WAR</artifactId>\n <version>1.0</version>\n <packaging>war</packaging>\n <dependencies>\n <dependency>\n <groupId>com.companyname.groupname</groupId>\n <artifactId>App-Core-lib</artifactId>\n <version>1.0</version>\n </dependency>\n </dependencies> \n <dependencies>\n <dependency>\n <groupId>com.companyname.groupname</groupId>\n <artifactId>App-Data-lib</artifactId>\n <version>1.0</version>\n </dependency>\n </dependencies> \n</project>" }, { "code": null, "e": 6156, "s": 6143, "text": "App-Core-lib" }, { "code": null, "e": 6712, "s": 6156, "text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0\n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <parent>\n <artifactId>Root</artifactId>\n <groupId>com.companyname.groupname</groupId>\n <version>1.0</version>\n </parent>\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.groupname</groupId>\n <artifactId>App-Core-lib</artifactId>\n <version>1.0</version> \n <packaging>jar</packaging>\n</project>" }, { "code": null, "e": 6725, "s": 6712, "text": "App-Data-lib" }, { "code": null, "e": 7283, "s": 6725, "text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0\n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <parent>\n <artifactId>Root</artifactId>\n <groupId>com.companyname.groupname</groupId>\n <version>1.0</version>\n </parent>\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.groupname</groupId>\n <artifactId>App-Data-lib</artifactId>\n <version>1.0</version> \n <packaging>jar</packaging>\n</project>" }, { "code": null, "e": 7288, "s": 7283, "text": "Root" }, { "code": null, "e": 8306, "s": 7288, "text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0\n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.groupname</groupId>\n <artifactId>Root</artifactId>\n <version>1.0</version>\n <packaging>pom</packaging>\n <dependencies>\n <dependency>\n <groupId>com.companyname.groupname1</groupId>\n <artifactId>Lib1</artifactId>\n <version>1.0</version>\n </dependency>\n </dependencies> \n <dependencies>\n <dependency>\n <groupId>com.companyname.groupname2</groupId>\n <artifactId>Lib2</artifactId>\n <version>2.1</version>\n </dependency>\n </dependencies> \n <dependencies>\n <dependency>\n <groupId>com.companyname.groupname3</groupId>\n <artifactId>Lib3</artifactId>\n <version>1.1</version>\n </dependency>\n </dependencies> \n</project>" }, { "code": null, "e": 8447, "s": 8306, "text": "Now when we build App-UI-WAR project, Maven will discover all the dependencies by traversing the dependency graph and build the application." }, { "code": null, "e": 8509, "s": 8447, "text": "From above example, we can learn the following key concepts −" }, { "code": null, "e": 8714, "s": 8509, "text": "Common dependencies can be placed at single place using concept of parent pom. Dependencies of App-Data-lib and App-Core-lib project are listed in Root project (See the packaging type of Root. It is POM)." }, { "code": null, "e": 8919, "s": 8714, "text": "Common dependencies can be placed at single place using concept of parent pom. Dependencies of App-Data-lib and App-Core-lib project are listed in Root project (See the packaging type of Root. It is POM)." }, { "code": null, "e": 9062, "s": 8919, "text": "There is no need to specify Lib1, lib2, Lib3 as dependency in App-UI-WAR. Maven use the Transitive Dependency Mechanism to manage such detail." }, { "code": null, "e": 9205, "s": 9062, "text": "There is no need to specify Lib1, lib2, Lib3 as dependency in App-UI-WAR. Maven use the Transitive Dependency Mechanism to manage such detail." }, { "code": null, "e": 9238, "s": 9205, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 9252, "s": 9238, "text": " Karthikeya T" }, { "code": null, "e": 9287, "s": 9252, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9305, "s": 9287, "text": " Quaatso Learning" }, { "code": null, "e": 9312, "s": 9305, "text": " Print" }, { "code": null, "e": 9323, "s": 9312, "text": " Add Notes" } ]
Unix / Linux - Regular Expressions with SED
In this chapter, we will discuss in detail about regular expressions with SED in Unix. A regular expression is a string that can be used to describe several sequences of characters. Regular expressions are used by several different Unix commands, including ed, sed, awk, grep, and to a more limited extent, vi. Here SED stands for stream editor. This stream-oriented editor was created exclusively for executing scripts. Thus, all the input you feed into it passes through and goes to STDOUT and it does not change the input file. Before we start, let us ensure we have a local copy of /etc/passwd text file to work with sed. As mentioned previously, sed can be invoked by sending data through a pipe to it as follows − $ cat /etc/passwd | sed Usage: sed [OPTION]... {script-other-script} [input-file]... -n, --quiet, --silent suppress automatic printing of pattern space -e script, --expression = script ............................... The cat command dumps the contents of /etc/passwd to sed through the pipe into sed's pattern space. The pattern space is the internal work buffer that sed uses for its operations. Following is the general syntax for sed − /pattern/action Here, pattern is a regular expression, and action is one of the commands given in the following table. If pattern is omitted, action is performed for every line as we have seen above. The slash character (/) that surrounds the pattern are required because they are used as delimiters. p Prints the line d Deletes the line s/pattern1/pattern2/ Substitutes the first occurrence of pattern1 with pattern2 We will now understand how to delete all lines with sed. Invoke sed again; but the sed is now supposed to use the editing command delete line, denoted by the single letter d − $ cat /etc/passwd | sed 'd' $ Instead of invoking sed by sending a file to it through a pipe, the sed can be instructed to read the data from a file, as in the following example. The following command does exactly the same as in the previous example, without the cat command − $ sed -e 'd' /etc/passwd $ The sed also supports addresses. Addresses are either particular locations in a file or a range where a particular editing command should be applied. When the sed encounters no addresses, it performs its operations on every line in the file. The following command adds a basic address to the sed command you've been using − $ cat /etc/passwd | sed '1d' |more daemon:x:1:1:daemon:/usr/sbin:/bin/sh bin:x:2:2:bin:/bin:/bin/sh sys:x:3:3:sys:/dev:/bin/sh sync:x:4:65534:sync:/bin:/bin/sync games:x:5:60:games:/usr/games:/bin/sh man:x:6:12:man:/var/cache/man:/bin/sh mail:x:8:8:mail:/var/mail:/bin/sh news:x:9:9:news:/var/spool/news:/bin/sh backup:x:34:34:backup:/var/backups:/bin/sh $ Notice that the number 1 is added before the delete edit command. This instructs the sed to perform the editing command on the first line of the file. In this example, the sed will delete the first line of /etc/password and print the rest of the file. We will now understand how to work with the sed address ranges. So what if you want to remove more than one line from a file? You can specify an address range with sed as follows − $ cat /etc/passwd | sed '1, 5d' |more games:x:5:60:games:/usr/games:/bin/sh man:x:6:12:man:/var/cache/man:/bin/sh mail:x:8:8:mail:/var/mail:/bin/sh news:x:9:9:news:/var/spool/news:/bin/sh backup:x:34:34:backup:/var/backups:/bin/sh $ The above command will be applied on all the lines starting from 1 through 5. This deletes the first five lines. Try out the following address ranges − '4,10d' Lines starting from the 4th till the 10th are deleted '10,4d' Only 10th line is deleted, because the sed does not work in reverse direction '4,+5d' This matches line 4 in the file, deletes that line, continues to delete the next five lines, and then ceases its deletion and prints the rest '2,5!d' This deletes everything except starting from 2nd till 5th line '1~3d' This deletes the first line, steps over the next three lines, and then deletes the fourth line. Sed continues to apply this pattern until the end of the file. '2~2d' This tells sed to delete the second line, step over the next line, delete the next line, and repeat until the end of the file is reached '4,10p' Lines starting from 4th till 10th are printed '4,d' This generates the syntax error ',10d' This would also generate syntax error Note − While using the p action, you should use the -n option to avoid repetition of line printing. Check the difference in between the following two commands − $ cat /etc/passwd | sed -n '1,3p' Check the above command without -n as follows − $ cat /etc/passwd | sed '1,3p' The substitution command, denoted by s, will substitute any string that you specify with any other string that you specify. To substitute one string with another, the sed needs to have the information on where the first string ends and the substitution string begins. For this, we proceed with bookending the two strings with the forward slash (/) character. The following command substitutes the first occurrence on a line of the string root with the string amrood. $ cat /etc/passwd | sed 's/root/amrood/' amrood:x:0:0:root user:/root:/bin/sh daemon:x:1:1:daemon:/usr/sbin:/bin/sh .......................... It is very important to note that sed substitutes only the first occurrence on a line. If the string root occurs more than once on a line only the first match will be replaced. For the sed to perform a global substitution, add the letter g to the end of the command as follows − $ cat /etc/passwd | sed 's/root/amrood/g' amrood:x:0:0:amrood user:/amrood:/bin/sh daemon:x:1:1:daemon:/usr/sbin:/bin/sh bin:x:2:2:bin:/bin:/bin/sh sys:x:3:3:sys:/dev:/bin/sh ........................... There are a number of other useful flags that can be passed in addition to the g flag, and you can specify more than one at a time. g Replaces all matches, not just the first match NUMBER Replaces only NUMBERth match p If substitution was made, then prints the pattern space w FILENAME If substitution was made, then writes result to FILENAME I or i Matches in a case-insensitive manner M or m In addition to the normal behavior of the special regular expression characters ^ and $, this flag causes ^ to match the empty string after a newline and $ to match the empty string before a newline Suppose you have to do a substitution on a string that includes the forward slash character. In this case, you can specify a different separator by providing the designated character after the s. $ cat /etc/passwd | sed 's:/root:/amrood:g' amrood:x:0:0:amrood user:/amrood:/bin/sh daemon:x:1:1:daemon:/usr/sbin:/bin/sh In the above example, we have used : as the delimiter instead of slash / because we were trying to search /root instead of the simple root. Use an empty substitution string to delete the root string from the /etc/passwd file entirely − $ cat /etc/passwd | sed 's/root//g' :x:0:0::/:/bin/sh daemon:x:1:1:daemon:/usr/sbin:/bin/sh If you want to substitute the string sh with the string quiet only on line 10, you can specify it as follows − $ cat /etc/passwd | sed '10s/sh/quiet/g' root:x:0:0:root user:/root:/bin/sh daemon:x:1:1:daemon:/usr/sbin:/bin/sh bin:x:2:2:bin:/bin:/bin/sh sys:x:3:3:sys:/dev:/bin/sh sync:x:4:65534:sync:/bin:/bin/sync games:x:5:60:games:/usr/games:/bin/sh man:x:6:12:man:/var/cache/man:/bin/sh mail:x:8:8:mail:/var/mail:/bin/sh news:x:9:9:news:/var/spool/news:/bin/sh backup:x:34:34:backup:/var/backups:/bin/quiet Similarly, to do an address range substitution, you could do something like the following − $ cat /etc/passwd | sed '1,5s/sh/quiet/g' root:x:0:0:root user:/root:/bin/quiet daemon:x:1:1:daemon:/usr/sbin:/bin/quiet bin:x:2:2:bin:/bin:/bin/quiet sys:x:3:3:sys:/dev:/bin/quiet sync:x:4:65534:sync:/bin:/bin/sync games:x:5:60:games:/usr/games:/bin/sh man:x:6:12:man:/var/cache/man:/bin/sh mail:x:8:8:mail:/var/mail:/bin/sh news:x:9:9:news:/var/spool/news:/bin/sh backup:x:34:34:backup:/var/backups:/bin/sh As you can see from the output, the first five lines had the string sh changed to quiet, but the rest of the lines were left untouched. You would use the p option along with the -n option to print all the matching lines as follows − $ cat testing | sed -n '/root/p' root:x:0:0:root user:/root:/bin/sh [root@ip-72-167-112-17 amrood]# vi testing root:x:0:0:root user:/root:/bin/sh daemon:x:1:1:daemon:/usr/sbin:/bin/sh bin:x:2:2:bin:/bin:/bin/sh sys:x:3:3:sys:/dev:/bin/sh sync:x:4:65534:sync:/bin:/bin/sync games:x:5:60:games:/usr/games:/bin/sh man:x:6:12:man:/var/cache/man:/bin/sh mail:x:8:8:mail:/var/mail:/bin/sh news:x:9:9:news:/var/spool/news:/bin/sh backup:x:34:34:backup:/var/backups:/bin/sh While matching patterns, you can use the regular expression which provides more flexibility. Check the following example which matches all the lines starting with daemon and then deletes them − $ cat testing | sed '/^daemon/d' root:x:0:0:root user:/root:/bin/sh bin:x:2:2:bin:/bin:/bin/sh sys:x:3:3:sys:/dev:/bin/sh sync:x:4:65534:sync:/bin:/bin/sync games:x:5:60:games:/usr/games:/bin/sh man:x:6:12:man:/var/cache/man:/bin/sh mail:x:8:8:mail:/var/mail:/bin/sh news:x:9:9:news:/var/spool/news:/bin/sh backup:x:34:34:backup:/var/backups:/bin/sh Following is the example which deletes all the lines ending with sh − $ cat testing | sed '/sh$/d' sync:x:4:65534:sync:/bin:/bin/sync The following table lists four special characters that are very useful in regular expressions. ^ Matches the beginning of lines $ Matches the end of lines . Matches any single character * Matches zero or more occurrences of the previous character [chars] Matches any one of the characters given in chars, where chars is a sequence of characters. You can use the - character to indicate a range of characters. Look at a few more expressions to demonstrate the use of metacharacters. For example, the following pattern − /a.c/ Matches lines that contain strings such as a+c, a-c, abc, match, and a3c /a*c/ Matches the same strings along with strings such as ace, yacc, and arctic /[tT]he/ Matches the string The and the /^$/ Matches blank lines /^.*$/ Matches an entire line whatever it is / */ Matches one or more spaces /^$/ Matches blank lines Following table shows some frequently used sets of characters − [a-z] Matches a single lowercase letter [A-Z] Matches a single uppercase letter [a-zA-Z] Matches a single letter [0-9] Matches a single number [a-zA-Z0-9] Matches a single letter or number Some special keywords are commonly available to regexps, especially GNU utilities that employ regexps. These are very useful for sed regular expressions as they simplify things and enhance readability. For example, the characters a through z and the characters A through Z, constitute one such class of characters that has the keyword [[:alpha:]] Using the alphabet character class keyword, this command prints only those lines in the /etc/syslog.conf file that start with a letter of the alphabet − $ cat /etc/syslog.conf | sed -n '/^[[:alpha:]]/p' authpriv.* /var/log/secure mail.* -/var/log/maillog cron.* /var/log/cron uucp,news.crit /var/log/spooler local7.* /var/log/boot.log The following table is a complete list of the available character class keywords in GNU sed. [[:alnum:]] Alphanumeric [a-z A-Z 0-9] [[:alpha:]] Alphabetic [a-z A-Z] [[:blank:]] Blank characters (spaces or tabs) [[:cntrl:]] Control characters [[:digit:]] Numbers [0-9] [[:graph:]] Any visible characters (excludes whitespace) [[:lower:]] Lowercase letters [a-z] [[:print:]] Printable characters (non-control characters) [[:punct:]] Punctuation characters [[:space:]] Whitespace [[:upper:]] Uppercase letters [A-Z] [[:xdigit:]] Hex digits [0-9 a-f A-F] The sed metacharacter & represents the contents of the pattern that was matched. For instance, say you have a file called phone.txt full of phone numbers, such as the following − 5555551212 5555551213 5555551214 6665551215 6665551216 7775551217 You want to make the area code (the first three digits) surrounded by parentheses for easier reading. To do this, you can use the ampersand replacement character − $ sed -e 's/^[[:digit:]][[:digit:]][[:digit:]]/(&)/g' phone.txt (555)5551212 (555)5551213 (555)5551214 (666)5551215 (666)5551216 (777)5551217 Here in the pattern part you are matching the first 3 digits and then using & you are replacing those 3 digits with the surrounding parentheses. You can use multiple sed commands in a single sed command as follows − $ sed -e 'command1' -e 'command2' ... -e 'commandN' files Here command1 through commandN are sed commands of the type discussed previously. These commands are applied to each of the lines in the list of files given by files. Using the same mechanism, we can write the above phone number example as follows − $ sed -e 's/^[[:digit:]]\{3\}/(&)/g' \ -e 's/)[[:digit:]]\{3\}/&-/g' phone.txt (555)555-1212 (555)555-1213 (555)555-1214 (666)555-1215 (666)555-1216 (777)555-1217 Note − In the above example, instead of repeating the character class keyword [[:digit:]] three times, we replaced it with \{3\}, which means the preceding regular expression is matched three times. We have also used \ to give line break and this has to be removed before the command is run. The ampersand metacharacter is useful, but even more useful is the ability to define specific regions in regular expressions. These special regions can be used as reference in your replacement strings. By defining specific parts of a regular expression, you can then refer back to those parts with a special reference character. To do back references, you have to first define a region and then refer back to that region. To define a region, you insert backslashed parentheses around each region of interest. The first region that you surround with backslashes is then referenced by \1, the second region by \2, and so on. Assuming phone.txt has the following text − (555)555-1212 (555)555-1213 (555)555-1214 (666)555-1215 (666)555-1216 (777)555-1217 Try the following command − $ cat phone.txt | sed 's/\(.*)\)\(.*-\)\(.*$\)/Area \ code: \1 Second: \2 Third: \3/' Area code: (555) Second: 555- Third: 1212 Area code: (555) Second: 555- Third: 1213 Area code: (555) Second: 555- Third: 1214 Area code: (666) Second: 555- Third: 1215 Area code: (666) Second: 555- Third: 1216 Area code: (777) Second: 555- Third: 1217 Note − In the above example, each regular expression inside the parenthesis would be back referenced by \1, \2 and so on. We have used \ to give line break here. This should be removed before running the command. 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": 2834, "s": 2747, "text": "In this chapter, we will discuss in detail about regular expressions with SED in Unix." }, { "code": null, "e": 3058, "s": 2834, "text": "A regular expression is a string that can be used to describe several sequences of characters. Regular expressions are used by several different Unix commands, including ed, sed, awk, grep, and to a more limited extent, vi." }, { "code": null, "e": 3278, "s": 3058, "text": "Here SED stands for stream editor. This stream-oriented editor was created exclusively for executing scripts. Thus, all the input you feed into it passes through and goes to STDOUT and it does not change the input file." }, { "code": null, "e": 3373, "s": 3278, "text": "Before we start, let us ensure we have a local copy of /etc/passwd text file to work with sed." }, { "code": null, "e": 3467, "s": 3373, "text": "As mentioned previously, sed can be invoked by sending data through a pipe to it as follows −" }, { "code": null, "e": 3707, "s": 3467, "text": "$ cat /etc/passwd | sed\nUsage: sed [OPTION]... {script-other-script} [input-file]...\n\n -n, --quiet, --silent\n suppress automatic printing of pattern space\n -e script, --expression = script\n...............................\n" }, { "code": null, "e": 3887, "s": 3707, "text": "The cat command dumps the contents of /etc/passwd to sed through the pipe into sed's pattern space. The pattern space is the internal work buffer that sed uses for its operations." }, { "code": null, "e": 3929, "s": 3887, "text": "Following is the general syntax for sed −" }, { "code": null, "e": 3946, "s": 3929, "text": "/pattern/action\n" }, { "code": null, "e": 4130, "s": 3946, "text": "Here, pattern is a regular expression, and action is one of the commands given in the following table. If pattern is omitted, action is performed for every line as we have seen above." }, { "code": null, "e": 4231, "s": 4130, "text": "The slash character (/) that surrounds the pattern are required because they are used as delimiters." }, { "code": null, "e": 4233, "s": 4231, "text": "p" }, { "code": null, "e": 4249, "s": 4233, "text": "Prints the line" }, { "code": null, "e": 4251, "s": 4249, "text": "d" }, { "code": null, "e": 4268, "s": 4251, "text": "Deletes the line" }, { "code": null, "e": 4289, "s": 4268, "text": "s/pattern1/pattern2/" }, { "code": null, "e": 4348, "s": 4289, "text": "Substitutes the first occurrence of pattern1 with pattern2" }, { "code": null, "e": 4524, "s": 4348, "text": "We will now understand how to delete all lines with sed. Invoke sed again; but the sed is now supposed to use the editing command delete line, denoted by the single letter d −" }, { "code": null, "e": 4555, "s": 4524, "text": "$ cat /etc/passwd | sed 'd'\n$\n" }, { "code": null, "e": 4704, "s": 4555, "text": "Instead of invoking sed by sending a file to it through a pipe, the sed can be instructed to read the data from a file, as in the following example." }, { "code": null, "e": 4802, "s": 4704, "text": "The following command does exactly the same as in the previous example, without the cat command −" }, { "code": null, "e": 4830, "s": 4802, "text": "$ sed -e 'd' /etc/passwd\n$\n" }, { "code": null, "e": 5072, "s": 4830, "text": "The sed also supports addresses. Addresses are either particular locations in a file or a range where a particular editing command should be applied. When the sed encounters no addresses, it performs its operations on every line in the file." }, { "code": null, "e": 5154, "s": 5072, "text": "The following command adds a basic address to the sed command you've been using −" }, { "code": null, "e": 5512, "s": 5154, "text": "$ cat /etc/passwd | sed '1d' |more\ndaemon:x:1:1:daemon:/usr/sbin:/bin/sh\nbin:x:2:2:bin:/bin:/bin/sh\nsys:x:3:3:sys:/dev:/bin/sh\nsync:x:4:65534:sync:/bin:/bin/sync\ngames:x:5:60:games:/usr/games:/bin/sh\nman:x:6:12:man:/var/cache/man:/bin/sh\nmail:x:8:8:mail:/var/mail:/bin/sh\nnews:x:9:9:news:/var/spool/news:/bin/sh\nbackup:x:34:34:backup:/var/backups:/bin/sh\n$\n" }, { "code": null, "e": 5764, "s": 5512, "text": "Notice that the number 1 is added before the delete edit command. This instructs the sed to perform the editing command on the first line of the file. In this example, the sed will delete the first line of /etc/password and print the rest of the file." }, { "code": null, "e": 5945, "s": 5764, "text": "We will now understand how to work with the sed address ranges. So what if you want to remove more than one line from a file? You can specify an address range with sed as follows −" }, { "code": null, "e": 6179, "s": 5945, "text": "$ cat /etc/passwd | sed '1, 5d' |more\ngames:x:5:60:games:/usr/games:/bin/sh\nman:x:6:12:man:/var/cache/man:/bin/sh\nmail:x:8:8:mail:/var/mail:/bin/sh\nnews:x:9:9:news:/var/spool/news:/bin/sh\nbackup:x:34:34:backup:/var/backups:/bin/sh\n$\n" }, { "code": null, "e": 6292, "s": 6179, "text": "The above command will be applied on all the lines starting from 1 through 5. This deletes the first five lines." }, { "code": null, "e": 6331, "s": 6292, "text": "Try out the following address ranges −" }, { "code": null, "e": 6339, "s": 6331, "text": "'4,10d'" }, { "code": null, "e": 6393, "s": 6339, "text": "Lines starting from the 4th till the 10th are deleted" }, { "code": null, "e": 6401, "s": 6393, "text": "'10,4d'" }, { "code": null, "e": 6479, "s": 6401, "text": "Only 10th line is deleted, because the sed does not work in reverse direction" }, { "code": null, "e": 6487, "s": 6479, "text": "'4,+5d'" }, { "code": null, "e": 6629, "s": 6487, "text": "This matches line 4 in the file, deletes that line, continues to delete the next five lines, and then ceases its deletion and prints the rest" }, { "code": null, "e": 6637, "s": 6629, "text": "'2,5!d'" }, { "code": null, "e": 6700, "s": 6637, "text": "This deletes everything except starting from 2nd till 5th line" }, { "code": null, "e": 6707, "s": 6700, "text": "'1~3d'" }, { "code": null, "e": 6866, "s": 6707, "text": "This deletes the first line, steps over the next three lines, and then deletes the fourth line. Sed continues to apply this pattern until the end of the file." }, { "code": null, "e": 6873, "s": 6866, "text": "'2~2d'" }, { "code": null, "e": 7010, "s": 6873, "text": "This tells sed to delete the second line, step over the next line, delete the next line, and repeat until the end of the file is reached" }, { "code": null, "e": 7018, "s": 7010, "text": "'4,10p'" }, { "code": null, "e": 7064, "s": 7018, "text": "Lines starting from 4th till 10th are printed" }, { "code": null, "e": 7070, "s": 7064, "text": "'4,d'" }, { "code": null, "e": 7102, "s": 7070, "text": "This generates the syntax error" }, { "code": null, "e": 7109, "s": 7102, "text": "',10d'" }, { "code": null, "e": 7147, "s": 7109, "text": "This would also generate syntax error" }, { "code": null, "e": 7308, "s": 7147, "text": "Note − While using the p action, you should use the -n option to avoid repetition of line printing. Check the difference in between the following two commands −" }, { "code": null, "e": 7422, "s": 7308, "text": "$ cat /etc/passwd | sed -n '1,3p'\nCheck the above command without -n as follows −\n$ cat /etc/passwd | sed '1,3p'\n" }, { "code": null, "e": 7546, "s": 7422, "text": "The substitution command, denoted by s, will substitute any string that you specify with any other string that you specify." }, { "code": null, "e": 7781, "s": 7546, "text": "To substitute one string with another, the sed needs to have the information on where the first string ends and the substitution string begins. For this, we proceed with bookending the two strings with the forward slash (/) character." }, { "code": null, "e": 7889, "s": 7781, "text": "The following command substitutes the first occurrence on a line of the string root with the string amrood." }, { "code": null, "e": 8033, "s": 7889, "text": "$ cat /etc/passwd | sed 's/root/amrood/'\namrood:x:0:0:root user:/root:/bin/sh\ndaemon:x:1:1:daemon:/usr/sbin:/bin/sh\n..........................\n" }, { "code": null, "e": 8210, "s": 8033, "text": "It is very important to note that sed substitutes only the first occurrence on a line. If the string root occurs more than once on a line only the first match will be replaced." }, { "code": null, "e": 8312, "s": 8210, "text": "For the sed to perform a global substitution, add the letter g to the end of the command as follows −" }, { "code": null, "e": 8516, "s": 8312, "text": "$ cat /etc/passwd | sed 's/root/amrood/g'\namrood:x:0:0:amrood user:/amrood:/bin/sh\ndaemon:x:1:1:daemon:/usr/sbin:/bin/sh\nbin:x:2:2:bin:/bin:/bin/sh\nsys:x:3:3:sys:/dev:/bin/sh\n...........................\n" }, { "code": null, "e": 8648, "s": 8516, "text": "There are a number of other useful flags that can be passed in addition to the g flag, and you can specify more than one at a time." }, { "code": null, "e": 8650, "s": 8648, "text": "g" }, { "code": null, "e": 8697, "s": 8650, "text": "Replaces all matches, not just the first match" }, { "code": null, "e": 8704, "s": 8697, "text": "NUMBER" }, { "code": null, "e": 8733, "s": 8704, "text": "Replaces only NUMBERth match" }, { "code": null, "e": 8735, "s": 8733, "text": "p" }, { "code": null, "e": 8791, "s": 8735, "text": "If substitution was made, then prints the pattern space" }, { "code": null, "e": 8802, "s": 8791, "text": "w FILENAME" }, { "code": null, "e": 8859, "s": 8802, "text": "If substitution was made, then writes result to FILENAME" }, { "code": null, "e": 8866, "s": 8859, "text": "I or i" }, { "code": null, "e": 8903, "s": 8866, "text": "Matches in a case-insensitive manner" }, { "code": null, "e": 8910, "s": 8903, "text": "M or m" }, { "code": null, "e": 9109, "s": 8910, "text": "In addition to the normal behavior of the special regular expression characters ^ and $, this flag causes ^ to match the empty string after a newline and $ to match the empty string before a newline" }, { "code": null, "e": 9305, "s": 9109, "text": "Suppose you have to do a substitution on a string that includes the forward slash character. In this case, you can specify a different separator by providing the designated character after the s." }, { "code": null, "e": 9429, "s": 9305, "text": "$ cat /etc/passwd | sed 's:/root:/amrood:g'\namrood:x:0:0:amrood user:/amrood:/bin/sh\ndaemon:x:1:1:daemon:/usr/sbin:/bin/sh\n" }, { "code": null, "e": 9569, "s": 9429, "text": "In the above example, we have used : as the delimiter instead of slash / because we were trying to search /root instead of the simple root." }, { "code": null, "e": 9665, "s": 9569, "text": "Use an empty substitution string to delete the root string from the /etc/passwd file entirely −" }, { "code": null, "e": 9758, "s": 9665, "text": "$ cat /etc/passwd | sed 's/root//g'\n:x:0:0::/:/bin/sh\ndaemon:x:1:1:daemon:/usr/sbin:/bin/sh\n" }, { "code": null, "e": 9869, "s": 9758, "text": "If you want to substitute the string sh with the string quiet only on line 10, you can specify it as follows −" }, { "code": null, "e": 10269, "s": 9869, "text": "$ cat /etc/passwd | sed '10s/sh/quiet/g'\nroot:x:0:0:root user:/root:/bin/sh\ndaemon:x:1:1:daemon:/usr/sbin:/bin/sh\nbin:x:2:2:bin:/bin:/bin/sh\nsys:x:3:3:sys:/dev:/bin/sh\nsync:x:4:65534:sync:/bin:/bin/sync\ngames:x:5:60:games:/usr/games:/bin/sh\nman:x:6:12:man:/var/cache/man:/bin/sh\nmail:x:8:8:mail:/var/mail:/bin/sh\nnews:x:9:9:news:/var/spool/news:/bin/sh\nbackup:x:34:34:backup:/var/backups:/bin/quiet\n" }, { "code": null, "e": 10361, "s": 10269, "text": "Similarly, to do an address range substitution, you could do something like the following −" }, { "code": null, "e": 10771, "s": 10361, "text": "$ cat /etc/passwd | sed '1,5s/sh/quiet/g'\nroot:x:0:0:root user:/root:/bin/quiet\ndaemon:x:1:1:daemon:/usr/sbin:/bin/quiet\nbin:x:2:2:bin:/bin:/bin/quiet\nsys:x:3:3:sys:/dev:/bin/quiet\nsync:x:4:65534:sync:/bin:/bin/sync\ngames:x:5:60:games:/usr/games:/bin/sh\nman:x:6:12:man:/var/cache/man:/bin/sh\nmail:x:8:8:mail:/var/mail:/bin/sh\nnews:x:9:9:news:/var/spool/news:/bin/sh\nbackup:x:34:34:backup:/var/backups:/bin/sh\n" }, { "code": null, "e": 10907, "s": 10771, "text": "As you can see from the output, the first five lines had the string sh changed to quiet, but the rest of the lines were left untouched." }, { "code": null, "e": 11004, "s": 10907, "text": "You would use the p option along with the -n option to print all the matching lines as follows −" }, { "code": null, "e": 11471, "s": 11004, "text": "$ cat testing | sed -n '/root/p'\nroot:x:0:0:root user:/root:/bin/sh\n[root@ip-72-167-112-17 amrood]# vi testing\nroot:x:0:0:root user:/root:/bin/sh\ndaemon:x:1:1:daemon:/usr/sbin:/bin/sh\nbin:x:2:2:bin:/bin:/bin/sh\nsys:x:3:3:sys:/dev:/bin/sh\nsync:x:4:65534:sync:/bin:/bin/sync\ngames:x:5:60:games:/usr/games:/bin/sh\nman:x:6:12:man:/var/cache/man:/bin/sh\nmail:x:8:8:mail:/var/mail:/bin/sh\nnews:x:9:9:news:/var/spool/news:/bin/sh\nbackup:x:34:34:backup:/var/backups:/bin/sh\n" }, { "code": null, "e": 11564, "s": 11471, "text": "While matching patterns, you can use the regular expression which provides more flexibility." }, { "code": null, "e": 11665, "s": 11564, "text": "Check the following example which matches all the lines starting with daemon and then deletes them −" }, { "code": null, "e": 12016, "s": 11665, "text": "$ cat testing | sed '/^daemon/d'\nroot:x:0:0:root user:/root:/bin/sh\nbin:x:2:2:bin:/bin:/bin/sh\nsys:x:3:3:sys:/dev:/bin/sh\nsync:x:4:65534:sync:/bin:/bin/sync\ngames:x:5:60:games:/usr/games:/bin/sh\nman:x:6:12:man:/var/cache/man:/bin/sh\nmail:x:8:8:mail:/var/mail:/bin/sh\nnews:x:9:9:news:/var/spool/news:/bin/sh\nbackup:x:34:34:backup:/var/backups:/bin/sh\n" }, { "code": null, "e": 12086, "s": 12016, "text": "Following is the example which deletes all the lines ending with sh −" }, { "code": null, "e": 12151, "s": 12086, "text": "$ cat testing | sed '/sh$/d'\nsync:x:4:65534:sync:/bin:/bin/sync\n" }, { "code": null, "e": 12246, "s": 12151, "text": "The following table lists four special characters that are very useful in regular expressions." }, { "code": null, "e": 12248, "s": 12246, "text": "^" }, { "code": null, "e": 12279, "s": 12248, "text": "Matches the beginning of lines" }, { "code": null, "e": 12281, "s": 12279, "text": "$" }, { "code": null, "e": 12306, "s": 12281, "text": "Matches the end of lines" }, { "code": null, "e": 12308, "s": 12306, "text": "." }, { "code": null, "e": 12337, "s": 12308, "text": "Matches any single character" }, { "code": null, "e": 12339, "s": 12337, "text": "*" }, { "code": null, "e": 12398, "s": 12339, "text": "Matches zero or more occurrences of the previous character" }, { "code": null, "e": 12406, "s": 12398, "text": "[chars]" }, { "code": null, "e": 12560, "s": 12406, "text": "Matches any one of the characters given in chars, where chars is a sequence of characters. You can use the - character to indicate a range of characters." }, { "code": null, "e": 12670, "s": 12560, "text": "Look at a few more expressions to demonstrate the use of metacharacters. For example, the following pattern −" }, { "code": null, "e": 12676, "s": 12670, "text": "/a.c/" }, { "code": null, "e": 12749, "s": 12676, "text": "Matches lines that contain strings such as a+c, a-c, abc, match, and a3c" }, { "code": null, "e": 12755, "s": 12749, "text": "/a*c/" }, { "code": null, "e": 12829, "s": 12755, "text": "Matches the same strings along with strings such as ace, yacc, and arctic" }, { "code": null, "e": 12838, "s": 12829, "text": "/[tT]he/" }, { "code": null, "e": 12869, "s": 12838, "text": "Matches the string The and the" }, { "code": null, "e": 12874, "s": 12869, "text": "/^$/" }, { "code": null, "e": 12894, "s": 12874, "text": "Matches blank lines" }, { "code": null, "e": 12901, "s": 12894, "text": "/^.*$/" }, { "code": null, "e": 12939, "s": 12901, "text": "Matches an entire line whatever it is" }, { "code": null, "e": 12944, "s": 12939, "text": "/ */" }, { "code": null, "e": 12971, "s": 12944, "text": "Matches one or more spaces" }, { "code": null, "e": 12976, "s": 12971, "text": "/^$/" }, { "code": null, "e": 12996, "s": 12976, "text": "Matches blank lines" }, { "code": null, "e": 13060, "s": 12996, "text": "Following table shows some frequently used sets of characters −" }, { "code": null, "e": 13066, "s": 13060, "text": "[a-z]" }, { "code": null, "e": 13100, "s": 13066, "text": "Matches a single lowercase letter" }, { "code": null, "e": 13106, "s": 13100, "text": "[A-Z]" }, { "code": null, "e": 13140, "s": 13106, "text": "Matches a single uppercase letter" }, { "code": null, "e": 13149, "s": 13140, "text": "[a-zA-Z]" }, { "code": null, "e": 13173, "s": 13149, "text": "Matches a single letter" }, { "code": null, "e": 13179, "s": 13173, "text": "[0-9]" }, { "code": null, "e": 13203, "s": 13179, "text": "Matches a single number" }, { "code": null, "e": 13215, "s": 13203, "text": "[a-zA-Z0-9]" }, { "code": null, "e": 13249, "s": 13215, "text": "Matches a single letter or number" }, { "code": null, "e": 13451, "s": 13249, "text": "Some special keywords are commonly available to regexps, especially GNU utilities that employ regexps. These are very useful for sed regular expressions as they simplify things and enhance readability." }, { "code": null, "e": 13596, "s": 13451, "text": "For example, the characters a through z and the characters A through Z, constitute one such class of characters that has the keyword [[:alpha:]]" }, { "code": null, "e": 13749, "s": 13596, "text": "Using the alphabet character class keyword, this command prints only those lines in the /etc/syslog.conf file that start with a letter of the alphabet −" }, { "code": null, "e": 14058, "s": 13749, "text": "$ cat /etc/syslog.conf | sed -n '/^[[:alpha:]]/p'\nauthpriv.* /var/log/secure\nmail.* -/var/log/maillog\ncron.* /var/log/cron\nuucp,news.crit /var/log/spooler\nlocal7.* /var/log/boot.log\n" }, { "code": null, "e": 14151, "s": 14058, "text": "The following table is a complete list of the available character class keywords in GNU sed." }, { "code": null, "e": 14163, "s": 14151, "text": "[[:alnum:]]" }, { "code": null, "e": 14190, "s": 14163, "text": "Alphanumeric [a-z A-Z 0-9]" }, { "code": null, "e": 14202, "s": 14190, "text": "[[:alpha:]]" }, { "code": null, "e": 14223, "s": 14202, "text": "Alphabetic [a-z A-Z]" }, { "code": null, "e": 14235, "s": 14223, "text": "[[:blank:]]" }, { "code": null, "e": 14269, "s": 14235, "text": "Blank characters (spaces or tabs)" }, { "code": null, "e": 14281, "s": 14269, "text": "[[:cntrl:]]" }, { "code": null, "e": 14300, "s": 14281, "text": "Control characters" }, { "code": null, "e": 14312, "s": 14300, "text": "[[:digit:]]" }, { "code": null, "e": 14326, "s": 14312, "text": "Numbers [0-9]" }, { "code": null, "e": 14338, "s": 14326, "text": "[[:graph:]]" }, { "code": null, "e": 14383, "s": 14338, "text": "Any visible characters (excludes whitespace)" }, { "code": null, "e": 14395, "s": 14383, "text": "[[:lower:]]" }, { "code": null, "e": 14419, "s": 14395, "text": "Lowercase letters [a-z]" }, { "code": null, "e": 14431, "s": 14419, "text": "[[:print:]]" }, { "code": null, "e": 14477, "s": 14431, "text": "Printable characters (non-control characters)" }, { "code": null, "e": 14489, "s": 14477, "text": "[[:punct:]]" }, { "code": null, "e": 14512, "s": 14489, "text": "Punctuation characters" }, { "code": null, "e": 14524, "s": 14512, "text": "[[:space:]]" }, { "code": null, "e": 14535, "s": 14524, "text": "Whitespace" }, { "code": null, "e": 14547, "s": 14535, "text": "[[:upper:]]" }, { "code": null, "e": 14571, "s": 14547, "text": "Uppercase letters [A-Z]" }, { "code": null, "e": 14584, "s": 14571, "text": "[[:xdigit:]]" }, { "code": null, "e": 14609, "s": 14584, "text": "Hex digits [0-9 a-f A-F]" }, { "code": null, "e": 14788, "s": 14609, "text": "The sed metacharacter & represents the contents of the pattern that was matched. For instance, say you have a file called phone.txt full of phone numbers, such as the following −" }, { "code": null, "e": 14855, "s": 14788, "text": "5555551212\n5555551213\n5555551214\n6665551215\n6665551216\n7775551217\n" }, { "code": null, "e": 15019, "s": 14855, "text": "You want to make the area code (the first three digits) surrounded by parentheses for easier reading. To do this, you can use the ampersand replacement character −" }, { "code": null, "e": 15163, "s": 15019, "text": "$ sed -e 's/^[[:digit:]][[:digit:]][[:digit:]]/(&)/g' phone.txt\n(555)5551212\n(555)5551213\n(555)5551214\n(666)5551215\n\n(666)5551216\n(777)5551217\n" }, { "code": null, "e": 15308, "s": 15163, "text": "Here in the pattern part you are matching the first 3 digits and then using & you are replacing those 3 digits with the surrounding parentheses." }, { "code": null, "e": 15379, "s": 15308, "text": "You can use multiple sed commands in a single sed command as follows −" }, { "code": null, "e": 15438, "s": 15379, "text": "$ sed -e 'command1' -e 'command2' ... -e 'commandN' files\n" }, { "code": null, "e": 15605, "s": 15438, "text": "Here command1 through commandN are sed commands of the type discussed previously. These commands are applied to each of the lines in the list of files given by files." }, { "code": null, "e": 15688, "s": 15605, "text": "Using the same mechanism, we can write the above phone number example as follows −" }, { "code": null, "e": 15863, "s": 15688, "text": "$ sed -e 's/^[[:digit:]]\\{3\\}/(&)/g' \\ \n -e 's/)[[:digit:]]\\{3\\}/&-/g' phone.txt \n(555)555-1212 \n(555)555-1213 \n(555)555-1214 \n(666)555-1215 \n(666)555-1216 \n(777)555-1217\n" }, { "code": null, "e": 16155, "s": 15863, "text": "Note − In the above example, instead of repeating the character class keyword [[:digit:]] three times, we replaced it with \\{3\\}, which means the preceding regular expression is matched three times. We have also used \\ to give line break and this has to be removed before the command is run." }, { "code": null, "e": 16484, "s": 16155, "text": "The ampersand metacharacter is useful, but even more useful is the ability to define specific regions in regular expressions. These special regions can be used as reference in your replacement strings. By defining specific parts of a regular expression, you can then refer back to those parts with a special reference character." }, { "code": null, "e": 16778, "s": 16484, "text": "To do back references, you have to first define a region and then refer back to that region. To define a region, you insert backslashed parentheses around each region of interest. The first region that you surround with backslashes is then referenced by \\1, the second region by \\2, and so on." }, { "code": null, "e": 16822, "s": 16778, "text": "Assuming phone.txt has the following text −" }, { "code": null, "e": 16907, "s": 16822, "text": "(555)555-1212\n(555)555-1213\n(555)555-1214\n(666)555-1215\n(666)555-1216\n(777)555-1217\n" }, { "code": null, "e": 16935, "s": 16907, "text": "Try the following command −" }, { "code": null, "e": 17284, "s": 16935, "text": "$ cat phone.txt | sed 's/\\(.*)\\)\\(.*-\\)\\(.*$\\)/Area \\ \n code: \\1 Second: \\2 Third: \\3/' \nArea code: (555) Second: 555- Third: 1212 \nArea code: (555) Second: 555- Third: 1213 \nArea code: (555) Second: 555- Third: 1214 \nArea code: (666) Second: 555- Third: 1215 \nArea code: (666) Second: 555- Third: 1216 \nArea code: (777) Second: 555- Third: 1217\n" }, { "code": null, "e": 17497, "s": 17284, "text": "Note − In the above example, each regular expression inside the parenthesis would be back referenced by \\1, \\2 and so on. We have used \\ to give line break here. This should be removed before running the command." }, { "code": null, "e": 17532, "s": 17497, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 17560, "s": 17532, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 17594, "s": 17560, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 17611, "s": 17594, "text": " Frahaan Hussain" }, { "code": null, "e": 17644, "s": 17611, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 17655, "s": 17644, "text": " Pradeep D" }, { "code": null, "e": 17690, "s": 17655, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 17706, "s": 17690, "text": " Musab Zayadneh" }, { "code": null, "e": 17739, "s": 17706, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 17751, "s": 17739, "text": " GUHARAJANM" }, { "code": null, "e": 17783, "s": 17751, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 17791, "s": 17783, "text": " Uplatz" }, { "code": null, "e": 17798, "s": 17791, "text": " Print" }, { "code": null, "e": 17809, "s": 17798, "text": " Add Notes" } ]
Neo4j for Diseases. Disclaimer: This article does not... | by Sixing Huang | Towards Data Science
This article shows how to: 1. Use Neo4j to get quick overviews over the KEGG Disease database. 2. Identify multipurpose drugs. 3. Show details about some pathogens such as SARS-CoV-2. 4. Form disease communities with Louvain and discover the most connected diseases with PageRank. SARS and COVID-19 are isolated “islands” separated from other large disease clusters. Disclaimer: This article does not provide medical advice. It is intended for informational purposes only. It is not a substitute for professional medical advice, diagnosis or treatment. COVID-19 has the world by the short hairs. This contagious disease has taken a heavy toll on our lives. It disrupts many families, causes enormous economic losses and perhaps forever changes our behavior. As a result, it raises our awareness of the public health issue. It becomes immediately clear that we the human race need to invest more in the medical research to avert the next calamity. Since my last story “Analyzing Genomes in a Graph Database”, I have noticed that there are still many treasures in the Kyoto Encyclopedia of Genes and Genomes (KEGG) database. One of them is without doubt the KEGG Disease Database. This database contains details about many known human diseases. Moreover, together with other databases such as Genome, Drug and Genes, KEGG provides us with a very extensive network of knowledge about disorders, their causes and drugs. As I mentioned in my article, a graph database like Neo4j is instrumental to knowledge discovery in biomedical research. This trove of information from KEGG is perfect for such a data project. Therefore, I have downloaded and processed the data from the KEGG Disease Database via API, imported them into Neo4j, run several analyses and have discovered some interesting information. In this article, I am going to focus on the relations among diseases, pathogens and drugs. The code for this project is hosted on my Github repository: github.com All the CSV files are located in the data folder. If you want to update the information, you can follow the instruction in my repo README.md. Download Neo4j Desktop from their official website. Once installed, add a new “Local DMBS” and name it “kegg_disease”. Open its Import folder by clicking through “...” -> “Open folder” -> “Import”. Put all the CSV files inside the folder. Afterwards, run the following commands and they will import all the information: Once the data are imported, we can have some basic statistics over the KEGG Disease database. These three commands get the total counts of all three types of nodes: So there are 333 kinds of pathogens, 1,339 drugs and 2,498 diseases recorded in the database. That is a sizeable dataset. We can also have a look at the topology of the data with Neo4j Bloom. Enter the following Cypher query in a search phrase and execute it (my previous article showed the detailed steps): MATCH p=(n:disease) <-[]-() RETURN p; Run the following command to get the top ten disease categories in the dataset. Be cautious though that some diseases such as Schwartz-Jampel syndrome and centronuclear myopathy are put into two categories and the query will not double-count them separately.: And you will be greeted with this result: To my surprise, under this query, the top spot was taken neither by infectious disease nor by the two notorious killers — cardiovascular disease and cancer. It was congenital malformation, including Nail-patella syndrome and Meckel syndrome. Infectious diseases can be caused by viruses, bacteria or eukaryota. The following command will show the numbers of each in the database: And the results are: Again, to my surprise, bacteria, not the viruses, are the most frequent pathogens in the data. We can look further inside the viruses by issuing: This query combines both the first and second levels of the taxonomy and tallies them. As you can see, Riboviria is the most abundant viral realm. But Riboviria is also a very diverse taxonomic group. Both SARS-CoV-2 and its predecessor SARS coronavirus, the causal agents for the 2002–2004 SARS outbreak, belong to Riboviria. But so do human immunodeficiency viruses (HIV) and hepatitis viruses. Finally, we can get the number of drugs against infectious diseases by issuing: The query returns 293 kinds of drugs. It is noteworthy that the “DISTINCT” keyword is necessary here, because some drugs can be administered to treat multiple diseases and they would have been double-counted without the “DISTINCT”. Multipurpose drugs are medications that can be used to treat more than one diseases. In other words, they are versatile. Because medications are expensive to develop and require vigorous clinical trials, so if an “old drug can do new tricks” (watch NIH’s director Francis Collins’ enlightening TED talk here), it is without doubt great news for both the patients and the pharmaceutical companies. In practice, medications are carefully regulated by authorities such as the FDA in USA and manufacturers can only market them for indications approved by the FDA. So it will be very interesting to find out what are the most versatile drugs in the data and what indications that they have. Issue the following command to see the top ten most versatile medicines: And the results are: The top ten list basically consists of two classes of drugs: steroid hormones and tetracycline antibiotic doxycycline. Steroid hormones are used to suppress the immune system and treat a variety of inflammatory conditions. The third in the list, Dexamethasone, has been studied under COVID-19 patients and the preliminary results showed that it reduced mortality rate among those who were receiving either invasive mechanical ventilation or oxygen alone but not among those receiving no respiratory support (The RECOVERY Collaborative Group, 2020). Doxycycline is a broad-spectrum antibiotic and used in the treatment of infectious diseases such as malaria, Lyme disease, cholera and syphilis. In fact, the following query shows that the indications for these steroid hormones greatly overlap each other, while doxycycline and its derivatives also target many of the same diseases. For example, the top two drugs in the list: prednisone and its active form prednisolone, have been approved for medical use in the United States since 1955. And they are popular: prednisone is the 21th and prednisolone is the 134th most prescribed medication in USA in 2021 so far according to DrugStats Database. Issue these two commands one by one to see the details of prednisolone sodium phosphate: And the query returns And: As it turned out, prednisolone is not only used to treat immune system disease, but also infectious diseases such as trichinosis and tuberculosis. It is also used in chronic obstructive pulmonary disease (COPD) for its anti-inflammatory effects. Its use in idiopathic pulmonary fibrosis (IPF) is however less certain. As to the most prescribed drug in 2021 so far in USA — Atorvastatin and its derivatives, their uses are limited to four metabolic or cardiovascular diseases: hyperlipidemia, familial hypercholesterolemia, Angina pectoris and myocardial infarction. Now it is time to explore the pathogen data. First, we can count how many different diseases that a pathogen can cause. All the top ten are viruses. The top two are papillomaviruses that can lead to different kinds of cancer in human. According to Wikipedia, most papillomavirus infections are asymptomatic and 90% of the cases go away within two years. But in other cases, they persist and results in either warts or lesions. These lesions increase the risk of cancer along the various tracts in the human body such as cervix, vulva, vagina, penis, anus, mouth, tonsils, or throat (Figure 5.). Nearly all cervical cancer is caused by HPV; And these top two strains account for 70% of cases. HPV16 alone is responsible for almost 90% of HPV-positive oropharyngeal cancers. In contrast, both SARS and SARS-CoV-2 are connected to one disease each. SARS caused the 2002–2004 SARS pandemic in China and so far there is no antiviral therapy for it. For COVID-19, KEGG lists the drug remdesivir. Siemieniuk et al. conducted a living systematic review (read it here) and stated that remdesivir may shorten the COVID symptoms. The antimalarial drug Hydroxychloroquine sulfate is NOT considered as a treatment to COVID-19 in KEGG. It echoes one of the conclusions in Siemieniuk’s study: Hydroxychloroquine may not reduce mortality or mechanical ventilation, and it seems unlikely to have any other benefits (for COVID-19). The topology in Figure 2. has some intriguing features. Many small networks surround a large cluster of interconnected dots. It will be interesting to determine those clusters and identify some of the most connected nodes, the so-called hubs. Fortunately, Neo4j provides us with a very powerful plugin: Graph Data Science (gds) to handle these sorts of tasks. First go to the project detail tab in Neo4j Desktop and install the plugin: In Neo4j, graph algorithms run on graph projections. To begin, we put all our nodes and edges into a named graph projection called “disease-graph” with Cypher. Now we can run the Louvain algorithm onto it to identify clusters or communities. This algorithm condenses close connected nodes into larger nodes and repeats until no condensation is possible. First, we ask how many communities can be formed: Out of 4,170 nodes, the Louvian algorithm could create 2,120 communities. I ran this query with different parameters such “maxIterations” and “tolerance” but could not see any big differences. We can check the largest communities and see their members: It returns: Now we can check the members in community “3421” with: And the members are: After going through the list it is clear that this community contains mainly tumor-related items. Pathogens such as Hepatitis B and D viruses that are known to increase cancer risk are also in this community. You can analyze the communities further. My own community analyses show that diseases in large clusters are those that have received the most research attention and they are well connected either through common pathogens or versatile drugs. In contrast, many isolated “islands” are rare diseases such as Christianson syndrome or Zimmermann-Laband syndrome. It is noteworthy that SARS and COVID-19 are two isolated “islands” (Figure 2.) even though they caused sensational pandemics. The message is also clear: we still know very little about COVID-19 relatively. Finally, we can use PageRank to check which nodes in the graph are well-connected: And the top results are: No drug or pathogen nodes made it into the top twelve most important list, all are diseases. This can be explained on the one hand that every pathogen and drug is guaranteed to be connected to a disease node in our data model. So disease nodes are by default quite central from the start. On the other hand, this top list consists of some of the most common human sufferings in the modern world and a lot of drugs have been developed to tackled them. In fact, with a more complex query we can count the drugs associated with these top disorders: As the results show, 103 drugs are indicated for the treatment of high blood pressure, the top node in the list. Psoriasis, as the last one on this list, affects 2–4% of the western population but it is treated with 34 drugs in the database. However, the drug amount ranking did not follow exactly the PageRank. For example, there were 48 drugs for rheumatoid arthritis, that is more than those of the higher ranked diseases such as breast cancer, major depressive disorder and schiziphrenia. This project is another example that demonstrates the power of Neo4j in biomedical research. Once imported, we can gain lots of quick numbers and details about diseases at our fingertips. If done in a relational database, we would have needed three tables to model the data, instead of the one in Neo4j. In addition, the Cypher queries are straightforward to formulate and for readers to understand without any “JOIN”. Finally, in a graph database we can run graph algorithms onto the data and discover some interesting new insights with ease. That is not to say that we should abandon other databases. Graph database is a good choice when our data contains lots of connections, such as our previous project and the KEGG Disease project here. In the case of simple tallies, such as price tables, we should use a relational database. For documents, we should consider document databases such as MongoDB. Time series also has its own kind of databases such as Amazon Timestream or InfluxDB. This project also taught us valuable lessons about diseases and health. One of them is about our immune system. During the current COVID-19 pandemic, we are more likely to buy into one of those many “boost your immune system” commercials. But our immune system is very delicate and we by no means want to see it go into overdrive. On the contrary, the analysis above showed that some of the most versatile and widely used drugs are actually immunosuppressants, drugs that suppress the immune system. And Johns Hopkins University estimated that 3% of the American population suffer from autoimmune diseases, that is around ten million people! It reminds me of a paragraph in An Elegant Defense by Matt Richtel, when hearing ads promising to boost the immune system, Dr Anthony Fauci said “It almost makes me chuckle. First of all, it is assuming your immune system needs boosting, which it very likely doesn’t. If you do successfully boost your immune system, you might boost it to do something bad.” This project only covers a small part of the KEGG: disease, drug and pathogen. I can only wonder what kind of new insights we can gain if we utilize all the information stored in KEGG. Therefore, I encourage you to use graph database to further explore this data treasure trove and show me the things you discover along the way. This article has been translated into Chinese by myself: https://blog.csdn.net/dgg32/article/details/119081851
[ { "code": null, "e": 198, "s": 171, "text": "This article shows how to:" }, { "code": null, "e": 266, "s": 198, "text": "1. Use Neo4j to get quick overviews over the KEGG Disease database." }, { "code": null, "e": 298, "s": 266, "text": "2. Identify multipurpose drugs." }, { "code": null, "e": 355, "s": 298, "text": "3. Show details about some pathogens such as SARS-CoV-2." }, { "code": null, "e": 538, "s": 355, "text": "4. Form disease communities with Louvain and discover the most connected diseases with PageRank. SARS and COVID-19 are isolated “islands” separated from other large disease clusters." }, { "code": null, "e": 724, "s": 538, "text": "Disclaimer: This article does not provide medical advice. It is intended for informational purposes only. It is not a substitute for professional medical advice, diagnosis or treatment." }, { "code": null, "e": 1118, "s": 724, "text": "COVID-19 has the world by the short hairs. This contagious disease has taken a heavy toll on our lives. It disrupts many families, causes enormous economic losses and perhaps forever changes our behavior. As a result, it raises our awareness of the public health issue. It becomes immediately clear that we the human race need to invest more in the medical research to avert the next calamity." }, { "code": null, "e": 1969, "s": 1118, "text": "Since my last story “Analyzing Genomes in a Graph Database”, I have noticed that there are still many treasures in the Kyoto Encyclopedia of Genes and Genomes (KEGG) database. One of them is without doubt the KEGG Disease Database. This database contains details about many known human diseases. Moreover, together with other databases such as Genome, Drug and Genes, KEGG provides us with a very extensive network of knowledge about disorders, their causes and drugs. As I mentioned in my article, a graph database like Neo4j is instrumental to knowledge discovery in biomedical research. This trove of information from KEGG is perfect for such a data project. Therefore, I have downloaded and processed the data from the KEGG Disease Database via API, imported them into Neo4j, run several analyses and have discovered some interesting information." }, { "code": null, "e": 2121, "s": 1969, "text": "In this article, I am going to focus on the relations among diseases, pathogens and drugs. The code for this project is hosted on my Github repository:" }, { "code": null, "e": 2132, "s": 2121, "text": "github.com" }, { "code": null, "e": 2274, "s": 2132, "text": "All the CSV files are located in the data folder. If you want to update the information, you can follow the instruction in my repo README.md." }, { "code": null, "e": 2594, "s": 2274, "text": "Download Neo4j Desktop from their official website. Once installed, add a new “Local DMBS” and name it “kegg_disease”. Open its Import folder by clicking through “...” -> “Open folder” -> “Import”. Put all the CSV files inside the folder. Afterwards, run the following commands and they will import all the information:" }, { "code": null, "e": 2759, "s": 2594, "text": "Once the data are imported, we can have some basic statistics over the KEGG Disease database. These three commands get the total counts of all three types of nodes:" }, { "code": null, "e": 3067, "s": 2759, "text": "So there are 333 kinds of pathogens, 1,339 drugs and 2,498 diseases recorded in the database. That is a sizeable dataset. We can also have a look at the topology of the data with Neo4j Bloom. Enter the following Cypher query in a search phrase and execute it (my previous article showed the detailed steps):" }, { "code": null, "e": 3105, "s": 3067, "text": "MATCH p=(n:disease) <-[]-() RETURN p;" }, { "code": null, "e": 3365, "s": 3105, "text": "Run the following command to get the top ten disease categories in the dataset. Be cautious though that some diseases such as Schwartz-Jampel syndrome and centronuclear myopathy are put into two categories and the query will not double-count them separately.:" }, { "code": null, "e": 3407, "s": 3365, "text": "And you will be greeted with this result:" }, { "code": null, "e": 3649, "s": 3407, "text": "To my surprise, under this query, the top spot was taken neither by infectious disease nor by the two notorious killers — cardiovascular disease and cancer. It was congenital malformation, including Nail-patella syndrome and Meckel syndrome." }, { "code": null, "e": 3787, "s": 3649, "text": "Infectious diseases can be caused by viruses, bacteria or eukaryota. The following command will show the numbers of each in the database:" }, { "code": null, "e": 3808, "s": 3787, "text": "And the results are:" }, { "code": null, "e": 3954, "s": 3808, "text": "Again, to my surprise, bacteria, not the viruses, are the most frequent pathogens in the data. We can look further inside the viruses by issuing:" }, { "code": null, "e": 4041, "s": 3954, "text": "This query combines both the first and second levels of the taxonomy and tallies them." }, { "code": null, "e": 4351, "s": 4041, "text": "As you can see, Riboviria is the most abundant viral realm. But Riboviria is also a very diverse taxonomic group. Both SARS-CoV-2 and its predecessor SARS coronavirus, the causal agents for the 2002–2004 SARS outbreak, belong to Riboviria. But so do human immunodeficiency viruses (HIV) and hepatitis viruses." }, { "code": null, "e": 4431, "s": 4351, "text": "Finally, we can get the number of drugs against infectious diseases by issuing:" }, { "code": null, "e": 4663, "s": 4431, "text": "The query returns 293 kinds of drugs. It is noteworthy that the “DISTINCT” keyword is necessary here, because some drugs can be administered to treat multiple diseases and they would have been double-counted without the “DISTINCT”." }, { "code": null, "e": 5349, "s": 4663, "text": "Multipurpose drugs are medications that can be used to treat more than one diseases. In other words, they are versatile. Because medications are expensive to develop and require vigorous clinical trials, so if an “old drug can do new tricks” (watch NIH’s director Francis Collins’ enlightening TED talk here), it is without doubt great news for both the patients and the pharmaceutical companies. In practice, medications are carefully regulated by authorities such as the FDA in USA and manufacturers can only market them for indications approved by the FDA. So it will be very interesting to find out what are the most versatile drugs in the data and what indications that they have." }, { "code": null, "e": 5422, "s": 5349, "text": "Issue the following command to see the top ten most versatile medicines:" }, { "code": null, "e": 5443, "s": 5422, "text": "And the results are:" }, { "code": null, "e": 6325, "s": 5443, "text": "The top ten list basically consists of two classes of drugs: steroid hormones and tetracycline antibiotic doxycycline. Steroid hormones are used to suppress the immune system and treat a variety of inflammatory conditions. The third in the list, Dexamethasone, has been studied under COVID-19 patients and the preliminary results showed that it reduced mortality rate among those who were receiving either invasive mechanical ventilation or oxygen alone but not among those receiving no respiratory support (The RECOVERY Collaborative Group, 2020). Doxycycline is a broad-spectrum antibiotic and used in the treatment of infectious diseases such as malaria, Lyme disease, cholera and syphilis. In fact, the following query shows that the indications for these steroid hormones greatly overlap each other, while doxycycline and its derivatives also target many of the same diseases." }, { "code": null, "e": 6728, "s": 6325, "text": "For example, the top two drugs in the list: prednisone and its active form prednisolone, have been approved for medical use in the United States since 1955. And they are popular: prednisone is the 21th and prednisolone is the 134th most prescribed medication in USA in 2021 so far according to DrugStats Database. Issue these two commands one by one to see the details of prednisolone sodium phosphate:" }, { "code": null, "e": 6750, "s": 6728, "text": "And the query returns" }, { "code": null, "e": 6755, "s": 6750, "text": "And:" }, { "code": null, "e": 7073, "s": 6755, "text": "As it turned out, prednisolone is not only used to treat immune system disease, but also infectious diseases such as trichinosis and tuberculosis. It is also used in chronic obstructive pulmonary disease (COPD) for its anti-inflammatory effects. Its use in idiopathic pulmonary fibrosis (IPF) is however less certain." }, { "code": null, "e": 7321, "s": 7073, "text": "As to the most prescribed drug in 2021 so far in USA — Atorvastatin and its derivatives, their uses are limited to four metabolic or cardiovascular diseases: hyperlipidemia, familial hypercholesterolemia, Angina pectoris and myocardial infarction." }, { "code": null, "e": 7441, "s": 7321, "text": "Now it is time to explore the pathogen data. First, we can count how many different diseases that a pathogen can cause." }, { "code": null, "e": 8094, "s": 7441, "text": "All the top ten are viruses. The top two are papillomaviruses that can lead to different kinds of cancer in human. According to Wikipedia, most papillomavirus infections are asymptomatic and 90% of the cases go away within two years. But in other cases, they persist and results in either warts or lesions. These lesions increase the risk of cancer along the various tracts in the human body such as cervix, vulva, vagina, penis, anus, mouth, tonsils, or throat (Figure 5.). Nearly all cervical cancer is caused by HPV; And these top two strains account for 70% of cases. HPV16 alone is responsible for almost 90% of HPV-positive oropharyngeal cancers." }, { "code": null, "e": 8440, "s": 8094, "text": "In contrast, both SARS and SARS-CoV-2 are connected to one disease each. SARS caused the 2002–2004 SARS pandemic in China and so far there is no antiviral therapy for it. For COVID-19, KEGG lists the drug remdesivir. Siemieniuk et al. conducted a living systematic review (read it here) and stated that remdesivir may shorten the COVID symptoms." }, { "code": null, "e": 8543, "s": 8440, "text": "The antimalarial drug Hydroxychloroquine sulfate is NOT considered as a treatment to COVID-19 in KEGG." }, { "code": null, "e": 8599, "s": 8543, "text": "It echoes one of the conclusions in Siemieniuk’s study:" }, { "code": null, "e": 8735, "s": 8599, "text": "Hydroxychloroquine may not reduce mortality or mechanical ventilation, and it seems unlikely to have any other benefits (for COVID-19)." }, { "code": null, "e": 9095, "s": 8735, "text": "The topology in Figure 2. has some intriguing features. Many small networks surround a large cluster of interconnected dots. It will be interesting to determine those clusters and identify some of the most connected nodes, the so-called hubs. Fortunately, Neo4j provides us with a very powerful plugin: Graph Data Science (gds) to handle these sorts of tasks." }, { "code": null, "e": 9171, "s": 9095, "text": "First go to the project detail tab in Neo4j Desktop and install the plugin:" }, { "code": null, "e": 9331, "s": 9171, "text": "In Neo4j, graph algorithms run on graph projections. To begin, we put all our nodes and edges into a named graph projection called “disease-graph” with Cypher." }, { "code": null, "e": 9575, "s": 9331, "text": "Now we can run the Louvain algorithm onto it to identify clusters or communities. This algorithm condenses close connected nodes into larger nodes and repeats until no condensation is possible. First, we ask how many communities can be formed:" }, { "code": null, "e": 9768, "s": 9575, "text": "Out of 4,170 nodes, the Louvian algorithm could create 2,120 communities. I ran this query with different parameters such “maxIterations” and “tolerance” but could not see any big differences." }, { "code": null, "e": 9828, "s": 9768, "text": "We can check the largest communities and see their members:" }, { "code": null, "e": 9840, "s": 9828, "text": "It returns:" }, { "code": null, "e": 9895, "s": 9840, "text": "Now we can check the members in community “3421” with:" }, { "code": null, "e": 9916, "s": 9895, "text": "And the members are:" }, { "code": null, "e": 10125, "s": 9916, "text": "After going through the list it is clear that this community contains mainly tumor-related items. Pathogens such as Hepatitis B and D viruses that are known to increase cancer risk are also in this community." }, { "code": null, "e": 10688, "s": 10125, "text": "You can analyze the communities further. My own community analyses show that diseases in large clusters are those that have received the most research attention and they are well connected either through common pathogens or versatile drugs. In contrast, many isolated “islands” are rare diseases such as Christianson syndrome or Zimmermann-Laband syndrome. It is noteworthy that SARS and COVID-19 are two isolated “islands” (Figure 2.) even though they caused sensational pandemics. The message is also clear: we still know very little about COVID-19 relatively." }, { "code": null, "e": 10771, "s": 10688, "text": "Finally, we can use PageRank to check which nodes in the graph are well-connected:" }, { "code": null, "e": 10796, "s": 10771, "text": "And the top results are:" }, { "code": null, "e": 11342, "s": 10796, "text": "No drug or pathogen nodes made it into the top twelve most important list, all are diseases. This can be explained on the one hand that every pathogen and drug is guaranteed to be connected to a disease node in our data model. So disease nodes are by default quite central from the start. On the other hand, this top list consists of some of the most common human sufferings in the modern world and a lot of drugs have been developed to tackled them. In fact, with a more complex query we can count the drugs associated with these top disorders:" }, { "code": null, "e": 11835, "s": 11342, "text": "As the results show, 103 drugs are indicated for the treatment of high blood pressure, the top node in the list. Psoriasis, as the last one on this list, affects 2–4% of the western population but it is treated with 34 drugs in the database. However, the drug amount ranking did not follow exactly the PageRank. For example, there were 48 drugs for rheumatoid arthritis, that is more than those of the higher ranked diseases such as breast cancer, major depressive disorder and schiziphrenia." }, { "code": null, "e": 12379, "s": 11835, "text": "This project is another example that demonstrates the power of Neo4j in biomedical research. Once imported, we can gain lots of quick numbers and details about diseases at our fingertips. If done in a relational database, we would have needed three tables to model the data, instead of the one in Neo4j. In addition, the Cypher queries are straightforward to formulate and for readers to understand without any “JOIN”. Finally, in a graph database we can run graph algorithms onto the data and discover some interesting new insights with ease." }, { "code": null, "e": 12824, "s": 12379, "text": "That is not to say that we should abandon other databases. Graph database is a good choice when our data contains lots of connections, such as our previous project and the KEGG Disease project here. In the case of simple tallies, such as price tables, we should use a relational database. For documents, we should consider document databases such as MongoDB. Time series also has its own kind of databases such as Amazon Timestream or InfluxDB." }, { "code": null, "e": 13611, "s": 12824, "text": "This project also taught us valuable lessons about diseases and health. One of them is about our immune system. During the current COVID-19 pandemic, we are more likely to buy into one of those many “boost your immune system” commercials. But our immune system is very delicate and we by no means want to see it go into overdrive. On the contrary, the analysis above showed that some of the most versatile and widely used drugs are actually immunosuppressants, drugs that suppress the immune system. And Johns Hopkins University estimated that 3% of the American population suffer from autoimmune diseases, that is around ten million people! It reminds me of a paragraph in An Elegant Defense by Matt Richtel, when hearing ads promising to boost the immune system, Dr Anthony Fauci said" }, { "code": null, "e": 13824, "s": 13611, "text": "“It almost makes me chuckle. First of all, it is assuming your immune system needs boosting, which it very likely doesn’t. If you do successfully boost your immune system, you might boost it to do something bad.”" }, { "code": null, "e": 14153, "s": 13824, "text": "This project only covers a small part of the KEGG: disease, drug and pathogen. I can only wonder what kind of new insights we can gain if we utilize all the information stored in KEGG. Therefore, I encourage you to use graph database to further explore this data treasure trove and show me the things you discover along the way." } ]
How to use LINQ to sort a list in C#?
Use the LINQ orderby keyword to sort a list in C#. In the below example, we have set the orderby for the elements − var myLen = from element in myList orderby element.Length select element; Let us see an example − Live Demo using System; using System.Collections.Generic; using System.Linq; class Demo { static void Main() { List <string> myList = new List<string>(); myList.Add("truck"); myList.Add("bus"); myList.Add("cab"); myList.Add("motorbike"); var myLen = from element in myList orderby element.Length select element; foreach (string str in myLen) { Console.WriteLine(str); } } } The above will produce the following result. The word with less number of characters will be displayed first like an ascending order list − bus cab truck motorbike
[ { "code": null, "e": 1113, "s": 1062, "text": "Use the LINQ orderby keyword to sort a list in C#." }, { "code": null, "e": 1178, "s": 1113, "text": "In the below example, we have set the orderby for the elements −" }, { "code": null, "e": 1252, "s": 1178, "text": "var myLen = from element in myList\norderby element.Length\nselect element;" }, { "code": null, "e": 1276, "s": 1252, "text": "Let us see an example −" }, { "code": null, "e": 1287, "s": 1276, "text": " Live Demo" }, { "code": null, "e": 1729, "s": 1287, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Demo {\n static void Main() {\n List <string> myList = new List<string>();\n myList.Add(\"truck\");\n myList.Add(\"bus\");\n myList.Add(\"cab\");\n myList.Add(\"motorbike\");\n\n var myLen = from element in myList\n orderby element.Length\n select element;\n\n foreach (string str in myLen) {\n Console.WriteLine(str);\n }\n }\n}" }, { "code": null, "e": 1869, "s": 1729, "text": "The above will produce the following result. The word with less number of characters will be displayed first like an ascending order list −" }, { "code": null, "e": 1893, "s": 1869, "text": "bus\ncab\ntruck\nmotorbike" } ]
How to Set a Tkinter Window With a Constant Size? - GeeksforGeeks
14 May, 2021 Prerequisite: Python GUI – tkinter minsize maxsize The task here is to produce a Tkinter window with a constant size. A window with a constant size cannot be resized as per users’ convenience, it holds its dimensions rigidly. A normal window on the other hand can be resized. Approach Import module Declare Tkinter object Create a fixed sized window using maxsize() and minsize() functions. Syntax: Here, height and width are in pixels. minsize(height, width) In Tkinter, minsize() method is used to set the minimum size of the Tkinter window. Using this method a user can set window’s initialized size to its minimum size, and still be able to maximize and scale the window larger. maxsize(height, width) This method is used to set the maximum size of the root window. User will still be able to shrink the size of the window to the minimum possible. Program 1: Creating a normal window Python3 # Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry("400x400") # Execute tkinterroot.mainloop() Output: Program 2: Creating a window with constant size Python3 # Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry("400x400") # set minimum window size valueroot.minsize(400, 400) # set maximum window size valueroot.maxsize(400, 400) # Execute tkinterroot.mainloop() Output: surinderdawra388 Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Python Classes and Objects Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n14 May, 2021" }, { "code": null, "e": 23915, "s": 23901, "text": "Prerequisite:" }, { "code": null, "e": 23936, "s": 23915, "text": "Python GUI – tkinter" }, { "code": null, "e": 23944, "s": 23936, "text": "minsize" }, { "code": null, "e": 23952, "s": 23944, "text": "maxsize" }, { "code": null, "e": 24177, "s": 23952, "text": "The task here is to produce a Tkinter window with a constant size. A window with a constant size cannot be resized as per users’ convenience, it holds its dimensions rigidly. A normal window on the other hand can be resized." }, { "code": null, "e": 24186, "s": 24177, "text": "Approach" }, { "code": null, "e": 24200, "s": 24186, "text": "Import module" }, { "code": null, "e": 24223, "s": 24200, "text": "Declare Tkinter object" }, { "code": null, "e": 24292, "s": 24223, "text": "Create a fixed sized window using maxsize() and minsize() functions." }, { "code": null, "e": 24300, "s": 24292, "text": "Syntax:" }, { "code": null, "e": 24338, "s": 24300, "text": "Here, height and width are in pixels." }, { "code": null, "e": 24361, "s": 24338, "text": "minsize(height, width)" }, { "code": null, "e": 24584, "s": 24361, "text": "In Tkinter, minsize() method is used to set the minimum size of the Tkinter window. Using this method a user can set window’s initialized size to its minimum size, and still be able to maximize and scale the window larger." }, { "code": null, "e": 24607, "s": 24584, "text": "maxsize(height, width)" }, { "code": null, "e": 24753, "s": 24607, "text": "This method is used to set the maximum size of the root window. User will still be able to shrink the size of the window to the minimum possible." }, { "code": null, "e": 24789, "s": 24753, "text": "Program 1: Creating a normal window" }, { "code": null, "e": 24797, "s": 24789, "text": "Python3" }, { "code": "# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry(\"400x400\") # Execute tkinterroot.mainloop()", "e": 24932, "s": 24797, "text": null }, { "code": null, "e": 24940, "s": 24932, "text": "Output:" }, { "code": null, "e": 24990, "s": 24942, "text": "Program 2: Creating a window with constant size" }, { "code": null, "e": 24998, "s": 24990, "text": "Python3" }, { "code": "# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry(\"400x400\") # set minimum window size valueroot.minsize(400, 400) # set maximum window size valueroot.maxsize(400, 400) # Execute tkinterroot.mainloop()", "e": 25241, "s": 24998, "text": null }, { "code": null, "e": 25249, "s": 25241, "text": "Output:" }, { "code": null, "e": 25266, "s": 25249, "text": "surinderdawra388" }, { "code": null, "e": 25281, "s": 25266, "text": "Python-tkinter" }, { "code": null, "e": 25288, "s": 25281, "text": "Python" }, { "code": null, "e": 25386, "s": 25288, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25395, "s": 25386, "text": "Comments" }, { "code": null, "e": 25408, "s": 25395, "text": "Old Comments" }, { "code": null, "e": 25440, "s": 25408, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25496, "s": 25440, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25538, "s": 25496, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25580, "s": 25538, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25616, "s": 25580, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 25655, "s": 25616, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25677, "s": 25655, "text": "Defaultdict in Python" }, { "code": null, "e": 25708, "s": 25677, "text": "Python | os.path.join() method" }, { "code": null, "e": 25735, "s": 25708, "text": "Python Classes and Objects" } ]
Explainable AI (XAI) with SHAP -Multi-Class Classification Problem | by Idit Cohen | Towards Data Science
Model explainability becomes a basic part of the machine learning pipeline. Keeping a machine learning model as a “black box” is not an option anymore. Luckily there are analytical tools such as (lime, ExplainerDashboard, Shapash, Dalex, and more) that are evolving rapidly and becoming more popular. In a previous post, we explained how to use SHAP for a regression problem. This guide provides a practical example of how to use and interpret the open-source python package, SHAP, for XAI analysis in Multi-class classification problems and use it to improve the model. SHAP (Shapley Additive Explanations) by Lundberg and Lee (2016) is a method to explain individual predictions, based on the game theoretically optimal Shapley values[1]. Calculating Shapley value to get feature contributions is computationally expensive. There are two methods to approximate SHAP values to improve computation efficiency: KernelSHAP, TreeSHAP (for tree-based models only). SHAP provides global and local interpretation methods based on aggregations of Shapley values. In this guide we will use the Internet Firewall Data Set example from Kaggle datasets [2], to demonstrate some of the SHAP output plots for a multiclass classification problem. # load the csv file as a data framedf = pd.read_csv('log2.csv')y = df.Action.copy()X = df.drop('Action',axis=1) Create the model and fit like you always do. X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, random_state=0)cls = RandomForestClassifier(max_depth=2, random_state=0)cls.fit(X_train, y_train) Now, just to get a basic impression of the model, I recommend viewing the feature importers and confusion matrix. Just to understand where we stand with the feature importance, I used scikit-learn that computes the impurity decrease within each tree [3]. ֫importances = cls.feature_importances_indices = np.argsort(importances)features = df.columnsplt.title('Feature Importances')plt.barh(range(len(indices)), importances[indices], color='g', align='center')plt.yticks(range(len(indices)), [features[i] for i in indices])plt.xlabel('Relative Importance')plt.show() Later we can compare these results to the feature importance calculated by the Shapley values. A confusion matrix is a way to visualize the performance of a model. And more important we can easily see where the model fails exactly. class_names = ['drop', 'allow', 'deny', 'reset-both']disp = plot_confusion_matrix(cls, X_test, y_test, display_labels=class_names, cmap=plt.cm.Blues, xticks_rotation='vertical') The model could not detect any instance from the class reset-both. The reason is an unbalanced dataset that gives a low number of examples of reset-both class to learn from. y.value_counts()allow 37640deny 14987drop 12851reset-both 54Name: Action, dtype: int64 SHAP values of a model’s output explain how features impact the output of the model. # compute SHAP valuesexplainer = shap.TreeExplainer(cls)shap_values = explainer.shap_values(X) Now we can plot relevant plots that will help us analyze the model. shap.summary_plot(shap_values, X.values, plot_type="bar", class_names= class_names, feature_names = X.columns) In this plot, the impact of a feature on the classes is stacked to create the feature importance plot. Thus, if you created features in order to differentiate a particular class from the rest, that is the plot where you can see it. In other words, summary plot for multiclass classification can show you what the machine managed to learn from the features. In the example below we can see that the class drop hardly uses the features Destination Plot, Source Port, and Bytes Sent. We can also see that the classes allow and deny uses the same features equally. That is the reason the confusion between them is relatively high. In order to separate better between the allow and deny classes, one needs to generate new features that uniquely be dedicated towards these classes. You can also see the summary_plot of a specific class. shap.summary_plot(shap_values[1], X.values, feature_names = X.columns) The summary plot combines feature importance with feature effects. Each point on the summary plot is a Shapley value for a feature and an instance. The position on the y-axis is determined by the feature and on the x-axis by the Shapley value. You can see that the feature pkts_sent, being the least important feature, has low Shapley values. The color represents the value of the feature from low to high. Overlapping points are jittered in the y-axis direction, so we get a sense of the distribution of the Shapley values per feature. The features are ordered according to their importance. In the summary plot, we see the first indications of the relationship between the value of a feature and the impact on the prediction. But to see the exact form of the relationship, we have to look at SHAP dependence plots. The partial dependence plot (short PDP or PD plot) shows the marginal effect one or two features have on the predicted outcome of a machine learning model (J. H. Friedman 2001 [3]). A partial dependence plot can show whether the relationship between the target and a feature is linear, monotonic, or more complex. The partial dependence plot is a global method: The method considers all instances and gives a statement about the global relationship of a feature with the predicted outcome. The PDP assumes that the first feature is not correlated with the second feature. If this assumption is violated, the averages calculated for the partial dependence plot will include data points that are very unlikely or even impossible. A dependence plot is a scatter plot that shows the effect a single feature has on the predictions made by the model. In this example, the property value increases significantly when the average number of rooms per dwelling is higher than 6. Each dot is a single prediction (row) from the dataset. The x-axis is the actual value from the dataset. The y-axis is the SHAP value for that feature, which represents how much knowing that feature’s value changes the output of the model for that sample’s prediction. The color corresponds to a second feature that may have an interaction effect with the feature we are plotting (by default this second feature is chosen automatically). If an interaction effect is present between this other feature and the feature we are plotting it will show up as a distinct vertical pattern of coloring. ֫# If we pass a numpy array instead of a data frame then we# need pass the feature names in separatelyshap.dependence_plot(0, shap_values[0], X.values, feature_names=X.columns) In the example above we can see a clear vertical pattern of coloring for the interaction between the features, Source Port and NAT Source Port. Force plot gives us the explainability of a single model prediction. In this plot, we can see how features contributed to the model’s prediction for a specific observation. It is very convenient to use for error analysis or a deep understanding of a particular case. i=8shap.force_plot(explainer.expected_value[0], shap_values[0][i], X.values[i], feature_names = X.columns) From the plot we can see: The model predict_proba value: 0.79The base value: this is the value that would be predicted if we didn’t know any features for the current instance. The base value is the average of the model output over the training dataset (explainer.expected_value in the code). In this example base value = 0.5749The numbers on the plot arrows are the value of the feature for this instance. Elapsed Time (sec)=5 and Packets = 1Red represents features that pushed the model score higher, and blue representing features that pushed the score lower.The bigger the arrow, the bigger the impact of the feature on the output. The amount of decrease or increase in the impact can be seen on the x-axis.Elapsed Time of 5 seconds increases the property that the class is allow, Packets of 6.546 reduce the property value. The model predict_proba value: 0.79 The base value: this is the value that would be predicted if we didn’t know any features for the current instance. The base value is the average of the model output over the training dataset (explainer.expected_value in the code). In this example base value = 0.5749 The numbers on the plot arrows are the value of the feature for this instance. Elapsed Time (sec)=5 and Packets = 1 Red represents features that pushed the model score higher, and blue representing features that pushed the score lower. The bigger the arrow, the bigger the impact of the feature on the output. The amount of decrease or increase in the impact can be seen on the x-axis. Elapsed Time of 5 seconds increases the property that the class is allow, Packets of 6.546 reduce the property value. The waterfall plot is another local analysis plot of a single instance prediction. Let’s take instance number 8 as an example: row = 8shap.waterfall_plot(shap.Explanation(values=shap_values[0][row], base_values=explainer.expected_value[0], data=X_test.iloc[row], feature_names=X_test.columns.tolist())) f(x) is the model predict_proba value: 0.79.E[f(x)] is the base value = 0.5749.On the left are the features value and on the arrows the feature contribution to the prediction.Each row shows how the positive (red) or negative (blue) contribution of each feature moves the value from the expected model output over the background dataset to the model output for this prediction [2]. f(x) is the model predict_proba value: 0.79. E[f(x)] is the base value = 0.5749. On the left are the features value and on the arrows the feature contribution to the prediction. Each row shows how the positive (red) or negative (blue) contribution of each feature moves the value from the expected model output over the background dataset to the model output for this prediction [2]. The SHAP framework has proved to be an important advancement in the field of machine learning model interpretation. SHAP combines several existing methods to create an intuitive, theoretically sound approach to explain predictions for any model. SHAP values quantify the magnitude and direction (positive or negative) of a feature’s effect on a prediction[6]. I believe XAI analysis with SHAP and other tools should be an integral part of the machine learning pipeline. The code in this post can be found here.
[ { "code": null, "e": 743, "s": 172, "text": "Model explainability becomes a basic part of the machine learning pipeline. Keeping a machine learning model as a “black box” is not an option anymore. Luckily there are analytical tools such as (lime, ExplainerDashboard, Shapash, Dalex, and more) that are evolving rapidly and becoming more popular. In a previous post, we explained how to use SHAP for a regression problem. This guide provides a practical example of how to use and interpret the open-source python package, SHAP, for XAI analysis in Multi-class classification problems and use it to improve the model." }, { "code": null, "e": 1133, "s": 743, "text": "SHAP (Shapley Additive Explanations) by Lundberg and Lee (2016) is a method to explain individual predictions, based on the game theoretically optimal Shapley values[1]. Calculating Shapley value to get feature contributions is computationally expensive. There are two methods to approximate SHAP values to improve computation efficiency: KernelSHAP, TreeSHAP (for tree-based models only)." }, { "code": null, "e": 1405, "s": 1133, "text": "SHAP provides global and local interpretation methods based on aggregations of Shapley values. In this guide we will use the Internet Firewall Data Set example from Kaggle datasets [2], to demonstrate some of the SHAP output plots for a multiclass classification problem." }, { "code": null, "e": 1517, "s": 1405, "text": "# load the csv file as a data framedf = pd.read_csv('log2.csv')y = df.Action.copy()X = df.drop('Action',axis=1)" }, { "code": null, "e": 1562, "s": 1517, "text": "Create the model and fit like you always do." }, { "code": null, "e": 1734, "s": 1562, "text": "X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, random_state=0)cls = RandomForestClassifier(max_depth=2, random_state=0)cls.fit(X_train, y_train)" }, { "code": null, "e": 1989, "s": 1734, "text": "Now, just to get a basic impression of the model, I recommend viewing the feature importers and confusion matrix. Just to understand where we stand with the feature importance, I used scikit-learn that computes the impurity decrease within each tree [3]." }, { "code": null, "e": 2299, "s": 1989, "text": "֫importances = cls.feature_importances_indices = np.argsort(importances)features = df.columnsplt.title('Feature Importances')plt.barh(range(len(indices)), importances[indices], color='g', align='center')plt.yticks(range(len(indices)), [features[i] for i in indices])plt.xlabel('Relative Importance')plt.show()" }, { "code": null, "e": 2394, "s": 2299, "text": "Later we can compare these results to the feature importance calculated by the Shapley values." }, { "code": null, "e": 2531, "s": 2394, "text": "A confusion matrix is a way to visualize the performance of a model. And more important we can easily see where the model fails exactly." }, { "code": null, "e": 2709, "s": 2531, "text": "class_names = ['drop', 'allow', 'deny', 'reset-both']disp = plot_confusion_matrix(cls, X_test, y_test, display_labels=class_names, cmap=plt.cm.Blues, xticks_rotation='vertical')" }, { "code": null, "e": 2883, "s": 2709, "text": "The model could not detect any instance from the class reset-both. The reason is an unbalanced dataset that gives a low number of examples of reset-both class to learn from." }, { "code": null, "e": 3002, "s": 2883, "text": "y.value_counts()allow 37640deny 14987drop 12851reset-both 54Name: Action, dtype: int64" }, { "code": null, "e": 3087, "s": 3002, "text": "SHAP values of a model’s output explain how features impact the output of the model." }, { "code": null, "e": 3182, "s": 3087, "text": "# compute SHAP valuesexplainer = shap.TreeExplainer(cls)shap_values = explainer.shap_values(X)" }, { "code": null, "e": 3250, "s": 3182, "text": "Now we can plot relevant plots that will help us analyze the model." }, { "code": null, "e": 3361, "s": 3250, "text": "shap.summary_plot(shap_values, X.values, plot_type=\"bar\", class_names= class_names, feature_names = X.columns)" }, { "code": null, "e": 3718, "s": 3361, "text": "In this plot, the impact of a feature on the classes is stacked to create the feature importance plot. Thus, if you created features in order to differentiate a particular class from the rest, that is the plot where you can see it. In other words, summary plot for multiclass classification can show you what the machine managed to learn from the features." }, { "code": null, "e": 4137, "s": 3718, "text": "In the example below we can see that the class drop hardly uses the features Destination Plot, Source Port, and Bytes Sent. We can also see that the classes allow and deny uses the same features equally. That is the reason the confusion between them is relatively high. In order to separate better between the allow and deny classes, one needs to generate new features that uniquely be dedicated towards these classes." }, { "code": null, "e": 4192, "s": 4137, "text": "You can also see the summary_plot of a specific class." }, { "code": null, "e": 4263, "s": 4192, "text": "shap.summary_plot(shap_values[1], X.values, feature_names = X.columns)" }, { "code": null, "e": 4856, "s": 4263, "text": "The summary plot combines feature importance with feature effects. Each point on the summary plot is a Shapley value for a feature and an instance. The position on the y-axis is determined by the feature and on the x-axis by the Shapley value. You can see that the feature pkts_sent, being the least important feature, has low Shapley values. The color represents the value of the feature from low to high. Overlapping points are jittered in the y-axis direction, so we get a sense of the distribution of the Shapley values per feature. The features are ordered according to their importance." }, { "code": null, "e": 5080, "s": 4856, "text": "In the summary plot, we see the first indications of the relationship between the value of a feature and the impact on the prediction. But to see the exact form of the relationship, we have to look at SHAP dependence plots." }, { "code": null, "e": 5394, "s": 5080, "text": "The partial dependence plot (short PDP or PD plot) shows the marginal effect one or two features have on the predicted outcome of a machine learning model (J. H. Friedman 2001 [3]). A partial dependence plot can show whether the relationship between the target and a feature is linear, monotonic, or more complex." }, { "code": null, "e": 5808, "s": 5394, "text": "The partial dependence plot is a global method: The method considers all instances and gives a statement about the global relationship of a feature with the predicted outcome. The PDP assumes that the first feature is not correlated with the second feature. If this assumption is violated, the averages calculated for the partial dependence plot will include data points that are very unlikely or even impossible." }, { "code": null, "e": 6049, "s": 5808, "text": "A dependence plot is a scatter plot that shows the effect a single feature has on the predictions made by the model. In this example, the property value increases significantly when the average number of rooms per dwelling is higher than 6." }, { "code": null, "e": 6105, "s": 6049, "text": "Each dot is a single prediction (row) from the dataset." }, { "code": null, "e": 6154, "s": 6105, "text": "The x-axis is the actual value from the dataset." }, { "code": null, "e": 6318, "s": 6154, "text": "The y-axis is the SHAP value for that feature, which represents how much knowing that feature’s value changes the output of the model for that sample’s prediction." }, { "code": null, "e": 6642, "s": 6318, "text": "The color corresponds to a second feature that may have an interaction effect with the feature we are plotting (by default this second feature is chosen automatically). If an interaction effect is present between this other feature and the feature we are plotting it will show up as a distinct vertical pattern of coloring." }, { "code": null, "e": 6819, "s": 6642, "text": "֫# If we pass a numpy array instead of a data frame then we# need pass the feature names in separatelyshap.dependence_plot(0, shap_values[0], X.values, feature_names=X.columns)" }, { "code": null, "e": 6963, "s": 6819, "text": "In the example above we can see a clear vertical pattern of coloring for the interaction between the features, Source Port and NAT Source Port." }, { "code": null, "e": 7230, "s": 6963, "text": "Force plot gives us the explainability of a single model prediction. In this plot, we can see how features contributed to the model’s prediction for a specific observation. It is very convenient to use for error analysis or a deep understanding of a particular case." }, { "code": null, "e": 7337, "s": 7230, "text": "i=8shap.force_plot(explainer.expected_value[0], shap_values[0][i], X.values[i], feature_names = X.columns)" }, { "code": null, "e": 7363, "s": 7337, "text": "From the plot we can see:" }, { "code": null, "e": 8165, "s": 7363, "text": "The model predict_proba value: 0.79The base value: this is the value that would be predicted if we didn’t know any features for the current instance. The base value is the average of the model output over the training dataset (explainer.expected_value in the code). In this example base value = 0.5749The numbers on the plot arrows are the value of the feature for this instance. Elapsed Time (sec)=5 and Packets = 1Red represents features that pushed the model score higher, and blue representing features that pushed the score lower.The bigger the arrow, the bigger the impact of the feature on the output. The amount of decrease or increase in the impact can be seen on the x-axis.Elapsed Time of 5 seconds increases the property that the class is allow, Packets of 6.546 reduce the property value." }, { "code": null, "e": 8201, "s": 8165, "text": "The model predict_proba value: 0.79" }, { "code": null, "e": 8468, "s": 8201, "text": "The base value: this is the value that would be predicted if we didn’t know any features for the current instance. The base value is the average of the model output over the training dataset (explainer.expected_value in the code). In this example base value = 0.5749" }, { "code": null, "e": 8584, "s": 8468, "text": "The numbers on the plot arrows are the value of the feature for this instance. Elapsed Time (sec)=5 and Packets = 1" }, { "code": null, "e": 8704, "s": 8584, "text": "Red represents features that pushed the model score higher, and blue representing features that pushed the score lower." }, { "code": null, "e": 8854, "s": 8704, "text": "The bigger the arrow, the bigger the impact of the feature on the output. The amount of decrease or increase in the impact can be seen on the x-axis." }, { "code": null, "e": 8972, "s": 8854, "text": "Elapsed Time of 5 seconds increases the property that the class is allow, Packets of 6.546 reduce the property value." }, { "code": null, "e": 9099, "s": 8972, "text": "The waterfall plot is another local analysis plot of a single instance prediction. Let’s take instance number 8 as an example:" }, { "code": null, "e": 9363, "s": 9099, "text": "row = 8shap.waterfall_plot(shap.Explanation(values=shap_values[0][row], base_values=explainer.expected_value[0], data=X_test.iloc[row], feature_names=X_test.columns.tolist()))" }, { "code": null, "e": 9744, "s": 9363, "text": "f(x) is the model predict_proba value: 0.79.E[f(x)] is the base value = 0.5749.On the left are the features value and on the arrows the feature contribution to the prediction.Each row shows how the positive (red) or negative (blue) contribution of each feature moves the value from the expected model output over the background dataset to the model output for this prediction [2]." }, { "code": null, "e": 9789, "s": 9744, "text": "f(x) is the model predict_proba value: 0.79." }, { "code": null, "e": 9825, "s": 9789, "text": "E[f(x)] is the base value = 0.5749." }, { "code": null, "e": 9922, "s": 9825, "text": "On the left are the features value and on the arrows the feature contribution to the prediction." }, { "code": null, "e": 10128, "s": 9922, "text": "Each row shows how the positive (red) or negative (blue) contribution of each feature moves the value from the expected model output over the background dataset to the model output for this prediction [2]." } ]
Setting the spacing between grouped bar plots in Matplotlib
To set the spacing between grouped bar plots in matplotlib, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Create a dictionary for bar details to be plotted. Create a dictionary for bar details to be plotted. Make a Pandas dataframe using dictionary, d. Make a Pandas dataframe using dictionary, d. Plot the bar using dictionary, d, with align="center". Plot the bar using dictionary, d, with align="center". To display the figure, use show() method. To display the figure, use show() method. import matplotlib.pyplot as plt import pandas as pd plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True d = {"Name": ["John", "Jacks", "James", "Joe"],"Age": [23, 12, 30, 26],"Marks": [98, 85, 70, 77]} df = pd.DataFrame(d) df.set_index('Name').plot(kind="bar", align='center', width=0.1) plt.tick_params(rotation=45) plt.show()
[ { "code": null, "e": 1156, "s": 1062, "text": "To set the spacing between grouped bar plots in matplotlib, we can take the following steps −" }, { "code": null, "e": 1232, "s": 1156, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1308, "s": 1232, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1359, "s": 1308, "text": "Create a dictionary for bar details to be plotted." }, { "code": null, "e": 1410, "s": 1359, "text": "Create a dictionary for bar details to be plotted." }, { "code": null, "e": 1455, "s": 1410, "text": "Make a Pandas dataframe using dictionary, d." }, { "code": null, "e": 1500, "s": 1455, "text": "Make a Pandas dataframe using dictionary, d." }, { "code": null, "e": 1555, "s": 1500, "text": "Plot the bar using dictionary, d, with align=\"center\"." }, { "code": null, "e": 1610, "s": 1555, "text": "Plot the bar using dictionary, d, with align=\"center\"." }, { "code": null, "e": 1652, "s": 1610, "text": "To display the figure, use show() method." }, { "code": null, "e": 1694, "s": 1652, "text": "To display the figure, use show() method." }, { "code": null, "e": 2061, "s": 1694, "text": "import matplotlib.pyplot as plt\nimport pandas as pd\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nd = {\"Name\": [\"John\", \"Jacks\", \"James\", \"Joe\"],\"Age\": [23, 12, 30, 26],\"Marks\": [98, 85, 70, 77]}\n\ndf = pd.DataFrame(d)\ndf.set_index('Name').plot(kind=\"bar\", align='center', width=0.1)\nplt.tick_params(rotation=45)\n\nplt.show()" } ]
Online Javascript Formatter
Editable Javascript Code 12345678910111213141516171819202122232425262728var msg = 'Welcome Back';var colorTimer = null;function toHex(n){var hexChars = '0123456789ABCDEF';if (n === 0) return n;var j, k;var temp = '';while (n !== 0){j = n % 16;n = (n - j)/16;temp = hexChars.charAt(j) + temp;}return temp;}function colorize(){if (!document.getElementById) return;for (i=0; i<msg.length; i++){k = Math.round(Math.random() * 16777215);k = toHex(k);while (k.length < 6){k = k + '0';}document.getElementById('colorizer' + i).style.color = '#' + k;}colorTimer = window.setTimeout(colorize(), 230);}X Privacy Policy Cookies Policy Terms of Use
[ { "code": null, "e": 25, "s": 0, "text": "Editable Javascript Code" }, { "code": null, "e": 594, "s": 25, "text": "12345678910111213141516171819202122232425262728var msg = 'Welcome Back';var colorTimer = null;function toHex(n){var hexChars = '0123456789ABCDEF';if (n === 0) return n;var j, k;var temp = '';while (n !== 0){j = n % 16;n = (n - j)/16;temp = hexChars.charAt(j) + temp;}return temp;}function colorize(){if (!document.getElementById) return;for (i=0; i<msg.length; i++){k = Math.round(Math.random() * 16777215);k = toHex(k);while (k.length < 6){k = k + '0';}document.getElementById('colorizer' + i).style.color = '#' + k;}colorTimer = window.setTimeout(colorize(), 230);}X" }, { "code": null, "e": 609, "s": 594, "text": "Privacy Policy" }, { "code": null, "e": 624, "s": 609, "text": "Cookies Policy" } ]
Stickler Thief | Practice | GeeksforGeeks
Stickler the thief wants to loot money from a society having n houses in a single line. He is a weird person and follows a certain rule when looting the houses. According to the rule, he will never loot two consecutive houses. At the same time, he wants to maximize the amount he loots. The thief knows which house has what amount of money but is unable to come up with an optimal looting strategy. He asks for your help to find the maximum money he can get if he strictly follows the rule. Each house has a[i]amount of money present in it. Example 1: Input: n = 6 a[] = {5,5,10,100,10,5} Output: 110 Explanation: 5+100+5=110 Example 2: Input: n = 3 a[] = {1,2,3} Output: 4 Explanation: 1+3=4 Your Task: Complete the functionFindMaxSum()which takes an array arr[] and n as input which returns the maximum money he can get following the rules Expected Time Complexity:O(N). Expected Space Complexity:O(N). Constraints: 1 ≤ n ≤ 104 1 ≤ a[i] ≤ 104 +1 kshitij14106 hours ago vector<int>dp(n+1,-1); dp[0]=0; dp[1]=arr[0]; for(int i=2;i<=n;i++) { dp[i]=max(dp[i-1], arr[i-1]+ dp[i-2]); } return dp[n]; 0 nirmal119140831 week ago int dp[100001]; int solve(int index,vector<int> v,int N) { if(index>=N) { return 0; } if(dp[index]!=-1) { return dp[index]; } int left_sum= v[index]+solve(index+2,v,N); int right_sum=solve(index+1,v,N); return dp[index]=max(left_sum,right_sum); } int FindMaxSum(int arr[], int n) { // Your code here vector<int> v; memset(dp,-1,100001); for(int i=0;i<n;i++) { v.push_back(arr[i]); } int N=v.size(); return solve(0,v,N); } // why my time limit is getting exceeded 0 abhiswc291 week ago Python Memoized class Solution: def FindMaxSum(self,a, n): dp = [-1 for _ in range(n+1)] def solve(arr, n): if n < 0: return 0 if dp[n] != -1: return dp[n] t1 = arr[n]+solve(arr, n-2) t2 = solve(arr, n-1) dp[n] = max(t1, t2) return dp[n] return solve(a, n-1) +1 manasbajpai163 weeks ago class Solution { public int FindMaxSum(int arr[], int n) { int inc = arr[0], excl = 0; for(int i = 1; i < n; i++) { int ninc = excl + arr[i]; int nexcl = Math.max(inc , excl); inc = ninc; excl = nexcl; } return Math.max(inc , excl); } } JAVA Solution +1 kashyapjhon3 weeks ago C++ Solution Time=(0.3/1.4) EASY : int help(vector<int> &dp,int arr[],int ind){ if(ind==0){ return arr[ind]; } if(ind<0){ return 0; } if(dp[ind]!=-1){ return dp[ind]; } int takemoney= help(dp,arr,ind-2)+arr[ind]; int skiphouse= help(dp,arr,ind-1); return dp[ind]=max(takemoney,skiphouse); } int FindMaxSum(int arr[], int n) { // Your code here vector<int> dp(n+1,-1); int ind=n-1; return help(dp,arr,ind); } +5 omkarg14174 weeks ago simple iterative solution: int FindMaxSum(int a[], int n) { vector<int> dp(n); dp[0] = a[0]; dp[1] = max(a[1], a[0]); for(int i = 2; i < n; ++i) { dp[i] = max(a[i] + dp[i-2], dp[i-1]); } return *max_element(dp.begin(), dp.end()); } +1 nikkipro94 weeks ago int prevAmount = 0; int sum = 0; bool isNumInBasePlace = true; for (int i = 0; i < n; i++) { if (prevAmount != arr[i]) { if (isNumInBasePlace) { sum += arr[i]; } isNumInBasePlace = isNumInBasePlace?false:true; } prevAmount = arr[i]; } return sum; 0 dineshsountyal1 month ago Can anyone tell me which case i am missing here. l_even = 0 l_odd = 0 for i in range(n): if i%2==0: l_even+=a[i] else: l_odd+=a[i] if l_even >= l_odd: return l_even else: return l_odd +3 deskhell1 month ago class Solution { public: //Function to find the maximum money the thief can get. int FindMaxSum(int arr[], int n) { int inc = 0, exc = 0; for(int i = 0; i < n; i++){ int temp = inc; inc = arr[i] + exc; exc = max(temp, exc); } return max(inc, exc); } }; 0 deskhell This comment was deleted. 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": 779, "s": 238, "text": "Stickler the thief wants to loot money from a society having n houses in a single line. He is a weird person and follows a certain rule when looting the houses. According to the rule, he will never loot two consecutive houses. At the same time, he wants to maximize the amount he loots. The thief knows which house has what amount of money but is unable to come up with an optimal looting strategy. He asks for your help to find the maximum money he can get if he strictly follows the rule. Each house has a[i]amount of money present in it." }, { "code": null, "e": 790, "s": 779, "text": "Example 1:" }, { "code": null, "e": 864, "s": 790, "text": "Input:\nn = 6\na[] = {5,5,10,100,10,5}\nOutput: 110\nExplanation: 5+100+5=110" }, { "code": null, "e": 875, "s": 864, "text": "Example 2:" }, { "code": null, "e": 931, "s": 875, "text": "Input:\nn = 3\na[] = {1,2,3}\nOutput: 4\nExplanation: 1+3=4" }, { "code": null, "e": 1080, "s": 931, "text": "Your Task:\nComplete the functionFindMaxSum()which takes an array arr[] and n as input which returns the maximum money he can get following the rules" }, { "code": null, "e": 1143, "s": 1080, "text": "Expected Time Complexity:O(N).\nExpected Space Complexity:O(N)." }, { "code": null, "e": 1183, "s": 1143, "text": "Constraints:\n1 ≤ n ≤ 104\n1 ≤ a[i] ≤ 104" }, { "code": null, "e": 1186, "s": 1183, "text": "+1" }, { "code": null, "e": 1209, "s": 1186, "text": "kshitij14106 hours ago" }, { "code": null, "e": 1402, "s": 1209, "text": " vector<int>dp(n+1,-1); dp[0]=0; dp[1]=arr[0]; for(int i=2;i<=n;i++) { dp[i]=max(dp[i-1], arr[i-1]+ dp[i-2]); } return dp[n];" }, { "code": null, "e": 1404, "s": 1402, "text": "0" }, { "code": null, "e": 1429, "s": 1404, "text": "nirmal119140831 week ago" }, { "code": null, "e": 1963, "s": 1429, "text": "int dp[100001]; int solve(int index,vector<int> v,int N) { if(index>=N) { return 0; } if(dp[index]!=-1) { return dp[index]; } int left_sum= v[index]+solve(index+2,v,N); int right_sum=solve(index+1,v,N); return dp[index]=max(left_sum,right_sum); } int FindMaxSum(int arr[], int n) { // Your code here vector<int> v; memset(dp,-1,100001); for(int i=0;i<n;i++) { v.push_back(arr[i]); } int N=v.size(); return solve(0,v,N); }" }, { "code": null, "e": 2004, "s": 1963, "text": "// why my time limit is getting exceeded" }, { "code": null, "e": 2006, "s": 2004, "text": "0" }, { "code": null, "e": 2026, "s": 2006, "text": "abhiswc291 week ago" }, { "code": null, "e": 2043, "s": 2026, "text": "Python Memoized " }, { "code": null, "e": 2426, "s": 2043, "text": "\nclass Solution: \n def FindMaxSum(self,a, n):\n dp = [-1 for _ in range(n+1)]\n \n def solve(arr, n):\n if n < 0:\n return 0\n if dp[n] != -1:\n return dp[n]\n t1 = arr[n]+solve(arr, n-2)\n t2 = solve(arr, n-1)\n dp[n] = max(t1, t2)\n return dp[n]\n return solve(a, n-1)" }, { "code": null, "e": 2429, "s": 2426, "text": "+1" }, { "code": null, "e": 2454, "s": 2429, "text": "manasbajpai163 weeks ago" }, { "code": null, "e": 2813, "s": 2454, "text": "class Solution\n{\n public int FindMaxSum(int arr[], int n)\n {\n int inc = arr[0], excl = 0;\n for(int i = 1; i < n; i++)\n {\n int ninc = excl + arr[i];\n int nexcl = Math.max(inc , excl);\n \n inc = ninc;\n excl = nexcl;\n }\n \n return Math.max(inc , excl);\n }\n}" }, { "code": null, "e": 2827, "s": 2813, "text": "JAVA Solution" }, { "code": null, "e": 2832, "s": 2829, "text": "+1" }, { "code": null, "e": 2855, "s": 2832, "text": "kashyapjhon3 weeks ago" }, { "code": null, "e": 2890, "s": 2855, "text": "C++ Solution Time=(0.3/1.4) EASY :" }, { "code": null, "e": 3379, "s": 2890, "text": "int help(vector<int> &dp,int arr[],int ind){ if(ind==0){ return arr[ind]; } if(ind<0){ return 0; } if(dp[ind]!=-1){ return dp[ind]; } int takemoney= help(dp,arr,ind-2)+arr[ind]; int skiphouse= help(dp,arr,ind-1); return dp[ind]=max(takemoney,skiphouse); } int FindMaxSum(int arr[], int n) { // Your code here vector<int> dp(n+1,-1); int ind=n-1; return help(dp,arr,ind); }" }, { "code": null, "e": 3382, "s": 3379, "text": "+5" }, { "code": null, "e": 3404, "s": 3382, "text": "omkarg14174 weeks ago" }, { "code": null, "e": 3431, "s": 3404, "text": "simple iterative solution:" }, { "code": null, "e": 3722, "s": 3431, "text": "int FindMaxSum(int a[], int n)\n {\n vector<int> dp(n);\n dp[0] = a[0];\n dp[1] = max(a[1], a[0]);\n \n for(int i = 2; i < n; ++i) {\n dp[i] = max(a[i] + dp[i-2], dp[i-1]);\n }\n \n return *max_element(dp.begin(), dp.end());\n }" }, { "code": null, "e": 3725, "s": 3722, "text": "+1" }, { "code": null, "e": 3746, "s": 3725, "text": "nikkipro94 weeks ago" }, { "code": null, "e": 3832, "s": 3746, "text": " int prevAmount = 0; int sum = 0; bool isNumInBasePlace = true;" }, { "code": null, "e": 4061, "s": 3832, "text": " for (int i = 0; i < n; i++) { if (prevAmount != arr[i]) { if (isNumInBasePlace) { sum += arr[i]; } isNumInBasePlace = isNumInBasePlace?false:true; }" }, { "code": null, "e": 4100, "s": 4061, "text": " prevAmount = arr[i]; }" }, { "code": null, "e": 4115, "s": 4100, "text": " return sum;" }, { "code": null, "e": 4117, "s": 4115, "text": "0" }, { "code": null, "e": 4143, "s": 4117, "text": "dineshsountyal1 month ago" }, { "code": null, "e": 4192, "s": 4143, "text": "Can anyone tell me which case i am missing here." }, { "code": null, "e": 4442, "s": 4194, "text": " l_even = 0 l_odd = 0 for i in range(n): if i%2==0: l_even+=a[i] else: l_odd+=a[i] if l_even >= l_odd: return l_even else: return l_odd " }, { "code": null, "e": 4451, "s": 4448, "text": "+3" }, { "code": null, "e": 4471, "s": 4451, "text": "deskhell1 month ago" }, { "code": null, "e": 4812, "s": 4471, "text": "class Solution\n{\n public:\n //Function to find the maximum money the thief can get.\n int FindMaxSum(int arr[], int n)\n {\n int inc = 0, exc = 0;\n for(int i = 0; i < n; i++){\n int temp = inc;\n inc = arr[i] + exc;\n exc = max(temp, exc);\n }\n return max(inc, exc);\n }\n};" }, { "code": null, "e": 4814, "s": 4812, "text": "0" }, { "code": null, "e": 4823, "s": 4814, "text": "deskhell" }, { "code": null, "e": 4849, "s": 4823, "text": "This comment was deleted." }, { "code": null, "e": 4995, "s": 4849, "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": 5031, "s": 4995, "text": " Login to access your submissions. " }, { "code": null, "e": 5041, "s": 5031, "text": "\nProblem\n" }, { "code": null, "e": 5051, "s": 5041, "text": "\nContest\n" }, { "code": null, "e": 5114, "s": 5051, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5262, "s": 5114, "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": 5470, "s": 5262, "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": 5576, "s": 5470, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Intersection of Two Arrays in C++
Suppose we have two arrays; we have to find their intersections. So, if the input is like [1,5,3,6,9],[2,8,9,6,7], then the output will be [9,6] To solve this, we will follow these steps − Define two maps mp1, mp2 Define two maps mp1, mp2 Define an array res Define an array res for x in nums1(increase mp1[x] by 1) for x in nums1 (increase mp1[x] by 1) (increase mp1[x] by 1) for x in nums2(increase mp2[x] by 1) for x in nums2 (increase mp2[x] by 1) (increase mp2[x] by 1) for each key-value pair x in mp1cnt := 0cnt := minimum of value of x and mp2[key of x]if cnt > 0, then −insert key of x at the end of res for each key-value pair x in mp1 cnt := 0 cnt := 0 cnt := minimum of value of x and mp2[key of x] cnt := minimum of value of x and mp2[key of x] if cnt > 0, then −insert key of x at the end of res if cnt > 0, then − insert key of x at the end of res insert key of x at the end of res return res return res Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; void print_vector(vector<auto> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2){ unordered_map<int, int> mp1, mp2; vector<int> res; for (auto x : nums1) mp1[x]++; for (auto x : nums2) mp2[x]++; for (auto x : mp1) { int cnt = 0; cnt = min(x.second, mp2[x.first]); if (cnt > 0) res.push_back(x.first); } return res; } }; main(){ Solution ob; vector<int> v = {1,5,3,6,9}, v1 = {2,8,9,6,7}; print_vector(ob.intersection(v, v1)); } {1,5,3,6,9},{2,8,9,6,7} [9, 6, ]
[ { "code": null, "e": 1127, "s": 1062, "text": "Suppose we have two arrays; we have to find their intersections." }, { "code": null, "e": 1207, "s": 1127, "text": "So, if the input is like [1,5,3,6,9],[2,8,9,6,7], then the output will be [9,6]" }, { "code": null, "e": 1251, "s": 1207, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1276, "s": 1251, "text": "Define two maps mp1, mp2" }, { "code": null, "e": 1301, "s": 1276, "text": "Define two maps mp1, mp2" }, { "code": null, "e": 1321, "s": 1301, "text": "Define an array res" }, { "code": null, "e": 1341, "s": 1321, "text": "Define an array res" }, { "code": null, "e": 1378, "s": 1341, "text": "for x in nums1(increase mp1[x] by 1)" }, { "code": null, "e": 1393, "s": 1378, "text": "for x in nums1" }, { "code": null, "e": 1416, "s": 1393, "text": "(increase mp1[x] by 1)" }, { "code": null, "e": 1439, "s": 1416, "text": "(increase mp1[x] by 1)" }, { "code": null, "e": 1476, "s": 1439, "text": "for x in nums2(increase mp2[x] by 1)" }, { "code": null, "e": 1491, "s": 1476, "text": "for x in nums2" }, { "code": null, "e": 1514, "s": 1491, "text": "(increase mp2[x] by 1)" }, { "code": null, "e": 1537, "s": 1514, "text": "(increase mp2[x] by 1)" }, { "code": null, "e": 1675, "s": 1537, "text": "for each key-value pair x in mp1cnt := 0cnt := minimum of value of x and mp2[key of x]if cnt > 0, then −insert key of x at the end of res" }, { "code": null, "e": 1708, "s": 1675, "text": "for each key-value pair x in mp1" }, { "code": null, "e": 1717, "s": 1708, "text": "cnt := 0" }, { "code": null, "e": 1726, "s": 1717, "text": "cnt := 0" }, { "code": null, "e": 1773, "s": 1726, "text": "cnt := minimum of value of x and mp2[key of x]" }, { "code": null, "e": 1820, "s": 1773, "text": "cnt := minimum of value of x and mp2[key of x]" }, { "code": null, "e": 1872, "s": 1820, "text": "if cnt > 0, then −insert key of x at the end of res" }, { "code": null, "e": 1891, "s": 1872, "text": "if cnt > 0, then −" }, { "code": null, "e": 1925, "s": 1891, "text": "insert key of x at the end of res" }, { "code": null, "e": 1959, "s": 1925, "text": "insert key of x at the end of res" }, { "code": null, "e": 1970, "s": 1959, "text": "return res" }, { "code": null, "e": 1981, "s": 1970, "text": "return res" }, { "code": null, "e": 2053, "s": 1981, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 2064, "s": 2053, "text": " Live Demo" }, { "code": null, "e": 2814, "s": 2064, "text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid print_vector(vector<auto> v){\n cout << \"[\";\n for(int i = 0; i<v.size(); i++){\n cout << v[i] << \", \";\n }\n cout << \"]\"<<endl;\n}\nclass Solution {\npublic:\n vector<int> intersection(vector<int>& nums1, vector<int>& nums2){\n unordered_map<int, int> mp1, mp2;\n vector<int> res;\n for (auto x : nums1)\n mp1[x]++;\n for (auto x : nums2)\n mp2[x]++;\n for (auto x : mp1) {\n int cnt = 0;\n cnt = min(x.second, mp2[x.first]);\n if (cnt > 0)\n res.push_back(x.first);\n }\n return res;\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {1,5,3,6,9}, v1 = {2,8,9,6,7};\n print_vector(ob.intersection(v, v1));\n}" }, { "code": null, "e": 2838, "s": 2814, "text": "{1,5,3,6,9},{2,8,9,6,7}" }, { "code": null, "e": 2847, "s": 2838, "text": "[9, 6, ]" } ]
Don’t Sweat the Solver Stuff. Tips for Better Logistic Regression... | by Jeff Hale | Towards Data Science
Logistic regression is the bread-and-butter algorithm for machine learning classification. If you’re a practicing or aspiring data scientist, you’ll want to know the ins and outs of how to use it. Also, Scikit-learn’s LogisticRegression is spitting out warnings about changing the default solver, so this is a great time to learn when to use which solver. 😀 FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning. In this article, you’ll learn about Scikit-learn LogisticRegression solver choices and see two evaluations of them. Also, you’ll see key API options and get answers to frequently asked questions. By the end of the article, you’ll know more about logistic regression in Scikit-learn and not sweat the solver stuff. 😓 I’m using Scikit-learn version 0.21.3 in this analysis. UPDATE December 20, 2019: I made several edits to this article after helpful feedback from Scikit-learn core developer and maintainer, Andreas Mueller. A classification problem is one in which you try to predict discrete outcomes, such as whether someone has a disease. In contrast, a regression problem is one in which you are trying to predict a value of a continuous variable, such as the sale price of a home. Although logistic regression has regression in its name, it’s an algorithm for classification problems. Logistic regression is probably the most important supervised learning classification method. It’s a fast, versatile extension of a generalized linear model. Logistic regression makes an excellent baseline algorithm. It works well when the relationship between the features and the target aren’t too complex. Logistic regression produces feature weights that are generally interpretable, which makes it especially useful when you need to be able to explain the reasons for a decision. This interpretability often comes in handy — for example, with lenders who need to justify their loan decisions. There is no closed-form solution for logistic regression problems. This is fine — we don’t use the closed form solution for linear regression problems anyway because it’s slow. 😉 Solving logistic regression is an optimization problem. Thankfully, nice folks have created several solver algorithms we can use. 😁 Scikit-learn ships with five different solvers. Each solver tries to find the parameter weights that minimize a cost function. Here are the five options: newton-cg — A newton method. Newton methods use an exact Hessian matrix. It's slow for large datasets, because it computes the second derivatives. lbfgs — Stands for Limited-memory Broyden–Fletcher–Goldfarb–Shanno. It approximates the second derivative matrix updates with gradient evaluations. It stores only the last few updates, so it saves memory. It isn't super fast with large data sets. It will be the default solver as of Scikit-learn version 0.22.0. liblinear — Library for Large Linear Classification. Uses a coordinate descent algorithm. Coordinate descent is based on minimizing a multivariate function by solving univariate optimization problems in a loop. In other words, it moves toward the minimum in one direction at a time. It is the default solver for Scikit-learn versions earlier than 0.22.0. It performs pretty well with high dimensionality. It does have a number of drawbacks. It can get stuck, is unable to run in parallel, and can only solve multi-class logistic regression with one-vs.-rest. sag — Stochastic Average Gradient descent. A variation of gradient descent and incremental aggregated gradient approaches that uses a random sample of previous gradient values. Fast for big datasets. saga — Extension of sag that also allows for L1 regularization. Should generally train faster than sag. An excellent discussion of the different options can be found in this Stack Overflow answer. The chart below from the Scikit-learn documentation lists characteristics of the solvers, including the the regularization penalties available. liblinear is fast with small datasets, but has problems with saddle points and can't be parallelized over multiple processor cores. It can only use one-vs.-rest to solve multi-class problems. It also penalizes the intercept, which isn't good for interpretation. lbfgs avoids these drawbacks and is relatively fast. It's the best choice for most cases without a really large dataset. Some discussion of why the default was changed is in this GitHub issue. Let’s evaluate the Logistic Regression solvers with two prediction classification projects — one binary and one multi-class. First, let’s look at a binary classification problem. I used the built-in scikit-learn breast_cancer dataset. The goal is to predict whether a breast mass is cancerous. The features consist of numeric data about cell nuclei. They were computed from digitized images of biopsies. The dataset contains 569 observations and 30 numeric features. I split the dataset into training and test sets and conducted a grid search on the training set with each different solver. You can access my Jupyter notebook used in all analyses on Kaggle. The most relevant code snippet is below. solver_list = ['liblinear', 'newton-cg', 'lbfgs', 'sag', 'saga']params = dict(solver=solver_list)log_reg = LogisticRegression(C=1, n_jobs=-1, random_state=34)clf = GridSearchCV(log_reg, params, cv=5)clf.fit(X_train, y_train)scores = clf.cv_results_['mean_test_score']for score, solver in zip(scores, solver_list): print(f" {solver} {score:.3f}" ) And here are the results: liblinear 0.939 newton-cg 0.939 lbfgs 0.934 sag 0.911 saga 0.904 The accuracy values for sag and saga are a bit lower than their peers. After scaling the features, the solvers all perform better and sag and saga are just as accurate as the other solvers. liblinear 0.960 newton-cg 0.962 lbfgs 0.962 sag 0.962 saga 0.962 Now let’s look at an example with three classes. I evaluated the logistic regression solvers in a multi-class classification problem with Scikit-learn’s wine dataset. The dataset contains 178 samples and 13 numeric features. The goal is to predict the type of grapes used to make the wine from the chemical features of the wine. solver_list = ['liblinear', 'newton-cg', 'lbfgs', 'sag', 'saga']parameters = dict(solver=solver_list)lr = LogisticRegression(random_state=34, multi_class="auto", n_jobs=-1, C=1)clf = GridSearchCV(lr, parameters, cv=5)clf.fit(X_train, y_train)scores = clf.cv_results_['mean_test_score']for score, solver, in zip(scores, solver_list): print(f"{solver}: {score:.3f}") Scikit-learn gives a warning that the sag and saga models did not converge. In other words, they never arrived at a minimum point. Unsurprisingly, the results aren’t so great for those solvers. liblinear: 0.962newton-cg: 0.947lbfgs: 0.955sag: 0.699saga: 0.662 Let’s make a little bar chart using the Seaborn library to show the scores. After scaling the features between 0 and 1, then sag and saga reach the same mean accuracy scores as the other models. liblinear: 0.955newton-cg: 0.970lbfgs: 0.970sag: 0.970saga: 0.970 Note the caveat that both of these examples are with small datasets. Also, we’re not looking at memory and speed requirements in these examples. Bottom line: the forthcoming default lbfgs solver is a good first choice for most cases. If you’re dealing with a large dataset or want to apply L1 regularization, I suggest you start with saga. Remember that saga needs the features to be on a similar scale. Do you have a use case for newton-cg or sag? If so, please share in the comments. 💬 Next, I’ll demystify key parameter options for LogisticRegression in Scikit-learn. The Scikit-learn LogisticRegression class can take the following arguments. penalty, dual, tol, C, fit_intercept, intercept_scaling, class_weight, random_state, solver, max_iter, verbose, warm_start, n_jobs, l1_ratio I won’t include all of the parameters below, just excerpts from those parameters most likely to be valuable to most folks. See the docs for those that are omitted. I’ve added additional information in italics. C — float, optional, default = 1. Smaller values have more regularization. Inverse of regularization strength. Must be positive value. Usually search logarithmically: [.001, .01, .1, 1, 10, 100, 1000] random_state : int, RandomState instance or None, optional (default=None) Note that you must set the random state here for reproducibility. solver {‘newton-cg’, ‘lbfgs’, ‘liblinear’, ‘sag’, ‘saga’}, optional (default=’liblinear’). See the chart above for more info. Changed in version 0.20: Default will change from ‘liblinear’ to ‘lbfgs’ in 0.22. multi_class : str, {‘ovr’, ‘multinomial’, ‘auto’}, optional (default=’ovr’) If the option chosen is ‘ovr’, then a binary problem is fit for each label. For ‘multinomial’ the loss minimised is the multinomial loss fit across the entire probability distribution, even when the data is binary. ‘multinomial’ is unavailable when solver=’liblinear’. ‘auto’ selects ‘ovr’ if the data is binary, or if solver=’liblinear’, and otherwise selects ‘multinomial’. Changed in version 0.20: Default will change from ‘ovr’ to ‘auto’ in 0.22. ovr stands for one vs. rest. See further discussion below. l1_ratio : float or None, optional (default=None) The Elastic-Net mixing parameter, with 0 <= l1_ratio <= 1. Only used if penalty='elasticnet'. Setting `l1_ratio=0 is equivalent to using penalty='l2', while setting l1_ratio=1 is equivalent to using penalty='l1'. For 0 < l1_ratio <1, the penalty is a combination of L1 and L2. Only for saga. Commentary: If you have a multiclass problem, then setting multi-class to auto will use the multinomial option every time it's available. That's the most theoretically sound choice. auto will soon be the default. Use l1_ratio if want to use some L1 regularization with the saga solver. Note that like the ElasticNet linear regression option, you can use a mix of L1 and L2 penalization. Also note that an L2 regularization of C=1 is applied by default. This default regularization makes models more robust to multicollinearity, but at the expense of less interpretability (hat tip to Andreas Mueller). After fitting the model the attributes are: classes_, coef_, intercept_, and n_iter. coef_ contains an array of the feature weights. Now let’s address those nagging questions you might have about Logistic Regression in Scikit-learn. Nope. Sorry, if you need that, find another classification algorithm here. Regularization shifts your model toward the bias side of things in the bias/variance tradeoff. Regularization makes for a more generalizable logistic regression model, especially in cases with few data points. You’ll probably want to hyperparameter search over the regularization parameter C. If you want to do some dimensionality reduction through regularization, use L1 regularization. L1 regularization is Manhattan or Taxicab regularization. L2 regularization is Euclidian regularization and generally performs better in generalized linear regression problems. You must use the saga solver if you want to apply a mix of L1 and L2 regularization. The liblinear solver requires you to have regularization. However, you could just make C such as a large value that it had a very, very small regularization penalty. Again, C is currently set to 1 by default. If using sag and saga solvers, make sure the features are on a similar scale. We saw the importance of this above. Andreas Mueller, in private correspondence, also mentioned that he found convergence issues on unscaled data with lbfgs, although it was more robust than sag and saga. Bottom line: to be safe, scale your data. Probably. Removing outliers will generally improve model performance. Standardizing the inputs would also reduce outliers’ effects. RobustScaler can scale features and you can avoid dropping outliers. See my article discussing scaling and standardizing here. Observations should be independent of each other. Just as in linear regression, you can use higher order polynomials and interactions. This transformation allows your model to learn a more complex decision boundary. Then, you aren’t limited to a linear decision boundary. However, overfitting becomes a risk and interpreting feature importances gets trickier. It might also be more difficult for the solver to find the global minimum. Maybe. Principal Components Analysis is a nice choice if interpretability isn’t vital. Recursive Feature Elimination can help you remove the least important features. Alternatively, L1 regularization can drive less important feature weights to zero if you are using the saga solver. It is for interpretation of the feature importances. You can’t rely on the model weights to be meaningful when there is high correlation between the variables. Credit for affecting the outcome variable might go to just one of the correlated features. There are many ways to test for multicollinearity. See Kraha et al. (2012) here. One popular option is to check the Variance Inflation Factor (VIF). A VIF cutoff around 5 to 10 is common, but there’s a lively debate as to what an appropriate VIF cutoff should be. You can compute the VIF by taking the correlation matrix, inverting it, and taking the values on the diagonal for each feature. The correlation coefficients alone are not sufficient to determine problematic multicollinearity with multiple features. If the sample size is small, getting more data might be most helpful for removing multi-collinearity. LogisticRegressionCV is the Scikit-learn algorithm you want if you have a lot of data and want to speed up your calculations while doing cross-validation to tune your hyperparameters. Now you know what to do when you see the LogisticRegression solver warning — and better yet, how to avoid it in the first place. No more sweat! 😅 I suggest you use the upcoming default lbfgs solver for most cases. If you have a lot of data or need L1 regularization, try saga. Make sure you scale your features if you’re using saga. I hope you found this discussion of logistic regression helpful. If you did, please share it on your favorite social media so other people can find it, too. 👍 I write about Python, Docker, SQL, data science and other tech topics. If any of that’s of interest to you, read more here and sign up for my newsletter.😄
[ { "code": null, "e": 530, "s": 172, "text": "Logistic regression is the bread-and-butter algorithm for machine learning classification. If you’re a practicing or aspiring data scientist, you’ll want to know the ins and outs of how to use it. Also, Scikit-learn’s LogisticRegression is spitting out warnings about changing the default solver, so this is a great time to learn when to use which solver. 😀" }, { "code": null, "e": 638, "s": 530, "text": "FutureWarning: Default solver will be changed to 'lbfgs' in 0.22. Specify a solver to silence this warning." }, { "code": null, "e": 954, "s": 638, "text": "In this article, you’ll learn about Scikit-learn LogisticRegression solver choices and see two evaluations of them. Also, you’ll see key API options and get answers to frequently asked questions. By the end of the article, you’ll know more about logistic regression in Scikit-learn and not sweat the solver stuff. 😓" }, { "code": null, "e": 1010, "s": 954, "text": "I’m using Scikit-learn version 0.21.3 in this analysis." }, { "code": null, "e": 1162, "s": 1010, "text": "UPDATE December 20, 2019: I made several edits to this article after helpful feedback from Scikit-learn core developer and maintainer, Andreas Mueller." }, { "code": null, "e": 1528, "s": 1162, "text": "A classification problem is one in which you try to predict discrete outcomes, such as whether someone has a disease. In contrast, a regression problem is one in which you are trying to predict a value of a continuous variable, such as the sale price of a home. Although logistic regression has regression in its name, it’s an algorithm for classification problems." }, { "code": null, "e": 1686, "s": 1528, "text": "Logistic regression is probably the most important supervised learning classification method. It’s a fast, versatile extension of a generalized linear model." }, { "code": null, "e": 1837, "s": 1686, "text": "Logistic regression makes an excellent baseline algorithm. It works well when the relationship between the features and the target aren’t too complex." }, { "code": null, "e": 2126, "s": 1837, "text": "Logistic regression produces feature weights that are generally interpretable, which makes it especially useful when you need to be able to explain the reasons for a decision. This interpretability often comes in handy — for example, with lenders who need to justify their loan decisions." }, { "code": null, "e": 2305, "s": 2126, "text": "There is no closed-form solution for logistic regression problems. This is fine — we don’t use the closed form solution for linear regression problems anyway because it’s slow. 😉" }, { "code": null, "e": 2437, "s": 2305, "text": "Solving logistic regression is an optimization problem. Thankfully, nice folks have created several solver algorithms we can use. 😁" }, { "code": null, "e": 2591, "s": 2437, "text": "Scikit-learn ships with five different solvers. Each solver tries to find the parameter weights that minimize a cost function. Here are the five options:" }, { "code": null, "e": 2738, "s": 2591, "text": "newton-cg — A newton method. Newton methods use an exact Hessian matrix. It's slow for large datasets, because it computes the second derivatives." }, { "code": null, "e": 3050, "s": 2738, "text": "lbfgs — Stands for Limited-memory Broyden–Fletcher–Goldfarb–Shanno. It approximates the second derivative matrix updates with gradient evaluations. It stores only the last few updates, so it saves memory. It isn't super fast with large data sets. It will be the default solver as of Scikit-learn version 0.22.0." }, { "code": null, "e": 3609, "s": 3050, "text": "liblinear — Library for Large Linear Classification. Uses a coordinate descent algorithm. Coordinate descent is based on minimizing a multivariate function by solving univariate optimization problems in a loop. In other words, it moves toward the minimum in one direction at a time. It is the default solver for Scikit-learn versions earlier than 0.22.0. It performs pretty well with high dimensionality. It does have a number of drawbacks. It can get stuck, is unable to run in parallel, and can only solve multi-class logistic regression with one-vs.-rest." }, { "code": null, "e": 3809, "s": 3609, "text": "sag — Stochastic Average Gradient descent. A variation of gradient descent and incremental aggregated gradient approaches that uses a random sample of previous gradient values. Fast for big datasets." }, { "code": null, "e": 3913, "s": 3809, "text": "saga — Extension of sag that also allows for L1 regularization. Should generally train faster than sag." }, { "code": null, "e": 4006, "s": 3913, "text": "An excellent discussion of the different options can be found in this Stack Overflow answer." }, { "code": null, "e": 4150, "s": 4006, "text": "The chart below from the Scikit-learn documentation lists characteristics of the solvers, including the the regularization penalties available." }, { "code": null, "e": 4412, "s": 4150, "text": "liblinear is fast with small datasets, but has problems with saddle points and can't be parallelized over multiple processor cores. It can only use one-vs.-rest to solve multi-class problems. It also penalizes the intercept, which isn't good for interpretation." }, { "code": null, "e": 4605, "s": 4412, "text": "lbfgs avoids these drawbacks and is relatively fast. It's the best choice for most cases without a really large dataset. Some discussion of why the default was changed is in this GitHub issue." }, { "code": null, "e": 4730, "s": 4605, "text": "Let’s evaluate the Logistic Regression solvers with two prediction classification projects — one binary and one multi-class." }, { "code": null, "e": 4899, "s": 4730, "text": "First, let’s look at a binary classification problem. I used the built-in scikit-learn breast_cancer dataset. The goal is to predict whether a breast mass is cancerous." }, { "code": null, "e": 5263, "s": 4899, "text": "The features consist of numeric data about cell nuclei. They were computed from digitized images of biopsies. The dataset contains 569 observations and 30 numeric features. I split the dataset into training and test sets and conducted a grid search on the training set with each different solver. You can access my Jupyter notebook used in all analyses on Kaggle." }, { "code": null, "e": 5304, "s": 5263, "text": "The most relevant code snippet is below." }, { "code": null, "e": 5655, "s": 5304, "text": "solver_list = ['liblinear', 'newton-cg', 'lbfgs', 'sag', 'saga']params = dict(solver=solver_list)log_reg = LogisticRegression(C=1, n_jobs=-1, random_state=34)clf = GridSearchCV(log_reg, params, cv=5)clf.fit(X_train, y_train)scores = clf.cv_results_['mean_test_score']for score, solver in zip(scores, solver_list): print(f\" {solver} {score:.3f}\" )" }, { "code": null, "e": 5681, "s": 5655, "text": "And here are the results:" }, { "code": null, "e": 5752, "s": 5681, "text": " liblinear 0.939 newton-cg 0.939 lbfgs 0.934 sag 0.911 saga 0.904" }, { "code": null, "e": 5823, "s": 5752, "text": "The accuracy values for sag and saga are a bit lower than their peers." }, { "code": null, "e": 5942, "s": 5823, "text": "After scaling the features, the solvers all perform better and sag and saga are just as accurate as the other solvers." }, { "code": null, "e": 6022, "s": 5942, "text": " liblinear 0.960 newton-cg 0.962 lbfgs 0.962 sag 0.962 saga 0.962" }, { "code": null, "e": 6071, "s": 6022, "text": "Now let’s look at an example with three classes." }, { "code": null, "e": 6351, "s": 6071, "text": "I evaluated the logistic regression solvers in a multi-class classification problem with Scikit-learn’s wine dataset. The dataset contains 178 samples and 13 numeric features. The goal is to predict the type of grapes used to make the wine from the chemical features of the wine." }, { "code": null, "e": 6719, "s": 6351, "text": "solver_list = ['liblinear', 'newton-cg', 'lbfgs', 'sag', 'saga']parameters = dict(solver=solver_list)lr = LogisticRegression(random_state=34, multi_class=\"auto\", n_jobs=-1, C=1)clf = GridSearchCV(lr, parameters, cv=5)clf.fit(X_train, y_train)scores = clf.cv_results_['mean_test_score']for score, solver, in zip(scores, solver_list): print(f\"{solver}: {score:.3f}\")" }, { "code": null, "e": 6913, "s": 6719, "text": "Scikit-learn gives a warning that the sag and saga models did not converge. In other words, they never arrived at a minimum point. Unsurprisingly, the results aren’t so great for those solvers." }, { "code": null, "e": 6979, "s": 6913, "text": "liblinear: 0.962newton-cg: 0.947lbfgs: 0.955sag: 0.699saga: 0.662" }, { "code": null, "e": 7055, "s": 6979, "text": "Let’s make a little bar chart using the Seaborn library to show the scores." }, { "code": null, "e": 7174, "s": 7055, "text": "After scaling the features between 0 and 1, then sag and saga reach the same mean accuracy scores as the other models." }, { "code": null, "e": 7240, "s": 7174, "text": "liblinear: 0.955newton-cg: 0.970lbfgs: 0.970sag: 0.970saga: 0.970" }, { "code": null, "e": 7385, "s": 7240, "text": "Note the caveat that both of these examples are with small datasets. Also, we’re not looking at memory and speed requirements in these examples." }, { "code": null, "e": 7644, "s": 7385, "text": "Bottom line: the forthcoming default lbfgs solver is a good first choice for most cases. If you’re dealing with a large dataset or want to apply L1 regularization, I suggest you start with saga. Remember that saga needs the features to be on a similar scale." }, { "code": null, "e": 7728, "s": 7644, "text": "Do you have a use case for newton-cg or sag? If so, please share in the comments. 💬" }, { "code": null, "e": 7811, "s": 7728, "text": "Next, I’ll demystify key parameter options for LogisticRegression in Scikit-learn." }, { "code": null, "e": 7887, "s": 7811, "text": "The Scikit-learn LogisticRegression class can take the following arguments." }, { "code": null, "e": 8028, "s": 7887, "text": "penalty, dual, tol, C, fit_intercept, intercept_scaling, class_weight, random_state, solver, max_iter, verbose, warm_start, n_jobs, l1_ratio" }, { "code": null, "e": 8238, "s": 8028, "text": "I won’t include all of the parameters below, just excerpts from those parameters most likely to be valuable to most folks. See the docs for those that are omitted. I’ve added additional information in italics." }, { "code": null, "e": 8439, "s": 8238, "text": "C — float, optional, default = 1. Smaller values have more regularization. Inverse of regularization strength. Must be positive value. Usually search logarithmically: [.001, .01, .1, 1, 10, 100, 1000]" }, { "code": null, "e": 8579, "s": 8439, "text": "random_state : int, RandomState instance or None, optional (default=None) Note that you must set the random state here for reproducibility." }, { "code": null, "e": 8705, "s": 8579, "text": "solver {‘newton-cg’, ‘lbfgs’, ‘liblinear’, ‘sag’, ‘saga’}, optional (default=’liblinear’). See the chart above for more info." }, { "code": null, "e": 8787, "s": 8705, "text": "Changed in version 0.20: Default will change from ‘liblinear’ to ‘lbfgs’ in 0.22." }, { "code": null, "e": 9239, "s": 8787, "text": "multi_class : str, {‘ovr’, ‘multinomial’, ‘auto’}, optional (default=’ovr’) If the option chosen is ‘ovr’, then a binary problem is fit for each label. For ‘multinomial’ the loss minimised is the multinomial loss fit across the entire probability distribution, even when the data is binary. ‘multinomial’ is unavailable when solver=’liblinear’. ‘auto’ selects ‘ovr’ if the data is binary, or if solver=’liblinear’, and otherwise selects ‘multinomial’." }, { "code": null, "e": 9373, "s": 9239, "text": "Changed in version 0.20: Default will change from ‘ovr’ to ‘auto’ in 0.22. ovr stands for one vs. rest. See further discussion below." }, { "code": null, "e": 9715, "s": 9373, "text": "l1_ratio : float or None, optional (default=None) The Elastic-Net mixing parameter, with 0 <= l1_ratio <= 1. Only used if penalty='elasticnet'. Setting `l1_ratio=0 is equivalent to using penalty='l2', while setting l1_ratio=1 is equivalent to using penalty='l1'. For 0 < l1_ratio <1, the penalty is a combination of L1 and L2. Only for saga." }, { "code": null, "e": 9928, "s": 9715, "text": "Commentary: If you have a multiclass problem, then setting multi-class to auto will use the multinomial option every time it's available. That's the most theoretically sound choice. auto will soon be the default." }, { "code": null, "e": 10102, "s": 9928, "text": "Use l1_ratio if want to use some L1 regularization with the saga solver. Note that like the ElasticNet linear regression option, you can use a mix of L1 and L2 penalization." }, { "code": null, "e": 10317, "s": 10102, "text": "Also note that an L2 regularization of C=1 is applied by default. This default regularization makes models more robust to multicollinearity, but at the expense of less interpretability (hat tip to Andreas Mueller)." }, { "code": null, "e": 10450, "s": 10317, "text": "After fitting the model the attributes are: classes_, coef_, intercept_, and n_iter. coef_ contains an array of the feature weights." }, { "code": null, "e": 10550, "s": 10450, "text": "Now let’s address those nagging questions you might have about Logistic Regression in Scikit-learn." }, { "code": null, "e": 10625, "s": 10550, "text": "Nope. Sorry, if you need that, find another classification algorithm here." }, { "code": null, "e": 10918, "s": 10625, "text": "Regularization shifts your model toward the bias side of things in the bias/variance tradeoff. Regularization makes for a more generalizable logistic regression model, especially in cases with few data points. You’ll probably want to hyperparameter search over the regularization parameter C." }, { "code": null, "e": 11190, "s": 10918, "text": "If you want to do some dimensionality reduction through regularization, use L1 regularization. L1 regularization is Manhattan or Taxicab regularization. L2 regularization is Euclidian regularization and generally performs better in generalized linear regression problems." }, { "code": null, "e": 11484, "s": 11190, "text": "You must use the saga solver if you want to apply a mix of L1 and L2 regularization. The liblinear solver requires you to have regularization. However, you could just make C such as a large value that it had a very, very small regularization penalty. Again, C is currently set to 1 by default." }, { "code": null, "e": 11767, "s": 11484, "text": "If using sag and saga solvers, make sure the features are on a similar scale. We saw the importance of this above. Andreas Mueller, in private correspondence, also mentioned that he found convergence issues on unscaled data with lbfgs, although it was more robust than sag and saga." }, { "code": null, "e": 11809, "s": 11767, "text": "Bottom line: to be safe, scale your data." }, { "code": null, "e": 11941, "s": 11809, "text": "Probably. Removing outliers will generally improve model performance. Standardizing the inputs would also reduce outliers’ effects." }, { "code": null, "e": 12068, "s": 11941, "text": "RobustScaler can scale features and you can avoid dropping outliers. See my article discussing scaling and standardizing here." }, { "code": null, "e": 12118, "s": 12068, "text": "Observations should be independent of each other." }, { "code": null, "e": 12503, "s": 12118, "text": "Just as in linear regression, you can use higher order polynomials and interactions. This transformation allows your model to learn a more complex decision boundary. Then, you aren’t limited to a linear decision boundary. However, overfitting becomes a risk and interpreting feature importances gets trickier. It might also be more difficult for the solver to find the global minimum." }, { "code": null, "e": 12786, "s": 12503, "text": "Maybe. Principal Components Analysis is a nice choice if interpretability isn’t vital. Recursive Feature Elimination can help you remove the least important features. Alternatively, L1 regularization can drive less important feature weights to zero if you are using the saga solver." }, { "code": null, "e": 13037, "s": 12786, "text": "It is for interpretation of the feature importances. You can’t rely on the model weights to be meaningful when there is high correlation between the variables. Credit for affecting the outcome variable might go to just one of the correlated features." }, { "code": null, "e": 13118, "s": 13037, "text": "There are many ways to test for multicollinearity. See Kraha et al. (2012) here." }, { "code": null, "e": 13301, "s": 13118, "text": "One popular option is to check the Variance Inflation Factor (VIF). A VIF cutoff around 5 to 10 is common, but there’s a lively debate as to what an appropriate VIF cutoff should be." }, { "code": null, "e": 13429, "s": 13301, "text": "You can compute the VIF by taking the correlation matrix, inverting it, and taking the values on the diagonal for each feature." }, { "code": null, "e": 13550, "s": 13429, "text": "The correlation coefficients alone are not sufficient to determine problematic multicollinearity with multiple features." }, { "code": null, "e": 13652, "s": 13550, "text": "If the sample size is small, getting more data might be most helpful for removing multi-collinearity." }, { "code": null, "e": 13836, "s": 13652, "text": "LogisticRegressionCV is the Scikit-learn algorithm you want if you have a lot of data and want to speed up your calculations while doing cross-validation to tune your hyperparameters." }, { "code": null, "e": 13982, "s": 13836, "text": "Now you know what to do when you see the LogisticRegression solver warning — and better yet, how to avoid it in the first place. No more sweat! 😅" }, { "code": null, "e": 14169, "s": 13982, "text": "I suggest you use the upcoming default lbfgs solver for most cases. If you have a lot of data or need L1 regularization, try saga. Make sure you scale your features if you’re using saga." }, { "code": null, "e": 14328, "s": 14169, "text": "I hope you found this discussion of logistic regression helpful. If you did, please share it on your favorite social media so other people can find it, too. 👍" } ]
Python Getting started with psycopg2-PostgreSQL
In this tutorial, we are going to learn how to use PostgreSQL with Python. You have to install certain thing before going into the tutorial. Let's install them. Install the PostgreSQL with the guide.. Install the Python module psycopg2 for PostgreSQL connection and working. Run the command to install it. pip install psycopg2 Now, open the pgAdmin. And create a sample database. Next, follow the below steps to get started with database operations. Import the psycopg2 module. Store the database name, username, and password in separate variables. Make a connection to the database using psycopg2.connect(database=name, user=name, password=password) method. Instantiate a cursor object to execute SQL commands. Create queries and execute them with cursor.execute(query) method. And get the information using cursor.fetchall() method if available. Close the connection using connection.close() method. # importing the psycopg2 module import psycopg2 # storing all the information database = 'testing' user = 'postgres' password = 'C&o%Z?bc' # connecting to the database connection = psycopg2.connect(database=database, user=user, password=password) # instantiating the cursor cursor = connection.cursor() # query to create a table create_table = "CREATE TABLE testing_members (id SERIAL PRIMARY KEY, name VARCH 25) NOT NULL)" # executing the query cursor.execute(create_table) # sample data to populate the database table testing_members = ['Python', 'C', 'JavaScript', 'React', 'Django'] # query to populate the table testing_members for testing_member in testing_members: populate_db = f"INSERT INTO testing_members (name) VALUES ('{testing_member cursor.execute(populate_db) # saving the changes to the database connection.commit() # query to fetch all fetch_all = "SELECT * FROM testing_members" cursor.execute(fetch_all) # fetching all the rows rows = cursor.fetchall() # printing the data for row in rows: print(f"{row[0]} {row[1]}") # closing the connection connection.close() If you run the above code, then you will get the following result. 1 Python 2 C 3 JavaScript 4 React 5 Django If you have any doubts in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1223, "s": 1062, "text": "In this tutorial, we are going to learn how to use PostgreSQL with Python. You have to install certain thing before going into the tutorial. Let's install them." }, { "code": null, "e": 1263, "s": 1223, "text": "Install the PostgreSQL with the guide.." }, { "code": null, "e": 1368, "s": 1263, "text": "Install the Python module psycopg2 for PostgreSQL connection and working. Run the command to install it." }, { "code": null, "e": 1389, "s": 1368, "text": "pip install psycopg2" }, { "code": null, "e": 1512, "s": 1389, "text": "Now, open the pgAdmin. And create a sample database. Next, follow the below steps to get started with database operations." }, { "code": null, "e": 1540, "s": 1512, "text": "Import the psycopg2 module." }, { "code": null, "e": 1611, "s": 1540, "text": "Store the database name, username, and password in separate variables." }, { "code": null, "e": 1721, "s": 1611, "text": "Make a connection to the database using psycopg2.connect(database=name,\nuser=name, password=password) method." }, { "code": null, "e": 1774, "s": 1721, "text": "Instantiate a cursor object to execute SQL commands." }, { "code": null, "e": 1841, "s": 1774, "text": "Create queries and execute them with cursor.execute(query) method." }, { "code": null, "e": 1910, "s": 1841, "text": "And get the information using cursor.fetchall() method if available." }, { "code": null, "e": 1964, "s": 1910, "text": "Close the connection using connection.close() method." }, { "code": null, "e": 3097, "s": 1964, "text": "# importing the psycopg2 module\nimport psycopg2\n# storing all the information\ndatabase = 'testing'\nuser = 'postgres'\npassword = 'C&o%Z?bc'\n# connecting to the database\nconnection = psycopg2.connect(database=database, user=user, password=password)\n# instantiating the cursor\ncursor = connection.cursor()\n# query to create a table\ncreate_table = \"CREATE TABLE testing_members (id SERIAL PRIMARY KEY, name VARCH\n25) NOT NULL)\"\n# executing the query\ncursor.execute(create_table)\n# sample data to populate the database table\ntesting_members = ['Python', 'C', 'JavaScript', 'React', 'Django']\n# query to populate the table testing_members\nfor testing_member in testing_members:\n populate_db = f\"INSERT INTO testing_members (name) VALUES ('{testing_member\n cursor.execute(populate_db)\n # saving the changes to the database\n connection.commit()\n # query to fetch all\n fetch_all = \"SELECT * FROM testing_members\"\n cursor.execute(fetch_all)\n # fetching all the rows\n rows = cursor.fetchall()\n # printing the data\n for row in rows:\n print(f\"{row[0]} {row[1]}\")\n # closing the connection\n connection.close()" }, { "code": null, "e": 3164, "s": 3097, "text": "If you run the above code, then you will get the following result." }, { "code": null, "e": 3207, "s": 3164, "text": "1 Python\n2 C\n3 JavaScript\n4 React\n5 Django" }, { "code": null, "e": 3284, "s": 3207, "text": "If you have any doubts in the tutorial, mention them in the comment section." } ]
Difference between Comparable and Comparator in Java
Comparable and comparator both are an interface that can be used to sort the elements of the collection. Comparator interface belongs to java.util package while comparable belongs to java.lang package. Comparator interface sort collection using two objects provided to it, whereas comparable interface compares" this" refers to the one objects provided to it. public class ComparableExample { public static void main(String[] args) { List<Laptop> laptopList = new ArrayList<>(); laptopList.add(new Laptop("HCL", 16, 800)); laptopList.add(new Laptop("Apple", 8, 100)); laptopList.add(new Laptop("Dell", 4, 600)); Collections.sort(laptopList); for (Laptop lap : laptopList) { System.out.println(lap.getRam()); } } } public class Laptop implements Comparable<Laptop> { String name; int ram; int price; public Laptop(String name, int ram, int price) { super(); this.name = name; this.ram = ram; this.price = price; } public String getName() { return name; } public int getRam() { return ram; } public void setRam(int ram) { this.ram = ram; } public void setName(String name) { this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public int compareTo(Laptop o) { if (this.ram > o.getRam()) return 1; else { return -1; } } } 4 8 16 import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Laptop implements Comparator { String name; int ram; int price; public Laptop(String name, int ram, int price) { super(); this.name = name; this.ram = ram; this.price = price; } public String getName() { return name; } public int getRam() { return ram; } public void setRam(int ram) { this.ram = ram; } public void setName(String name) { this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public int compare(Laptop o1, Laptop o2) { if (o1.getRam() < o2.getRam()) { return -1; }else if (o1.getRam() > o2.getRam()) { return 1; } else { return 0; } } public static void main(String[] args) { List laptopList = new ArrayList<>(); laptopList.add(new Laptop("HCL", 16, 800)); laptopList.add(new Laptop("Apple", 8, 100)); laptopList.add(new Laptop("Dell", 4, 600)); Comparator com = (Laptop o1, Laptop o2) -> o1.getName().compareTo(o2.getName()); Collections.sort(laptopList, com); for (Laptop lap : laptopList) { System.out.println(lap.getName()); } } } Apple Dell HCL
[ { "code": null, "e": 1423, "s": 1062, "text": "Comparable and comparator both are an interface that can be used to sort the elements of the collection. Comparator interface belongs to java.util package while comparable belongs to java.lang package. Comparator interface sort collection using two objects provided to it, whereas comparable interface compares\" this\" refers to the one objects provided to it. " }, { "code": null, "e": 2571, "s": 1423, "text": "public class ComparableExample {\n public static void main(String[] args) {\n List<Laptop> laptopList = new ArrayList<>();\n laptopList.add(new Laptop(\"HCL\", 16, 800));\n laptopList.add(new Laptop(\"Apple\", 8, 100));\n laptopList.add(new Laptop(\"Dell\", 4, 600));\n Collections.sort(laptopList);\n for (Laptop lap : laptopList) {\n System.out.println(lap.getRam());\n }\n }\n}\npublic class Laptop implements Comparable<Laptop> {\n String name;\n int ram;\n int price;\n public Laptop(String name, int ram, int price) {\n super();\n this.name = name;\n this.ram = ram;\n this.price = price;\n }\n public String getName() {\n return name;\n }\n public int getRam() {\n return ram;\n }\n public void setRam(int ram) {\n this.ram = ram;\n }\n public void setName(String name) {\n this.name = name;\n }\n public int getPrice() {\n return price;\n }\n public void setPrice(int price) {\n this.price = price;\n }\n @Override\n public int compareTo(Laptop o) {\n if (this.ram > o.getRam())\n return 1;\n else {\n return -1;\n } \n }\n}" }, { "code": null, "e": 2578, "s": 2571, "text": "4\n8\n16" }, { "code": null, "e": 3959, "s": 2578, "text": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.List;\n\npublic class Laptop implements Comparator {\n String name;\n int ram;\n int price;\n public Laptop(String name, int ram, int price) {\n super();\n this.name = name;\n this.ram = ram;\n this.price = price;\n }\n public String getName() {\n return name;\n }\n public int getRam() {\n return ram;\n }\n public void setRam(int ram) {\n this.ram = ram;\n }\n public void setName(String name) {\n this.name = name;\n }\n public int getPrice() {\n return price;\n }\n public void setPrice(int price) {\n this.price = price;\n }\n @Override\n public int compare(Laptop o1, Laptop o2) {\n if (o1.getRam() < o2.getRam()) {\n return -1;\n }else if (o1.getRam() > o2.getRam()) {\n return 1;\n } else {\n return 0;\n }\n }\n public static void main(String[] args) {\n List laptopList = new ArrayList<>();\n laptopList.add(new Laptop(\"HCL\", 16, 800));\n laptopList.add(new Laptop(\"Apple\", 8, 100));\n laptopList.add(new Laptop(\"Dell\", 4, 600));\n Comparator com = (Laptop o1, Laptop o2) -> o1.getName().compareTo(o2.getName());\n Collections.sort(laptopList, com);\n for (Laptop lap : laptopList) {\n System.out.println(lap.getName());\n }\n }\n}" }, { "code": null, "e": 3974, "s": 3959, "text": "Apple\nDell\nHCL" } ]
Java sql.Date setTime() method with example.
The setTime() method of the java.util.Date class accepts a variable of long type, representing the number of milliseconds from the epoch time (January 1, 1970 00:00:00.000 GMT) to the required time, and sets the specified time value to the current Date object. //Setting time date.setTime(time_value_in_long); Let us create a table with name dispatches in MySQL database using CREATE statement as follows − CREATE TABLE dispatches( ProductName VARCHAR(255), CustomerName VARCHAR(255), DispatchDate date, DeliveryTime time, Price INT, Location VARCHAR(255)); Now, we will insert 5 records in dispatches table using INSERT statements − insert into dispatches values('Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'Hyderabad'); insert into dispatches values('Earphones', 'Roja', DATE('2019-05-01'), TIME('11:00:00'), 2000, 'Vishakhapatnam'); insert into dispatches values('Mouse', 'Puja', DATE('2019-03-01'), TIME('10:59:59'), 3000, 'Vijayawada'); insert into dispatches values('Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai'); insert into dispatches values('Headset', 'Jalaja', DATE('2019-04-06'), TIME('11:08:59'), 6000, 'Goa'); Following JDBC example inserts a new record into the dispatches table by passing the required values. import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Time; public class Date_setTime { 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......"); //Instantiating the Time class Date date = new Date(0L); //Setting time date.setTime(new java.util.Date().getTime()); //Creating a Prepared Statement String query = "INSERT INTO Dispatches VALUES (?, ?, ?, ?, ?, ?)"; PreparedStatement pstmt = con.prepareStatement(query); pstmt.setString(1, "Watch"); pstmt.setString(2, "Rajan"); pstmt.setDate(3, date); pstmt.setTime(4, new Time(date.getTime())); pstmt.setInt(5, 4000); pstmt.setString(6, "Chennai"); pstmt.execute(); System.out.println("Rows inserted ...."); //Retrieving values Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from dispatches"); while(rs.next()) { System.out.println("Product Name: "+rs.getString("ProductName")); System.out.println("Customer Name: "+rs.getString("CustomerName")); System.out.println("Date Of Dispatch: "+rs.getDate("DispatchDate")); System.out.println("Delivery Time: "+rs.getTime("DeliveryTime")); System.out.println("Location: "+rs.getString("Location")); System.out.println(); } } } Here, in this program we have instantiated a Date class by passing 0L to its constructor (epoch time:1970-01-01 05:30:00.0) and changed its time to current time using the setTime() method. And we are trying to insert this time value under the DeliveryTime column in this record. Connection established...... Rows inserted .... Product Name: Key-Board Customer Name: Raja Date Of Dispatch: 2019-09-01 Delivery Time: 11:00:00 Location: Hyderabad Product Name: Earphones Customer Name: Roja Date Of Dispatch: 2019-05-01 Delivery Time: 11:00:00 Location: Vishakhapatnam Product Name: Mouse Customer Name: Puja Date Of Dispatch: 2019-03-01 Delivery Time: 10:59:59 Location: Vijayawada Product Name: Mobile Customer Name: Vanaja Date Of Dispatch: 2019-03-01 Delivery Time: 10:10:52 Location: Chennai Product Name: Headset Customer Name: Jalaja Date Of Dispatch: 2019-04-06 Delivery Time: 11:08:59 Location: Goa Product Name: Watch Customer Name: Rajan Date Of Dispatch: 2019-03-28 Delivery Time: 17:49:35 Location: Chennai
[ { "code": null, "e": 1323, "s": 1062, "text": "The setTime() method of the java.util.Date class accepts a variable of long type, representing the number of milliseconds from the epoch time (January 1, 1970 00:00:00.000 GMT) to the required time, and sets the specified time value to the current Date object." }, { "code": null, "e": 1372, "s": 1323, "text": "//Setting time\ndate.setTime(time_value_in_long);" }, { "code": null, "e": 1469, "s": 1372, "text": "Let us create a table with name dispatches in MySQL database using CREATE statement as follows −" }, { "code": null, "e": 1638, "s": 1469, "text": "CREATE TABLE dispatches(\n ProductName VARCHAR(255),\n CustomerName VARCHAR(255),\n DispatchDate date,\n DeliveryTime time,\n Price INT,\n Location VARCHAR(255));" }, { "code": null, "e": 1714, "s": 1638, "text": "Now, we will insert 5 records in dispatches table using INSERT statements −" }, { "code": null, "e": 2252, "s": 1714, "text": "insert into dispatches values('Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'Hyderabad');\ninsert into dispatches values('Earphones', 'Roja', DATE('2019-05-01'), TIME('11:00:00'), 2000, 'Vishakhapatnam');\ninsert into dispatches values('Mouse', 'Puja', DATE('2019-03-01'), TIME('10:59:59'), 3000, 'Vijayawada');\ninsert into dispatches values('Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai');\ninsert into dispatches values('Headset', 'Jalaja', DATE('2019-04-06'), TIME('11:08:59'), 6000, 'Goa');" }, { "code": null, "e": 2354, "s": 2252, "text": "Following JDBC example inserts a new record into the dispatches table by passing the required values." }, { "code": null, "e": 4181, "s": 2354, "text": "import java.sql.Connection;\nimport java.sql.Date;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\nimport java.sql.Time;\npublic class Date_setTime {\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 //Instantiating the Time class\n Date date = new Date(0L);\n //Setting time\n date.setTime(new java.util.Date().getTime());\n //Creating a Prepared Statement\n String query = \"INSERT INTO Dispatches VALUES (?, ?, ?, ?, ?, ?)\";\n PreparedStatement pstmt = con.prepareStatement(query);\n pstmt.setString(1, \"Watch\");\n pstmt.setString(2, \"Rajan\");\n pstmt.setDate(3, date);\n pstmt.setTime(4, new Time(date.getTime()));\n pstmt.setInt(5, 4000);\n pstmt.setString(6, \"Chennai\");\n pstmt.execute();\n System.out.println(\"Rows inserted ....\");\n //Retrieving values\n Statement stmt = con.createStatement();\n ResultSet rs = stmt.executeQuery(\"select * from dispatches\");\n while(rs.next()) {\n System.out.println(\"Product Name: \"+rs.getString(\"ProductName\"));\n System.out.println(\"Customer Name: \"+rs.getString(\"CustomerName\"));\n System.out.println(\"Date Of Dispatch: \"+rs.getDate(\"DispatchDate\"));\n System.out.println(\"Delivery Time: \"+rs.getTime(\"DeliveryTime\"));\n System.out.println(\"Location: \"+rs.getString(\"Location\"));\n System.out.println();\n }\n }\n}" }, { "code": null, "e": 4370, "s": 4181, "text": "Here, in this program we have instantiated a Date class by passing 0L to its constructor (epoch time:1970-01-01 05:30:00.0) and changed its time to current time using the setTime() method." }, { "code": null, "e": 4460, "s": 4370, "text": "And we are trying to insert this time value under the DeliveryTime column in this record." }, { "code": null, "e": 5198, "s": 4460, "text": "Connection established......\nRows inserted ....\nProduct Name: Key-Board\nCustomer Name: Raja\nDate Of Dispatch: 2019-09-01\nDelivery Time: 11:00:00\nLocation: Hyderabad\nProduct Name: Earphones\nCustomer Name: Roja\nDate Of Dispatch: 2019-05-01\nDelivery Time: 11:00:00\nLocation: Vishakhapatnam\nProduct Name: Mouse\nCustomer Name: Puja\nDate Of Dispatch: 2019-03-01\nDelivery Time: 10:59:59\nLocation: Vijayawada\nProduct Name: Mobile\nCustomer Name: Vanaja\nDate Of Dispatch: 2019-03-01\nDelivery Time: 10:10:52\nLocation: Chennai\nProduct Name: Headset\nCustomer Name: Jalaja\nDate Of Dispatch: 2019-04-06\nDelivery Time: 11:08:59\nLocation: Goa\nProduct Name: Watch\nCustomer Name: Rajan\nDate Of Dispatch: 2019-03-28\nDelivery Time: 17:49:35\nLocation: Chennai" } ]
Implementation of Threads
In this chapter, we will learn how to implement threads in Python. Python threads are sometimes called lightweight processes because threads occupy much less memory than processes. Threads allow performing multiple tasks at once. In Python, we have the following two modules that implement threads in a program − <_thread>module <_thread>module <threading>module <threading>module The main difference between these two modules is that <_thread> module treats a thread as a function whereas, the <threading> module treats every thread as an object and implements it in an object oriented way. Moreover, the <_thread>module is effective in low level threading and has fewer capabilities than the <threading> module. In the earlier version of Python, we had the <thread> module but it has been considered as "deprecated" for quite a long time. Users have been encouraged to use the <threading> module instead. Therefore, in Python 3 the module "thread" is not available anymore. It has been renamed to "<_thread>" for backwards incompatibilities in Python3. To generate new thread with the help of the <_thread> module, we need to call the start_new_thread method of it. The working of this method can be understood with the help of following syntax − _thread.start_new_thread ( function, args[, kwargs] ) Here − args is a tuple of arguments args is a tuple of arguments kwargs is an optional dictionary of keyword arguments kwargs is an optional dictionary of keyword arguments If we want to call function without passing an argument then we need to use an empty tuple of arguments in args. This method call returns immediately, the child thread starts, and calls function with the passed list, if any, of args. The thread terminates as and when the function returns. Following is an example for generating new thread by using the <_thread> module. We are using the start_new_thread() method here. import _thread import time def print_time( threadName, delay): count = 0 while count < 5: time.sleep(delay) count += 1 print ("%s: %s" % ( threadName, time.ctime(time.time()) )) try: _thread.start_new_thread( print_time, ("Thread-1", 2, ) ) _thread.start_new_thread( print_time, ("Thread-2", 4, ) ) except: print ("Error: unable to start thread") while 1: pass The following output will help us understand the generation of new threads bwith the help of the <_thread> module. Thread-1: Mon Apr 23 10:03:33 2018 Thread-2: Mon Apr 23 10:03:35 2018 Thread-1: Mon Apr 23 10:03:35 2018 Thread-1: Mon Apr 23 10:03:37 2018 Thread-2: Mon Apr 23 10:03:39 2018 Thread-1: Mon Apr 23 10:03:39 2018 Thread-1: Mon Apr 23 10:03:41 2018 Thread-2: Mon Apr 23 10:03:43 2018 Thread-2: Mon Apr 23 10:03:47 2018 Thread-2: Mon Apr 23 10:03:51 2018 The <threading> module implements in an object oriented way and treats every thread as an object. Therefore, it provides much more powerful, high-level support for threads than the <_thread> module. This module is included with Python 2.4. The <threading> module comprises all the methods of the <_thread> module but it provides additional methods as well. The additional methods are as follows − threading.activeCount() − This method returns the number of thread objects that are active threading.activeCount() − This method returns the number of thread objects that are active threading.currentThread() − This method returns the number of thread objects in the caller's thread control. threading.currentThread() − This method returns the number of thread objects in the caller's thread control. threading.enumerate() − This method returns a list of all thread objects that are currently active. threading.enumerate() − This method returns a list of all thread objects that are currently active. For implementing threading, the <threading> module has the Thread class which provides the following methods − run() − The run() method is the entry point for a thread. run() − The run() method is the entry point for a thread. start() − The start() method starts a thread by calling the run method. start() − The start() method starts a thread by calling the run method. join([time]) − The join() waits for threads to terminate. join([time]) − The join() waits for threads to terminate. isAlive() − The isAlive() method checks whether a thread is still executing. isAlive() − The isAlive() method checks whether a thread is still executing. getName() − The getName() method returns the name of a thread. getName() − The getName() method returns the name of a thread. setName() − The setName() method sets the name of a thread. setName() − The setName() method sets the name of a thread. In this section, we will learn how to create threads using the <threading> module. Follow these steps to create a new thread using the <threading> module − Step 1 − In this step, we need to define a new subclass of the Thread class. Step 1 − In this step, we need to define a new subclass of the Thread class. Step 2 − Then for adding additional arguments, we need to override the __init__(self [,args]) method. Step 2 − Then for adding additional arguments, we need to override the __init__(self [,args]) method. Step 3 − In this step, we need to override the run(self [,args]) method to implement what the thread should do when started. Step 3 − In this step, we need to override the run(self [,args]) method to implement what the thread should do when started. Now, after creating the new Thread subclass, we can create an instance of it and then start a new thread by invoking the start(), which in turn calls the run() method. Consider this example to learn how to generate a new thread by using the <threading> module. import threading import time exitFlag = 0 class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print ("Starting " + self.name) print_time(self.name, self.counter, 5) print ("Exiting " + self.name) def print_time(threadName, delay, counter): while counter: if exitFlag: threadName.exit() time.sleep(delay) print ("%s: %s" % (threadName, time.ctime(time.time()))) counter -= 1 thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) thread1.start() thread2.start() thread1.join() thread2.join() print ("Exiting Main Thread") Starting Thread-1 Starting Thread-2 Now, consider the following output − Thread-1: Mon Apr 23 10:52:09 2018 Thread-1: Mon Apr 23 10:52:10 2018 Thread-2: Mon Apr 23 10:52:10 2018 Thread-1: Mon Apr 23 10:52:11 2018 Thread-1: Mon Apr 23 10:52:12 2018 Thread-2: Mon Apr 23 10:52:12 2018 Thread-1: Mon Apr 23 10:52:13 2018 Exiting Thread-1 Thread-2: Mon Apr 23 10:52:14 2018 Thread-2: Mon Apr 23 10:52:16 2018 Thread-2: Mon Apr 23 10:52:18 2018 Exiting Thread-2 Exiting Main Thread There are five thread states - new, runnable, running, waiting and dead. Among these five Of these five, we will majorly focus on three states - running, waiting and dead. A thread gets its resources in the running state, waits for the resources in the waiting state; the final release of the resource, if executing and acquired is in the dead state. The following Python program with the help of start(), sleep() and join() methods will show how a thread entered in running, waiting and dead state respectively. Step 1 − Import the necessary modules, <threading> and <time> import threading import time Step 2 − Define a function, which will be called while creating a thread. def thread_states(): print("Thread entered in running state") Step 3 − We are using the sleep() method of time module to make our thread waiting for say 2 seconds. time.sleep(2) Step 4 − Now, we are creating a thread named T1, which takes the argument of the function defined above. T1 = threading.Thread(target=thread_states) Step 5 − Now, with the help of the start() function we can start our thread. It will produce the message, which has been set by us while defining the function. T1.start() Thread entered in running state Step 6 − Now, at last we can kill the thread with the join() method after it finishes its execution. T1.join() In python, we can start a new thread by different ways but the easiest one among them is to define it as a single function. After defining the function, we can pass this as the target for a new threading.Thread object and so on. Execute the following Python code to understand how the function works − import threading import time import random def Thread_execution(i): print("Execution of Thread {} started\n".format(i)) sleepTime = random.randint(1,4) time.sleep(sleepTime) print("Execution of Thread {} finished".format(i)) for i in range(4): thread = threading.Thread(target=Thread_execution, args=(i,)) thread.start() print("Active Threads:" , threading.enumerate()) Execution of Thread 0 started Active Threads: [<_MainThread(MainThread, started 6040)>, <HistorySavingThread(IPythonHistorySavingThread, started 5968)>, <Thread(Thread-3576, started 3932)>] Execution of Thread 1 started Active Threads: [<_MainThread(MainThread, started 6040)>, <HistorySavingThread(IPythonHistorySavingThread, started 5968)>, <Thread(Thread-3576, started 3932)>, <Thread(Thread-3577, started 3080)>] Execution of Thread 2 started Active Threads: [<_MainThread(MainThread, started 6040)>, <HistorySavingThread(IPythonHistorySavingThread, started 5968)>, <Thread(Thread-3576, started 3932)>, <Thread(Thread-3577, started 3080)>, <Thread(Thread-3578, started 2268)>] Execution of Thread 3 started Active Threads: [<_MainThread(MainThread, started 6040)>, <HistorySavingThread(IPythonHistorySavingThread, started 5968)>, <Thread(Thread-3576, started 3932)>, <Thread(Thread-3577, started 3080)>, <Thread(Thread-3578, started 2268)>, <Thread(Thread-3579, started 4520)>] Execution of Thread 0 finished Execution of Thread 1 finished Execution of Thread 2 finished Execution of Thread 3 finished Before implementing the daemon threads in Python, we need to know about daemon threads and their usage. In terms of computing, daemon is a background process that handles the requests for various services such as data sending, file transfers, etc. It would be dormant if it is not required any more. The same task can be done with the help of non-daemon threads also. However, in this case, the main thread has to keep track of the non-daemon threads manually. On the other hand, if we are using daemon threads then the main thread can completely forget about this and it will be killed when main thread exits. Another important point about daemon threads is that we can opt to use them only for non-essential tasks that would not affect us if it does not complete or gets killed in between. Following is the implementation of daemon threads in python − import threading import time def nondaemonThread(): print("starting my thread") time.sleep(8) print("ending my thread") def daemonThread(): while True: print("Hello") time.sleep(2) if __name__ == '__main__': nondaemonThread = threading.Thread(target = nondaemonThread) daemonThread = threading.Thread(target = daemonThread) daemonThread.setDaemon(True) daemonThread.start() nondaemonThread.start() In the above code, there are two functions namely >nondaemonThread() and >daemonThread(). The first function prints its state and sleeps after 8 seconds while the the deamonThread() function prints Hello after every 2 seconds indefinitely. We can understand the difference between nondaemon and daemon threads with the help of following output − Hello starting my thread Hello Hello Hello Hello ending my thread Hello Hello Hello Hello Hello 57 Lectures 8 hours Denis Tishkov Print Add Notes Bookmark this page
[ { "code": null, "e": 1989, "s": 1922, "text": "In this chapter, we will learn how to implement threads in Python." }, { "code": null, "e": 2235, "s": 1989, "text": "Python threads are sometimes called lightweight processes because threads occupy much less memory than processes. Threads allow performing multiple tasks at once. In Python, we have the following two modules that implement threads in a program −" }, { "code": null, "e": 2251, "s": 2235, "text": "<_thread>module" }, { "code": null, "e": 2267, "s": 2251, "text": "<_thread>module" }, { "code": null, "e": 2285, "s": 2267, "text": "<threading>module" }, { "code": null, "e": 2303, "s": 2285, "text": "<threading>module" }, { "code": null, "e": 2636, "s": 2303, "text": "The main difference between these two modules is that <_thread> module treats a thread as a function whereas, the <threading> module treats every thread as an object and implements it in an object oriented way. Moreover, the <_thread>module is effective in low level threading and has fewer capabilities than the <threading> module." }, { "code": null, "e": 2977, "s": 2636, "text": "In the earlier version of Python, we had the <thread> module but it has been considered as \"deprecated\" for quite a long time. Users have been encouraged to use the <threading> module instead. Therefore, in Python 3 the module \"thread\" is not available anymore. It has been renamed to \"<_thread>\" for backwards incompatibilities in Python3." }, { "code": null, "e": 3171, "s": 2977, "text": "To generate new thread with the help of the <_thread> module, we need to call the start_new_thread method of it. The working of this method can be understood with the help of following syntax −" }, { "code": null, "e": 3226, "s": 3171, "text": "_thread.start_new_thread ( function, args[, kwargs] )\n" }, { "code": null, "e": 3233, "s": 3226, "text": "Here −" }, { "code": null, "e": 3262, "s": 3233, "text": "args is a tuple of arguments" }, { "code": null, "e": 3291, "s": 3262, "text": "args is a tuple of arguments" }, { "code": null, "e": 3345, "s": 3291, "text": "kwargs is an optional dictionary of keyword arguments" }, { "code": null, "e": 3399, "s": 3345, "text": "kwargs is an optional dictionary of keyword arguments" }, { "code": null, "e": 3512, "s": 3399, "text": "If we want to call function without passing an argument then we need to use an empty tuple of arguments in args." }, { "code": null, "e": 3689, "s": 3512, "text": "This method call returns immediately, the child thread starts, and calls function with the passed list, if any, of args. The thread terminates as and when the function returns." }, { "code": null, "e": 3819, "s": 3689, "text": "Following is an example for generating new thread by using the <_thread> module. We are using the start_new_thread() method here." }, { "code": null, "e": 4218, "s": 3819, "text": "import _thread\nimport time\n\ndef print_time( threadName, delay):\n count = 0\n while count < 5:\n time.sleep(delay)\n count += 1\n print (\"%s: %s\" % ( threadName, time.ctime(time.time()) ))\n\ntry:\n _thread.start_new_thread( print_time, (\"Thread-1\", 2, ) )\n _thread.start_new_thread( print_time, (\"Thread-2\", 4, ) )\nexcept:\n print (\"Error: unable to start thread\")\nwhile 1:\n pass" }, { "code": null, "e": 4333, "s": 4218, "text": "The following output will help us understand the generation of new threads bwith the help of the <_thread> module." }, { "code": null, "e": 4684, "s": 4333, "text": "Thread-1: Mon Apr 23 10:03:33 2018\nThread-2: Mon Apr 23 10:03:35 2018\nThread-1: Mon Apr 23 10:03:35 2018\nThread-1: Mon Apr 23 10:03:37 2018\nThread-2: Mon Apr 23 10:03:39 2018\nThread-1: Mon Apr 23 10:03:39 2018\nThread-1: Mon Apr 23 10:03:41 2018\nThread-2: Mon Apr 23 10:03:43 2018\nThread-2: Mon Apr 23 10:03:47 2018\nThread-2: Mon Apr 23 10:03:51 2018\n" }, { "code": null, "e": 4924, "s": 4684, "text": "The <threading> module implements in an object oriented way and treats every thread as an object. Therefore, it provides much more powerful, high-level support for threads than the <_thread> module. This module is included with Python 2.4." }, { "code": null, "e": 5081, "s": 4924, "text": "The <threading> module comprises all the methods of the <_thread> module but it provides additional methods as well. The additional methods are as follows −" }, { "code": null, "e": 5172, "s": 5081, "text": "threading.activeCount() − This method returns the number of thread objects that are active" }, { "code": null, "e": 5263, "s": 5172, "text": "threading.activeCount() − This method returns the number of thread objects that are active" }, { "code": null, "e": 5372, "s": 5263, "text": "threading.currentThread() − This method returns the number of thread objects in the caller's thread control." }, { "code": null, "e": 5481, "s": 5372, "text": "threading.currentThread() − This method returns the number of thread objects in the caller's thread control." }, { "code": null, "e": 5581, "s": 5481, "text": "threading.enumerate() − This method returns a list of all thread objects that are currently active." }, { "code": null, "e": 5681, "s": 5581, "text": "threading.enumerate() − This method returns a list of all thread objects that are currently active." }, { "code": null, "e": 5792, "s": 5681, "text": "For implementing threading, the <threading> module has the Thread class which provides the following methods −" }, { "code": null, "e": 5850, "s": 5792, "text": "run() − The run() method is the entry point for a thread." }, { "code": null, "e": 5908, "s": 5850, "text": "run() − The run() method is the entry point for a thread." }, { "code": null, "e": 5980, "s": 5908, "text": "start() − The start() method starts a thread by calling the run method." }, { "code": null, "e": 6052, "s": 5980, "text": "start() − The start() method starts a thread by calling the run method." }, { "code": null, "e": 6110, "s": 6052, "text": "join([time]) − The join() waits for threads to terminate." }, { "code": null, "e": 6168, "s": 6110, "text": "join([time]) − The join() waits for threads to terminate." }, { "code": null, "e": 6245, "s": 6168, "text": "isAlive() − The isAlive() method checks whether a thread is still executing." }, { "code": null, "e": 6322, "s": 6245, "text": "isAlive() − The isAlive() method checks whether a thread is still executing." }, { "code": null, "e": 6385, "s": 6322, "text": "getName() − The getName() method returns the name of a thread." }, { "code": null, "e": 6448, "s": 6385, "text": "getName() − The getName() method returns the name of a thread." }, { "code": null, "e": 6508, "s": 6448, "text": "setName() − The setName() method sets the name of a thread." }, { "code": null, "e": 6568, "s": 6508, "text": "setName() − The setName() method sets the name of a thread." }, { "code": null, "e": 6724, "s": 6568, "text": "In this section, we will learn how to create threads using the <threading> module. Follow these steps to create a new thread using the <threading> module −" }, { "code": null, "e": 6801, "s": 6724, "text": "Step 1 − In this step, we need to define a new subclass of the Thread class." }, { "code": null, "e": 6878, "s": 6801, "text": "Step 1 − In this step, we need to define a new subclass of the Thread class." }, { "code": null, "e": 6980, "s": 6878, "text": "Step 2 − Then for adding additional arguments, we need to override the __init__(self [,args]) method." }, { "code": null, "e": 7082, "s": 6980, "text": "Step 2 − Then for adding additional arguments, we need to override the __init__(self [,args]) method." }, { "code": null, "e": 7207, "s": 7082, "text": "Step 3 − In this step, we need to override the run(self [,args]) method to implement what the thread should do when started." }, { "code": null, "e": 7332, "s": 7207, "text": "Step 3 − In this step, we need to override the run(self [,args]) method to implement what the thread should do when started." }, { "code": null, "e": 7500, "s": 7332, "text": "Now, after creating the new Thread subclass, we can create an instance of it and then start a new thread by invoking the start(), which in turn calls the run() method." }, { "code": null, "e": 7593, "s": 7500, "text": "Consider this example to learn how to generate a new thread by using the <threading> module." }, { "code": null, "e": 8396, "s": 7593, "text": "import threading\nimport time\nexitFlag = 0\n\nclass myThread (threading.Thread):\n def __init__(self, threadID, name, counter):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.counter = counter\n def run(self):\n print (\"Starting \" + self.name)\n print_time(self.name, self.counter, 5)\n print (\"Exiting \" + self.name)\ndef print_time(threadName, delay, counter):\n while counter:\n if exitFlag:\n threadName.exit()\n time.sleep(delay)\n print (\"%s: %s\" % (threadName, time.ctime(time.time())))\n counter -= 1\n\nthread1 = myThread(1, \"Thread-1\", 1)\nthread2 = myThread(2, \"Thread-2\", 2)\n\nthread1.start()\nthread2.start()\nthread1.join()\nthread2.join()\nprint (\"Exiting Main Thread\")\nStarting Thread-1\nStarting Thread-2" }, { "code": null, "e": 8433, "s": 8396, "text": "Now, consider the following output −" }, { "code": null, "e": 8838, "s": 8433, "text": "Thread-1: Mon Apr 23 10:52:09 2018\nThread-1: Mon Apr 23 10:52:10 2018\nThread-2: Mon Apr 23 10:52:10 2018\nThread-1: Mon Apr 23 10:52:11 2018\nThread-1: Mon Apr 23 10:52:12 2018\nThread-2: Mon Apr 23 10:52:12 2018\nThread-1: Mon Apr 23 10:52:13 2018\nExiting Thread-1\nThread-2: Mon Apr 23 10:52:14 2018\nThread-2: Mon Apr 23 10:52:16 2018\nThread-2: Mon Apr 23 10:52:18 2018\nExiting Thread-2\nExiting Main Thread\n" }, { "code": null, "e": 9189, "s": 8838, "text": "There are five thread states - new, runnable, running, waiting and dead. Among these five Of these five, we will majorly focus on three states - running, waiting and dead. A thread gets its resources in the running state, waits for the resources in the waiting state; the final release of the resource, if executing and acquired is in the dead state." }, { "code": null, "e": 9351, "s": 9189, "text": "The following Python program with the help of start(), sleep() and join() methods will show how a thread entered in running, waiting and dead state respectively." }, { "code": null, "e": 9413, "s": 9351, "text": "Step 1 − Import the necessary modules, <threading> and <time>" }, { "code": null, "e": 9442, "s": 9413, "text": "import threading\nimport time" }, { "code": null, "e": 9516, "s": 9442, "text": "Step 2 − Define a function, which will be called while creating a thread." }, { "code": null, "e": 9581, "s": 9516, "text": "def thread_states():\n print(\"Thread entered in running state\")" }, { "code": null, "e": 9683, "s": 9581, "text": "Step 3 − We are using the sleep() method of time module to make our thread waiting for say 2 seconds." }, { "code": null, "e": 9697, "s": 9683, "text": "time.sleep(2)" }, { "code": null, "e": 9802, "s": 9697, "text": "Step 4 − Now, we are creating a thread named T1, which takes the argument of the function defined above." }, { "code": null, "e": 9846, "s": 9802, "text": "T1 = threading.Thread(target=thread_states)" }, { "code": null, "e": 10006, "s": 9846, "text": "Step 5 − Now, with the help of the start() function we can start our thread. It will produce the message, which has been set by us while defining the function." }, { "code": null, "e": 10049, "s": 10006, "text": "T1.start()\nThread entered in running state" }, { "code": null, "e": 10150, "s": 10049, "text": "Step 6 − Now, at last we can kill the thread with the join() method after it finishes its execution." }, { "code": null, "e": 10160, "s": 10150, "text": "T1.join()" }, { "code": null, "e": 10462, "s": 10160, "text": "In python, we can start a new thread by different ways but the easiest one among them is to define it as a single function. After defining the function, we can pass this as the target for a new threading.Thread object and so on. Execute the following Python code to understand how the function works −" }, { "code": null, "e": 10853, "s": 10462, "text": "import threading\nimport time\nimport random\ndef Thread_execution(i):\n print(\"Execution of Thread {} started\\n\".format(i))\n sleepTime = random.randint(1,4)\n time.sleep(sleepTime)\n print(\"Execution of Thread {} finished\".format(i))\nfor i in range(4):\n thread = threading.Thread(target=Thread_execution, args=(i,))\n thread.start()\n print(\"Active Threads:\" , threading.enumerate())" }, { "code": null, "e": 12059, "s": 10853, "text": "Execution of Thread 0 started\nActive Threads:\n [<_MainThread(MainThread, started 6040)>,\n <HistorySavingThread(IPythonHistorySavingThread, started 5968)>,\n <Thread(Thread-3576, started 3932)>]\n\nExecution of Thread 1 started\nActive Threads:\n [<_MainThread(MainThread, started 6040)>,\n <HistorySavingThread(IPythonHistorySavingThread, started 5968)>,\n <Thread(Thread-3576, started 3932)>,\n <Thread(Thread-3577, started 3080)>]\n\nExecution of Thread 2 started\nActive Threads:\n [<_MainThread(MainThread, started 6040)>,\n <HistorySavingThread(IPythonHistorySavingThread, started 5968)>,\n <Thread(Thread-3576, started 3932)>,\n <Thread(Thread-3577, started 3080)>,\n <Thread(Thread-3578, started 2268)>]\n\nExecution of Thread 3 started\nActive Threads:\n [<_MainThread(MainThread, started 6040)>,\n <HistorySavingThread(IPythonHistorySavingThread, started 5968)>,\n <Thread(Thread-3576, started 3932)>,\n <Thread(Thread-3577, started 3080)>,\n <Thread(Thread-3578, started 2268)>,\n <Thread(Thread-3579, started 4520)>]\nExecution of Thread 0 finished\nExecution of Thread 1 finished\nExecution of Thread 2 finished\nExecution of Thread 3 finished\n" }, { "code": null, "e": 12913, "s": 12059, "text": "Before implementing the daemon threads in Python, we need to know about daemon threads and their usage. In terms of computing, daemon is a background process that handles the requests for various services such as data sending, file transfers, etc. It would be dormant if it is not required any more. The same task can be done with the help of non-daemon threads also. However, in this case, the main thread has to keep track of the non-daemon threads manually. On the other hand, if we are using daemon threads then the main thread can completely forget about this and it will be killed when main thread exits. Another important point about daemon threads is that we can opt to use them only for non-essential tasks that would not affect us if it does not complete or gets killed in between. Following is the implementation of daemon threads in python −" }, { "code": null, "e": 13345, "s": 12913, "text": "import threading\nimport time\n\ndef nondaemonThread():\n print(\"starting my thread\")\n time.sleep(8)\n print(\"ending my thread\")\ndef daemonThread():\n while True:\n print(\"Hello\")\n time.sleep(2)\nif __name__ == '__main__':\n nondaemonThread = threading.Thread(target = nondaemonThread)\n daemonThread = threading.Thread(target = daemonThread)\n daemonThread.setDaemon(True)\n daemonThread.start()\n nondaemonThread.start()" }, { "code": null, "e": 13691, "s": 13345, "text": "In the above code, there are two functions namely >nondaemonThread() and >daemonThread(). The first function prints its state and sleeps after 8 seconds while the the deamonThread() function prints Hello after every 2 seconds indefinitely. We can understand the difference between nondaemon and daemon threads with the help of following output −" }, { "code": null, "e": 13789, "s": 13691, "text": "Hello\n\nstarting my thread\nHello\nHello\nHello\nHello\nending my thread\nHello\nHello\nHello\nHello\nHello\n" }, { "code": null, "e": 13822, "s": 13789, "text": "\n 57 Lectures \n 8 hours \n" }, { "code": null, "e": 13837, "s": 13822, "text": " Denis Tishkov" }, { "code": null, "e": 13844, "s": 13837, "text": " Print" }, { "code": null, "e": 13855, "s": 13844, "text": " Add Notes" } ]
Get only the file extension from a column with file names as strings in MySQL?
For this, use the substring_index() function. The syntax is as follows select substring_index(yourColumnName, '. ', -1) AS anyAliasNamefrom yourTableName; Let us first create a table. The query to create a table is as follows mysql> create table AllFiles - > ( - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, - > UserName varchar(10), - > FileName varchar(100) - > ); Query OK, 0 rows affected (0.65 sec) Insert some records in the table using insert command. The query is as follows mysql> insert into AllFiles(UserName,FileName) values('Larry','AddTwoNumber.java'); Query OK, 1 row affected (0.18 sec) mysql> insert into AllFiles(UserName,FileName) values('Mike','AddTwoNumber.python'); Query OK, 1 row affected (0.15 sec) mysql> insert into AllFiles(UserName,FileName) values('Sam','MatrixMultiplication.c'); Query OK, 1 row affected (0.16 sec) mysql> insert into AllFiles(UserName,FileName) values('Carol','vector.cpp'); Query OK, 1 row affected (0.15 sec) Display all records from the table using select statement. The query is as follows mysql> select *from AllFiles; The following is the output +----+----------+------------------------+ | Id | UserName | FileName | +----+----------+------------------------+ | 1 | Larry | AddTwoNumber.java | | 2 | Mike | AddTwoNumber.python | | 3 | Sam | MatrixMultiplication.c | | 4 | Carol | vector.cpp | +----+----------+------------------------+ 4 rows in set (0.00 sec) Here is the query to get only the file extension in MySQL mysql> select substring_index(FileName,'.',-1) AS ALLFILENAMEEXTENSIONS from AllFiles; The following is the output +-----------------------+ | ALLFILENAMEEXTENSIONS | +-----------------------+ | java | | python | | c | | cpp | +-----------------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1108, "s": 1062, "text": "For this, use the substring_index() function." }, { "code": null, "e": 1133, "s": 1108, "text": "The syntax is as follows" }, { "code": null, "e": 1217, "s": 1133, "text": "select substring_index(yourColumnName, '. ', -1) AS anyAliasNamefrom yourTableName;" }, { "code": null, "e": 1288, "s": 1217, "text": "Let us first create a table. The query to create a table is as follows" }, { "code": null, "e": 1482, "s": 1288, "text": "mysql> create table AllFiles\n - > (\n - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n - > UserName varchar(10),\n - > FileName varchar(100)\n - > );\nQuery OK, 0 rows affected (0.65 sec)" }, { "code": null, "e": 1537, "s": 1482, "text": "Insert some records in the table using insert command." }, { "code": null, "e": 1561, "s": 1537, "text": "The query is as follows" }, { "code": null, "e": 2038, "s": 1561, "text": "mysql> insert into AllFiles(UserName,FileName) values('Larry','AddTwoNumber.java');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into AllFiles(UserName,FileName) values('Mike','AddTwoNumber.python');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into AllFiles(UserName,FileName) values('Sam','MatrixMultiplication.c');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into AllFiles(UserName,FileName) values('Carol','vector.cpp');\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 2097, "s": 2038, "text": "Display all records from the table using select statement." }, { "code": null, "e": 2121, "s": 2097, "text": "The query is as follows" }, { "code": null, "e": 2151, "s": 2121, "text": "mysql> select *from AllFiles;" }, { "code": null, "e": 2179, "s": 2151, "text": "The following is the output" }, { "code": null, "e": 2548, "s": 2179, "text": "+----+----------+------------------------+\n| Id | UserName | FileName |\n+----+----------+------------------------+\n| 1 | Larry | AddTwoNumber.java |\n| 2 | Mike | AddTwoNumber.python |\n| 3 | Sam | MatrixMultiplication.c |\n| 4 | Carol | vector.cpp |\n+----+----------+------------------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2606, "s": 2548, "text": "Here is the query to get only the file extension in MySQL" }, { "code": null, "e": 2693, "s": 2606, "text": "mysql> select substring_index(FileName,'.',-1) AS ALLFILENAMEEXTENSIONS from AllFiles;" }, { "code": null, "e": 2721, "s": 2693, "text": "The following is the output" }, { "code": null, "e": 2954, "s": 2721, "text": "+-----------------------+\n| ALLFILENAMEEXTENSIONS |\n+-----------------------+\n| java |\n| python |\n| c |\n| cpp |\n+-----------------------+\n4 rows in set (0.00 sec)" } ]
C++ Program to Find Hamiltonian Cycle in an UnWeighted Graph
A Hamiltonian cycle is a Hamiltonian Path such that there is an edge (in graph) from the last vertex to the first vertex of the Hamiltonian Path. It is in an undirected graph is a path that visits each vertex of the graph exactly once. Begin 1. function isSafe() is used to check for whether it is adjacent to the previously added vertex and already not added. 2. function hamiltonianCycle() solves the hamiltonian problem. 3. function hamCycle() uses hamiltonianCycle() to solve the hamiltonian problem. It returns false if there is no Hamiltonian Cycle possible, otherwise return true and prints the path. End #include <iostream> #include <cstdio> #include <cstdlib> #define N 5 using namespace std; void displaytheSolution(int path[]); bool isSafe(int n, bool g[N][N], int path[], int pos) { if (g [path[pos-1]][n] == 0) return false; for (int i = 0; i < pos; i++) if (path[i] == n) return false; return true; } bool hamiltonianCycle(bool g[N][N], int path[], int pos) { //If all vertices are included in Hamiltonian Cycle if (pos == N) { if (g[ path[pos-1] ][ path[0] ] == 1) return true; else return false; } for (int n = 1; n < N; n++) { if (isSafe(n, g, path, pos)) { //Check if this vertex can be added to Hamiltonian Cycle path[pos] = n; //recur to construct rest of the path if (hamiltonianCycle (g, path, pos+1) == true) return true; path[pos] = -1; //remove vertex if it doesn’t lead to the solution } } return false; } bool hamCycle(bool g[N][N]) { int *path = new int[N]; for (int i = 0; i < N; i++) path[i] = -1; //put vertex 0 as the first vertex in the path. If there is a Hamiltonian Cycle, then the path can be started from any point //of the cycle as the graph is undirected path[0] = 0; if (hamiltonianCycle(g, path, 1) == false) { cout<<"\nCycle does not exist"<<endl; return false; } displaytheSolution(path); return true; } void displaytheSolution(int p[]) { cout<<"Cycle Exists:"; cout<<" Following is one Hamiltonian Cycle \n"<<endl; for (int i = 0; i < N; i++) cout<<p[i]<<" "; cout<< p[0]<<endl; } int main() { bool g[N][N] = {{0, 1, 0, 1, 1}, {0, 0, 1, 1, 0}, {0, 1, 0, 1, 1}, {1, 1, 1, 0, 1}, {0, 1, 1, 0, 0}, }; hamCycle(g); return 0; } Cycle Exists: Following is one Hamiltonian Cycle 0 4 1 2 3 0
[ { "code": null, "e": 1298, "s": 1062, "text": "A Hamiltonian cycle is a Hamiltonian Path such that there is an edge (in graph) from the last vertex to the first vertex of the Hamiltonian Path. It is in an undirected graph is a path that visits each vertex of the graph exactly once." }, { "code": null, "e": 1692, "s": 1298, "text": "Begin\n 1. function isSafe() is used to check for whether it is\n adjacent to the previously added vertex and already not added.\n 2. function hamiltonianCycle() solves the hamiltonian problem.\n 3. function hamCycle() uses hamiltonianCycle() to solve\n the hamiltonian problem. It returns false if there is no\n Hamiltonian Cycle possible, otherwise return true and prints the path.\nEnd" }, { "code": null, "e": 3479, "s": 1692, "text": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#define N 5\nusing namespace std;\nvoid displaytheSolution(int path[]);\nbool isSafe(int n, bool g[N][N], int path[], int pos) {\n if (g [path[pos-1]][n] == 0)\n return false;\n for (int i = 0; i < pos; i++)\n if (path[i] == n)\n return false;\n return true;\n}\nbool hamiltonianCycle(bool g[N][N], int path[], int pos) {\n //If all vertices are included in Hamiltonian Cycle\n if (pos == N) {\n if (g[ path[pos-1] ][ path[0] ] == 1)\n return true;\n else\n return false;\n }\n for (int n = 1; n < N; n++) {\n if (isSafe(n, g, path, pos)) { //Check if this vertex can be added to Hamiltonian Cycle\n path[pos] = n;\n //recur to construct rest of the path\n if (hamiltonianCycle (g, path, pos+1) == true)\n return true;\n path[pos] = -1; //remove vertex if it doesn’t lead to the solution\n }\n }\n return false;\n}\nbool hamCycle(bool g[N][N]) {\n int *path = new int[N];\n for (int i = 0; i < N; i++)\n path[i] = -1;\n //put vertex 0 as the first vertex in the path. If there is a Hamiltonian Cycle, then the path can be started from any point\n //of the cycle as the graph is undirected\n path[0] = 0;\n if (hamiltonianCycle(g, path, 1) == false) {\n cout<<\"\\nCycle does not exist\"<<endl;\n return false;\n }\n displaytheSolution(path);\n return true;\n}\nvoid displaytheSolution(int p[]) {\n cout<<\"Cycle Exists:\";\n cout<<\" Following is one Hamiltonian Cycle \\n\"<<endl;\n for (int i = 0; i < N; i++)\n cout<<p[i]<<\" \";\n cout<< p[0]<<endl;\n}\nint main() {\n bool g[N][N] = {{0, 1, 0, 1, 1},\n {0, 0, 1, 1, 0},\n {0, 1, 0, 1, 1},\n {1, 1, 1, 0, 1},\n {0, 1, 1, 0, 0},\n };\n hamCycle(g);\n return 0;\n}" }, { "code": null, "e": 3540, "s": 3479, "text": "Cycle Exists: Following is one Hamiltonian Cycle\n0 4 1 2 3 0" } ]
Usage and syntax of INNER and OUTER JOIN in DB2
Problem: How to explain INNER JOIN and OUTER JOIN with the help of an example on ORDERS and TRANSACTION DB2 table. Solution The JOIN is used to combine data from one or more tables in DB2. There are two main types of JOIN — INNER JOIN and OUTER JOIN. The basic difference between them is, INNER JOIN is an intersection of two or more tables while outer join is union of two or more tables. Basically, INNER JOIN is used to combine the data from multiple tables using equal column value and on the other hand, in case of OUTER JOIN, if the column values are not equal then also the row will b e displayed with NULL values. For example, consider the table below. For INNER JOIN, we will use the below query. SELECT ORDER_ID, TRANSACTION_ID FROM ORDERS FULL OUTER JOIN TRANSACTIONS ON ORDERS.TRANSACTION_ID = TRANSACTIONS.TRANSACTION_ID For OUTER JOIN, we will use the below query. SELECT ORDER_ID, TRANSACTION_ID FROM ORDERS FULL OUTER JOIN TRANSACTIONS ON ORDERS.TRANSACTION_ID = TRANSACTIONS.TRANSACTION_ID
[ { "code": null, "e": 1177, "s": 1062, "text": "Problem: How to explain INNER JOIN and OUTER JOIN with the help of an example on ORDERS and TRANSACTION DB2 table." }, { "code": null, "e": 1186, "s": 1177, "text": "Solution" }, { "code": null, "e": 1686, "s": 1186, "text": "The JOIN is used to combine data from one or more tables in DB2. There are two main types of JOIN — INNER JOIN and OUTER JOIN. The basic difference between them is, INNER JOIN is an intersection of two or more tables while outer join is union of two or more tables. Basically, INNER JOIN is used to combine the data from multiple tables using equal column value and on the other hand, in case of OUTER JOIN, if the column values are not equal then also the row will b e displayed with NULL values." }, { "code": null, "e": 1725, "s": 1686, "text": "For example, consider the table below." }, { "code": null, "e": 1772, "s": 1727, "text": "For INNER JOIN, we will use the below query." }, { "code": null, "e": 1906, "s": 1772, "text": "SELECT ORDER_ID, TRANSACTION_ID FROM\n ORDERS FULL OUTER JOIN TRANSACTIONS ON\n ORDERS.TRANSACTION_ID = TRANSACTIONS.TRANSACTION_ID" }, { "code": null, "e": 1951, "s": 1906, "text": "For OUTER JOIN, we will use the below query." }, { "code": null, "e": 2085, "s": 1951, "text": "SELECT ORDER_ID, TRANSACTION_ID FROM\n ORDERS FULL OUTER JOIN TRANSACTIONS ON\n ORDERS.TRANSACTION_ID = TRANSACTIONS.TRANSACTION_ID" } ]
How To Deploy A Postgres Database For Free | by Cody Nicholson | Towards Data Science
PostgreSQL is one of the most popular relational database management systems in the world powering some of the biggest businesses. If you download Postgres, you may be annoyed to find that you can only host it on your machine’s localhost server unless you pay a recurring fee to host it on a platform like AWS or Azure. In this guide, I’ll show you how you can deploy your database for free using Heroku and write to it in Python. Install the latest version of Postgres, install pgadmin4, install python3, and pip3 install sqlalchemy and psycopg2 The first step to deploying our free Postgres database is to create a free account on Heroku. Heroku is a cloud platform that you can deploy your apps and databases to. Once you have created your account and logged in, you should see a dashboard screen similar to this: Your new account won’t have any apps like I have listed above. Find and click the “Create new app” button to get to the following page: Choose a name for your app that hasn’t already been taken and create it. After clicking the “Create app” button you should get to this page: You now have your first Heroku app, let’s add a database! Click the “Resources” tab from your app’s Heroku page to see the empty lists of Dynos and Add-ons your project has. We want to attach the Heroku Postgres add-on to your project, so click the purple “Find more add-ons” button seen on the right of the below picture: Once on the Heroku Add-ons page, enter “Heroku Postgres” into the “Search Elements” bar on the top right of the page: You should now have found the Add-on for Heroku Postgres that you can see in the below picture. From here, click the purple “Install Heroku Postgres” button on the top right so we can add it to your newly created app. On this final page for attaching the Heroku Postgres add-on to your project you’ll be able to select the plan and the project you want to attach the add-on to. Make sure you select the “Hobby Dev - Free” plan so you don’t pay for anything! After, search for your project name, select it, and click the purple “Provision add-on” button. Let’s learn how to connect to your new Postgres database! To connect to your new database, return to the “Resources” page of your Heroku app. You should see the attached add-on “Heroku Postgres”. Click the “Heroku Postgres” link on the bottom right of the below picture to go to the database management page. The Database Overview page shows you high-level information about your database. Initially you should have no connections, rows, or tables. The Data Size starts at 7.9MBs which accounts for the program files related to your database that you won’t ever need to see or worry about. Once you add more data, that size will increase. On the free plan, you are only allows to have 20 connections and 10,000 rows of data in your database — making it very practical for personal projects and experimentation. If you go to the “Settings” tab and then click the “View Credentials” button you will be able to see the database credentials you’ll use to connect to your database. Do not share this info! Now that we have our Database Credentials we can connect to pgadmin. Open the pgadmin application you should have installed on your computer and it should open a window in your default browser like this: From here you can click the “Add New Server” button on the pgadmin dashboard and enter your database credentials into the prompt. You do not need a Role or Service: Once you’ve entered all the fields correctly you can click “Save” and should see your Postgres server listed like it is below. This is a shared server with many databases and you will only be allowed to access your database by finding it in the list: You’re now connected to your free Postgres Database in pgadmin! In this last step we’re going to write python code that will create a table and add data to it in your database. We’ll start by creating a config.py file to store our database credentials. Our database creds should be stored in a separate file so we can add this file to our .gitignore and share our code on GitHub without fear of anyone accessing our database. host = ec2-34-200-42-57.compute-1.amazonaws.comport = 5432database = dfg5a7fake6perlmsuser = fdpbgfakeggheshfbvpassword = a7cb88511fakea656dd5bb175220caa9646defd4f79e62085486b The below script create_table.py lives in the same folder as the config.py. First, we import all of the config variables and sqlalchemy. Then we create an engine that takes all of the config variables and uses them to connect to the database using “engine.connect()”. Once we’re connected to the database we grab the database’s metadata so we can modify the schema on the “metadata = MetaData()” line. We’re ready to create our first table! from sqlalchemy import *from config import host, port, database, user, passwordconn_str = f"postgresql://{user}:{password}@{host}/{database}"engine = create_engine(conn_str)connection = engine.connect()metadata = MetaData()first_tb = Table('first_table', metadata, Column('id', Integer, primary_key=True), Column('name', String(255), nullable=False), Column('isHappy', Boolean, nullable=False))metadata.create_all(engine)query = insert(first_tb).values(id=1, name="Student", isHappy=True)ResultProxy = connection.execute(query) On the line starting with “first_table” we create our table by passing the table name, the metadata, and all the columns. For each column we can set the name, the type, and the constraints we want each column to have. Finally, on the “metadata.create_all(engine)” line we create our new table in the database. Now that our table is created, we can create a query using the insert() sqlAlchemy method and give it the table and the values we want to add to that table. Lastly, we can execute our query on the last line. Returning to pgadmin, we can go to: “database_name” -> “Schemas” -> “public” -> “Tables”. If you Right-Click on “first_table” you can select: “View/Edit Data” -> “All Rows”. This will run a select query and return to you the row we added — as seen below! Thanks for reading! I’d love to hear your feedback or take any questions you have, so please comment below. Please let me know if any of the pictures or information are no longer up to date!
[ { "code": null, "e": 603, "s": 172, "text": "PostgreSQL is one of the most popular relational database management systems in the world powering some of the biggest businesses. If you download Postgres, you may be annoyed to find that you can only host it on your machine’s localhost server unless you pay a recurring fee to host it on a platform like AWS or Azure. In this guide, I’ll show you how you can deploy your database for free using Heroku and write to it in Python." }, { "code": null, "e": 719, "s": 603, "text": "Install the latest version of Postgres, install pgadmin4, install python3, and pip3 install sqlalchemy and psycopg2" }, { "code": null, "e": 989, "s": 719, "text": "The first step to deploying our free Postgres database is to create a free account on Heroku. Heroku is a cloud platform that you can deploy your apps and databases to. Once you have created your account and logged in, you should see a dashboard screen similar to this:" }, { "code": null, "e": 1125, "s": 989, "text": "Your new account won’t have any apps like I have listed above. Find and click the “Create new app” button to get to the following page:" }, { "code": null, "e": 1266, "s": 1125, "text": "Choose a name for your app that hasn’t already been taken and create it. After clicking the “Create app” button you should get to this page:" }, { "code": null, "e": 1324, "s": 1266, "text": "You now have your first Heroku app, let’s add a database!" }, { "code": null, "e": 1589, "s": 1324, "text": "Click the “Resources” tab from your app’s Heroku page to see the empty lists of Dynos and Add-ons your project has. We want to attach the Heroku Postgres add-on to your project, so click the purple “Find more add-ons” button seen on the right of the below picture:" }, { "code": null, "e": 1707, "s": 1589, "text": "Once on the Heroku Add-ons page, enter “Heroku Postgres” into the “Search Elements” bar on the top right of the page:" }, { "code": null, "e": 1925, "s": 1707, "text": "You should now have found the Add-on for Heroku Postgres that you can see in the below picture. From here, click the purple “Install Heroku Postgres” button on the top right so we can add it to your newly created app." }, { "code": null, "e": 2261, "s": 1925, "text": "On this final page for attaching the Heroku Postgres add-on to your project you’ll be able to select the plan and the project you want to attach the add-on to. Make sure you select the “Hobby Dev - Free” plan so you don’t pay for anything! After, search for your project name, select it, and click the purple “Provision add-on” button." }, { "code": null, "e": 2319, "s": 2261, "text": "Let’s learn how to connect to your new Postgres database!" }, { "code": null, "e": 2570, "s": 2319, "text": "To connect to your new database, return to the “Resources” page of your Heroku app. You should see the attached add-on “Heroku Postgres”. Click the “Heroku Postgres” link on the bottom right of the below picture to go to the database management page." }, { "code": null, "e": 3072, "s": 2570, "text": "The Database Overview page shows you high-level information about your database. Initially you should have no connections, rows, or tables. The Data Size starts at 7.9MBs which accounts for the program files related to your database that you won’t ever need to see or worry about. Once you add more data, that size will increase. On the free plan, you are only allows to have 20 connections and 10,000 rows of data in your database — making it very practical for personal projects and experimentation." }, { "code": null, "e": 3262, "s": 3072, "text": "If you go to the “Settings” tab and then click the “View Credentials” button you will be able to see the database credentials you’ll use to connect to your database. Do not share this info!" }, { "code": null, "e": 3466, "s": 3262, "text": "Now that we have our Database Credentials we can connect to pgadmin. Open the pgadmin application you should have installed on your computer and it should open a window in your default browser like this:" }, { "code": null, "e": 3631, "s": 3466, "text": "From here you can click the “Add New Server” button on the pgadmin dashboard and enter your database credentials into the prompt. You do not need a Role or Service:" }, { "code": null, "e": 3882, "s": 3631, "text": "Once you’ve entered all the fields correctly you can click “Save” and should see your Postgres server listed like it is below. This is a shared server with many databases and you will only be allowed to access your database by finding it in the list:" }, { "code": null, "e": 3946, "s": 3882, "text": "You’re now connected to your free Postgres Database in pgadmin!" }, { "code": null, "e": 4308, "s": 3946, "text": "In this last step we’re going to write python code that will create a table and add data to it in your database. We’ll start by creating a config.py file to store our database credentials. Our database creds should be stored in a separate file so we can add this file to our .gitignore and share our code on GitHub without fear of anyone accessing our database." }, { "code": null, "e": 4484, "s": 4308, "text": "host = ec2-34-200-42-57.compute-1.amazonaws.comport = 5432database = dfg5a7fake6perlmsuser = fdpbgfakeggheshfbvpassword = a7cb88511fakea656dd5bb175220caa9646defd4f79e62085486b" }, { "code": null, "e": 4925, "s": 4484, "text": "The below script create_table.py lives in the same folder as the config.py. First, we import all of the config variables and sqlalchemy. Then we create an engine that takes all of the config variables and uses them to connect to the database using “engine.connect()”. Once we’re connected to the database we grab the database’s metadata so we can modify the schema on the “metadata = MetaData()” line. We’re ready to create our first table!" }, { "code": null, "e": 5459, "s": 4925, "text": "from sqlalchemy import *from config import host, port, database, user, passwordconn_str = f\"postgresql://{user}:{password}@{host}/{database}\"engine = create_engine(conn_str)connection = engine.connect()metadata = MetaData()first_tb = Table('first_table', metadata, Column('id', Integer, primary_key=True), Column('name', String(255), nullable=False), Column('isHappy', Boolean, nullable=False))metadata.create_all(engine)query = insert(first_tb).values(id=1, name=\"Student\", isHappy=True)ResultProxy = connection.execute(query)" }, { "code": null, "e": 5977, "s": 5459, "text": "On the line starting with “first_table” we create our table by passing the table name, the metadata, and all the columns. For each column we can set the name, the type, and the constraints we want each column to have. Finally, on the “metadata.create_all(engine)” line we create our new table in the database. Now that our table is created, we can create a query using the insert() sqlAlchemy method and give it the table and the values we want to add to that table. Lastly, we can execute our query on the last line." }, { "code": null, "e": 6232, "s": 5977, "text": "Returning to pgadmin, we can go to: “database_name” -> “Schemas” -> “public” -> “Tables”. If you Right-Click on “first_table” you can select: “View/Edit Data” -> “All Rows”. This will run a select query and return to you the row we added — as seen below!" } ]
C/C++ Program to find Product of unique prime factors of a number - GeeksforGeeks
05 Dec, 2018 Given a number n, we need to find the product of all of its unique prime factors. Prime factors: It is basically a factor of the number that is a prime number itself. Examples: Input: num = 10 Output: Product is 10 Explanation: Here, the input number is 10 having only 2 prime factors and they are 5 and 2. And hence their product is 10. Input : num = 25 Output: Product is 5 Explanation: Here, for the input to be 25 we have only one unique prime factor i.e 5. And hence the required product is 5. Method 1 (Simple)Using a loop from i = 2 to n and check if i is a factor of n then check if i is prime number itself if yes then store product in product variable and continue this process till i = n. // C++ program to find product of// unique prime factors of a number#include <bits/stdc++.h>using namespace std; long long int productPrimeFactors(int n){ long long int product = 1; for (int i = 2; i <= n; i++) { // Checking if 'i' is factor of num if (n % i == 0) { // Checking if 'i' is a Prime number bool isPrime = true; for (int j = 2; j <= i / 2; j++) { if (i % j == 0) { isPrime = false; break; } } // condition if 'i' is Prime number // as well as factor of num if (isPrime) { product = product * i; } } } return product;} // driver functionint main(){ int n = 44; cout << productPrimeFactors(n); return 0;} 22 Method 2 (Efficient)The idea is based on Efficient program to print all prime factors of a given number // C++ program to find product of// unique prime factors of a number#include <bits/stdc++.h>using namespace std; // A function to print all prime factors of// a given number nlong long int productPrimeFactors(int n){ long long int product = 1; // Handle prime factor 2 explicitly so that // can optimally handle other prime factors. if (n % 2 == 0) { product *= 2; while (n % 2 == 0) n = n / 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i + 2) { // While i divides n, print i and // divide n if (n % i == 0) { product = product * i; while (n % i == 0) n = n / i; } } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) product = product * n; return product;} // driver functionint main(){ int n = 44; cout << productPrimeFactors(n); return 0;} 22 Please refer complete article on Product of unique prime factors of a number for more details! C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C Program to read contents of Whole File Producer Consumer Problem in C C program to find the length of a string Exit codes in C/C++ with Examples Difference between break and continue statement in C Regular expressions in C How to store words in an array in C? Handling multiple clients on server with multithreading using Socket Programming in C/C++ Conditional wait and signal in multi-threading C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
[ { "code": null, "e": 24563, "s": 24535, "text": "\n05 Dec, 2018" }, { "code": null, "e": 24730, "s": 24563, "text": "Given a number n, we need to find the product of all of its unique prime factors. Prime factors: It is basically a factor of the number that is a prime number itself." }, { "code": null, "e": 24740, "s": 24730, "text": "Examples:" }, { "code": null, "e": 25065, "s": 24740, "text": "Input: num = 10\nOutput: Product is 10\nExplanation:\nHere, the input number is 10 having only 2 prime factors and they are 5 and 2.\nAnd hence their product is 10.\n\nInput : num = 25\nOutput: Product is 5\nExplanation:\nHere, for the input to be 25 we have only one unique prime factor i.e 5.\nAnd hence the required product is 5.\n" }, { "code": null, "e": 25266, "s": 25065, "text": "Method 1 (Simple)Using a loop from i = 2 to n and check if i is a factor of n then check if i is prime number itself if yes then store product in product variable and continue this process till i = n." }, { "code": "// C++ program to find product of// unique prime factors of a number#include <bits/stdc++.h>using namespace std; long long int productPrimeFactors(int n){ long long int product = 1; for (int i = 2; i <= n; i++) { // Checking if 'i' is factor of num if (n % i == 0) { // Checking if 'i' is a Prime number bool isPrime = true; for (int j = 2; j <= i / 2; j++) { if (i % j == 0) { isPrime = false; break; } } // condition if 'i' is Prime number // as well as factor of num if (isPrime) { product = product * i; } } } return product;} // driver functionint main(){ int n = 44; cout << productPrimeFactors(n); return 0;}", "e": 26107, "s": 25266, "text": null }, { "code": null, "e": 26111, "s": 26107, "text": "22\n" }, { "code": null, "e": 26215, "s": 26111, "text": "Method 2 (Efficient)The idea is based on Efficient program to print all prime factors of a given number" }, { "code": "// C++ program to find product of// unique prime factors of a number#include <bits/stdc++.h>using namespace std; // A function to print all prime factors of// a given number nlong long int productPrimeFactors(int n){ long long int product = 1; // Handle prime factor 2 explicitly so that // can optimally handle other prime factors. if (n % 2 == 0) { product *= 2; while (n % 2 == 0) n = n / 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i + 2) { // While i divides n, print i and // divide n if (n % i == 0) { product = product * i; while (n % i == 0) n = n / i; } } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) product = product * n; return product;} // driver functionint main(){ int n = 44; cout << productPrimeFactors(n); return 0;}", "e": 27228, "s": 26215, "text": null }, { "code": null, "e": 27232, "s": 27228, "text": "22\n" }, { "code": null, "e": 27327, "s": 27232, "text": "Please refer complete article on Product of unique prime factors of a number for more details!" }, { "code": null, "e": 27338, "s": 27327, "text": "C Programs" }, { "code": null, "e": 27436, "s": 27338, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27445, "s": 27436, "text": "Comments" }, { "code": null, "e": 27458, "s": 27445, "text": "Old Comments" }, { "code": null, "e": 27499, "s": 27458, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 27530, "s": 27499, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 27571, "s": 27530, "text": "C program to find the length of a string" }, { "code": null, "e": 27605, "s": 27571, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 27658, "s": 27605, "text": "Difference between break and continue statement in C" }, { "code": null, "e": 27683, "s": 27658, "text": "Regular expressions in C" }, { "code": null, "e": 27720, "s": 27683, "text": "How to store words in an array in C?" }, { "code": null, "e": 27810, "s": 27720, "text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++" }, { "code": null, "e": 27857, "s": 27810, "text": "Conditional wait and signal in multi-threading" } ]
MySQL order by string with numbers?
To MySQL order string with numbers, the following is the syntax, wherein we have used ORDER BY, SUBSTR() and CAST() − SELECT *FROM yourTableName ORDER BY SUBSTR(yourColumnName FROM 1 FOR 2), CAST(SUBSTR(yourColumnName FROM 2) AS UNSIGNED); To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table OrderByStringWithNumbers -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Words varchar(10), -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.86 sec) Insert some records in the table using insert command. The query is as follows − mysql> insert into OrderByStringWithNumbers(Words) values('A10'); Query OK, 1 row affected (0.19 sec) mysql> insert into OrderByStringWithNumbers(Words) values('A30'); Query OK, 1 row affected (0.19 sec) mysql> insert into OrderByStringWithNumbers(Words) values('A12'); Query OK, 1 row affected (0.13 sec) mysql> insert into OrderByStringWithNumbers(Words) values('A11'); Query OK, 1 row affected (0.17 sec) mysql> insert into OrderByStringWithNumbers(Words) values('A28'); Query OK, 1 row affected (0.13 sec) mysql> insert into OrderByStringWithNumbers(Words) values('A21'); Query OK, 1 row affected (0.20 sec) Display all records from the table using select statement − mysql> select *from OrderByStringWithNumbers; The following is the output − +----+-------+ | Id | Words | +----+-------+ | 1 | A10 | | 2 | A30 | | 3 | A12 | | 4 | A11 | | 5 | A28 | | 6 | A21 | +----+-------+ 6 rows in set (0.00 sec) Here is the query to order by string with numbers − mysql> select *from OrderByStringWithNumbers order by -> substr(Words from 1 for 2), -> cast(substr(Words from 2) AS UNSIGNED); The following is the output − +----+-------+ | Id | Words | +----+-------+ | 1 | A10 | | 4 | A11 | | 3 | A12 | | 6 | A21 | | 5 | A28 | | 2 | A30 | +----+-------+ 6 rows in set (0.00 sec)
[ { "code": null, "e": 1180, "s": 1062, "text": "To MySQL order string with numbers, the following is the syntax, wherein we have used ORDER BY, SUBSTR() and CAST() −" }, { "code": null, "e": 1302, "s": 1180, "text": "SELECT *FROM yourTableName ORDER BY\nSUBSTR(yourColumnName FROM 1 FOR 2),\nCAST(SUBSTR(yourColumnName FROM 2) AS UNSIGNED);" }, { "code": null, "e": 1401, "s": 1302, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1585, "s": 1401, "text": "mysql> create table OrderByStringWithNumbers\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> Words varchar(10),\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.86 sec)" }, { "code": null, "e": 1666, "s": 1585, "text": "Insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2283, "s": 1666, "text": "mysql> insert into OrderByStringWithNumbers(Words) values('A10');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into OrderByStringWithNumbers(Words) values('A30');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into OrderByStringWithNumbers(Words) values('A12');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into OrderByStringWithNumbers(Words) values('A11');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into OrderByStringWithNumbers(Words) values('A28');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into OrderByStringWithNumbers(Words) values('A21');\nQuery OK, 1 row affected (0.20 sec)" }, { "code": null, "e": 2343, "s": 2283, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2389, "s": 2343, "text": "mysql> select *from OrderByStringWithNumbers;" }, { "code": null, "e": 2419, "s": 2389, "text": "The following is the output −" }, { "code": null, "e": 2594, "s": 2419, "text": "+----+-------+\n| Id | Words |\n+----+-------+\n| 1 | A10 |\n| 2 | A30 |\n| 3 | A12 |\n| 4 | A11 |\n| 5 | A28 |\n| 6 | A21 |\n+----+-------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2646, "s": 2594, "text": "Here is the query to order by string with numbers −" }, { "code": null, "e": 2780, "s": 2646, "text": "mysql> select *from OrderByStringWithNumbers order by\n -> substr(Words from 1 for 2),\n -> cast(substr(Words from 2) AS UNSIGNED);" }, { "code": null, "e": 2810, "s": 2780, "text": "The following is the output −" }, { "code": null, "e": 2985, "s": 2810, "text": "+----+-------+\n| Id | Words |\n+----+-------+\n| 1 | A10 |\n| 4 | A11 |\n| 3 | A12 |\n| 6 | A21 |\n| 5 | A28 |\n| 2 | A30 |\n+----+-------+\n6 rows in set (0.00 sec)" } ]
C# | How to get hash code for the specified key of a Hashtable - GeeksforGeeks
01 Feb, 2019 Hashtable.GetHash(Object) method is used to get the hashcode of the specified key of a Hashtable object. This method is inherited from the Object Class. Syntax: protected virtual int GetHash(Object Key); Exception: This method will give NullReferenceException if the key is null. Below programs illustrate the use of above-discussed method: Example 1: // C# Program to illustrate the // Hashtable.GetHash(Object) methodusing System;using System.Collections; // Inheriting Hashtable as // Hashtable.GetHash(Object) // method is protected methodclass HashCode : Hashtable { // Main Method static void Main(string[] args) { // creating object for HashCode as // to access protected methods we // have to create object for the // derived class HashCode h = new HashCode(); // Add Elements into Hashtable h.Add("1001", "Parek Shetty"); h.Add("1002", "Deshmuk Narayan"); h.Add("1003", "Ratan Kaalikaran"); ICollection Key = h.Keys; foreach(string val in Key) { // printing Hashtable Console.Write(val + " : " + h[val]); Console.Write("\n"); // printing hashcode with keys int hcode = h.GetHash(val); Console.Write(val + " : " + hcode); Console.Write("\n"); } }} 1002 : Deshmuk Narayan 1002 : 985757554 1001 : Parek Shetty 1001 : -1708895167 1003 : Ratan Kaalikaran 1003 : -1892225314 Example 2: // C# Program to illustrate the // Hashtable.GetHash(Object) methodusing System;using System.Collections; class HashCode : Hashtable { // Main Method static void Main(string[] args) { HashCode h = new HashCode(); // Adding elements h.Add('A', "Pritam Devadhya"); h.Add('B', "Arjun Balachi"); h.Add('C', "Timanad Panigrahi"); ICollection Key = h.Keys; int hcode = h.GetHash('C'); Console.Write("HashCode: " + hcode); }} HashCode: 4390979 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.gethash?view=netframework-4.7.2 CSharp-Collections-Hashtable CSharp-Collections-Namespace CSharp-method Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Destructors in C# Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? Partial Classes in C# C# | Inheritance C# | List Class Difference between Hashtable and Dictionary in C# Lambda Expressions in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24455, "s": 24302, "text": "Hashtable.GetHash(Object) method is used to get the hashcode of the specified key of a Hashtable object. This method is inherited from the Object Class." }, { "code": null, "e": 24463, "s": 24455, "text": "Syntax:" }, { "code": null, "e": 24507, "s": 24463, "text": "protected virtual int GetHash(Object Key);\n" }, { "code": null, "e": 24583, "s": 24507, "text": "Exception: This method will give NullReferenceException if the key is null." }, { "code": null, "e": 24644, "s": 24583, "text": "Below programs illustrate the use of above-discussed method:" }, { "code": null, "e": 24655, "s": 24644, "text": "Example 1:" }, { "code": "// C# Program to illustrate the // Hashtable.GetHash(Object) methodusing System;using System.Collections; // Inheriting Hashtable as // Hashtable.GetHash(Object) // method is protected methodclass HashCode : Hashtable { // Main Method static void Main(string[] args) { // creating object for HashCode as // to access protected methods we // have to create object for the // derived class HashCode h = new HashCode(); // Add Elements into Hashtable h.Add(\"1001\", \"Parek Shetty\"); h.Add(\"1002\", \"Deshmuk Narayan\"); h.Add(\"1003\", \"Ratan Kaalikaran\"); ICollection Key = h.Keys; foreach(string val in Key) { // printing Hashtable Console.Write(val + \" : \" + h[val]); Console.Write(\"\\n\"); // printing hashcode with keys int hcode = h.GetHash(val); Console.Write(val + \" : \" + hcode); Console.Write(\"\\n\"); } }}", "e": 25721, "s": 24655, "text": null }, { "code": null, "e": 25844, "s": 25721, "text": "1002 : Deshmuk Narayan\n1002 : 985757554\n1001 : Parek Shetty\n1001 : -1708895167\n1003 : Ratan Kaalikaran\n1003 : -1892225314\n" }, { "code": null, "e": 25855, "s": 25844, "text": "Example 2:" }, { "code": "// C# Program to illustrate the // Hashtable.GetHash(Object) methodusing System;using System.Collections; class HashCode : Hashtable { // Main Method static void Main(string[] args) { HashCode h = new HashCode(); // Adding elements h.Add('A', \"Pritam Devadhya\"); h.Add('B', \"Arjun Balachi\"); h.Add('C', \"Timanad Panigrahi\"); ICollection Key = h.Keys; int hcode = h.GetHash('C'); Console.Write(\"HashCode: \" + hcode); }}", "e": 26389, "s": 25855, "text": null }, { "code": null, "e": 26408, "s": 26389, "text": "HashCode: 4390979\n" }, { "code": null, "e": 26419, "s": 26408, "text": "Reference:" }, { "code": null, "e": 26524, "s": 26419, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.gethash?view=netframework-4.7.2" }, { "code": null, "e": 26553, "s": 26524, "text": "CSharp-Collections-Hashtable" }, { "code": null, "e": 26582, "s": 26553, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 26596, "s": 26582, "text": "CSharp-method" }, { "code": null, "e": 26603, "s": 26596, "text": "Picked" }, { "code": null, "e": 26606, "s": 26603, "text": "C#" }, { "code": null, "e": 26704, "s": 26606, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26722, "s": 26704, "text": "Destructors in C#" }, { "code": null, "e": 26745, "s": 26722, "text": "Extension Method in C#" }, { "code": null, "e": 26773, "s": 26745, "text": "HashSet in C# with Examples" }, { "code": null, "e": 26813, "s": 26773, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 26856, "s": 26813, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 26878, "s": 26856, "text": "Partial Classes in C#" }, { "code": null, "e": 26895, "s": 26878, "text": "C# | Inheritance" }, { "code": null, "e": 26911, "s": 26895, "text": "C# | List Class" }, { "code": null, "e": 26961, "s": 26911, "text": "Difference between Hashtable and Dictionary in C#" } ]
C# program to check for URL in a String
Use the StartWith() method in C# to check for URL in a String. Let us say our input string is − string input = "https://example.com/new.html"; Now we need to check for www or non-www link. For this, use the if statement in C# − if (input.StartsWith("https://www.example.com") || input.StartsWith("https://example.com")) { } You can try to run the following code to check for URL in a string. Live Demo using System; class Demo { static void Main() { string input = "https://example.com/new.html"; // See if input matches one of these starts. if (input.StartsWith("https://www.example.com") || input.StartsWith("https://example.com")) { Console.WriteLine(true); } } } True
[ { "code": null, "e": 1125, "s": 1062, "text": "Use the StartWith() method in C# to check for URL in a String." }, { "code": null, "e": 1158, "s": 1125, "text": "Let us say our input string is −" }, { "code": null, "e": 1205, "s": 1158, "text": "string input = \"https://example.com/new.html\";" }, { "code": null, "e": 1290, "s": 1205, "text": "Now we need to check for www or non-www link. For this, use the if statement in C# −" }, { "code": null, "e": 1386, "s": 1290, "text": "if (input.StartsWith(\"https://www.example.com\") || input.StartsWith(\"https://example.com\")) {\n}" }, { "code": null, "e": 1454, "s": 1386, "text": "You can try to run the following code to check for URL in a string." }, { "code": null, "e": 1464, "s": 1454, "text": "Live Demo" }, { "code": null, "e": 1768, "s": 1464, "text": "using System;\nclass Demo {\n static void Main() {\n string input = \"https://example.com/new.html\";\n // See if input matches one of these starts.\n if (input.StartsWith(\"https://www.example.com\") || input.StartsWith(\"https://example.com\")) {\n Console.WriteLine(true);\n }\n }\n}" }, { "code": null, "e": 1773, "s": 1768, "text": "True" } ]
C# | Check if an array contain the elements that match the specified conditions - GeeksforGeeks
01 Feb, 2019 Array.Exists(T[], Predicate<T>) Method is used to check whether the specified array contains elements that match the conditions defined by the specified predicate. Syntax: public static bool Exists<T> (T[] array, Predicate<T> match); Parameters: array: It is a one-dimensional, zero-based Array to search.match: It is a Predicate that defines the conditions of the elements to search for. Where T is a type of the elements present in the array. Return Value: The return type of this method is System.Boolean. It return true if array contains one or more elements that match the conditions defined by the specified predicate. Otherwise, return false. Exception: This method will give ArgumentNullException if the value of array is null, or if the value of match is null. Below given are some examples to understand the implementation in a better way: Example 1: // C# program to illustrate the // Array.Exists(T[], Predicate<T>) Methodusing System; class GFG { // Main method static public void Main() { // Create and initialize array string[] language = {"Ruby", "C", "C++", "Java", "Perl", "C#", "Python", "PHP"}; // Display language array Console.WriteLine("Display the array:"); foreach(string i in language) { Console.WriteLine(i); } // Display and check the given elements // present in the array or not // Using Exists() method Console.WriteLine("Is Ruby part of language: {0}", Array.Exists(language, element => element == "Ruby")); Console.WriteLine("Is VB part of language: {0}", Array.Exists(language, element => element == "VB")); }} Display the array: Ruby C C++ Java Perl C# Python PHP Is Ruby part of language: True Is VB part of language: False Example 2: // C# program to illustrate the // Array.Exists(T[], Predicate<T>) Methodusing System; public class GFG { // Main methodstatic public void Main(){ // Create and initialize array string[] ds = {"Array", "Queue", "LinkedList", "Stack", "Graph" }; // Display ds array Console.WriteLine("Given Array: "); foreach(string i in ds) { Console.WriteLine(i); } // Display and check the given elements with the // specified letter is present in the array or not // Using Exists() method Console.WriteLine("Is element start with L letter is present in array: {0}", Array.Exists(ds, element => element.StartsWith("L"))); Console.WriteLine("Is element start with O letter is present in array: {0}", Array.Exists(ds, element => element.StartsWith("O")));}} Given Array: Array Queue LinkedList Stack Graph Is element start with L letter is present in array: True Is element start with O letter is present in array: False Note: This method is an O(n) operation, where n is the Length of array. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.array.exists?view=netcore-2.1#definition CSharp-Arrays CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Destructors in C# C# | Delegates C# | Constructors Extension Method in C# Introduction to .NET Framework C# | Class and Object C# | Abstract Classes C# | Data Types C# | Encapsulation HashSet in C# with Examples
[ { "code": null, "e": 24494, "s": 24466, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24658, "s": 24494, "text": "Array.Exists(T[], Predicate<T>) Method is used to check whether the specified array contains elements that match the conditions defined by the specified predicate." }, { "code": null, "e": 24666, "s": 24658, "text": "Syntax:" }, { "code": null, "e": 24728, "s": 24666, "text": "public static bool Exists<T> (T[] array, Predicate<T> match);" }, { "code": null, "e": 24740, "s": 24728, "text": "Parameters:" }, { "code": null, "e": 24939, "s": 24740, "text": "array: It is a one-dimensional, zero-based Array to search.match: It is a Predicate that defines the conditions of the elements to search for. Where T is a type of the elements present in the array." }, { "code": null, "e": 25144, "s": 24939, "text": "Return Value: The return type of this method is System.Boolean. It return true if array contains one or more elements that match the conditions defined by the specified predicate. Otherwise, return false." }, { "code": null, "e": 25264, "s": 25144, "text": "Exception: This method will give ArgumentNullException if the value of array is null, or if the value of match is null." }, { "code": null, "e": 25344, "s": 25264, "text": "Below given are some examples to understand the implementation in a better way:" }, { "code": null, "e": 25355, "s": 25344, "text": "Example 1:" }, { "code": "// C# program to illustrate the // Array.Exists(T[], Predicate<T>) Methodusing System; class GFG { // Main method static public void Main() { // Create and initialize array string[] language = {\"Ruby\", \"C\", \"C++\", \"Java\", \"Perl\", \"C#\", \"Python\", \"PHP\"}; // Display language array Console.WriteLine(\"Display the array:\"); foreach(string i in language) { Console.WriteLine(i); } // Display and check the given elements // present in the array or not // Using Exists() method Console.WriteLine(\"Is Ruby part of language: {0}\", Array.Exists(language, element => element == \"Ruby\")); Console.WriteLine(\"Is VB part of language: {0}\", Array.Exists(language, element => element == \"VB\")); }}", "e": 26245, "s": 25355, "text": null }, { "code": null, "e": 26361, "s": 26245, "text": "Display the array:\nRuby\nC\nC++\nJava\nPerl\nC#\nPython\nPHP\nIs Ruby part of language: True\nIs VB part of language: False\n" }, { "code": null, "e": 26372, "s": 26361, "text": "Example 2:" }, { "code": "// C# program to illustrate the // Array.Exists(T[], Predicate<T>) Methodusing System; public class GFG { // Main methodstatic public void Main(){ // Create and initialize array string[] ds = {\"Array\", \"Queue\", \"LinkedList\", \"Stack\", \"Graph\" }; // Display ds array Console.WriteLine(\"Given Array: \"); foreach(string i in ds) { Console.WriteLine(i); } // Display and check the given elements with the // specified letter is present in the array or not // Using Exists() method Console.WriteLine(\"Is element start with L letter is present in array: {0}\", Array.Exists(ds, element => element.StartsWith(\"L\"))); Console.WriteLine(\"Is element start with O letter is present in array: {0}\", Array.Exists(ds, element => element.StartsWith(\"O\")));}}", "e": 27261, "s": 26372, "text": null }, { "code": null, "e": 27426, "s": 27261, "text": "Given Array: \nArray\nQueue\nLinkedList\nStack\nGraph\nIs element start with L letter is present in array: True\nIs element start with O letter is present in array: False\n" }, { "code": null, "e": 27498, "s": 27426, "text": "Note: This method is an O(n) operation, where n is the Length of array." }, { "code": null, "e": 27601, "s": 27498, "text": "Reference: https://docs.microsoft.com/en-us/dotnet/api/system.array.exists?view=netcore-2.1#definition" }, { "code": null, "e": 27615, "s": 27601, "text": "CSharp-Arrays" }, { "code": null, "e": 27629, "s": 27615, "text": "CSharp-method" }, { "code": null, "e": 27632, "s": 27629, "text": "C#" }, { "code": null, "e": 27730, "s": 27632, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27748, "s": 27730, "text": "Destructors in C#" }, { "code": null, "e": 27763, "s": 27748, "text": "C# | Delegates" }, { "code": null, "e": 27781, "s": 27763, "text": "C# | Constructors" }, { "code": null, "e": 27804, "s": 27781, "text": "Extension Method in C#" }, { "code": null, "e": 27835, "s": 27804, "text": "Introduction to .NET Framework" }, { "code": null, "e": 27857, "s": 27835, "text": "C# | Class and Object" }, { "code": null, "e": 27879, "s": 27857, "text": "C# | Abstract Classes" }, { "code": null, "e": 27895, "s": 27879, "text": "C# | Data Types" }, { "code": null, "e": 27914, "s": 27895, "text": "C# | Encapsulation" } ]
Plotly Front to Back: Bar Charts & Line Charts | by Dario Radečić | Towards Data Science
A couple of days ago I’ve announced an upcoming series dealing with the Plotly library, covering everything you need to know to take your visualizations to the next level. Although I recommend you to read the series from the beginning, articles are formed in that way that each one is independent and doesn’t require you to read everything before it. Today you’ll read the second article in the series, where the first was dealing with only the reasons why should you even consider Plotly: towardsdatascience.com So make sure to check that one out if you’re struggling to choose a data visualization platform or just want to try something new. Today, we’ll focus on two very common types of charts: Bar charts Line charts The first one you’ll use almost anytime you want to see the difference between categories and the ladder is basically present in any dashboard out there, usually representing time-series data of some sort. Without much ado, let’s jump in. Imports-wise we’ll only have a few libraries, two of which are present in every data science notebook, and the last two are from Plotly: import numpy as npimport pandas as pdimport plotly.graph_objs as go import plotly.offline as pyo As for the dataset, we’ll declare something random in Pandas, let’s say various bill amounts for different months in a year: df = pd.DataFrame(data={ ‘Month’: [‘January’, ‘February’, ‘March’], ‘Water’: [50, 61, 43], ‘Electricity’: [100, 88, 112], ‘Heat’: [86, 92, 104], ‘Total’: [236, 241, 259]}) Okay, we have everything to get started. Let’s explore all the different ways this dataset can be plotted. We’ll cover three types of bar charts today: (Normal) bar chartsNested bar chartsStacked bar charts (Normal) bar charts Nested bar charts Stacked bar charts You don’t need to know beforehand the differences between those as everything will be explained in the article. The idea is to show you every way you can represent data with bars, and then it’s up to you to choose the most suitable option. Okay, let’s plot the Month on the x-axis and Total on the y-axis. As always, you’ll declare a figure object and put data and layout inside. This one is pretty simple and doesn’t need further explanation: fig = go.Figure( data=[ go.Bar( x=df[‘Month’], y=df[‘Total’] ) ], layout=go.Layout( title=’Total Monthly Cost’ ))pyo.plot(fig) If you were to execute this code, a plot like this would come out: Okay, not bad, but not great either — here we’re only displaying the total amounts, which isn’t showing us the whole picture. Let’s see how to improve. In this one, we’ll be able to visualize each expense and not only the total amounts. Keep in mind, if you have a lot of data and a lot of categories this type of chart might become hard to look at — but it is just fine for our case. And it’s really simple to do so — we only need to put a go.Bar object in our data array for every category we want to visualize. Here’s the code: fig = go.Figure( data=[ go.Bar( x=df[‘Month’], y=df[‘Water’], name=’Water’, marker=dict(color=’#3498db’) ), go.Bar( x=df[‘Month’], y=df[‘Electricity’], name=’Electricity’, marker=dict(color=’#f1c40f’) ), go.Bar( x=df[‘Month’], y=df[‘Heat’], name=’Heat’, marker=dict(color=’#e74c3c’) ) ], layout=go.Layout( title=’Monthly Cost per Item’ ))pyo.plot(fig) Executing the above code would produce a nice-looking chart: If you ask me, this is a great improvement from what we’ve had previously. Let’s explore another option before concluding this section. In most cases this is my favorite option. Takes as little space as your regular bar chart, and displays as much information as a nested bar chart. The code is pretty much identical as the one for a nested bar chart, the only difference is that you need to specify barmode='stack' in the layout. Let’s see this in action: fig = go.Figure( data=[ go.Bar( x=df[‘Month’], y=df[‘Water’], name=’Water’, marker=dict(color=’#3498db’) ), go.Bar( x=df[‘Month’], y=df[‘Electricity’], name=’Electricity’, marker=dict(color=’#f1c40f’) ), go.Bar( x=df[‘Month’], y=df[‘Heat’], name=’Heat’, marker=dict(color=’#e74c3c’) ) ], layout=go.Layout( title=’Monthly Cost per Item’, barmode=’stack’ ))pyo.plot(fig) Executing the above code would result in a chart like this one: Great! We’ve covered bar charts in-depth, let’s now see what can we do with line charts! For this part, we’ll only need two Numpy arrays: x = np.linspace(0, 49, 50)y = np.random.randint(10, 20, 50) And that’s it — we can begin exploring. As with the bar charts, we’ll cover two options: Basic Line Chart Line Chart with Markers Multiple Line Chart If it’s not clear to you what is meant with the second option, bear with me for a minute. Here’s how we can make a basic line chart from those two previously declared Numpy arrays: fig = go.Figure( data=[ go.Scatter( x=x, y=y, mode=’lines’ ) ], layout=go.Layout( title=’Line Chart’ ))pyo.plot(fig) Executing this code will result in the following chart: Not the best-looking line chart, we’ll explore how to tweak the visuals towards the end of the article. If you don’t have too many data points, sometimes is convenient to show little markers alongside the lines. Code-wise changes are minimal — as we only need to tweak the mode option, and set it as mode='lines+markers'. Let’s see the code: fig = go.Figure( data=[ go.Scatter( x=x, y=y, mode=’lines+markers’ ) ], layout=go.Layout( title=’Line Chart’ ))pyo.plot(fig) Executing the above-written code will result in this chart: Nice. Let’s now see how we can combine multiple lines into a single line chart. Let’s now see how easy it is to combine multiple lines into a single chart. Just like with the bar chart, we’ll put multiple go.Scatter objects into our data array. To spicy things up a bit, we added a few layout options just to give you a feel of what can be done, appearance-wise. Here’s the code: fig = go.Figure( data=[ go.Scatter( x=x, y=y, mode=’lines’, name=’Lines’, line=dict( color=’#3498db’, width=4 ) ), go.Scatter( x=x, y=y + 10, mode=’lines+markers’, name=’Lines + Markers’, line=dict( color=’#f1c40f’, dash=’dash’, width=4 ) ) ], layout=go.Layout( title=’Line Chart’, hovermode=’x’ ))pyo.plot(fig) Executing the code will produce this chart: Awesome! And that will be just enough for today. This was quite a longer article than I usually write. But I hope you’ve managed to follow along. We covered a lot of ground today, but there’s still much more to come. The following article will cover scatter charts and bubble charts, so stay tuned if that’s something that you’d find interesting. Thanks for reading, and as always don’t hesitate to put your questions and comments below. Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
[ { "code": null, "e": 523, "s": 172, "text": "A couple of days ago I’ve announced an upcoming series dealing with the Plotly library, covering everything you need to know to take your visualizations to the next level. Although I recommend you to read the series from the beginning, articles are formed in that way that each one is independent and doesn’t require you to read everything before it." }, { "code": null, "e": 662, "s": 523, "text": "Today you’ll read the second article in the series, where the first was dealing with only the reasons why should you even consider Plotly:" }, { "code": null, "e": 685, "s": 662, "text": "towardsdatascience.com" }, { "code": null, "e": 816, "s": 685, "text": "So make sure to check that one out if you’re struggling to choose a data visualization platform or just want to try something new." }, { "code": null, "e": 871, "s": 816, "text": "Today, we’ll focus on two very common types of charts:" }, { "code": null, "e": 882, "s": 871, "text": "Bar charts" }, { "code": null, "e": 894, "s": 882, "text": "Line charts" }, { "code": null, "e": 1100, "s": 894, "text": "The first one you’ll use almost anytime you want to see the difference between categories and the ladder is basically present in any dashboard out there, usually representing time-series data of some sort." }, { "code": null, "e": 1133, "s": 1100, "text": "Without much ado, let’s jump in." }, { "code": null, "e": 1270, "s": 1133, "text": "Imports-wise we’ll only have a few libraries, two of which are present in every data science notebook, and the last two are from Plotly:" }, { "code": null, "e": 1367, "s": 1270, "text": "import numpy as npimport pandas as pdimport plotly.graph_objs as go import plotly.offline as pyo" }, { "code": null, "e": 1492, "s": 1367, "text": "As for the dataset, we’ll declare something random in Pandas, let’s say various bill amounts for different months in a year:" }, { "code": null, "e": 1674, "s": 1492, "text": "df = pd.DataFrame(data={ ‘Month’: [‘January’, ‘February’, ‘March’], ‘Water’: [50, 61, 43], ‘Electricity’: [100, 88, 112], ‘Heat’: [86, 92, 104], ‘Total’: [236, 241, 259]})" }, { "code": null, "e": 1781, "s": 1674, "text": "Okay, we have everything to get started. Let’s explore all the different ways this dataset can be plotted." }, { "code": null, "e": 1826, "s": 1781, "text": "We’ll cover three types of bar charts today:" }, { "code": null, "e": 1881, "s": 1826, "text": "(Normal) bar chartsNested bar chartsStacked bar charts" }, { "code": null, "e": 1901, "s": 1881, "text": "(Normal) bar charts" }, { "code": null, "e": 1919, "s": 1901, "text": "Nested bar charts" }, { "code": null, "e": 1938, "s": 1919, "text": "Stacked bar charts" }, { "code": null, "e": 2178, "s": 1938, "text": "You don’t need to know beforehand the differences between those as everything will be explained in the article. The idea is to show you every way you can represent data with bars, and then it’s up to you to choose the most suitable option." }, { "code": null, "e": 2382, "s": 2178, "text": "Okay, let’s plot the Month on the x-axis and Total on the y-axis. As always, you’ll declare a figure object and put data and layout inside. This one is pretty simple and doesn’t need further explanation:" }, { "code": null, "e": 2555, "s": 2382, "text": "fig = go.Figure( data=[ go.Bar( x=df[‘Month’], y=df[‘Total’] ) ], layout=go.Layout( title=’Total Monthly Cost’ ))pyo.plot(fig)" }, { "code": null, "e": 2622, "s": 2555, "text": "If you were to execute this code, a plot like this would come out:" }, { "code": null, "e": 2774, "s": 2622, "text": "Okay, not bad, but not great either — here we’re only displaying the total amounts, which isn’t showing us the whole picture. Let’s see how to improve." }, { "code": null, "e": 3007, "s": 2774, "text": "In this one, we’ll be able to visualize each expense and not only the total amounts. Keep in mind, if you have a lot of data and a lot of categories this type of chart might become hard to look at — but it is just fine for our case." }, { "code": null, "e": 3153, "s": 3007, "text": "And it’s really simple to do so — we only need to put a go.Bar object in our data array for every category we want to visualize. Here’s the code:" }, { "code": null, "e": 3675, "s": 3153, "text": "fig = go.Figure( data=[ go.Bar( x=df[‘Month’], y=df[‘Water’], name=’Water’, marker=dict(color=’#3498db’) ), go.Bar( x=df[‘Month’], y=df[‘Electricity’], name=’Electricity’, marker=dict(color=’#f1c40f’) ), go.Bar( x=df[‘Month’], y=df[‘Heat’], name=’Heat’, marker=dict(color=’#e74c3c’) ) ], layout=go.Layout( title=’Monthly Cost per Item’ ))pyo.plot(fig)" }, { "code": null, "e": 3736, "s": 3675, "text": "Executing the above code would produce a nice-looking chart:" }, { "code": null, "e": 3872, "s": 3736, "text": "If you ask me, this is a great improvement from what we’ve had previously. Let’s explore another option before concluding this section." }, { "code": null, "e": 4167, "s": 3872, "text": "In most cases this is my favorite option. Takes as little space as your regular bar chart, and displays as much information as a nested bar chart. The code is pretty much identical as the one for a nested bar chart, the only difference is that you need to specify barmode='stack' in the layout." }, { "code": null, "e": 4193, "s": 4167, "text": "Let’s see this in action:" }, { "code": null, "e": 4738, "s": 4193, "text": "fig = go.Figure( data=[ go.Bar( x=df[‘Month’], y=df[‘Water’], name=’Water’, marker=dict(color=’#3498db’) ), go.Bar( x=df[‘Month’], y=df[‘Electricity’], name=’Electricity’, marker=dict(color=’#f1c40f’) ), go.Bar( x=df[‘Month’], y=df[‘Heat’], name=’Heat’, marker=dict(color=’#e74c3c’) ) ], layout=go.Layout( title=’Monthly Cost per Item’, barmode=’stack’ ))pyo.plot(fig)" }, { "code": null, "e": 4802, "s": 4738, "text": "Executing the above code would result in a chart like this one:" }, { "code": null, "e": 4891, "s": 4802, "text": "Great! We’ve covered bar charts in-depth, let’s now see what can we do with line charts!" }, { "code": null, "e": 4940, "s": 4891, "text": "For this part, we’ll only need two Numpy arrays:" }, { "code": null, "e": 5000, "s": 4940, "text": "x = np.linspace(0, 49, 50)y = np.random.randint(10, 20, 50)" }, { "code": null, "e": 5040, "s": 5000, "text": "And that’s it — we can begin exploring." }, { "code": null, "e": 5089, "s": 5040, "text": "As with the bar charts, we’ll cover two options:" }, { "code": null, "e": 5106, "s": 5089, "text": "Basic Line Chart" }, { "code": null, "e": 5130, "s": 5106, "text": "Line Chart with Markers" }, { "code": null, "e": 5150, "s": 5130, "text": "Multiple Line Chart" }, { "code": null, "e": 5240, "s": 5150, "text": "If it’s not clear to you what is meant with the second option, bear with me for a minute." }, { "code": null, "e": 5331, "s": 5240, "text": "Here’s how we can make a basic line chart from those two previously declared Numpy arrays:" }, { "code": null, "e": 5502, "s": 5331, "text": "fig = go.Figure( data=[ go.Scatter( x=x, y=y, mode=’lines’ ) ], layout=go.Layout( title=’Line Chart’ ))pyo.plot(fig)" }, { "code": null, "e": 5558, "s": 5502, "text": "Executing this code will result in the following chart:" }, { "code": null, "e": 5662, "s": 5558, "text": "Not the best-looking line chart, we’ll explore how to tweak the visuals towards the end of the article." }, { "code": null, "e": 5900, "s": 5662, "text": "If you don’t have too many data points, sometimes is convenient to show little markers alongside the lines. Code-wise changes are minimal — as we only need to tweak the mode option, and set it as mode='lines+markers'. Let’s see the code:" }, { "code": null, "e": 6082, "s": 5900, "text": "fig = go.Figure( data=[ go.Scatter( x=x, y=y, mode=’lines+markers’ ) ], layout=go.Layout( title=’Line Chart’ ))pyo.plot(fig)" }, { "code": null, "e": 6142, "s": 6082, "text": "Executing the above-written code will result in this chart:" }, { "code": null, "e": 6222, "s": 6142, "text": "Nice. Let’s now see how we can combine multiple lines into a single line chart." }, { "code": null, "e": 6387, "s": 6222, "text": "Let’s now see how easy it is to combine multiple lines into a single chart. Just like with the bar chart, we’ll put multiple go.Scatter objects into our data array." }, { "code": null, "e": 6505, "s": 6387, "text": "To spicy things up a bit, we added a few layout options just to give you a feel of what can be done, appearance-wise." }, { "code": null, "e": 6522, "s": 6505, "text": "Here’s the code:" }, { "code": null, "e": 7028, "s": 6522, "text": "fig = go.Figure( data=[ go.Scatter( x=x, y=y, mode=’lines’, name=’Lines’, line=dict( color=’#3498db’, width=4 ) ), go.Scatter( x=x, y=y + 10, mode=’lines+markers’, name=’Lines + Markers’, line=dict( color=’#f1c40f’, dash=’dash’, width=4 ) ) ], layout=go.Layout( title=’Line Chart’, hovermode=’x’ ))pyo.plot(fig)" }, { "code": null, "e": 7072, "s": 7028, "text": "Executing the code will produce this chart:" }, { "code": null, "e": 7121, "s": 7072, "text": "Awesome! And that will be just enough for today." }, { "code": null, "e": 7289, "s": 7121, "text": "This was quite a longer article than I usually write. But I hope you’ve managed to follow along. We covered a lot of ground today, but there’s still much more to come." }, { "code": null, "e": 7419, "s": 7289, "text": "The following article will cover scatter charts and bubble charts, so stay tuned if that’s something that you’d find interesting." }, { "code": null, "e": 7510, "s": 7419, "text": "Thanks for reading, and as always don’t hesitate to put your questions and comments below." } ]
Bootstrap 4 | Badges - GeeksforGeeks
29 Apr, 2022 The .badge class is used to add additional information to the content. For example, some websites associate a number of notifications to the link. The notification number is seen when logged in to a particular website which tells the numbers of news or notifications to see by clicking it.Example: HTML <!DOCTYPE html><html lang="en"><head> <title>Bootstrap Badges</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <div class="container"> <h4>Notifications heading <span class="badge badge-secondary"> 4 </span> </h4> <h4>Updates <span class="badge badge-secondary"> 2 </span> </h4> <h4>Messages <span class="badge badge-secondary"> 1 </span> </h4> <h4>Request <span class="badge badge-secondary"> 0 </span> </h4> </div></body></html> Output: Contextual Badges: The contextual classes (.badge-*) is used to change the color of badges. Badges can be used as part of links or button to provide a counter. Depending on how they used, badges must be confusing for the users. For this purpose different color of variations are used so that the user may not get confused.Example: HTML <!DOCTYPE html><html lang="en"><head> <title>Bootstrap Badges</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <div class="container"> <h4>Notifications heading <span class="badge badge-primary"> 4 </span> </h4> <h4>Updates <span class="badge badge-warning"> 2 </span> </h4> <h4>Messages <span class="badge badge-success"> 1 </span> </h4> <h4>Request <span class="badge badge-danger"> 0 </span> </h4> </div></body></html> Output: Pill Badges: The .badge-pill class is used to make badges corner more rounded.Example: HTML <!DOCTYPE html><html lang="en"><head> <title>Bootstrap Badges</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <div class="container"> <h4>Notifications heading <span class="badge badge-primary badge-pill"> 4 </span> </h4> <h4>Updates <span class="badge badge-warning badge-pill"> 2 </span> </h4> <h4>Messages <span class="badge badge-success badge-pill"> 1 </span> </h4> <h4>Request <span class="badge badge-danger badge-pill"> 0 </span> </h4> </div></body></html> Output: Badge inside an Element: Badges can be created inside an element.Example: HTML <!DOCTYPE html><html lang="en"><head> <title>Bootstrap Badges</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head><body> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <div class="container"> <button type="button" class="btn btn-primary"> <h4>Notifications heading <span class="badge badge-primary badge-danger">4</span> </h4> </button><br><br> <button type="button" class="btn btn-warning"> <h4>Updates <span class="badge badge-light">2</span> </h4> </button><br><br> <button type="button" class="btn btn-primary"> <h4>Messages <span class="badge badge-success">1</span> </h4> </button><br><br> <button type="button" class="btn btn-danger"> <h4>Request <span class="badge badge-primary">0</span> </h4> </button> </div></body></html> Output: Supported Browsers: Google Chrome Internet Explorer Firefox Opera Safari ysachin2314 Bootstrap-4 Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to change navigation bar color in Bootstrap ? Form validation using jQuery How to align navbar items to the right in Bootstrap 4 ? How to pass data into a bootstrap modal? How to Show Images on Click using HTML ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 28440, "s": 28412, "text": "\n29 Apr, 2022" }, { "code": null, "e": 28740, "s": 28440, "text": "The .badge class is used to add additional information to the content. For example, some websites associate a number of notifications to the link. The notification number is seen when logged in to a particular website which tells the numbers of news or notifications to see by clicking it.Example: " }, { "code": null, "e": 28745, "s": 28740, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Badges</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <div class=\"container\"> <h4>Notifications heading <span class=\"badge badge-secondary\"> 4 </span> </h4> <h4>Updates <span class=\"badge badge-secondary\"> 2 </span> </h4> <h4>Messages <span class=\"badge badge-secondary\"> 1 </span> </h4> <h4>Request <span class=\"badge badge-secondary\"> 0 </span> </h4> </div></body></html>", "e": 29955, "s": 28745, "text": null }, { "code": null, "e": 29965, "s": 29955, "text": "Output: " }, { "code": null, "e": 30298, "s": 29965, "text": "Contextual Badges: The contextual classes (.badge-*) is used to change the color of badges. Badges can be used as part of links or button to provide a counter. Depending on how they used, badges must be confusing for the users. For this purpose different color of variations are used so that the user may not get confused.Example: " }, { "code": null, "e": 30303, "s": 30298, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Badges</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <div class=\"container\"> <h4>Notifications heading <span class=\"badge badge-primary\"> 4 </span> </h4> <h4>Updates <span class=\"badge badge-warning\"> 2 </span> </h4> <h4>Messages <span class=\"badge badge-success\"> 1 </span> </h4> <h4>Request <span class=\"badge badge-danger\"> 0 </span> </h4> </div></body></html>", "e": 31504, "s": 30303, "text": null }, { "code": null, "e": 31514, "s": 31504, "text": "Output: " }, { "code": null, "e": 31603, "s": 31514, "text": "Pill Badges: The .badge-pill class is used to make badges corner more rounded.Example: " }, { "code": null, "e": 31608, "s": 31603, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Badges</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <div class=\"container\"> <h4>Notifications heading <span class=\"badge badge-primary badge-pill\"> 4 </span> </h4> <h4>Updates <span class=\"badge badge-warning badge-pill\"> 2 </span> </h4> <h4>Messages <span class=\"badge badge-success badge-pill\"> 1 </span> </h4> <h4>Request <span class=\"badge badge-danger badge-pill\"> 0 </span> </h4> </div></body></html>", "e": 32853, "s": 31608, "text": null }, { "code": null, "e": 32863, "s": 32853, "text": "Output: " }, { "code": null, "e": 32939, "s": 32863, "text": "Badge inside an Element: Badges can be created inside an element.Example: " }, { "code": null, "e": 32944, "s": 32939, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Badges</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head><body> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <div class=\"container\"> <button type=\"button\" class=\"btn btn-primary\"> <h4>Notifications heading <span class=\"badge badge-primary badge-danger\">4</span> </h4> </button><br><br> <button type=\"button\" class=\"btn btn-warning\"> <h4>Updates <span class=\"badge badge-light\">2</span> </h4> </button><br><br> <button type=\"button\" class=\"btn btn-primary\"> <h4>Messages <span class=\"badge badge-success\">1</span> </h4> </button><br><br> <button type=\"button\" class=\"btn btn-danger\"> <h4>Request <span class=\"badge badge-primary\">0</span> </h4> </button> </div></body></html>", "e": 34392, "s": 32944, "text": null }, { "code": null, "e": 34402, "s": 34392, "text": "Output: " }, { "code": null, "e": 34422, "s": 34402, "text": "Supported Browsers:" }, { "code": null, "e": 34436, "s": 34422, "text": "Google Chrome" }, { "code": null, "e": 34454, "s": 34436, "text": "Internet Explorer" }, { "code": null, "e": 34462, "s": 34454, "text": "Firefox" }, { "code": null, "e": 34468, "s": 34462, "text": "Opera" }, { "code": null, "e": 34475, "s": 34468, "text": "Safari" }, { "code": null, "e": 34487, "s": 34475, "text": "ysachin2314" }, { "code": null, "e": 34499, "s": 34487, "text": "Bootstrap-4" }, { "code": null, "e": 34509, "s": 34499, "text": "Bootstrap" }, { "code": null, "e": 34526, "s": 34509, "text": "Web Technologies" }, { "code": null, "e": 34624, "s": 34526, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34674, "s": 34624, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 34703, "s": 34674, "text": "Form validation using jQuery" }, { "code": null, "e": 34759, "s": 34703, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 34800, "s": 34759, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 34841, "s": 34800, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 34883, "s": 34841, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 34916, "s": 34883, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34959, "s": 34916, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 35009, "s": 34959, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Conditional Selection and Assignment With .loc in Pandas | by Byron Dolon | Towards Data Science
There are many different ways to select data in Pandas, but some methods work better than others. In this piece, we’ll go over how to edit your DataFrames based on conditional statements using the .loc method. If you’ve been working with Pandas for a while now, you may already have come across the dreaded “SettingwithCopyWarning” message when you run your code. It may seem scary at first (trust me, I’ve been there), but all it’s telling you is that you are probably trying to assign a value to a copy of a Pandas object when in reality you want to be editing the actual value. For some operations, you can get around this warning simply by adding the inplace=True parameter to whatever function you’re running. When you’re working with conditional selection, however, it’s worth going over a few examples to understand how to make your changes stick properly. Examples in this piece will use some old Tesla stock price data from Yahoo Finance. Feel free to run the code below if you want to follow along. For more information on pd.read_html and df.sort_values, check out the links at the end of this piece. import pandas as pddf = pd.read_html("https://finance.yahoo.com/quote/TSLA/history?period1=1546300800&period2=1550275200&interval=1d&filter=history&frequency=1d")[0]df = df.head(11).sort_values(by='Date')df = df.astype({"Open":'float', "High":'float', "Low":'float', "Close*":'float', "Adj Close**":'float', "Volume":'float'})df['Gain'] = df['Close*'] - df['Open'] If you haven’t worked with .loc in the past at all, check out this piece for some simple examples. Otherwise, let’s dive straight in! First, let’s just try to grab all rows in our DataFrame that match one condition. In this example, I’d just like to get all the rows that occur after a certain date, so we’ll run the following code below: df1 = df.loc[df['Date'] > 'Feb 06, 2019'] And that’s all! .loc allows you to set a condition and the result will be a DataFrame that contains only the rows that match that condition. Now that we understand the basic syntax, let’s move on to a slightly more interesting example. Now, we’ll introduce the syntax that allows you to specify which columns you want .loc to return. In this case, we’ll use the same conditional statement as before to filter out specific dates. However, our goal this time is to only select two columns (Date and Open) from the original DataFrame. To do so, we run the following code: df2 = df.loc[df['Date'] > 'Feb 06, 2019', ['Date','Open']] As you can see, after the conditional statement .loc, we simply pass a list of the columns we would like to find in the original DataFrame. The resulting DataFrame gives us only the Date and Open columns for rows with a Date value greater than February 6, 2019. But what if we wanted to filter by multiple conditions? Let’s keep going. If you have two or more conditions you would like to use to get a very specific subset of your data, .loc allows you to do that very easily. In our case, let’s take the rows that not only occur after a specific date but also have an Open value greater than a specific value. To do so, we run the following: df3 = df.loc[(df['Date'] > 'Feb 06, 2019') & (df['Open'] > 62), ['Date', 'Open']] As you can see, we’ve simply wrapped added another conditional by including the & sign to indicate that we want both conditions to be fulfilled (note that the | sign will also work for “or”). We’ve also wrapped each conditional statement in parentheses for a clean look. The result is a very small subset of the original DataFrame with only the rows that meet our two conditions. Now that we’ve gone over all the components, we’re ready to make changes to our DataFrame! As mentioned before, there may be other ways to do this, but you might end up with a “SettingwithCopyWarning” if you’re not careful. Using .loc to assign values will take care of this issue for you! We’ll put together all the previous steps and edit our DataFrame so that rows that meet a condition that we set will be assigned a specific value. In this case, we’ll create a new “Remarkable” column, which will include rows that either has a very high Volume or a positive Gain. To do so, we run the following code: remarkable_filter = (df['Volume'] > 30000000) | (df['Gain'] > 0)df4 = df.copy()df4['Remarkable'] = ''df4.loc[remarkable_filter, ['Remarkable']] = Truedf4.loc[~remarkable_filter, ['Remarkable']] = False For clarity, we put our conditional statements in a separate variable, which is used later in .loc. Then, we assign either True to the Remarkable column for all the rows that meet our conditional statements. We use the ~ symbol to find all the rows that don’t meet our conditional statement and then assign False to the Remarkable column for those rows. And that’s all! I hope you found this useful in further understanding .loc and how you can use it to filter and edit your DataFrames in Pandas! This way, you’ll also be safe from the “SettingwithCopyWarning”, because all we’re doing is following the warning’s instructions: Try using .loc[row_indexer, col_indexer] = value instead Best of luck on your Pandas adventures! More by me:- Don’t Miss Out on Rolling Window Functions in Pandas- 4 Different Ways to Efficiently Sort a Pandas DataFrame- Top 4 Repositories on GitHub to Learn Pandas- How to Quickly Create and Unpack Lists with Pandas- Learning to Forecast With Tableau in 5 Minutes Or Less
[ { "code": null, "e": 381, "s": 171, "text": "There are many different ways to select data in Pandas, but some methods work better than others. In this piece, we’ll go over how to edit your DataFrames based on conditional statements using the .loc method." }, { "code": null, "e": 752, "s": 381, "text": "If you’ve been working with Pandas for a while now, you may already have come across the dreaded “SettingwithCopyWarning” message when you run your code. It may seem scary at first (trust me, I’ve been there), but all it’s telling you is that you are probably trying to assign a value to a copy of a Pandas object when in reality you want to be editing the actual value." }, { "code": null, "e": 1035, "s": 752, "text": "For some operations, you can get around this warning simply by adding the inplace=True parameter to whatever function you’re running. When you’re working with conditional selection, however, it’s worth going over a few examples to understand how to make your changes stick properly." }, { "code": null, "e": 1283, "s": 1035, "text": "Examples in this piece will use some old Tesla stock price data from Yahoo Finance. Feel free to run the code below if you want to follow along. For more information on pd.read_html and df.sort_values, check out the links at the end of this piece." }, { "code": null, "e": 1723, "s": 1283, "text": "import pandas as pddf = pd.read_html(\"https://finance.yahoo.com/quote/TSLA/history?period1=1546300800&period2=1550275200&interval=1d&filter=history&frequency=1d\")[0]df = df.head(11).sort_values(by='Date')df = df.astype({\"Open\":'float', \"High\":'float', \"Low\":'float', \"Close*\":'float', \"Adj Close**\":'float', \"Volume\":'float'})df['Gain'] = df['Close*'] - df['Open']" }, { "code": null, "e": 1857, "s": 1723, "text": "If you haven’t worked with .loc in the past at all, check out this piece for some simple examples. Otherwise, let’s dive straight in!" }, { "code": null, "e": 2062, "s": 1857, "text": "First, let’s just try to grab all rows in our DataFrame that match one condition. In this example, I’d just like to get all the rows that occur after a certain date, so we’ll run the following code below:" }, { "code": null, "e": 2104, "s": 2062, "text": "df1 = df.loc[df['Date'] > 'Feb 06, 2019']" }, { "code": null, "e": 2120, "s": 2104, "text": "And that’s all!" }, { "code": null, "e": 2340, "s": 2120, "text": ".loc allows you to set a condition and the result will be a DataFrame that contains only the rows that match that condition. Now that we understand the basic syntax, let’s move on to a slightly more interesting example." }, { "code": null, "e": 2673, "s": 2340, "text": "Now, we’ll introduce the syntax that allows you to specify which columns you want .loc to return. In this case, we’ll use the same conditional statement as before to filter out specific dates. However, our goal this time is to only select two columns (Date and Open) from the original DataFrame. To do so, we run the following code:" }, { "code": null, "e": 2732, "s": 2673, "text": "df2 = df.loc[df['Date'] > 'Feb 06, 2019', ['Date','Open']]" }, { "code": null, "e": 2994, "s": 2732, "text": "As you can see, after the conditional statement .loc, we simply pass a list of the columns we would like to find in the original DataFrame. The resulting DataFrame gives us only the Date and Open columns for rows with a Date value greater than February 6, 2019." }, { "code": null, "e": 3068, "s": 2994, "text": "But what if we wanted to filter by multiple conditions? Let’s keep going." }, { "code": null, "e": 3375, "s": 3068, "text": "If you have two or more conditions you would like to use to get a very specific subset of your data, .loc allows you to do that very easily. In our case, let’s take the rows that not only occur after a specific date but also have an Open value greater than a specific value. To do so, we run the following:" }, { "code": null, "e": 3457, "s": 3375, "text": "df3 = df.loc[(df['Date'] > 'Feb 06, 2019') & (df['Open'] > 62), ['Date', 'Open']]" }, { "code": null, "e": 3837, "s": 3457, "text": "As you can see, we’ve simply wrapped added another conditional by including the & sign to indicate that we want both conditions to be fulfilled (note that the | sign will also work for “or”). We’ve also wrapped each conditional statement in parentheses for a clean look. The result is a very small subset of the original DataFrame with only the rows that meet our two conditions." }, { "code": null, "e": 3928, "s": 3837, "text": "Now that we’ve gone over all the components, we’re ready to make changes to our DataFrame!" }, { "code": null, "e": 4127, "s": 3928, "text": "As mentioned before, there may be other ways to do this, but you might end up with a “SettingwithCopyWarning” if you’re not careful. Using .loc to assign values will take care of this issue for you!" }, { "code": null, "e": 4444, "s": 4127, "text": "We’ll put together all the previous steps and edit our DataFrame so that rows that meet a condition that we set will be assigned a specific value. In this case, we’ll create a new “Remarkable” column, which will include rows that either has a very high Volume or a positive Gain. To do so, we run the following code:" }, { "code": null, "e": 4646, "s": 4444, "text": "remarkable_filter = (df['Volume'] > 30000000) | (df['Gain'] > 0)df4 = df.copy()df4['Remarkable'] = ''df4.loc[remarkable_filter, ['Remarkable']] = Truedf4.loc[~remarkable_filter, ['Remarkable']] = False" }, { "code": null, "e": 5000, "s": 4646, "text": "For clarity, we put our conditional statements in a separate variable, which is used later in .loc. Then, we assign either True to the Remarkable column for all the rows that meet our conditional statements. We use the ~ symbol to find all the rows that don’t meet our conditional statement and then assign False to the Remarkable column for those rows." }, { "code": null, "e": 5016, "s": 5000, "text": "And that’s all!" }, { "code": null, "e": 5274, "s": 5016, "text": "I hope you found this useful in further understanding .loc and how you can use it to filter and edit your DataFrames in Pandas! This way, you’ll also be safe from the “SettingwithCopyWarning”, because all we’re doing is following the warning’s instructions:" }, { "code": null, "e": 5331, "s": 5274, "text": "Try using .loc[row_indexer, col_indexer] = value instead" }, { "code": null, "e": 5371, "s": 5331, "text": "Best of luck on your Pandas adventures!" } ]
What is a one-dimensional array in C language?
An array is a group of related items that store with a common name. The syntax is as follows for declaring an array − datatype array_name [size]; Arrays are broadly classified into three types. They are as follows − One – dimensional arrays Two – dimensional arrays Multi – dimensional arrays The Syntax is as follows − datatype array name [size] For example, int a[5] Initialization An array can be initialized in two ways, which are as follows − Compile time initialization Runtime initialization Following is the C program on compile time initialization − Live Demo #include<stdio.h> int main ( ){ int a[5] = {10,20,30,40,50}; int i; printf ("elements of the array are"); for ( i=0; i<5; i++) printf ("%d", a[i]); } Upon execution, you will receive the following output − Elements of the array are 10 20 30 40 50 Following is the C program on runtime initialization − Live Demo #include<stdio.h> main ( ){ int a[5],i; printf ("enter 5 elements"); for ( i=0; i<5; i++) scanf("%d", &a[i]); printf("elements of the array are"); for (i=0; i<5; i++) printf("%d", a[i]); } The output is as follows − enter 5 elements 10 20 30 40 50 elements of the array are : 10 20 30 40 50 Note The output of compile time initialised program will not change during different runs of the program. The output of compile time initialised program will not change during different runs of the program. The output of run time initialised program will change for different runs because, user is given a chance of accepting different values during execution. The output of run time initialised program will change for different runs because, user is given a chance of accepting different values during execution. Following is another C program for one dimensional array − Live Demo #include <stdio.h> int main(void){ int a[4]; int b[4] = {1}; int c[4] = {1,2,3,4}; int i; //for loop counter //printing all elements of all arrays printf("\nArray a:\n"); for( i=0; i<4; i++ ) printf("arr[%d]: %d\n",i,a[i]); printf("\nArray b:\n"); for( i=0; i<4; i++) printf("arr[%d]: %d\n",i,b[i]); printf("\nArray c:\n"); for( i=0; i<4; i++ ) printf("arr[%d]: %d\n",i, c[i]); return 0; } The output is stated below − Array a: arr[0]: 8 arr[1]: 0 arr[2]: 54 arr[3]: 0 Array b: arr[0]: 1 arr[1]: 0 arr[2]: 0 arr[3]: 0 Array c: arr[0]: 1 arr[1]: 2 arr[2]: 3 arr[3]: 4
[ { "code": null, "e": 1130, "s": 1062, "text": "An array is a group of related items that store with a common name." }, { "code": null, "e": 1180, "s": 1130, "text": "The syntax is as follows for declaring an array −" }, { "code": null, "e": 1208, "s": 1180, "text": "datatype array_name [size];" }, { "code": null, "e": 1278, "s": 1208, "text": "Arrays are broadly classified into three types. They are as follows −" }, { "code": null, "e": 1303, "s": 1278, "text": "One – dimensional arrays" }, { "code": null, "e": 1328, "s": 1303, "text": "Two – dimensional arrays" }, { "code": null, "e": 1355, "s": 1328, "text": "Multi – dimensional arrays" }, { "code": null, "e": 1382, "s": 1355, "text": "The Syntax is as follows −" }, { "code": null, "e": 1409, "s": 1382, "text": "datatype array name [size]" }, { "code": null, "e": 1431, "s": 1409, "text": "For example, int a[5]" }, { "code": null, "e": 1446, "s": 1431, "text": "Initialization" }, { "code": null, "e": 1510, "s": 1446, "text": "An array can be initialized in two ways, which are as follows −" }, { "code": null, "e": 1538, "s": 1510, "text": "Compile time initialization" }, { "code": null, "e": 1561, "s": 1538, "text": "Runtime initialization" }, { "code": null, "e": 1621, "s": 1561, "text": "Following is the C program on compile time initialization −" }, { "code": null, "e": 1632, "s": 1621, "text": " Live Demo" }, { "code": null, "e": 1800, "s": 1632, "text": "#include<stdio.h>\nint main ( ){\n int a[5] = {10,20,30,40,50};\n int i;\n printf (\"elements of the array are\");\n for ( i=0; i<5; i++)\n printf (\"%d\", a[i]);\n}" }, { "code": null, "e": 1856, "s": 1800, "text": "Upon execution, you will receive the following output −" }, { "code": null, "e": 1897, "s": 1856, "text": "Elements of the array are\n10 20 30 40 50" }, { "code": null, "e": 1952, "s": 1897, "text": "Following is the C program on runtime initialization −" }, { "code": null, "e": 1963, "s": 1952, "text": " Live Demo" }, { "code": null, "e": 2179, "s": 1963, "text": "#include<stdio.h>\nmain ( ){\n int a[5],i;\n printf (\"enter 5 elements\");\n for ( i=0; i<5; i++)\n scanf(\"%d\", &a[i]);\n printf(\"elements of the array are\");\n for (i=0; i<5; i++)\n printf(\"%d\", a[i]);\n}" }, { "code": null, "e": 2206, "s": 2179, "text": "The output is as follows −" }, { "code": null, "e": 2281, "s": 2206, "text": "enter 5 elements 10 20 30 40 50\nelements of the array are : 10 20 30 40 50" }, { "code": null, "e": 2286, "s": 2281, "text": "Note" }, { "code": null, "e": 2387, "s": 2286, "text": "The output of compile time initialised program will not change during different runs of the program." }, { "code": null, "e": 2488, "s": 2387, "text": "The output of compile time initialised program will not change during different runs of the program." }, { "code": null, "e": 2642, "s": 2488, "text": "The output of run time initialised program will change for different runs because, user is given a chance of accepting different values during execution." }, { "code": null, "e": 2796, "s": 2642, "text": "The output of run time initialised program will change for different runs because, user is given a chance of accepting different values during execution." }, { "code": null, "e": 2855, "s": 2796, "text": "Following is another C program for one dimensional array −" }, { "code": null, "e": 2866, "s": 2855, "text": " Live Demo" }, { "code": null, "e": 3316, "s": 2866, "text": "#include <stdio.h>\nint main(void){\n int a[4];\n int b[4] = {1};\n int c[4] = {1,2,3,4};\n int i; //for loop counter\n //printing all elements of all arrays\n printf(\"\\nArray a:\\n\");\n for( i=0; i<4; i++ )\n printf(\"arr[%d]: %d\\n\",i,a[i]);\n printf(\"\\nArray b:\\n\");\n for( i=0; i<4; i++)\n printf(\"arr[%d]: %d\\n\",i,b[i]);\n printf(\"\\nArray c:\\n\");\n for( i=0; i<4; i++ )\n printf(\"arr[%d]: %d\\n\",i, c[i]);\n return 0;\n}" }, { "code": null, "e": 3345, "s": 3316, "text": "The output is stated below −" }, { "code": null, "e": 3493, "s": 3345, "text": "Array a:\narr[0]: 8\narr[1]: 0\narr[2]: 54\narr[3]: 0\nArray b:\narr[0]: 1\narr[1]: 0\narr[2]: 0\narr[3]: 0\nArray c:\narr[0]: 1\narr[1]: 2\narr[2]: 3\narr[3]: 4" } ]
FastText: Under the Hood. Where we look at how one of the best... | by Nishan Subedi | Towards Data Science
fastText as a library for efficient learning of word representations and sentence classification. It is written in C++ and supports multiprocessing during training. FastText allows you to train supervised and unsupervised representations of words and sentences. These representations (embeddings) can be used for numerous applications from data compression, as features into additional models, for candidate selection, or as initializers for transfer learning. FastText supports training continuous bag of words (CBOW) or Skip-gram models using negative sampling, softmax or hierarchical softmax loss functions. I have primarily used fastText for training semantic embeddings for a corpus of size in the order of tens millions, and am happy with how it has performed and scaled for this task. I had a hard time finding documentation beyond the documentation for getting started, so in this post I am going to walk you through the internals of fastText and how it works. An understanding of how the word2vec models work is expected. This post by Chris McCormick does a great job of explaining it. We can train a Skip-gram model via fastText with the following command: $ fasttext skipgram -input data.txt -output model where data.txt is the input data which can just be a sequence of text, and the output model gets saved under model.bin and vector representations for the input terms are saved under model.vec. FastText is able to achieve really good performance for word representations and sentence classification, specially in the case of rare words by making use of character level information. Each word is represented as a bag of character n-grams in addition to the word itself, so for example, for the word matter, with n = 3, the fastText representations for the character n-grams is <ma, mat, att, tte, ter, er>. < and > are added as boundary symbols to distinguish the ngram of a word from a word itself, so for example, if the word mat is part of the vocabulary, it is represented as <mat>. This helps preserve the meaning of shorter words that may show up as ngrams of other words. Inherently, this also allows you to capture meaning for suffixes/prefixes. The length of n-grams you use can be controlled by the -minn and -maxn flags for minimum and maximum number of characters to use respectively. These control the range of values to get n-grams for. The model is considered to be a bag of words model because aside of the sliding window of n-gram selection, there is no internal structure of a word that is taken into account for featurization, i.e as long as the characters fall under the window, the order of the character n-grams does not matter. You can also turn n-gram embeddings completely off as well by setting them both to 0. This can be useful when the ‘words’ in your model aren’t words for a particular language, and character level n-grams would not make sense. The most common use case is when you’re putting in ids as your words. During the model update, fastText learns weights for each of the n-grams as well as the entire word token. While the training for fastText is multi-threaded, reading the data in is done via a single thread. The parsing and tokenization is done when the input data is read. Let’s see how this is done in detail: FastText takes a file handle via -input argument for input data. Reading in data from stdin is not supported. FastText initializes a couple of vectors to keep track of the input information, internally called word2int_ and words_. word2int_ is indexed on the hash of the word string, and stores a sequential int index to the words_ array (std::vector) as it’s value. The words_ array is incrementally keyed in the order that unique words appear when reading the input, and stores as its value the struct entry that encapsulates all the information about the word token. entry contains the following information: struct entry { std::string word; int64_t count; entry_type type; std::vector<int32_t> subwords;}; A few things to note here, word is the string representation of the word, count is the total count of the respective word in the input line, entry_type is one of {word, label} with label only being used for the supervised case. All input tokens, regardless of entry_type are stored in the same dictionary, which makes extending fastText to contain other types of entities a lot easier (I will talk more about how to do this in a latter post). Finally, subwords is a vector of all the word n-grams of a particular word. These are also created when the input data is read, and passed to the training step. The word2int_ vector is of size MAX_VOCAB_SIZE = 30000000; This number is hard-coded. This size can be limiting when training on a large corpus, and can effectively be increased while maintaining performance. The index for the word2int_ array is the value of a string to int hash, and is unique number between 0 and MAX_VOCAB_SIZE. If there is a hash collision, and an entry has already been added to the hash, the value is incremented till we find a unique id to assign to a word. Because of this, performance can worsen considerably once the size of the vocabulary reaches MAX_VOCAB_SIZE. To prevent this, fastText prunes the vocabulary every time the size of the hash gets over 75% of MAX_VOCAB_SIZE. This is done by first incrementing the minimum count threshold for a word to qualify for being part of the vocabulary, and pruning the dictionary for all words that have a count less than this. The check for the 75% threshold happens when each new word is added, and so this automatic pruning can occur at any stage of the file reading process. Aside from the automatic pruning, the minimum count for words that are part of the vocabulary is controlled by using the -minCount and -minCountLabel flags for words and labels (used for supervised training) respectively. The pruning based on these flags happens after the entire training file has been processed. Your dictionary may be thresholded on a higher min count that manually specified if the total number of unique words in your triggers the automatic pruning specified earlier. The thresholding to the specified minCount will however always occur, effectively ensuring that words with a lower count do not make it as part of your input. For negative sampling loss, a table of negative words is then constructed of size NEGATIVE_TABLE_SIZE = 10000000. Note that this is 1⁄3 of the size of the MAX_VOCAB_SIZE. The table is constructed by drawing from a unigram distribution of the square root of the frequency of each word, ie. This ensures that the number of times each word appears in the negatives table is directly proportional square root of its frequency. This table is then shuffled to ensure randomization. Next, a sampling table to discard frequent words as outlined in section 2.3 of the original word2vec extension paper is constructed. The idea behind this is that words that get repeated a lot provide less information than words that are rare, and that their representation is not going to change by much after seeing already seeing many instances of the same word. The paper outlines the following method for discard: the training word is discarded with a probability of The authors suggest t = 10e-5to be a reasonable default. This formula discards words that have a frequency greater than the threshold value, and effectively samples less frequent words while still maintaining their relative frequency, and thus just acting to dampen the exaggerated effects of the frequency. FastText, on the other hand, defines this distribution as The default threshold can be manually edited via the -t arg. The threshold value, t does not hold the same meaning in fastText as it does in the original word2vec paper, and should be tuned for your application. A word gets discarded only if, during training stage, a random draw from a uniform distribution between 0 and 1 is greater than the probability of discard. Below is a plot of the distribution for values ranging from 0–1 for the default threshold. As shown in the plot, the probability of a draw being greater than P increases as the frequency increases, and therefore, it’s probability of being discarded increases as the frequency does as well. This only applies to unsupervised models. Words are not discarded for a supervised model. If we initialize the training with -pretrainedVectors flag, the values from the input file are used to initialize the input layer vectors. If unspecified, a matrix of dimension MxN where M = MAX_VOCAB_SIZE + bucket_size, N = dim is created. bucket_size corresponds to the total size of array allocated for all the ngram tokens. It is set via the -bucket flag, and is set to be 2000000 by default. Ngrams are initialized by via a numerical hash (the same hashing function) of the ngram text, and fitting the modulo of this hash number onto the initialized matrix at a position corresponding to MAX_VOCAB_SIZE + hash. Note that there could be collisions in the ngrams space, whereas collisions are not possible for original words. This could affect model performance as well. Dim represents the dimension of the hidden layer in training, and thus the dimension of the embeddings, and is set via the -dim flag. This is set to 100 by default. The matrix is initialized with a uniform real distribution between 0 and 1/dim, and is uniform in the unit cube. Once the input and hidden vectors are initialized, multiple training threads are kicked off. The number of threads is specified by -thread arg. All the training threads hold a shared pointer to the matrices for input and hidden vectors. The threads all read from the input file, updating the model with each input line that is read, i.e stochastic gradient descent with a batch size of 1. An input line is truncated if newline character is encountered, or if the count of words we’ve read reaches the maximum allowed line size. This is set via MAX_LINE_SIZE, and defaults to 1024. Both the continuous bag of words and the Skip-gram model update the weights for a context of size between a random uniform distribution between 1 and the value determined by -ws, i.e the window size is stochastic. The target vector for the loss function is computed via a normalized sum of all the input vectors. The input vectors are the vector representation for the original word, and all the n-grams of that word. The loss is computed which sets the weights for the forward pass, which propagate their way all the way back to the vectors for the input layer in the back propagation pass. This tuning of the input vector weights that happens during the back propagation pass is what allows us to learn representations that maximize co occurrence similarity. The learning rate -lr affects how much each particular instance affects the weights. The model input weights, hidden layer weights along with arguments passed in are saved in the .bin format and the -saveOutput flag controls whether a .vec file is also outputted which contains vectors for the hidden layer in the word2vec file format. I hope this walkthrough helped shed some light on the inner workings of fastText. I’ve personally had a lot of success using this library and highly recommend it for your embedding needs. In my next post, I will talk about a few additional functionalities I have added to fastText to generalize its capabilities. Stay tuned.. Huge thanks to Giovanni Fernandez-Kincade for your thoughtful feedback on this post.
[ { "code": null, "e": 632, "s": 171, "text": "fastText as a library for efficient learning of word representations and sentence classification. It is written in C++ and supports multiprocessing during training. FastText allows you to train supervised and unsupervised representations of words and sentences. These representations (embeddings) can be used for numerous applications from data compression, as features into additional models, for candidate selection, or as initializers for transfer learning." }, { "code": null, "e": 1267, "s": 632, "text": "FastText supports training continuous bag of words (CBOW) or Skip-gram models using negative sampling, softmax or hierarchical softmax loss functions. I have primarily used fastText for training semantic embeddings for a corpus of size in the order of tens millions, and am happy with how it has performed and scaled for this task. I had a hard time finding documentation beyond the documentation for getting started, so in this post I am going to walk you through the internals of fastText and how it works. An understanding of how the word2vec models work is expected. This post by Chris McCormick does a great job of explaining it." }, { "code": null, "e": 1339, "s": 1267, "text": "We can train a Skip-gram model via fastText with the following command:" }, { "code": null, "e": 1389, "s": 1339, "text": "$ fasttext skipgram -input data.txt -output model" }, { "code": null, "e": 1582, "s": 1389, "text": "where data.txt is the input data which can just be a sequence of text, and the output model gets saved under model.bin and vector representations for the input terms are saved under model.vec." }, { "code": null, "e": 1770, "s": 1582, "text": "FastText is able to achieve really good performance for word representations and sentence classification, specially in the case of rare words by making use of character level information." }, { "code": null, "e": 2341, "s": 1770, "text": "Each word is represented as a bag of character n-grams in addition to the word itself, so for example, for the word matter, with n = 3, the fastText representations for the character n-grams is <ma, mat, att, tte, ter, er>. < and > are added as boundary symbols to distinguish the ngram of a word from a word itself, so for example, if the word mat is part of the vocabulary, it is represented as <mat>. This helps preserve the meaning of shorter words that may show up as ngrams of other words. Inherently, this also allows you to capture meaning for suffixes/prefixes." }, { "code": null, "e": 3241, "s": 2341, "text": "The length of n-grams you use can be controlled by the -minn and -maxn flags for minimum and maximum number of characters to use respectively. These control the range of values to get n-grams for. The model is considered to be a bag of words model because aside of the sliding window of n-gram selection, there is no internal structure of a word that is taken into account for featurization, i.e as long as the characters fall under the window, the order of the character n-grams does not matter. You can also turn n-gram embeddings completely off as well by setting them both to 0. This can be useful when the ‘words’ in your model aren’t words for a particular language, and character level n-grams would not make sense. The most common use case is when you’re putting in ids as your words. During the model update, fastText learns weights for each of the n-grams as well as the entire word token." }, { "code": null, "e": 3445, "s": 3241, "text": "While the training for fastText is multi-threaded, reading the data in is done via a single thread. The parsing and tokenization is done when the input data is read. Let’s see how this is done in detail:" }, { "code": null, "e": 4057, "s": 3445, "text": "FastText takes a file handle via -input argument for input data. Reading in data from stdin is not supported. FastText initializes a couple of vectors to keep track of the input information, internally called word2int_ and words_. word2int_ is indexed on the hash of the word string, and stores a sequential int index to the words_ array (std::vector) as it’s value. The words_ array is incrementally keyed in the order that unique words appear when reading the input, and stores as its value the struct entry that encapsulates all the information about the word token. entry contains the following information:" }, { "code": null, "e": 4159, "s": 4057, "text": "struct entry { std::string word; int64_t count; entry_type type; std::vector<int32_t> subwords;};" }, { "code": null, "e": 4763, "s": 4159, "text": "A few things to note here, word is the string representation of the word, count is the total count of the respective word in the input line, entry_type is one of {word, label} with label only being used for the supervised case. All input tokens, regardless of entry_type are stored in the same dictionary, which makes extending fastText to contain other types of entities a lot easier (I will talk more about how to do this in a latter post). Finally, subwords is a vector of all the word n-grams of a particular word. These are also created when the input data is read, and passed to the training step." }, { "code": null, "e": 5245, "s": 4763, "text": "The word2int_ vector is of size MAX_VOCAB_SIZE = 30000000; This number is hard-coded. This size can be limiting when training on a large corpus, and can effectively be increased while maintaining performance. The index for the word2int_ array is the value of a string to int hash, and is unique number between 0 and MAX_VOCAB_SIZE. If there is a hash collision, and an entry has already been added to the hash, the value is incremented till we find a unique id to assign to a word." }, { "code": null, "e": 5812, "s": 5245, "text": "Because of this, performance can worsen considerably once the size of the vocabulary reaches MAX_VOCAB_SIZE. To prevent this, fastText prunes the vocabulary every time the size of the hash gets over 75% of MAX_VOCAB_SIZE. This is done by first incrementing the minimum count threshold for a word to qualify for being part of the vocabulary, and pruning the dictionary for all words that have a count less than this. The check for the 75% threshold happens when each new word is added, and so this automatic pruning can occur at any stage of the file reading process." }, { "code": null, "e": 6460, "s": 5812, "text": "Aside from the automatic pruning, the minimum count for words that are part of the vocabulary is controlled by using the -minCount and -minCountLabel flags for words and labels (used for supervised training) respectively. The pruning based on these flags happens after the entire training file has been processed. Your dictionary may be thresholded on a higher min count that manually specified if the total number of unique words in your triggers the automatic pruning specified earlier. The thresholding to the specified minCount will however always occur, effectively ensuring that words with a lower count do not make it as part of your input." }, { "code": null, "e": 6749, "s": 6460, "text": "For negative sampling loss, a table of negative words is then constructed of size NEGATIVE_TABLE_SIZE = 10000000. Note that this is 1⁄3 of the size of the MAX_VOCAB_SIZE. The table is constructed by drawing from a unigram distribution of the square root of the frequency of each word, ie." }, { "code": null, "e": 6936, "s": 6749, "text": "This ensures that the number of times each word appears in the negatives table is directly proportional square root of its frequency. This table is then shuffled to ensure randomization." }, { "code": null, "e": 7301, "s": 6936, "text": "Next, a sampling table to discard frequent words as outlined in section 2.3 of the original word2vec extension paper is constructed. The idea behind this is that words that get repeated a lot provide less information than words that are rare, and that their representation is not going to change by much after seeing already seeing many instances of the same word." }, { "code": null, "e": 7407, "s": 7301, "text": "The paper outlines the following method for discard: the training word is discarded with a probability of" }, { "code": null, "e": 7715, "s": 7407, "text": "The authors suggest t = 10e-5to be a reasonable default. This formula discards words that have a frequency greater than the threshold value, and effectively samples less frequent words while still maintaining their relative frequency, and thus just acting to dampen the exaggerated effects of the frequency." }, { "code": null, "e": 7773, "s": 7715, "text": "FastText, on the other hand, defines this distribution as" }, { "code": null, "e": 7985, "s": 7773, "text": "The default threshold can be manually edited via the -t arg. The threshold value, t does not hold the same meaning in fastText as it does in the original word2vec paper, and should be tuned for your application." }, { "code": null, "e": 8521, "s": 7985, "text": "A word gets discarded only if, during training stage, a random draw from a uniform distribution between 0 and 1 is greater than the probability of discard. Below is a plot of the distribution for values ranging from 0–1 for the default threshold. As shown in the plot, the probability of a draw being greater than P increases as the frequency increases, and therefore, it’s probability of being discarded increases as the frequency does as well. This only applies to unsupervised models. Words are not discarded for a supervised model." }, { "code": null, "e": 8918, "s": 8521, "text": "If we initialize the training with -pretrainedVectors flag, the values from the input file are used to initialize the input layer vectors. If unspecified, a matrix of dimension MxN where M = MAX_VOCAB_SIZE + bucket_size, N = dim is created. bucket_size corresponds to the total size of array allocated for all the ngram tokens. It is set via the -bucket flag, and is set to be 2000000 by default." }, { "code": null, "e": 9295, "s": 8918, "text": "Ngrams are initialized by via a numerical hash (the same hashing function) of the ngram text, and fitting the modulo of this hash number onto the initialized matrix at a position corresponding to MAX_VOCAB_SIZE + hash. Note that there could be collisions in the ngrams space, whereas collisions are not possible for original words. This could affect model performance as well." }, { "code": null, "e": 9573, "s": 9295, "text": "Dim represents the dimension of the hidden layer in training, and thus the dimension of the embeddings, and is set via the -dim flag. This is set to 100 by default. The matrix is initialized with a uniform real distribution between 0 and 1/dim, and is uniform in the unit cube." }, { "code": null, "e": 10154, "s": 9573, "text": "Once the input and hidden vectors are initialized, multiple training threads are kicked off. The number of threads is specified by -thread arg. All the training threads hold a shared pointer to the matrices for input and hidden vectors. The threads all read from the input file, updating the model with each input line that is read, i.e stochastic gradient descent with a batch size of 1. An input line is truncated if newline character is encountered, or if the count of words we’ve read reaches the maximum allowed line size. This is set via MAX_LINE_SIZE, and defaults to 1024." }, { "code": null, "e": 10368, "s": 10154, "text": "Both the continuous bag of words and the Skip-gram model update the weights for a context of size between a random uniform distribution between 1 and the value determined by -ws, i.e the window size is stochastic." }, { "code": null, "e": 11000, "s": 10368, "text": "The target vector for the loss function is computed via a normalized sum of all the input vectors. The input vectors are the vector representation for the original word, and all the n-grams of that word. The loss is computed which sets the weights for the forward pass, which propagate their way all the way back to the vectors for the input layer in the back propagation pass. This tuning of the input vector weights that happens during the back propagation pass is what allows us to learn representations that maximize co occurrence similarity. The learning rate -lr affects how much each particular instance affects the weights." }, { "code": null, "e": 11251, "s": 11000, "text": "The model input weights, hidden layer weights along with arguments passed in are saved in the .bin format and the -saveOutput flag controls whether a .vec file is also outputted which contains vectors for the hidden layer in the word2vec file format." }, { "code": null, "e": 11577, "s": 11251, "text": "I hope this walkthrough helped shed some light on the inner workings of fastText. I’ve personally had a lot of success using this library and highly recommend it for your embedding needs. In my next post, I will talk about a few additional functionalities I have added to fastText to generalize its capabilities. Stay tuned.." } ]
How to check if a variable is an array in JavaScript?
In javascript we can check whether a variable is array or not by using three methods. The Array.isArray() method checks whether the passed variable is array or not. If the variable is an array it displays true else displays false. Array.isArray(variableName) Live Demo <html> <body> <script type="text/javascript"> arr = [1,2,3,4,5]; str = "i love my india"; document.write( Array.isArray(arr)); document.write("</br>"); document.write( Array.isArray(str)); </script> </body> </html> true false The instanceof operator is used to test whether the prototype property of a constructor appears anywhere in the prototype chain of an object. In the following example the instanceof operator checks whether there exists an array prototype. variable instanceof Array Live Demo <html> <body> <script type="text/javascript"> arr = [1,2,3,4,5]; str = "i love my india"; document.write(str instanceof Array); document.write("</br>"); document.write(arr instanceof Array); </script> </body> </html> false true It displays true when the variable is same as what we specified. Here we specified that the variable should be array. So when the variable is array this method displays true else displays false. variable.constructor === Array Live Demo <html> <body> <script type="text/javascript"> arr = [1,2,3,4,5]; str = "i love my india"; document.write(str.constructor === Array); document.write("</br>"); document.write(arr.constructor === Array); </script> </body> </html> false true
[ { "code": null, "e": 1148, "s": 1062, "text": "In javascript we can check whether a variable is array or not by using three methods." }, { "code": null, "e": 1293, "s": 1148, "text": "The Array.isArray() method checks whether the passed variable is array or not. If the variable is an array it displays true else displays false." }, { "code": null, "e": 1321, "s": 1293, "text": "Array.isArray(variableName)" }, { "code": null, "e": 1331, "s": 1321, "text": "Live Demo" }, { "code": null, "e": 1561, "s": 1331, "text": "<html>\n<body>\n<script type=\"text/javascript\">\n arr = [1,2,3,4,5];\n str = \"i love my india\";\n document.write( Array.isArray(arr));\n document.write(\"</br>\");\n document.write( Array.isArray(str));\n</script>\n</body>\n</html>" }, { "code": null, "e": 1572, "s": 1561, "text": "true\nfalse" }, { "code": null, "e": 1811, "s": 1572, "text": "The instanceof operator is used to test whether the prototype property of a constructor appears anywhere in the prototype chain of an object. In the following example the instanceof operator checks whether there exists an array prototype." }, { "code": null, "e": 1837, "s": 1811, "text": "variable instanceof Array" }, { "code": null, "e": 1847, "s": 1837, "text": "Live Demo" }, { "code": null, "e": 2079, "s": 1847, "text": "<html>\n<body>\n<script type=\"text/javascript\">\n arr = [1,2,3,4,5];\n str = \"i love my india\";\n document.write(str instanceof Array);\n document.write(\"</br>\");\n document.write(arr instanceof Array);\n</script>\n</body>\n</html>" }, { "code": null, "e": 2090, "s": 2079, "text": "false\ntrue" }, { "code": null, "e": 2285, "s": 2090, "text": "It displays true when the variable is same as what we specified. Here we specified that the variable should be array. So when the variable is array this method displays true else displays false." }, { "code": null, "e": 2316, "s": 2285, "text": "variable.constructor === Array" }, { "code": null, "e": 2326, "s": 2316, "text": "Live Demo" }, { "code": null, "e": 2568, "s": 2326, "text": "<html>\n<body>\n<script type=\"text/javascript\">\n arr = [1,2,3,4,5];\n str = \"i love my india\";\n document.write(str.constructor === Array);\n document.write(\"</br>\");\n document.write(arr.constructor === Array);\n</script>\n</body>\n</html>" }, { "code": null, "e": 2579, "s": 2568, "text": "false\ntrue" } ]
How to detect constant, quasi-constant features in your dataset | by Samarth Agrawal | Towards Data Science
Two things distinguish top data scientists from others in most cases: Feature Creation and Feature Selection. i.e., creating features that capture deeper/hidden insights about the business or customer and then making the right choices about which features to choose for your model. Quality of Machine Learning model depends upon your data — Garbage in, Garbage out. (Garbage here would mean bad data/noise in data). After an extensive Feature Engineering step, you would end up with a large number of features. You may not use all the features in your model. You would be interested in feeding your model only those significant features or remove the ones that do not have any predictive power. This post is for identifying all those features that are Constant. It can be of two types: Constant Feature: Same value in all the records.Quasi Constant Feature: One of the values is dominant 99.9%. Constant Feature: Same value in all the records. Quasi Constant Feature: One of the values is dominant 99.9%. As shown in the example image, you only have Toyota as a value in Car Make for all the records in your data. Your machine learning model won’t learn anything insightful by keeping this feature in training. You are better off dropping this feature. Likewise, there can be many more such features, and you need a more automatic way of identifying this. 1) Use the get_constant_features functions to get all the constant features. 2) Store all the constant features as a list for removing from the dataset. 3) Drop all such features from the dataset. We can see that the number of features has dropped to 268 from 301. As shown in the example image — in your data, ‘Camry’ accounts for 99.9% of records. Your machine learning model won’t learn anything insightful by keeping this feature in training. Or worse, your model can learn from the fringe cases and cause overfitting. You are better off dropping this feature. Likewise, there can be many more such features, and you need a more automatic way of identifying this. 1) Use the get_constant_features functions to get all the constant features. threshold: cut-off value for defining the quasi-ness of the data you want to eliminate. 99%, 99.9%, 98% etc. 2) Store all the quasi constant features as a list for removing from the dataset. 3) Drop all such features from the dataset. We can see that the number of features has dropped to 123 from 268. Code Snippet for both Constant & Quasi Constant features: from fast_ml.utilities import display_allfrom fast_ml.feature_selection import get_constant_features# Use the function to get the results in dataframeconstant_features = get_constant_features(df)display_all(constant_features)# All the constant features stored in a listconstant_features_list = constant_features['Var'].to_list()# Drop all the constant features from the datasetdf.drop(columns = constant_features_list, inplace=True) If you enjoyed this, follow me on medium for more. Interested in collaborating? Let’s connect on Linkedin. Please feel free to write your thoughts/suggestions/feedback. Kaggle link Fast_ml link Notebook is available at the following location with fully functional code:
[ { "code": null, "e": 453, "s": 171, "text": "Two things distinguish top data scientists from others in most cases: Feature Creation and Feature Selection. i.e., creating features that capture deeper/hidden insights about the business or customer and then making the right choices about which features to choose for your model." }, { "code": null, "e": 587, "s": 453, "text": "Quality of Machine Learning model depends upon your data — Garbage in, Garbage out. (Garbage here would mean bad data/noise in data)." }, { "code": null, "e": 866, "s": 587, "text": "After an extensive Feature Engineering step, you would end up with a large number of features. You may not use all the features in your model. You would be interested in feeding your model only those significant features or remove the ones that do not have any predictive power." }, { "code": null, "e": 957, "s": 866, "text": "This post is for identifying all those features that are Constant. It can be of two types:" }, { "code": null, "e": 1066, "s": 957, "text": "Constant Feature: Same value in all the records.Quasi Constant Feature: One of the values is dominant 99.9%." }, { "code": null, "e": 1115, "s": 1066, "text": "Constant Feature: Same value in all the records." }, { "code": null, "e": 1176, "s": 1115, "text": "Quasi Constant Feature: One of the values is dominant 99.9%." }, { "code": null, "e": 1527, "s": 1176, "text": "As shown in the example image, you only have Toyota as a value in Car Make for all the records in your data. Your machine learning model won’t learn anything insightful by keeping this feature in training. You are better off dropping this feature. Likewise, there can be many more such features, and you need a more automatic way of identifying this." }, { "code": null, "e": 1604, "s": 1527, "text": "1) Use the get_constant_features functions to get all the constant features." }, { "code": null, "e": 1680, "s": 1604, "text": "2) Store all the constant features as a list for removing from the dataset." }, { "code": null, "e": 1792, "s": 1680, "text": "3) Drop all such features from the dataset. We can see that the number of features has dropped to 268 from 301." }, { "code": null, "e": 2195, "s": 1792, "text": "As shown in the example image — in your data, ‘Camry’ accounts for 99.9% of records. Your machine learning model won’t learn anything insightful by keeping this feature in training. Or worse, your model can learn from the fringe cases and cause overfitting. You are better off dropping this feature. Likewise, there can be many more such features, and you need a more automatic way of identifying this." }, { "code": null, "e": 2272, "s": 2195, "text": "1) Use the get_constant_features functions to get all the constant features." }, { "code": null, "e": 2381, "s": 2272, "text": "threshold: cut-off value for defining the quasi-ness of the data you want to eliminate. 99%, 99.9%, 98% etc." }, { "code": null, "e": 2463, "s": 2381, "text": "2) Store all the quasi constant features as a list for removing from the dataset." }, { "code": null, "e": 2575, "s": 2463, "text": "3) Drop all such features from the dataset. We can see that the number of features has dropped to 123 from 268." }, { "code": null, "e": 2633, "s": 2575, "text": "Code Snippet for both Constant & Quasi Constant features:" }, { "code": null, "e": 3066, "s": 2633, "text": "from fast_ml.utilities import display_allfrom fast_ml.feature_selection import get_constant_features# Use the function to get the results in dataframeconstant_features = get_constant_features(df)display_all(constant_features)# All the constant features stored in a listconstant_features_list = constant_features['Var'].to_list()# Drop all the constant features from the datasetdf.drop(columns = constant_features_list, inplace=True)" }, { "code": null, "e": 3117, "s": 3066, "text": "If you enjoyed this, follow me on medium for more." }, { "code": null, "e": 3173, "s": 3117, "text": "Interested in collaborating? Let’s connect on Linkedin." }, { "code": null, "e": 3235, "s": 3173, "text": "Please feel free to write your thoughts/suggestions/feedback." }, { "code": null, "e": 3247, "s": 3235, "text": "Kaggle link" }, { "code": null, "e": 3260, "s": 3247, "text": "Fast_ml link" } ]
Maximum sum of subarray less than or equal to x | Practice | GeeksforGeeks
Given an array arr[] of integers of size N and a number X, the task is to find the sum of subarray having maximum sum less than or equal to the given value of X. Example 1: Input: N = 5, X = 11 arr[] = {1, 2, 3, 4, 5} Output: 10 Explanation: Subarray having maximum sum is {1, 2, 3, 4}. Example 2: Input: N = 5, X = 7 arr[] = {2, 4, 6, 8, 10} Output: 6 Explanation: Subarray having maximum sum is {2, 4} or {6}. Your Task: This is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function calculateMaxSumLength() that takes array arr, integer N, and integer X as parameters and returns maximum sum of any subarray that is less than or equal to x. Expected Time Complexity: O(N). Expected Auxiliary Space: O(1). Constraints: 1 ≤ N ≤ 106 0 bharshit4682 months ago Easy to Understand | cpp class Solution{ public:int findMaxSubarraySum(long long arr[], int n, long long k){ int i = 0 , j = 0 , maxSum = 0 , sum = 0 ; while(j < n) { sum +=arr[j]; if(sum <= k) maxSum = max(maxSum , sum); else if(sum > k) { while(sum > k) { sum -=arr[i]; i++; } if(sum <= k) maxSum = max(maxSum , sum); } j++; } return maxSum;} }; 0 kake13373 months ago /*Its O(N) why? because every element gets add at most one time and gets removed from "s" at most one time, So the time complexity will be O(2N) which is linear!*/ int i=0; long long s=0,r=0; for(int j=0;j<n;j++) { s+=arr[j]; while(s>sum) { s-=arr[i]; i++; } r=max(r,s); } return r; +1 shyamprakash8073 months ago time complexity : 0.4/5.1 Pyhton solution using Sliding window Approach class Solution: def findMaxSubarraySum(self, arr, n, k): # Your code goes here sum = 0 ans = 0 i, j = 0, 0 while j < n: sum += arr[j] if sum < k: ans = max(ans, sum) j += 1 elif sum == k: return k else: while sum > k: sum -= arr[i] i += 1 ans = max(ans, sum) j += 1 return ans +2 krishnarajput10274 months ago int findMaxSubarraySum(long long arr[], int n, long long sum){ int j=0; int ans=INT_MIN; int s=0; for(int i=0;i<n;i++){ s+=arr[i]; while(s>sum){ s-=arr[j]; j++; } ans=max(s,ans); } return ans;} 0 shubodeepbera7 months ago int i=0,j=0,curr_sum=0; int ans=INT_MIN; while(i<n){ curr_sum+=arr[i]; i++; while(curr_sum>sum){ curr_sum-=arr[j]; j++; } ans=max(ans,curr_sum); } return ans; 0 delectable_boomer This comment was deleted. +1 Zilen Modi10 months ago Zilen Modi Consider this test case:3-1 7 117 right maximum sum=>7but, sliding Window giving =>6Add this test case. 0 Om Prakash10 months ago Om Prakash I thing Something is wrong with JAVA's Driver Code 0 Imran Wahid10 months ago Imran Wahid Easy C++ solution in O(n) TC and O(1) SChttps://ide.geeksforgeeks.o... 0 Aniket patel11 months ago Aniket patel class Solution{public:int findMaxSubarraySum(long long arr[], int n, long long sum){ int l=0,r=0; long long curr=arr[0],max=INT_MIN; while(r<n) {="" if(max<curr="" and="" curr<sum)="" max="curr;" if(curr="">sum) { curr-=arr[l]; l++; } else if(curr<sum) {="" if(r!="n-1)" {="" r++;="" curr+="arr[r];" }="" else="" break;="" }="" else="" (sum="=x)" return="" sum;="" }="" return="" max;="" }="" };="" https:="" practice.geeksforgeeks.org="" viewsol.php?subid="b36a06fad1b7f8ad91b5f81380720484&amp;pid=703423&amp;user=aniket66patel"> 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": 400, "s": 238, "text": "Given an array arr[] of integers of size N and a number X, the task is to find the sum of subarray having maximum sum less than or equal to the given value of X." }, { "code": null, "e": 411, "s": 400, "text": "Example 1:" }, { "code": null, "e": 528, "s": 411, "text": "Input: N = 5, X = 11\narr[] = {1, 2, 3, 4, 5} \nOutput: 10\nExplanation: Subarray having maximum \nsum is {1, 2, 3, 4}." }, { "code": null, "e": 541, "s": 528, "text": " \nExample 2:" }, { "code": null, "e": 658, "s": 541, "text": "Input: N = 5, X = 7\narr[] = {2, 4, 6, 8, 10} \nOutput: 6\nExplanation: Subarray having maximum \nsum is {2, 4} or {6}." }, { "code": null, "e": 980, "s": 660, "text": "Your Task:\nThis is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function calculateMaxSumLength() that takes array arr, integer N, and integer X as parameters and returns maximum sum of any subarray that is less than or equal to x." }, { "code": null, "e": 1047, "s": 982, "text": "Expected Time Complexity: O(N). \nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1074, "s": 1049, "text": "Constraints:\n1 ≤ N ≤ 106" }, { "code": null, "e": 1076, "s": 1074, "text": "0" }, { "code": null, "e": 1100, "s": 1076, "text": "bharshit4682 months ago" }, { "code": null, "e": 1125, "s": 1100, "text": "Easy to Understand | cpp" }, { "code": null, "e": 1141, "s": 1125, "text": "class Solution{" }, { "code": null, "e": 1650, "s": 1141, "text": "public:int findMaxSubarraySum(long long arr[], int n, long long k){ int i = 0 , j = 0 , maxSum = 0 , sum = 0 ; while(j < n) { sum +=arr[j]; if(sum <= k) maxSum = max(maxSum , sum); else if(sum > k) { while(sum > k) { sum -=arr[i]; i++; } if(sum <= k) maxSum = max(maxSum , sum); } j++; } return maxSum;} " }, { "code": null, "e": 1656, "s": 1652, "text": "}; " }, { "code": null, "e": 1660, "s": 1658, "text": "0" }, { "code": null, "e": 1681, "s": 1660, "text": "kake13373 months ago" }, { "code": null, "e": 2065, "s": 1681, "text": " /*Its O(N) why?\n because every element gets add at most one time and gets removed from \"s\" at most one time, So the time complexity will be O(2N) which is linear!*/\n \n int i=0;\n long long s=0,r=0;\n for(int j=0;j<n;j++)\n {\n s+=arr[j];\n while(s>sum)\n {\n s-=arr[i];\n i++;\n }\n r=max(r,s);\n }\n return r;" }, { "code": null, "e": 2068, "s": 2065, "text": "+1" }, { "code": null, "e": 2096, "s": 2068, "text": "shyamprakash8073 months ago" }, { "code": null, "e": 2122, "s": 2096, "text": "time complexity : 0.4/5.1" }, { "code": null, "e": 2168, "s": 2122, "text": "Pyhton solution using Sliding window Approach" }, { "code": null, "e": 2643, "s": 2168, "text": "class Solution: def findMaxSubarraySum(self, arr, n, k): # Your code goes here sum = 0 ans = 0 i, j = 0, 0 while j < n: sum += arr[j] if sum < k: ans = max(ans, sum) j += 1 elif sum == k: return k else: while sum > k: sum -= arr[i] i += 1 ans = max(ans, sum) j += 1 return ans" }, { "code": null, "e": 2646, "s": 2643, "text": "+2" }, { "code": null, "e": 2676, "s": 2646, "text": "krishnarajput10274 months ago" }, { "code": null, "e": 2940, "s": 2676, "text": "int findMaxSubarraySum(long long arr[], int n, long long sum){ int j=0; int ans=INT_MIN; int s=0; for(int i=0;i<n;i++){ s+=arr[i]; while(s>sum){ s-=arr[j]; j++; } ans=max(s,ans); } return ans;} " }, { "code": null, "e": 2942, "s": 2940, "text": "0" }, { "code": null, "e": 2968, "s": 2942, "text": "shubodeepbera7 months ago" }, { "code": null, "e": 3169, "s": 2968, "text": " int i=0,j=0,curr_sum=0; int ans=INT_MIN; while(i<n){ curr_sum+=arr[i]; i++; while(curr_sum>sum){ curr_sum-=arr[j]; j++; } ans=max(ans,curr_sum); } return ans;" }, { "code": null, "e": 3171, "s": 3169, "text": "0" }, { "code": null, "e": 3189, "s": 3171, "text": "delectable_boomer" }, { "code": null, "e": 3215, "s": 3189, "text": "This comment was deleted." }, { "code": null, "e": 3218, "s": 3215, "text": "+1" }, { "code": null, "e": 3242, "s": 3218, "text": "Zilen Modi10 months ago" }, { "code": null, "e": 3253, "s": 3242, "text": "Zilen Modi" }, { "code": null, "e": 3287, "s": 3253, "text": "Consider this test case:3-1 7 117" }, { "code": null, "e": 3357, "s": 3287, "text": "right maximum sum=>7but, sliding Window giving =>6Add this test case." }, { "code": null, "e": 3359, "s": 3357, "text": "0" }, { "code": null, "e": 3383, "s": 3359, "text": "Om Prakash10 months ago" }, { "code": null, "e": 3394, "s": 3383, "text": "Om Prakash" }, { "code": null, "e": 3445, "s": 3394, "text": "I thing Something is wrong with JAVA's Driver Code" }, { "code": null, "e": 3447, "s": 3445, "text": "0" }, { "code": null, "e": 3472, "s": 3447, "text": "Imran Wahid10 months ago" }, { "code": null, "e": 3484, "s": 3472, "text": "Imran Wahid" }, { "code": null, "e": 3555, "s": 3484, "text": "Easy C++ solution in O(n) TC and O(1) SChttps://ide.geeksforgeeks.o..." }, { "code": null, "e": 3557, "s": 3555, "text": "0" }, { "code": null, "e": 3583, "s": 3557, "text": "Aniket patel11 months ago" }, { "code": null, "e": 3596, "s": 3583, "text": "Aniket patel" }, { "code": null, "e": 4179, "s": 3596, "text": "class Solution{public:int findMaxSubarraySum(long long arr[], int n, long long sum){ int l=0,r=0; long long curr=arr[0],max=INT_MIN; while(r<n) {=\"\" if(max<curr=\"\" and=\"\" curr<sum)=\"\" max=\"curr;\" if(curr=\"\">sum) { curr-=arr[l]; l++; } else if(curr<sum) {=\"\" if(r!=\"n-1)\" {=\"\" r++;=\"\" curr+=\"arr[r];\" }=\"\" else=\"\" break;=\"\" }=\"\" else=\"\" (sum=\"=x)\" return=\"\" sum;=\"\" }=\"\" return=\"\" max;=\"\" }=\"\" };=\"\" https:=\"\" practice.geeksforgeeks.org=\"\" viewsol.php?subid=\"b36a06fad1b7f8ad91b5f81380720484&amp;pid=703423&amp;user=aniket66patel\">" }, { "code": null, "e": 4325, "s": 4179, "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": 4361, "s": 4325, "text": " Login to access your submissions. " }, { "code": null, "e": 4371, "s": 4361, "text": "\nProblem\n" }, { "code": null, "e": 4381, "s": 4371, "text": "\nContest\n" }, { "code": null, "e": 4444, "s": 4381, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4592, "s": 4444, "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": 4800, "s": 4592, "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": 4906, "s": 4800, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Combining multiple images into a single one using JavaScript
Following is the code for combining multiple images into a single one using JavaScript − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } </style> </head> <body> <h1>Combining multiple images into a single one</h1> <img class="image" src="https://i.picsum.photos/id/845/250/250.jpg?hmac=2l7QArh4UKul2qF-JvTjaBu3-WF2KpKBgpBALmFoxWY"/> <img class="image" src="https://i.picsum.photos/id/925/250/250.jpg?hmac=twWJdaKT46cPk1aNvB7aKdiLZoQ zvzu5VW85OEUO4ys"/> <canvas class="result"></canvas> <br /> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to combine the two images above together</h3> <script> let imgEle1 = document.querySelectorAll(".image")[0]; let imgEle2 = document.querySelectorAll(".image")[1]; let resEle = document.querySelector(".result"); var context = resEle.getContext("2d"); let BtnEle = document.querySelector(".Btn"); BtnEle.addEventListener("click", () => { resEle.width = imgEle1.width; resEle.height = imgEle1.height; context.globalAlpha = 1.0; context.drawImage(imgEle1, 0, 0); context.globalAlpha = 0.5; context.drawImage(imgEle2, 0, 0); }); </script> </body> </html> On clicking the ‘CLICK HERE’ button −
[ { "code": null, "e": 1151, "s": 1062, "text": "Following is the code for combining multiple images into a single one using JavaScript −" }, { "code": null, "e": 1162, "s": 1151, "text": " Live Demo" }, { "code": null, "e": 2445, "s": 1162, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n</style>\n</head>\n<body>\n<h1>Combining multiple images into a single one</h1>\n<img class=\"image\" src=\"https://i.picsum.photos/id/845/250/250.jpg?hmac=2l7QArh4UKul2qF-JvTjaBu3-WF2KpKBgpBALmFoxWY\"/>\n<img class=\"image\" src=\"https://i.picsum.photos/id/925/250/250.jpg?hmac=twWJdaKT46cPk1aNvB7aKdiLZoQ zvzu5VW85OEUO4ys\"/>\n<canvas class=\"result\"></canvas>\n<br />\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click on the above button to combine the two images above together</h3>\n<script>\n let imgEle1 = document.querySelectorAll(\".image\")[0];\n let imgEle2 = document.querySelectorAll(\".image\")[1];\n let resEle = document.querySelector(\".result\");\n var context = resEle.getContext(\"2d\");\n let BtnEle = document.querySelector(\".Btn\");\n BtnEle.addEventListener(\"click\", () => {\n resEle.width = imgEle1.width;\n resEle.height = imgEle1.height;\n context.globalAlpha = 1.0;\n context.drawImage(imgEle1, 0, 0);\n context.globalAlpha = 0.5;\n context.drawImage(imgEle2, 0, 0);\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2483, "s": 2445, "text": "On clicking the ‘CLICK HERE’ button −" } ]
What is the significant difference between MySQL TRUNCATE() and ROUND() function?
The TRUNCATE() function is used to return the value of X truncated to D number of decimal places. If D is 0, then the decimal point is removed. If D is negative, then D number of values in the integer part of the value is truncated. Consider the following example – mysql> Select TRUNCATE(7.536432,2); +----------------------+ | TRUNCATE(7.536432,2) | +----------------------+ | 7.53 | +----------------------+ 1 row in set (0.00 sec) The ROUND() function returns X rounded to the nearest integer. If a second argument, D, is supplied, then the function returns X rounded to D decimal places. D must be positive or all digits to the right of the decimal point will be removed. Consider the following example − mysql>SELECT ROUND(5.693893); +---------------------------------------------------------+ | ROUND(5.693893) | +---------------------------------------------------------+ | 6 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql>SELECT ROUND(5.693893,2); +---------------------------------------------------------+ | ROUND(5.693893,2) | +---------------------------------------------------------+ | 5.69 | +---------------------------------------------------------+ 1 row in set (0.00 sec) From the above definition and examples we can observe the following difference between these two functions − ROUND() function rounds the number up or down depends upon the second argument D and the number itself(digit after D decimal places >=5 or not). TRUNCATE() function truncate the number up to D number of decimal places without checking whether the digit after D decimal >=5 or not. mysql> Select ROUND(1.289,2)AS 'AFTER ROUND',TRUNCATE(1.289,2)AS 'AFTER TRUNCATE'; +-------------+----------------+ | AFTER ROUND | AFTER TRUNCATE | +-------------+----------------+ | 1.29 | 1.28 | +-------------+----------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1328, "s": 1062, "text": "The TRUNCATE() function is used to return the value of X truncated to D number of decimal places. If D is 0, then the decimal point is removed. If D is negative, then D number of values in the integer part of the value is truncated. Consider the following example –" }, { "code": null, "e": 1513, "s": 1328, "text": "mysql> Select TRUNCATE(7.536432,2);\n+----------------------+\n| TRUNCATE(7.536432,2) |\n+----------------------+\n| 7.53 |\n+----------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 1790, "s": 1513, "text": "The ROUND() function returns X rounded to the nearest integer. If a second argument, D, is supplied, then the function returns X rounded to D decimal places. D must be positive or all digits to the right of the decimal point will be removed. Consider the following example − " }, { "code": null, "e": 2505, "s": 1790, "text": "mysql>SELECT ROUND(5.693893);\n+---------------------------------------------------------+\n| ROUND(5.693893) |\n+---------------------------------------------------------+\n| 6 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec) \n\nmysql>SELECT ROUND(5.693893,2);\n+---------------------------------------------------------+\n| ROUND(5.693893,2) |\n+---------------------------------------------------------+\n| 5.69 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec) " }, { "code": null, "e": 2614, "s": 2505, "text": "From the above definition and examples we can observe the following difference between these two functions −" }, { "code": null, "e": 2761, "s": 2614, "text": "ROUND() function rounds the number up or down depends upon the second argument D and the number itself(digit after D decimal places >=5 or not). " }, { "code": null, "e": 2899, "s": 2761, "text": "TRUNCATE() function truncate the number up to D number of decimal places without checking whether the digit after D decimal >=5 or not. " }, { "code": null, "e": 3171, "s": 2899, "text": "mysql> Select ROUND(1.289,2)AS 'AFTER ROUND',TRUNCATE(1.289,2)AS 'AFTER TRUNCATE';\n+-------------+----------------+\n| AFTER ROUND | AFTER TRUNCATE |\n+-------------+----------------+\n| 1.29 | 1.28 |\n+-------------+----------------+\n1 row in set (0.00 sec)" } ]
Yolov5 Object Detection on NVIDIA Jetson Nano | by Amirhossein Heydarian | Towards Data Science
This article represents JetsonYolo which is a simple and easy process for CSI camera installation, software, and hardware setup, and object detection using Yolov5 and openCV on NVIDIA Jetson Nano. This project uses CSI-Camera to create a pipeline and capture frames, and Yolov5 to detect objects, implementing a complete and executable code on Jetson Development Kits. Check out the CodePlay jetson nano youtube playlist for video instructions and JetsonYolo Github. One of the most common cameras used with the Jetson Nano is the Raspberry Pi Camera Module V2, but what if you need a higher resolution? Recently I tried to use the Waveshare IMX477 CSI camera for a project but had trouble connecting it to the board. Finally, after trying several different methods, I came up with a simple process and decided to share it with others. This article consists of several parts including, hardware, driver, and python libraries installation, and finally, the Yolov5. These steps are all essential for object detection using the camera on the Jetson Nano board. Install the camera in the MIPI-CSI Camera Connector on the carrier board. Pull up the plastic edges of the camera port. Push in the camera ribbon and make sure that the pins on the camera ribbon face the Jetson Nano module. Push the plastic connector down. You can use the Arducam camera setup guide for more info. By default, NVIDIA JetPack supports several cameras with different sensors, one of the most famous of which is the Raspberry Pi camera v2. But if you are using another camera type, you need to install a sensor driver. A 12.3 MP camera with an IMX477–160 sensor is used in this project, requiring an additional driver to connect. Arducam provides an IMX477 driver with easy insulation for cameras with an IMX477 sensor. (Make sure to check the website and use the latest commands.) Download automatic installation script: cd ~wget https://github.com/ArduCAM/MIPI_Camera/releases/download/v0.0.3/install_full.sh Install the driver: chmod +x install_full.sh./install_full.sh -m imx477 And finally, enter y to reboot the board. Use the following command to check if the camera is recognized correctly. ls /dev/video0 You can use the JetsonHacks python code to capture frames from the camera using OpenCV. Yolov5 model is implemented in the Pytorch framework. PyTorch is an open-source machine learning library based on the Torch library, used for computer vision and natural language processing applications. Here is a complete guide for installing PyTorch & torchvision on Jetson Development Kits. Clone JetsonYolo repository on Jetson nano. git clone https://github.com/amirhosseinh77/JetsonYolo.git Select the desired model based on model size, required speed, and accuracy. You can find available models here in the Assets section. Download the model using the command below and move it to the weights folder. cd weightswget https://github.com/ultralytics/yolov5/releases/download/v5.0/yolov5s.pt Run JetsonYolo.py to detect objects with the camera. python3 JetsonYolo.py This article focuses on using an IMX477 camera to capture frames and perform object detection. Setting up this type of camera requires an additional driver installation step, and Arducam has provided a driver for Jetson Linux Driver (L4T). After installing the necessary drivers and Python libraries, the Yolov5 is implemented on the Jetson Nano as JetsonYolo and achieves satisfactory results with 12 frames per second.
[ { "code": null, "e": 639, "s": 172, "text": "This article represents JetsonYolo which is a simple and easy process for CSI camera installation, software, and hardware setup, and object detection using Yolov5 and openCV on NVIDIA Jetson Nano. This project uses CSI-Camera to create a pipeline and capture frames, and Yolov5 to detect objects, implementing a complete and executable code on Jetson Development Kits. Check out the CodePlay jetson nano youtube playlist for video instructions and JetsonYolo Github." }, { "code": null, "e": 1230, "s": 639, "text": "One of the most common cameras used with the Jetson Nano is the Raspberry Pi Camera Module V2, but what if you need a higher resolution? Recently I tried to use the Waveshare IMX477 CSI camera for a project but had trouble connecting it to the board. Finally, after trying several different methods, I came up with a simple process and decided to share it with others. This article consists of several parts including, hardware, driver, and python libraries installation, and finally, the Yolov5. These steps are all essential for object detection using the camera on the Jetson Nano board." }, { "code": null, "e": 1545, "s": 1230, "text": "Install the camera in the MIPI-CSI Camera Connector on the carrier board. Pull up the plastic edges of the camera port. Push in the camera ribbon and make sure that the pins on the camera ribbon face the Jetson Nano module. Push the plastic connector down. You can use the Arducam camera setup guide for more info." }, { "code": null, "e": 2026, "s": 1545, "text": "By default, NVIDIA JetPack supports several cameras with different sensors, one of the most famous of which is the Raspberry Pi camera v2. But if you are using another camera type, you need to install a sensor driver. A 12.3 MP camera with an IMX477–160 sensor is used in this project, requiring an additional driver to connect. Arducam provides an IMX477 driver with easy insulation for cameras with an IMX477 sensor. (Make sure to check the website and use the latest commands.)" }, { "code": null, "e": 2066, "s": 2026, "text": "Download automatic installation script:" }, { "code": null, "e": 2155, "s": 2066, "text": "cd ~wget https://github.com/ArduCAM/MIPI_Camera/releases/download/v0.0.3/install_full.sh" }, { "code": null, "e": 2175, "s": 2155, "text": "Install the driver:" }, { "code": null, "e": 2227, "s": 2175, "text": "chmod +x install_full.sh./install_full.sh -m imx477" }, { "code": null, "e": 2269, "s": 2227, "text": "And finally, enter y to reboot the board." }, { "code": null, "e": 2343, "s": 2269, "text": "Use the following command to check if the camera is recognized correctly." }, { "code": null, "e": 2358, "s": 2343, "text": "ls /dev/video0" }, { "code": null, "e": 2446, "s": 2358, "text": "You can use the JetsonHacks python code to capture frames from the camera using OpenCV." }, { "code": null, "e": 2740, "s": 2446, "text": "Yolov5 model is implemented in the Pytorch framework. PyTorch is an open-source machine learning library based on the Torch library, used for computer vision and natural language processing applications. Here is a complete guide for installing PyTorch & torchvision on Jetson Development Kits." }, { "code": null, "e": 2784, "s": 2740, "text": "Clone JetsonYolo repository on Jetson nano." }, { "code": null, "e": 2843, "s": 2784, "text": "git clone https://github.com/amirhosseinh77/JetsonYolo.git" }, { "code": null, "e": 3055, "s": 2843, "text": "Select the desired model based on model size, required speed, and accuracy. You can find available models here in the Assets section. Download the model using the command below and move it to the weights folder." }, { "code": null, "e": 3142, "s": 3055, "text": "cd weightswget https://github.com/ultralytics/yolov5/releases/download/v5.0/yolov5s.pt" }, { "code": null, "e": 3195, "s": 3142, "text": "Run JetsonYolo.py to detect objects with the camera." }, { "code": null, "e": 3217, "s": 3195, "text": "python3 JetsonYolo.py" } ]
Intro to probabilistic programming | by Fabiana Clemente | Towards Data Science
The idea behind Probabilistic programming to bring the inference algorithms and theory from statistics combined with formal semantics, compilers, and other tools from programming languages to build efficient inference evaluators for models and applications from Machine Learning. In other words, probabilistic programming is a tool for statistical modeling. The idea is to borrow lessons from the world of programming languages and apply them to the problems of designing and using statistical models. Probabilistic programming is about doing statistics using the tools of computer science. In the above figure you can see a typical computer science programming pipeline: Write a program, specify the values of its arguments then evaluate the program to produce an output. The right-hand side illustrates the approach taken to modeling in statistics: Start with the output, the observations or data Y, then specify an abstract generative model p(X,Y), often denoted mathematically, and finally use algebra and inference techniques to characterize the posterior distribution, p(X | Y ), of the unknown quantities in the model given the observed quantities. Whereas in Probabilistic programming: a programming language for model definitions and statistical inference algorithms for computing the conditional distribution of the program inputs that could have given rise to the observed program output. Note: Probabilistic programming is not about writing software that behaves probabilistically. To implement such Ensemble Architecture Tensorflow introduces Tensorflow-probability. TensorFlow Probability is a library for probabilistic reasoning and statistical analysis in TensorFlow. As part of the TensorFlow ecosystem, TensorFlow Probability provides integration of probabilistic methods with deep networks, gradient-based inference via automatic differentiation, and scalability to large datasets and models via hardware acceleration (e.g., GPUs) and distributed computation.Probabilistic Machine Learning tools in TensorFlow-probability are structured in different levels. In this blog, we’ll discuss Statistical building blocks and Model Building using TensorFlow-probability. Let’s start with importing necessary modules: A tfp.distributions.Distribution is a class with two core methods: sample and log_prob. This class contains many distributions which can be seen by writing: print_subclasses_from_module(tfp.distributions, tfp.distributions.Distribution) Let’s see how to sample a Normal Distribution which is a good starter in stat101 using tf-probability: # A standard normalnormal = tfd.Normal(loc=0., scale=1.) # mean=0, std=3samples = normal.sample(1000)sns.distplot(samples)plt.title("Samples from a standard Normal")plt.show()'''log of the probability density/mass function evaluated at the given sample value.'''print("log(PDF):",normal.log_prob(0.)) Now in order to calculate other statistical parameters like cumulative distribution function and multiple distributions we can still utilize tf-probabilities native classes. # Define a single scalar Normal distribution.dist = tfd.Normal(loc=0., scale=3.) # mean=0, std=3# Evaluate the cdf at 1, returning a scalar.dist.cdf(1.)# Define a batch of two scalar valued Normals.# The first has mean 1 and standard deviation 11, the second 2 and 22.dist = tfd.Normal(loc=[1, 2.], scale=[11, 22.])# Evaluate the pdf of the first distribution on 0, and the second on 1.5,# returning a length two tensor.dist.prob([0, 1.5])# Get 3 samples, returning a 3 x 2 tensor.dist.sample([3]) Using the above code you can calculate CDFs and Multiple Normal Distributions on-the-fly.While using statistical-tools in your project you might also require declaring Multivariate Distributions, tf-probability has got you covered here as well! mvn = tfd.MultivariateNormalDiag(loc=[0., 0.], scale_diag = [1., 1.])print("Batch shape:", mvn.batch_shape)print("Event shape:", mvn.event_shape)samples = mvn.sample(1000)print("Samples shape:", samples.shape)g = sns.jointplot(samples[:, 0], samples[:, 1], kind='scatter')plt.show() There are tons of distributions like these inside the tfp module, LogNormal, Logistic, LogitNormal Mixture, Multinomial, MultivariateNormalDiag, to name a few. Every distribution comes with a plethora of statistical inferences and functions. Bijectors represent invertible, smooth functions. They can be used to transform distributions, preserving the ability to take samples and compute log_probs. They can be accessed from the tfp.bijectors module. Each bijector implements at least 3 methods: forward inverse, and (at least) one of forward_log_det_jacobian and inverse_log_det_jacobian. With these ingredients, we can transform a distribution and still get samples and log probs from the result! print_subclasses_from_module(tfp.bijectors, tfp.bijectors.Bijector) Using the code snippet above we can list all the bijector functions available in tf-probability. Now let’s see how to declare a NormalCDF using bijectors and calculate the log of the determinant of the Jacobian in forward propagation. normal_cdf = tfp.bijectors.NormalCDF()xs = np.linspace(-4., 4., 200)plt.plot(xs, normal_cdf.forward(xs))plt.show()plt.plot(xs, normal_cdf.forward_log_det_jacobian(xs, event_ndims=0))plt.show() Bijectors are mainly used for transforming Distributions. Here’s a quick example where transformation is applied: # creates a Y=g(X)=exp(X) transformexp_bijector = tfp.bijectors.Exp()# declare a Normal Distribution and Transform itlog_normal = exp_bijector(tfd.Normal(0., .5))samples = log_normal.sample(1000)xs = np.linspace(1e-10, np.max(samples), 200)sns.distplot(samples, norm_hist=True, kde=False)plt.plot(xs, log_normal.prob(xs), c='k', alpha=.75)plt.show() After running the above snippet you’ll see a transformed distribution(bins in blue) and probability density estimation plot (curve in black) We successfully implemented the building blocks of statistical inference in Tensorflow-probability, now let’s see how we can use the same framework with tabular time-series data. TensorFlow-Probability (TFP) features built-in support for fitting and forecasting using structural time series models. This support includes the Bayesian inference of the model. Because they’re built-in TensorFlow, these methods naturally take advantage of vectorized hardware (GPUs and TPUs), can efficiently process many time series in parallel, and can be integrated with deep neural networks. Let’s solve a time-series problem using TensorFlow-probability: Now let’s define a time-series problem of Co2 concentration over the years (sampled by month): We’ll model this series with a local linear trend, plus a month-of-year seasonal effect, and fit the model using variational inference. This involves running an optimizer to minimize a variational loss function, the negative evidence lower bound (ELBO). This fits a set of approximate posterior distributions for the parameters (in practice we assume these to be independent Normals transformed to the support space of each parameter). The tfp.sts forecasting methods require posterior samples as inputs, so we'll finish by drawing a set of samples from the variational posterior. After running the above script you’ll see a plot like this: Now let’s use the fitted model to construct a forecast. We just call tfp.sts.forecast, which returns a TensorFlow Distribution instance representing the predictive distribution over future timesteps. In particular, the mean and stddev of the forecast distribution give us a prediction with marginal uncertainty at each timestep, and we can also draw samples of possible futures. Lets now visualize the forecast of the Co2 Concentration. We can observe here that the forecast made by our model turned out pretty good. It was able to capture seasonal changes and the overall trend of the time-series and able to predict the Co2 concentrations as it happened. Let’s now see the Trend and Seasonality of the Co2 concentration: As we already discussed how statistical inferences and tools can be easily implemented through TFP. In the above plot, we can identify trends and seasonality from the data just as efficiently as other core stats modules. Congratulations! we just learned about the use and importance of Probabilistic-programming and discussed statistical tools in TensorFlow-probability. Not to mention we just solved a structured time-series problem using models from Tensorflow-probability! Fabiana Clemente is Chief Data Officer at YData. Making data available with privacy by design. YData helps data science teams deliver ML models, simplifying data acquisition, so data scientists can focus their time on things that matter.
[ { "code": null, "e": 673, "s": 171, "text": "The idea behind Probabilistic programming to bring the inference algorithms and theory from statistics combined with formal semantics, compilers, and other tools from programming languages to build efficient inference evaluators for models and applications from Machine Learning. In other words, probabilistic programming is a tool for statistical modeling. The idea is to borrow lessons from the world of programming languages and apply them to the problems of designing and using statistical models." }, { "code": null, "e": 762, "s": 673, "text": "Probabilistic programming is about doing statistics using the tools of computer science." }, { "code": null, "e": 1571, "s": 762, "text": "In the above figure you can see a typical computer science programming pipeline: Write a program, specify the values of its arguments then evaluate the program to produce an output. The right-hand side illustrates the approach taken to modeling in statistics: Start with the output, the observations or data Y, then specify an abstract generative model p(X,Y), often denoted mathematically, and finally use algebra and inference techniques to characterize the posterior distribution, p(X | Y ), of the unknown quantities in the model given the observed quantities. Whereas in Probabilistic programming: a programming language for model definitions and statistical inference algorithms for computing the conditional distribution of the program inputs that could have given rise to the observed program output." }, { "code": null, "e": 1665, "s": 1571, "text": "Note: Probabilistic programming is not about writing software that behaves probabilistically." }, { "code": null, "e": 1751, "s": 1665, "text": "To implement such Ensemble Architecture Tensorflow introduces Tensorflow-probability." }, { "code": null, "e": 2353, "s": 1751, "text": "TensorFlow Probability is a library for probabilistic reasoning and statistical analysis in TensorFlow. As part of the TensorFlow ecosystem, TensorFlow Probability provides integration of probabilistic methods with deep networks, gradient-based inference via automatic differentiation, and scalability to large datasets and models via hardware acceleration (e.g., GPUs) and distributed computation.Probabilistic Machine Learning tools in TensorFlow-probability are structured in different levels. In this blog, we’ll discuss Statistical building blocks and Model Building using TensorFlow-probability." }, { "code": null, "e": 2399, "s": 2353, "text": "Let’s start with importing necessary modules:" }, { "code": null, "e": 2556, "s": 2399, "text": "A tfp.distributions.Distribution is a class with two core methods: sample and log_prob. This class contains many distributions which can be seen by writing:" }, { "code": null, "e": 2636, "s": 2556, "text": "print_subclasses_from_module(tfp.distributions, tfp.distributions.Distribution)" }, { "code": null, "e": 2739, "s": 2636, "text": "Let’s see how to sample a Normal Distribution which is a good starter in stat101 using tf-probability:" }, { "code": null, "e": 3040, "s": 2739, "text": "# A standard normalnormal = tfd.Normal(loc=0., scale=1.) # mean=0, std=3samples = normal.sample(1000)sns.distplot(samples)plt.title(\"Samples from a standard Normal\")plt.show()'''log of the probability density/mass function evaluated at the given sample value.'''print(\"log(PDF):\",normal.log_prob(0.))" }, { "code": null, "e": 3214, "s": 3040, "text": "Now in order to calculate other statistical parameters like cumulative distribution function and multiple distributions we can still utilize tf-probabilities native classes." }, { "code": null, "e": 3713, "s": 3214, "text": "# Define a single scalar Normal distribution.dist = tfd.Normal(loc=0., scale=3.) # mean=0, std=3# Evaluate the cdf at 1, returning a scalar.dist.cdf(1.)# Define a batch of two scalar valued Normals.# The first has mean 1 and standard deviation 11, the second 2 and 22.dist = tfd.Normal(loc=[1, 2.], scale=[11, 22.])# Evaluate the pdf of the first distribution on 0, and the second on 1.5,# returning a length two tensor.dist.prob([0, 1.5])# Get 3 samples, returning a 3 x 2 tensor.dist.sample([3])" }, { "code": null, "e": 3958, "s": 3713, "text": "Using the above code you can calculate CDFs and Multiple Normal Distributions on-the-fly.While using statistical-tools in your project you might also require declaring Multivariate Distributions, tf-probability has got you covered here as well!" }, { "code": null, "e": 4241, "s": 3958, "text": "mvn = tfd.MultivariateNormalDiag(loc=[0., 0.], scale_diag = [1., 1.])print(\"Batch shape:\", mvn.batch_shape)print(\"Event shape:\", mvn.event_shape)samples = mvn.sample(1000)print(\"Samples shape:\", samples.shape)g = sns.jointplot(samples[:, 0], samples[:, 1], kind='scatter')plt.show()" }, { "code": null, "e": 4483, "s": 4241, "text": "There are tons of distributions like these inside the tfp module, LogNormal, Logistic, LogitNormal Mixture, Multinomial, MultivariateNormalDiag, to name a few. Every distribution comes with a plethora of statistical inferences and functions." }, { "code": null, "e": 4692, "s": 4483, "text": "Bijectors represent invertible, smooth functions. They can be used to transform distributions, preserving the ability to take samples and compute log_probs. They can be accessed from the tfp.bijectors module." }, { "code": null, "e": 4737, "s": 4692, "text": "Each bijector implements at least 3 methods:" }, { "code": null, "e": 4745, "s": 4737, "text": "forward" }, { "code": null, "e": 4758, "s": 4745, "text": "inverse, and" }, { "code": null, "e": 4831, "s": 4758, "text": "(at least) one of forward_log_det_jacobian and inverse_log_det_jacobian." }, { "code": null, "e": 4940, "s": 4831, "text": "With these ingredients, we can transform a distribution and still get samples and log probs from the result!" }, { "code": null, "e": 5008, "s": 4940, "text": "print_subclasses_from_module(tfp.bijectors, tfp.bijectors.Bijector)" }, { "code": null, "e": 5105, "s": 5008, "text": "Using the code snippet above we can list all the bijector functions available in tf-probability." }, { "code": null, "e": 5243, "s": 5105, "text": "Now let’s see how to declare a NormalCDF using bijectors and calculate the log of the determinant of the Jacobian in forward propagation." }, { "code": null, "e": 5436, "s": 5243, "text": "normal_cdf = tfp.bijectors.NormalCDF()xs = np.linspace(-4., 4., 200)plt.plot(xs, normal_cdf.forward(xs))plt.show()plt.plot(xs, normal_cdf.forward_log_det_jacobian(xs, event_ndims=0))plt.show()" }, { "code": null, "e": 5550, "s": 5436, "text": "Bijectors are mainly used for transforming Distributions. Here’s a quick example where transformation is applied:" }, { "code": null, "e": 5900, "s": 5550, "text": "# creates a Y=g(X)=exp(X) transformexp_bijector = tfp.bijectors.Exp()# declare a Normal Distribution and Transform itlog_normal = exp_bijector(tfd.Normal(0., .5))samples = log_normal.sample(1000)xs = np.linspace(1e-10, np.max(samples), 200)sns.distplot(samples, norm_hist=True, kde=False)plt.plot(xs, log_normal.prob(xs), c='k', alpha=.75)plt.show()" }, { "code": null, "e": 6041, "s": 5900, "text": "After running the above snippet you’ll see a transformed distribution(bins in blue) and probability density estimation plot (curve in black)" }, { "code": null, "e": 6220, "s": 6041, "text": "We successfully implemented the building blocks of statistical inference in Tensorflow-probability, now let’s see how we can use the same framework with tabular time-series data." }, { "code": null, "e": 6618, "s": 6220, "text": "TensorFlow-Probability (TFP) features built-in support for fitting and forecasting using structural time series models. This support includes the Bayesian inference of the model. Because they’re built-in TensorFlow, these methods naturally take advantage of vectorized hardware (GPUs and TPUs), can efficiently process many time series in parallel, and can be integrated with deep neural networks." }, { "code": null, "e": 6682, "s": 6618, "text": "Let’s solve a time-series problem using TensorFlow-probability:" }, { "code": null, "e": 6777, "s": 6682, "text": "Now let’s define a time-series problem of Co2 concentration over the years (sampled by month):" }, { "code": null, "e": 7213, "s": 6777, "text": "We’ll model this series with a local linear trend, plus a month-of-year seasonal effect, and fit the model using variational inference. This involves running an optimizer to minimize a variational loss function, the negative evidence lower bound (ELBO). This fits a set of approximate posterior distributions for the parameters (in practice we assume these to be independent Normals transformed to the support space of each parameter)." }, { "code": null, "e": 7358, "s": 7213, "text": "The tfp.sts forecasting methods require posterior samples as inputs, so we'll finish by drawing a set of samples from the variational posterior." }, { "code": null, "e": 7418, "s": 7358, "text": "After running the above script you’ll see a plot like this:" }, { "code": null, "e": 7618, "s": 7418, "text": "Now let’s use the fitted model to construct a forecast. We just call tfp.sts.forecast, which returns a TensorFlow Distribution instance representing the predictive distribution over future timesteps." }, { "code": null, "e": 7797, "s": 7618, "text": "In particular, the mean and stddev of the forecast distribution give us a prediction with marginal uncertainty at each timestep, and we can also draw samples of possible futures." }, { "code": null, "e": 7855, "s": 7797, "text": "Lets now visualize the forecast of the Co2 Concentration." }, { "code": null, "e": 8075, "s": 7855, "text": "We can observe here that the forecast made by our model turned out pretty good. It was able to capture seasonal changes and the overall trend of the time-series and able to predict the Co2 concentrations as it happened." }, { "code": null, "e": 8141, "s": 8075, "text": "Let’s now see the Trend and Seasonality of the Co2 concentration:" }, { "code": null, "e": 8362, "s": 8141, "text": "As we already discussed how statistical inferences and tools can be easily implemented through TFP. In the above plot, we can identify trends and seasonality from the data just as efficiently as other core stats modules." }, { "code": null, "e": 8617, "s": 8362, "text": "Congratulations! we just learned about the use and importance of Probabilistic-programming and discussed statistical tools in TensorFlow-probability. Not to mention we just solved a structured time-series problem using models from Tensorflow-probability!" }, { "code": null, "e": 8666, "s": 8617, "text": "Fabiana Clemente is Chief Data Officer at YData." }, { "code": null, "e": 8712, "s": 8666, "text": "Making data available with privacy by design." } ]
How to calculate the difference between two dates in JavaScript?
To get dates in JavaScript, use the getTime() method. Forgetting the difference between two dates, calculate the difference between date and time. You can try to run the following code to learn how to calculate a difference between two dates − Live Demo <!DOCTYPE html> <html> <body> <script> var dateFirst = new Date("11/25/2017"); var dateSecond = new Date("11/28/2017"); // time difference var timeDiff = Math.abs(dateSecond.getTime() - dateFirst.getTime()); // days difference var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); // difference alert(diffDays); </script> </body> </html>
[ { "code": null, "e": 1209, "s": 1062, "text": "To get dates in JavaScript, use the getTime() method. Forgetting the difference between two dates, calculate the difference between date and time." }, { "code": null, "e": 1306, "s": 1209, "text": "You can try to run the following code to learn how to calculate a difference between two dates −" }, { "code": null, "e": 1316, "s": 1306, "text": "Live Demo" }, { "code": null, "e": 1750, "s": 1316, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n var dateFirst = new Date(\"11/25/2017\");\n var dateSecond = new Date(\"11/28/2017\");\n\n // time difference\n var timeDiff = Math.abs(dateSecond.getTime() - dateFirst.getTime());\n\n // days difference\n var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));\n\n // difference\n alert(diffDays);\n </script>\n </body>\n</html>" } ]
Persistently storing and retrieving data from R Shiny Apps | by Rahul Saxena | Towards Data Science
My last post intrigued quite a lot of people because of the novel and innovative nature of my last R Shiny app. This use case of Shiny was mostly unheard of, as primarily this is not what R Shiny was designed for. However, due to some personal and professional reasons, I decided to undertake the project of “Creating a centralized platform for my university exam resources” in R Shiny and here in this article, I’ll share the solution to the biggest hurdle you might face in file handling using R Shiny. Whenever you are dealing with persistent data storage in R Shiny apps, you are bound to come across articles by Dean Attali, especially this article. This article, covers a wide variety of possible scenarios for you. I, however, was left wanting for more, as it still did not align with my requirements. What I wanted was the functionality for users to upload any number of files and then for every other users to be able to download those files. When you work with R Shiny, you would across the functions fileInput() and the downloadHandler(). These functions can only help you to work with temporary files (files that will remain as long as the “session” is not changed). To persistently store the data, I tried exporting the “temporary” uploaded file to a “DropBox” profile with the help of “rdrop2”, but this process was painfully slow. Also since I was dealing with PDF files, connecting MongoDB servers or MySQL servers was not a viable option. This whole ordeal made one thing painfully clear for me. Remote storage could not be used for my project and local storage was the way to go. So, if you look into the available resources on the internet, the closest you’d come to accomplishing this is by following Dean’s example here. But, here again, he is simply using the function write.csv() and providing the local storage path name in the path parameter of the function. This still leaves us to figure out how do you “write” a PDF file to a specific location (www folder) in your local storage. I searched online for R packages that deal with PDFs and I came across the packages “pdftools” and “qpdf” . Since “qpdf” was a requirement of the “pdftools” package, I decided to only install the “pdftools” package. Unfortunately, this function too did not provide us the functionality to “write a PDF” onto a given file path. The functions “pdftools” provided are listed below. The functions provided by the “qpdf” package are as follows. Amongst these functions, what caught my eye was the function pdf_subset() , because it had a parameter called “output”. So, it could potentially mean to store a subset of a particular PDF file in the specified file path by means of the output parameter. The “pages” parameter was specified using the above mentioned pdf_info() function (pdf_info$pages to be more specific). And, VOILA!!! This little experiment of mine worked and I attained the functionality that I wanted to. Here’s a code snippet from my actual deployed app highlighting how I managed the upload part in my app. https://gist.github.com/hinduBale/5356a228372b3ec8fe08ea04c1802b71 output$upload_questionSet_button <- renderUI({ validate( need(input$display_name_ques != "", "Please enter the display name of the uploader") ) fileInput( inputId = "multi_sol_id", label = "Please upload the question set available with you :) (PDFs only)", multiple = TRUE, accept = c(".pdf"), buttonLabel = "Upload Papers") }) observeEvent(input$multi_sol_id, { fileName_set <- sprintf("www/%s/questionSet_%s_%s.pdf", input$sem_select_mul,input$exam_select_mul, input$display_name_ques) pages_set <- pdf_info(input$multi_sol_id$datapath)$pages pdf_subset(input$multi_sol_id$datapath, pages = 1:pages_set, output = fileName_set)}) Now, after the files were being uploaded successfully, I needed a way to actually be able to download resources from my local storage using R Shiny. For this too, I searched far and wide, read the official docs, but to no avail. After tinkering around with all available options and a voracious reading for relevant materials over the internet, I got a little hint from this Stack Overflow answer. Therefore, I used the file.copy() function and converted the “filename” and “content” parameters to function to accomplish my task. Here’s a code snippet from my actual deployed app that showcases how I handled the download part of my app. https://gist.github.com/hinduBale/eddf858962865f43f4ac152116dc84e3 output$download_single_qp_button <- renderUI({ downloadBttn( outputId = "qp_down_sin", label = "Download Question Paper :)", style = "float", color = "warning", size = "lg", no_outline = FALSE) }) output$qp_down_sin <- downloadHandler( filename <- function(){ search_ques_fileName <- sprintf("www/%s/%s", input$sem_select_solution, input$avail_paper) return (search_ques_fileName) }, content <- function(file) { file.copy(filename(), file) }, contentType = "application/pdf" ) So, we have actually been able to accomplish what we set out to do. It sure is euphoric when you solve a problem, isn’t it!! I seriously felt like punching my screen many times when I was solving this problem, hence I wrote this article so that it may save a precious life or at least a precious monitor 😜 One thing to note here, is that, at the point of writing, https://www.shinyapps.io/ does not provide the facility of a local storage (at least, not in their free tier). So, you’ll have to set up your own R server on the cloud service provider of your choice if you want to reap the benefits of local storage. You could also buy me a coffee to support my work. Thank You and Godspeed.
[ { "code": null, "e": 677, "s": 172, "text": "My last post intrigued quite a lot of people because of the novel and innovative nature of my last R Shiny app. This use case of Shiny was mostly unheard of, as primarily this is not what R Shiny was designed for. However, due to some personal and professional reasons, I decided to undertake the project of “Creating a centralized platform for my university exam resources” in R Shiny and here in this article, I’ll share the solution to the biggest hurdle you might face in file handling using R Shiny." }, { "code": null, "e": 981, "s": 677, "text": "Whenever you are dealing with persistent data storage in R Shiny apps, you are bound to come across articles by Dean Attali, especially this article. This article, covers a wide variety of possible scenarios for you. I, however, was left wanting for more, as it still did not align with my requirements." }, { "code": null, "e": 1124, "s": 981, "text": "What I wanted was the functionality for users to upload any number of files and then for every other users to be able to download those files." }, { "code": null, "e": 1628, "s": 1124, "text": "When you work with R Shiny, you would across the functions fileInput() and the downloadHandler(). These functions can only help you to work with temporary files (files that will remain as long as the “session” is not changed). To persistently store the data, I tried exporting the “temporary” uploaded file to a “DropBox” profile with the help of “rdrop2”, but this process was painfully slow. Also since I was dealing with PDF files, connecting MongoDB servers or MySQL servers was not a viable option." }, { "code": null, "e": 1770, "s": 1628, "text": "This whole ordeal made one thing painfully clear for me. Remote storage could not be used for my project and local storage was the way to go." }, { "code": null, "e": 2180, "s": 1770, "text": "So, if you look into the available resources on the internet, the closest you’d come to accomplishing this is by following Dean’s example here. But, here again, he is simply using the function write.csv() and providing the local storage path name in the path parameter of the function. This still leaves us to figure out how do you “write” a PDF file to a specific location (www folder) in your local storage." }, { "code": null, "e": 2559, "s": 2180, "text": "I searched online for R packages that deal with PDFs and I came across the packages “pdftools” and “qpdf” . Since “qpdf” was a requirement of the “pdftools” package, I decided to only install the “pdftools” package. Unfortunately, this function too did not provide us the functionality to “write a PDF” onto a given file path. The functions “pdftools” provided are listed below." }, { "code": null, "e": 2620, "s": 2559, "text": "The functions provided by the “qpdf” package are as follows." }, { "code": null, "e": 2994, "s": 2620, "text": "Amongst these functions, what caught my eye was the function pdf_subset() , because it had a parameter called “output”. So, it could potentially mean to store a subset of a particular PDF file in the specified file path by means of the output parameter. The “pages” parameter was specified using the above mentioned pdf_info() function (pdf_info$pages to be more specific)." }, { "code": null, "e": 3201, "s": 2994, "text": "And, VOILA!!! This little experiment of mine worked and I attained the functionality that I wanted to. Here’s a code snippet from my actual deployed app highlighting how I managed the upload part in my app." }, { "code": null, "e": 3268, "s": 3201, "text": "https://gist.github.com/hinduBale/5356a228372b3ec8fe08ea04c1802b71" }, { "code": null, "e": 4338, "s": 3268, "text": "output$upload_questionSet_button <- renderUI({ validate( need(input$display_name_ques != \"\", \"Please enter the display name of the uploader\") ) fileInput( inputId = \"multi_sol_id\", label = \"Please upload the question set available with you :) (PDFs only)\", multiple = TRUE, accept = c(\".pdf\"), buttonLabel = \"Upload Papers\") }) observeEvent(input$multi_sol_id, { fileName_set <- sprintf(\"www/%s/questionSet_%s_%s.pdf\", input$sem_select_mul,input$exam_select_mul, input$display_name_ques) pages_set <- pdf_info(input$multi_sol_id$datapath)$pages pdf_subset(input$multi_sol_id$datapath, pages = 1:pages_set, output = fileName_set)})" }, { "code": null, "e": 4868, "s": 4338, "text": "Now, after the files were being uploaded successfully, I needed a way to actually be able to download resources from my local storage using R Shiny. For this too, I searched far and wide, read the official docs, but to no avail. After tinkering around with all available options and a voracious reading for relevant materials over the internet, I got a little hint from this Stack Overflow answer. Therefore, I used the file.copy() function and converted the “filename” and “content” parameters to function to accomplish my task." }, { "code": null, "e": 4976, "s": 4868, "text": "Here’s a code snippet from my actual deployed app that showcases how I handled the download part of my app." }, { "code": null, "e": 5043, "s": 4976, "text": "https://gist.github.com/hinduBale/eddf858962865f43f4ac152116dc84e3" }, { "code": null, "e": 5683, "s": 5043, "text": "output$download_single_qp_button <- renderUI({ downloadBttn( outputId = \"qp_down_sin\", label = \"Download Question Paper :)\", style = \"float\", color = \"warning\", size = \"lg\", no_outline = FALSE) }) output$qp_down_sin <- downloadHandler( filename <- function(){ search_ques_fileName <- sprintf(\"www/%s/%s\", input$sem_select_solution, input$avail_paper) return (search_ques_fileName) }, content <- function(file) { file.copy(filename(), file) }, contentType = \"application/pdf\" )" }, { "code": null, "e": 5808, "s": 5683, "text": "So, we have actually been able to accomplish what we set out to do. It sure is euphoric when you solve a problem, isn’t it!!" }, { "code": null, "e": 5989, "s": 5808, "text": "I seriously felt like punching my screen many times when I was solving this problem, hence I wrote this article so that it may save a precious life or at least a precious monitor 😜" }, { "code": null, "e": 6298, "s": 5989, "text": "One thing to note here, is that, at the point of writing, https://www.shinyapps.io/ does not provide the facility of a local storage (at least, not in their free tier). So, you’ll have to set up your own R server on the cloud service provider of your choice if you want to reap the benefits of local storage." }, { "code": null, "e": 6349, "s": 6298, "text": "You could also buy me a coffee to support my work." } ]
Finding the multiples of a number in a given list using NumPy
In this program, we will find the index position at which a multiple of a given number exists. We will use both the Numpy and the Pandas library for this task. Step 1: Define a Pandas series. Step 2: Input a number n from the user. Step 3: Find the multiples of that number from the series using argwhere() function in the numpy library. import numpy as np listnum = np.arange(1,20) multiples = [] print("NumList:\n",listnum) n = int(input("Enter the number you want to find multiples of: ")) for num in listnum: if num % n == 0: multiples.append(num) print("Multiples of {} are {}".format(n, multiples)) NumList: [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] Enter the number you want to find multiples of: 5 Multiples of 5 are [5, 10, 15]
[ { "code": null, "e": 1222, "s": 1062, "text": "In this program, we will find the index position at which a multiple of a given number exists. We will use both the Numpy and the Pandas library for this task." }, { "code": null, "e": 1400, "s": 1222, "text": "Step 1: Define a Pandas series.\nStep 2: Input a number n from the user.\nStep 3: Find the multiples of that number from the series using argwhere() function in the numpy library." }, { "code": null, "e": 1678, "s": 1400, "text": "import numpy as np\n\nlistnum = np.arange(1,20)\nmultiples = []\n\nprint(\"NumList:\\n\",listnum)\nn = int(input(\"Enter the number you want to find multiples of: \"))\nfor num in listnum:\n if num % n == 0:\n multiples.append(num)\nprint(\"Multiples of {} are {}\".format(n, multiples))" }, { "code": null, "e": 1826, "s": 1678, "text": "NumList:\n[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]\nEnter the number you want to find multiples of: 5\nMultiples of 5 are [5, 10, 15]" } ]
Minimum cost required to connect all houses in a city
07 Jun, 2022 Given a 2D array houses[][] consisting of N 2D coordinates {x, y} where each coordinate represents the location of each house, the task is to find the minimum cost to connect all the houses of the city. Cost of connecting two houses is the Manhattan Distance between the two points (xi, yi) and (xj, yj) i.e., |xi – xj| + |yi – yj|, where |p| denotes the absolute value of p. Examples: Input: houses[][] = [[0, 0], [2, 2], [3, 10], [5, 2], [7, 0]]Output: 20Explanation: Connect house 1 (0, 0) with house 2 (2, 2) with cost = 4Connect house 2 (2, 2) with house 3 (3, 10) with cost =9 Connect house 2 (2, 2) with house 4 (5, 2) with cost =3 At last, connect house 4 (5, 2) with house 5 (7, 0) with cost 4.All the houses are connected now.The overall minimum cost is 4 + 9 + 3 + 4 = 20. Input: houses[][] = [[3, 12], [-2, 5], [-4, 1]]Output: 18Explanation:Connect house 1 (3, 12) with house 2 (-2, 5) with cost = 12Connect house 2 (-2, 5) with house 3 (-4, 1) with cost = 6All the houses are connected now.The overall minimum cost is 12 + 6 = 18. Approach: The idea is to create a weighted graph from the given information with weights between any pair of edges equal to the cost of connecting them, say Ci i.e., the Manhattan distance between the two coordinates. Once the graph is generated, apply Kruskal’s Algorithm to find the Minimum Spanning Tree of the graph using Disjoint Set. Finally, print the minimum cost. Below is the implementation of the above approach: C++ Java Python3 Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; vector<int> parent, size; // Utility function to find set of an// element v using path compression// techniqueint find_set(int v){ // If v is the parent if (v == parent[v]) return v; // Otherwise, recursively // find its parent return parent[v] = find_set(parent[v]);} // Function to perform union// of the sets a and bint union_sets(int a, int b){ // Find parent of a and b a = find_set(a); b = find_set(b); // If parent are different if (a != b) { // Swap Operation if (size[a] < size[b]) swap(a, b); // Update parent of b as a parent[b] = a; size[a] += size[b]; return 1; } // Otherwise, return 0 return 0;} // Function to create a Minimum Cost// Spanning tree for given housesvoid MST(int houses[][2], int n){ // Stores adjacency list of graph vector<pair<int, pair<int, int> > > v; // Traverse each coordinate for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // Find the Manhattan distance int p = abs(houses[i][0] - houses[j][0]); p += abs(houses[i][1] - houses[j][1]); // Add the edges v.push_back({ p, { i, j } }); } } parent.resize(n); size.resize(n); // Sort all the edges sort(v.begin(), v.end()); // Initialize parent[] and size[] for (int i = 0; i < n; i++) { parent[i] = i, size[i] = 1; } /// Stores the minimum cost int ans = 0; // Finding the minimum cost for (auto x : v) { // Perform the unioun operation if (union_sets(x.second.first, x.second.second)) { ans += x.first; } } // Print the minimum cost cout << ans;} // Driver Codeint main(){ // Given houses int houses[][2] = { { 0, 0 }, { 2, 2 }, { 3, 10 }, { 5, 2 }, { 7, 0 }}; int N = sizeof(houses) / sizeof(houses[0]); // Function Call MST(houses, N); return 0;} // Java program for the above approachimport java.util.*; // Class for DSU implementationclass DSU{ int parent[];int rank[]; // Constructor to initialize DSUDSU(int n){ parent = new int[n]; rank = new int[n]; for(int i = 0; i < n; i++) { parent[i] = -1; rank[i] = 1; }} // Utility function to find set of an// element v using path compression// techniqueint find_set(int v){ // If v is the parent if (parent[v] == -1) return v; // Otherwise, recursively // find its parent return parent[v] = find_set(parent[v]);} // Function to perform union// of the sets a and bvoid union_sets(int a, int b){ // Find parent of a and b int p1 = find_set(a); int p2 = find_set(b); // If parent are different if (p1 != p2) { // Swap Operation if (rank[p1] > rank[p2]) { parent[p2] = p1; rank[p1] += rank[p2]; } else { parent[p1] = p2; rank[p2] += rank[p1]; } }}} class GFG{ // Function to create a Minimum Cost// Spanning tree for given housesstatic void MST(int houses[][], int n){ int ans = 0; ArrayList<int[]> edges = new ArrayList<>(); // Traverse each coordinate for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { // Find the Manhattan distance int p = Math.abs(houses[i][0] - houses[j][0]); p += Math.abs(houses[i][1] - houses[j][1]); // Add the edges edges.add(new int[]{ p, i, j }); } } // Sorting arraylist using custome comparator // on the basis of weight i.e first element in // array object stored in Arraylist Collections.sort(edges, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return Integer.compare(o1[0], o2[0]); } }); // Calling DSU class DSU d = new DSU(n); for(int i = 0; i < edges.size(); i++) { int from = edges.get(i)[1]; int to = edges.get(i)[2]; // Checking if they lie in different component // or not i.e they have same parent or not in // DSU if (d.find_set(from) != d.find_set(to)) { // Calling union_sets d.union_sets(from, to); ans += edges.get(i)[0]; } } // Printing the minimum cost System.out.println(ans);} // Driver codepublic static void main(String args[]){ // Graph in form of 2D array int houses[][] = { { 0, 0 }, { 2, 2 }, { 3, 10 }, { 5, 2 }, { 7, 0 } }; int n = houses.length; // Function Call MST(houses, n);}} // This code is contributed by Rahul Verma # Python3 program for the above approachparent = [0] * 100size = [0] * 100 # Utility function to find set of an# element v using path compression# techniquedef find_set(v): # If v is the parent if (v == parent[v]): return v # Otherwise, recursively # find its parent parent[v] = find_set(parent[v]) return parent[v] # Function to perform union# of the sets a and bdef union_sets(a, b): # Find parent of a and b a = find_set(a) b = find_set(b) # If parent are different if (a != b): # Swap Operation if (size[a] < size[b]): a, b = b, a # Update parent of b as a parent[b] = a size[a] += size[b] return 1 # Otherwise, return 0 return 0 # Function to create a Minimum Cost# Spanning tree for given housesdef MST(houses, n): # Stores adjacency list of graph v = [] # Traverse each coordinate for i in range(n): for j in range(i + 1, n): # Find the Manhattan distance p = abs(houses[i][0] - houses[j][0]) p += abs(houses[i][1] - houses[j][1]) # Add the edges v.append([p, i, j]) # Sort all the edges v = sorted(v) # Initialize parent[] and size[] for i in range(n): parent[i] = i size[i] = 1 # Stores the minimum cost ans = 0 # Finding the minimum cost for x in v: # Perform the unioun operation if (union_sets(x[1], x[2])): ans += x[0] # Print the minimum cost print(ans) # Driver Codeif __name__ == '__main__': # Given houses houses = [ [ 0, 0 ], [ 2, 2 ], [ 3, 10 ], [ 5, 2 ], [ 7, 0 ] ] N = len(houses) # Function Call MST(houses, N) # This code is contributed by mohit kumar 29 <script> // JavaScript program for the above approachlet parent = new Array(100).fill(0)let size = new Array(100).fill(0) // Utility function to find set of an// element v using path compression// techniquefunction find_set(v){ // If v is the parent if (v == parent[v]) return v // Otherwise, recursively // find its parent parent[v] = find_set(parent[v]) return parent[v]} // Function to perform union// of the sets a and bfunction union_sets(a, b){ // Find parent of a and b a = find_set(a) b = find_set(b) // If parent are different if (a != b){ // Swap Operation if (size[a] < size[b]){ a, b = b, a } // Update parent of b as a parent[b] = a size[a] += size[b] return 1 } // Otherwise, return 0 return 0} // Function to create a Minimum Cost// Spanning tree for given housesfunction MST(houses, n){ // Stores adjacency list of graph let v = [] // Traverse each coordinate for(let i=0;i<n;i++){ for(let j=i+1;j<n;j++){ // Find the Manhattan distance let p = Math.abs(houses[i][0] - houses[j][0]) p += Math.abs(houses[i][1] - houses[j][1]) // Add the edges v.push([p, i, j]) } } // Sort all the edges v.sort((a,b)=>a[0]-b[0]) // Initialize parent[] and size[] for(let i=0;i<n;i++){ parent[i] = i size[i] = 1 } // Stores the minimum cost let ans = 0 // Finding the minimum cost for(let x of v){ // Perform the unioun operation if (union_sets(x[1], x[2])) ans += x[0] } // Print the minimum cost document.write(ans,"</br>")} // Driver Code // Given houseslet houses = [ [ 0, 0 ], [ 2, 2 ], [ 3, 10 ], [ 5, 2 ],[ 7, 0 ] ] let N = houses.length // Function CallMST(houses, N) // This code is contributed by shinjanpatra </script> 20 Time Complexity: O(N2)Auxiliary Space: O(N2) mohit kumar 29 rv60231023 surinderdawra388 simmytarika5 shinjanpatra Kruskal'sAlgorithm Minimum Spanning Tree MST Arrays Graph Greedy Sorting Arrays Greedy Sorting Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jun, 2022" }, { "code": null, "e": 257, "s": 54, "text": "Given a 2D array houses[][] consisting of N 2D coordinates {x, y} where each coordinate represents the location of each house, the task is to find the minimum cost to connect all the houses of the city." }, { "code": null, "e": 430, "s": 257, "text": "Cost of connecting two houses is the Manhattan Distance between the two points (xi, yi) and (xj, yj) i.e., |xi – xj| + |yi – yj|, where |p| denotes the absolute value of p." }, { "code": null, "e": 440, "s": 430, "text": "Examples:" }, { "code": null, "e": 524, "s": 440, "text": "Input: houses[][] = [[0, 0], [2, 2], [3, 10], [5, 2], [7, 0]]Output: 20Explanation:" }, { "code": null, "e": 838, "s": 524, "text": "Connect house 1 (0, 0) with house 2 (2, 2) with cost = 4Connect house 2 (2, 2) with house 3 (3, 10) with cost =9 Connect house 2 (2, 2) with house 4 (5, 2) with cost =3 At last, connect house 4 (5, 2) with house 5 (7, 0) with cost 4.All the houses are connected now.The overall minimum cost is 4 + 9 + 3 + 4 = 20." }, { "code": null, "e": 1098, "s": 838, "text": "Input: houses[][] = [[3, 12], [-2, 5], [-4, 1]]Output: 18Explanation:Connect house 1 (3, 12) with house 2 (-2, 5) with cost = 12Connect house 2 (-2, 5) with house 3 (-4, 1) with cost = 6All the houses are connected now.The overall minimum cost is 12 + 6 = 18." }, { "code": null, "e": 1471, "s": 1098, "text": "Approach: The idea is to create a weighted graph from the given information with weights between any pair of edges equal to the cost of connecting them, say Ci i.e., the Manhattan distance between the two coordinates. Once the graph is generated, apply Kruskal’s Algorithm to find the Minimum Spanning Tree of the graph using Disjoint Set. Finally, print the minimum cost." }, { "code": null, "e": 1522, "s": 1471, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1526, "s": 1522, "text": "C++" }, { "code": null, "e": 1531, "s": 1526, "text": "Java" }, { "code": null, "e": 1539, "s": 1531, "text": "Python3" }, { "code": null, "e": 1550, "s": 1539, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; vector<int> parent, size; // Utility function to find set of an// element v using path compression// techniqueint find_set(int v){ // If v is the parent if (v == parent[v]) return v; // Otherwise, recursively // find its parent return parent[v] = find_set(parent[v]);} // Function to perform union// of the sets a and bint union_sets(int a, int b){ // Find parent of a and b a = find_set(a); b = find_set(b); // If parent are different if (a != b) { // Swap Operation if (size[a] < size[b]) swap(a, b); // Update parent of b as a parent[b] = a; size[a] += size[b]; return 1; } // Otherwise, return 0 return 0;} // Function to create a Minimum Cost// Spanning tree for given housesvoid MST(int houses[][2], int n){ // Stores adjacency list of graph vector<pair<int, pair<int, int> > > v; // Traverse each coordinate for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // Find the Manhattan distance int p = abs(houses[i][0] - houses[j][0]); p += abs(houses[i][1] - houses[j][1]); // Add the edges v.push_back({ p, { i, j } }); } } parent.resize(n); size.resize(n); // Sort all the edges sort(v.begin(), v.end()); // Initialize parent[] and size[] for (int i = 0; i < n; i++) { parent[i] = i, size[i] = 1; } /// Stores the minimum cost int ans = 0; // Finding the minimum cost for (auto x : v) { // Perform the unioun operation if (union_sets(x.second.first, x.second.second)) { ans += x.first; } } // Print the minimum cost cout << ans;} // Driver Codeint main(){ // Given houses int houses[][2] = { { 0, 0 }, { 2, 2 }, { 3, 10 }, { 5, 2 }, { 7, 0 }}; int N = sizeof(houses) / sizeof(houses[0]); // Function Call MST(houses, N); return 0;}", "e": 3718, "s": 1550, "text": null }, { "code": "// Java program for the above approachimport java.util.*; // Class for DSU implementationclass DSU{ int parent[];int rank[]; // Constructor to initialize DSUDSU(int n){ parent = new int[n]; rank = new int[n]; for(int i = 0; i < n; i++) { parent[i] = -1; rank[i] = 1; }} // Utility function to find set of an// element v using path compression// techniqueint find_set(int v){ // If v is the parent if (parent[v] == -1) return v; // Otherwise, recursively // find its parent return parent[v] = find_set(parent[v]);} // Function to perform union// of the sets a and bvoid union_sets(int a, int b){ // Find parent of a and b int p1 = find_set(a); int p2 = find_set(b); // If parent are different if (p1 != p2) { // Swap Operation if (rank[p1] > rank[p2]) { parent[p2] = p1; rank[p1] += rank[p2]; } else { parent[p1] = p2; rank[p2] += rank[p1]; } }}} class GFG{ // Function to create a Minimum Cost// Spanning tree for given housesstatic void MST(int houses[][], int n){ int ans = 0; ArrayList<int[]> edges = new ArrayList<>(); // Traverse each coordinate for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { // Find the Manhattan distance int p = Math.abs(houses[i][0] - houses[j][0]); p += Math.abs(houses[i][1] - houses[j][1]); // Add the edges edges.add(new int[]{ p, i, j }); } } // Sorting arraylist using custome comparator // on the basis of weight i.e first element in // array object stored in Arraylist Collections.sort(edges, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return Integer.compare(o1[0], o2[0]); } }); // Calling DSU class DSU d = new DSU(n); for(int i = 0; i < edges.size(); i++) { int from = edges.get(i)[1]; int to = edges.get(i)[2]; // Checking if they lie in different component // or not i.e they have same parent or not in // DSU if (d.find_set(from) != d.find_set(to)) { // Calling union_sets d.union_sets(from, to); ans += edges.get(i)[0]; } } // Printing the minimum cost System.out.println(ans);} // Driver codepublic static void main(String args[]){ // Graph in form of 2D array int houses[][] = { { 0, 0 }, { 2, 2 }, { 3, 10 }, { 5, 2 }, { 7, 0 } }; int n = houses.length; // Function Call MST(houses, n);}} // This code is contributed by Rahul Verma", "e": 6584, "s": 3718, "text": null }, { "code": "# Python3 program for the above approachparent = [0] * 100size = [0] * 100 # Utility function to find set of an# element v using path compression# techniquedef find_set(v): # If v is the parent if (v == parent[v]): return v # Otherwise, recursively # find its parent parent[v] = find_set(parent[v]) return parent[v] # Function to perform union# of the sets a and bdef union_sets(a, b): # Find parent of a and b a = find_set(a) b = find_set(b) # If parent are different if (a != b): # Swap Operation if (size[a] < size[b]): a, b = b, a # Update parent of b as a parent[b] = a size[a] += size[b] return 1 # Otherwise, return 0 return 0 # Function to create a Minimum Cost# Spanning tree for given housesdef MST(houses, n): # Stores adjacency list of graph v = [] # Traverse each coordinate for i in range(n): for j in range(i + 1, n): # Find the Manhattan distance p = abs(houses[i][0] - houses[j][0]) p += abs(houses[i][1] - houses[j][1]) # Add the edges v.append([p, i, j]) # Sort all the edges v = sorted(v) # Initialize parent[] and size[] for i in range(n): parent[i] = i size[i] = 1 # Stores the minimum cost ans = 0 # Finding the minimum cost for x in v: # Perform the unioun operation if (union_sets(x[1], x[2])): ans += x[0] # Print the minimum cost print(ans) # Driver Codeif __name__ == '__main__': # Given houses houses = [ [ 0, 0 ], [ 2, 2 ], [ 3, 10 ], [ 5, 2 ], [ 7, 0 ] ] N = len(houses) # Function Call MST(houses, N) # This code is contributed by mohit kumar 29", "e": 8444, "s": 6584, "text": null }, { "code": "<script> // JavaScript program for the above approachlet parent = new Array(100).fill(0)let size = new Array(100).fill(0) // Utility function to find set of an// element v using path compression// techniquefunction find_set(v){ // If v is the parent if (v == parent[v]) return v // Otherwise, recursively // find its parent parent[v] = find_set(parent[v]) return parent[v]} // Function to perform union// of the sets a and bfunction union_sets(a, b){ // Find parent of a and b a = find_set(a) b = find_set(b) // If parent are different if (a != b){ // Swap Operation if (size[a] < size[b]){ a, b = b, a } // Update parent of b as a parent[b] = a size[a] += size[b] return 1 } // Otherwise, return 0 return 0} // Function to create a Minimum Cost// Spanning tree for given housesfunction MST(houses, n){ // Stores adjacency list of graph let v = [] // Traverse each coordinate for(let i=0;i<n;i++){ for(let j=i+1;j<n;j++){ // Find the Manhattan distance let p = Math.abs(houses[i][0] - houses[j][0]) p += Math.abs(houses[i][1] - houses[j][1]) // Add the edges v.push([p, i, j]) } } // Sort all the edges v.sort((a,b)=>a[0]-b[0]) // Initialize parent[] and size[] for(let i=0;i<n;i++){ parent[i] = i size[i] = 1 } // Stores the minimum cost let ans = 0 // Finding the minimum cost for(let x of v){ // Perform the unioun operation if (union_sets(x[1], x[2])) ans += x[0] } // Print the minimum cost document.write(ans,\"</br>\")} // Driver Code // Given houseslet houses = [ [ 0, 0 ], [ 2, 2 ], [ 3, 10 ], [ 5, 2 ],[ 7, 0 ] ] let N = houses.length // Function CallMST(houses, N) // This code is contributed by shinjanpatra </script>", "e": 10434, "s": 8444, "text": null }, { "code": null, "e": 10437, "s": 10434, "text": "20" }, { "code": null, "e": 10484, "s": 10439, "text": "Time Complexity: O(N2)Auxiliary Space: O(N2)" }, { "code": null, "e": 10499, "s": 10484, "text": "mohit kumar 29" }, { "code": null, "e": 10510, "s": 10499, "text": "rv60231023" }, { "code": null, "e": 10527, "s": 10510, "text": "surinderdawra388" }, { "code": null, "e": 10540, "s": 10527, "text": "simmytarika5" }, { "code": null, "e": 10553, "s": 10540, "text": "shinjanpatra" }, { "code": null, "e": 10572, "s": 10553, "text": "Kruskal'sAlgorithm" }, { "code": null, "e": 10594, "s": 10572, "text": "Minimum Spanning Tree" }, { "code": null, "e": 10598, "s": 10594, "text": "MST" }, { "code": null, "e": 10605, "s": 10598, "text": "Arrays" }, { "code": null, "e": 10611, "s": 10605, "text": "Graph" }, { "code": null, "e": 10618, "s": 10611, "text": "Greedy" }, { "code": null, "e": 10626, "s": 10618, "text": "Sorting" }, { "code": null, "e": 10633, "s": 10626, "text": "Arrays" }, { "code": null, "e": 10640, "s": 10633, "text": "Greedy" }, { "code": null, "e": 10648, "s": 10640, "text": "Sorting" }, { "code": null, "e": 10654, "s": 10648, "text": "Graph" } ]
Python – tensorflow.GradientTape.gradient()
10 Jul, 2020 TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. gradient() is used to computes the gradient using operations recorded in context of this tape. Syntax: gradient(target, sources, output_gradients, unconnected_gradients) Parameters: target: It is Tensor or list of Tensor to be differentiated. sources: It is Tensor or list of Tensor. Target values are differentiated against the source. output_gradients: It is a list of gradients with default value None. unconnected_gradients: It’s value can be either none or zero with default value none. Returns: It returns a list or nested structure of Tensor. Example 1: Python3 # Importing the libraryimport tensorflow as tf x = tf.constant(4.0) # Using GradientTapewith tf.GradientTape() as gfg: gfg.watch(x) y = x * x * x # Computing gradientres = gfg.gradient(y, x) # Printing resultprint("res: ",res) Output: res: tf.Tensor(48.0, shape=(), dtype=float32) Example 2: Python3 # Importing the libraryimport tensorflow as tf x = tf.constant(4.0) # Using GradientTapewith tf.GradientTape() as gfg: gfg.watch(x) # Using nested GradientTape for # calculating higher order derivative with tf.GradientTape() as gg: gg.watch(x) y = x * x * x # Computing first order gradient first_order = gg.gradient(y, x) # Computing Second order gradientsecond_order = gfg.gradient(first_order, x) # Printing resultprint("first_order: ",first_order)print("second_order: ",second_order) Output: first_order: tf.Tensor(48.0, shape=(), dtype=float32) second_order: tf.Tensor(24.0, shape=(), dtype=float32) Python Tensorflow-math-functions Python-Tensorflow Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jul, 2020" }, { "code": null, "e": 160, "s": 28, "text": "TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. " }, { "code": null, "e": 255, "s": 160, "text": "gradient() is used to computes the gradient using operations recorded in context of this tape." }, { "code": null, "e": 330, "s": 255, "text": "Syntax: gradient(target, sources, output_gradients, unconnected_gradients)" }, { "code": null, "e": 342, "s": 330, "text": "Parameters:" }, { "code": null, "e": 403, "s": 342, "text": "target: It is Tensor or list of Tensor to be differentiated." }, { "code": null, "e": 497, "s": 403, "text": "sources: It is Tensor or list of Tensor. Target values are differentiated against the source." }, { "code": null, "e": 566, "s": 497, "text": "output_gradients: It is a list of gradients with default value None." }, { "code": null, "e": 652, "s": 566, "text": "unconnected_gradients: It’s value can be either none or zero with default value none." }, { "code": null, "e": 710, "s": 652, "text": "Returns: It returns a list or nested structure of Tensor." }, { "code": null, "e": 721, "s": 710, "text": "Example 1:" }, { "code": null, "e": 729, "s": 721, "text": "Python3" }, { "code": "# Importing the libraryimport tensorflow as tf x = tf.constant(4.0) # Using GradientTapewith tf.GradientTape() as gfg: gfg.watch(x) y = x * x * x # Computing gradientres = gfg.gradient(y, x) # Printing resultprint(\"res: \",res)", "e": 964, "s": 729, "text": null }, { "code": null, "e": 972, "s": 964, "text": "Output:" }, { "code": null, "e": 1021, "s": 972, "text": "\nres: tf.Tensor(48.0, shape=(), dtype=float32)\n" }, { "code": null, "e": 1032, "s": 1021, "text": "Example 2:" }, { "code": null, "e": 1040, "s": 1032, "text": "Python3" }, { "code": "# Importing the libraryimport tensorflow as tf x = tf.constant(4.0) # Using GradientTapewith tf.GradientTape() as gfg: gfg.watch(x) # Using nested GradientTape for # calculating higher order derivative with tf.GradientTape() as gg: gg.watch(x) y = x * x * x # Computing first order gradient first_order = gg.gradient(y, x) # Computing Second order gradientsecond_order = gfg.gradient(first_order, x) # Printing resultprint(\"first_order: \",first_order)print(\"second_order: \",second_order)", "e": 1551, "s": 1040, "text": null }, { "code": null, "e": 1559, "s": 1551, "text": "Output:" }, { "code": null, "e": 1673, "s": 1559, "text": "\nfirst_order: tf.Tensor(48.0, shape=(), dtype=float32)\nsecond_order: tf.Tensor(24.0, shape=(), dtype=float32)\n\n" }, { "code": null, "e": 1706, "s": 1673, "text": "Python Tensorflow-math-functions" }, { "code": null, "e": 1724, "s": 1706, "text": "Python-Tensorflow" }, { "code": null, "e": 1731, "s": 1724, "text": "Python" }, { "code": null, "e": 1829, "s": 1731, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1847, "s": 1829, "text": "Python Dictionary" }, { "code": null, "e": 1889, "s": 1847, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1911, "s": 1889, "text": "Enumerate() in Python" }, { "code": null, "e": 1946, "s": 1911, "text": "Read a file line by line in Python" }, { "code": null, "e": 1972, "s": 1946, "text": "Python String | replace()" }, { "code": null, "e": 2004, "s": 1972, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2033, "s": 2004, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2060, "s": 2033, "text": "Python Classes and Objects" }, { "code": null, "e": 2090, "s": 2060, "text": "Iterate over a list in Python" } ]
Sum of even numbers at even position
13 Jun, 2022 Given an array of size n. The problem is to find the sum of numbers which are even and are at even index.Examples: Input : arr[] = {5, 6, 12, 1, 18, 8} Output : 30 Explanation: Here, n = 6 Now here are index and numbers as: index->arr[index] 0->5, 1->6, 2->12, 3->1, 4->18, 5->8 so, number which are even and are at even indices are: 2->12, 4->18 sum = 12+18 = 30 Input : arr[] = {3, 20, 17, 9, 2, 10, 18, 13, 6, 18} Output : 26 Explanation: Here, n = 10 Now here are index and numbers as: index->arr[index] 0->3, 1->20, 2->17, 3->9, 4->2, 5->10, 6->18, 7->13, 8->6, 9->18 So, number which are even and are at even indices are: 4->2, 6->18, 8->6 sum = 2+18+6 = 26 C++ Java Python3 C# PHP Javascript // C++ implementation to// find sum of even numbers// at even indices#include <bits/stdc++.h>using namespace std; // Function to calculate sum// of even numbers at even indicesint sum_even_and_even_index( int arr[], int n) { int i = 0, sum = 0; // calculating sum of even // number at even index for (i = 0; i < n; i+=2) { if (arr[i] % 2 == 0) { sum += arr[i]; } } // required sum return sum;} // Driver program to test aboveint main() { int arr[] = {5, 6, 12, 1, 18, 8}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Sum of even numbers at even indices is " << sum_even_and_even_index(arr, n); return 0;} // Java implementation to find sum of// even numbers at even indices import java.io.*; class GFG { // Function to calculate sum // of even numbers at even indices static int sum_even_and_even_index( int arr[], int n) { int i = 0, sum = 0; // calculating sum of even // number at even index for (i = 0; i < n; i+=2) { if (arr[i] % 2 == 0) { sum += arr[i]; } } // required sum return sum; } // Driver program to test above public static void main (String[] args) { int arr[] = {5, 6, 12, 1, 18, 8}; int n = arr.length; System.out.println("Sum of even numbers" + " at even indices is " + + sum_even_and_even_index(arr, n)); }} // This code is contributed by vt_m. # python 3 implementation to# find sum of even numbers# at even indices # Function to calculate sum# of even numbers at even indicesdef sum_even_and_even_index(arr,n): i = 0 sum = 0 # calculating sum of even# number at even index for i in range(0,n,2): if (arr[i] % 2 == 0) : sum += arr[i] # required sum return sum # Driver program to test abovearr = [5, 6, 12, 1, 18, 8]n = len(arr)print("Sum of even numbers at ", "even indices is ", sum_even_and_even_index(arr, n)) # This code is contributed by Sam007 // C# implementation to find sum of// even numbers at even indices using System; class GFG { // Function to calculate sum // of even numbers at even indices static int sum_even_and_even_index( int []arr, int n) { int i = 0, sum = 0; // calculating sum of even // number at even index for (i = 0; i < n; i+=2) { if (arr[i] % 2 == 0) { sum += arr[i]; } } // required sum return sum; } // Driver program to test above public static void Main () { int []arr = {5, 6, 12, 1, 18, 8}; int n = arr.Length; Console.WriteLine("Sum of even numbers" + " at even indices is " + + sum_even_and_even_index(arr, n)); }} //This code is contributed by vt_m. <?php// PHP implementation to// find sum of even numbers// at even indices // Function to calculate sum// of even numbers at even indicesfunction sum_even_and_even_index($arr, $n){ $i = 0; $sum = 0; // calculating sum of even // number at even index for ($i = 0; $i < $n; $i=$i+2) { if ($arr[$i] % 2 == 0) { $sum += $arr[$i]; } } // required sum return $sum;} // Driver Code{ $arr = array(5, 6, 12, 1, 18, 8); $n = sizeof($arr) / sizeof($arr[0]); echo "Sum of even numbers at ". "even indices is ", sum_even_and_even_index($arr, $n); return 0;} // This code is contributed by nitin mittal.?> <script> // Javascript implementation to// find sum of even numbers// at even indices // Function to calculate sum// of even numbers at even indicesfunction sum_even_and_even_index( arr, n) { let i = 0, sum = 0; // calculating sum of even // number at even index for (i = 0; i < n; i += 2) { if (arr[i] % 2 == 0) { sum += arr[i]; } } // required sum return sum;} // Driver code let arr = [5, 6, 12, 1, 18, 8]; let n = arr.length; document.write("Sum of even numbers at even indices is " + sum_even_and_even_index(arr, n)); // This code is contributed by Mayank Tyagi </script> Output: Sum of even numbers at even indices is 30 Time Complexity: O(n) Auxiliary Space: O(1) nitin mittal Sam007 shashank2714 mayanktyagi1709 hasani Arrays School Programming Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Python Dictionary Reverse a string in Java Introduction To PYTHON Interfaces in Java Inheritance in C++
[ { "code": null, "e": 53, "s": 25, "text": "\n13 Jun, 2022" }, { "code": null, "e": 170, "s": 53, "text": "Given an array of size n. The problem is to find the sum of numbers which are even and are at even index.Examples: " }, { "code": null, "e": 752, "s": 170, "text": "Input : arr[] = {5, 6, 12, 1, 18, 8}\nOutput : 30\nExplanation: Here, n = 6 \nNow here are index and numbers as: index->arr[index]\n0->5, 1->6, 2->12, 3->1, 4->18, 5->8\nso, number which are even and are at even indices \nare: 2->12, 4->18\nsum = 12+18 = 30\n\nInput : arr[] = {3, 20, 17, 9, 2, 10, \n 18, 13, 6, 18}\nOutput : 26\nExplanation: Here, n = 10\nNow here are index and numbers as: index->arr[index]\n0->3, 1->20, 2->17, 3->9, 4->2, 5->10, \n6->18, 7->13, 8->6, 9->18 \nSo, number which are even and are at even indices are: \n4->2, 6->18, 8->6\nsum = 2+18+6 = 26" }, { "code": null, "e": 760, "s": 756, "text": "C++" }, { "code": null, "e": 765, "s": 760, "text": "Java" }, { "code": null, "e": 773, "s": 765, "text": "Python3" }, { "code": null, "e": 776, "s": 773, "text": "C#" }, { "code": null, "e": 780, "s": 776, "text": "PHP" }, { "code": null, "e": 791, "s": 780, "text": "Javascript" }, { "code": "// C++ implementation to// find sum of even numbers// at even indices#include <bits/stdc++.h>using namespace std; // Function to calculate sum// of even numbers at even indicesint sum_even_and_even_index( int arr[], int n) { int i = 0, sum = 0; // calculating sum of even // number at even index for (i = 0; i < n; i+=2) { if (arr[i] % 2 == 0) { sum += arr[i]; } } // required sum return sum;} // Driver program to test aboveint main() { int arr[] = {5, 6, 12, 1, 18, 8}; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Sum of even numbers at even indices is \" << sum_even_and_even_index(arr, n); return 0;}", "e": 1513, "s": 791, "text": null }, { "code": "// Java implementation to find sum of// even numbers at even indices import java.io.*; class GFG { // Function to calculate sum // of even numbers at even indices static int sum_even_and_even_index( int arr[], int n) { int i = 0, sum = 0; // calculating sum of even // number at even index for (i = 0; i < n; i+=2) { if (arr[i] % 2 == 0) { sum += arr[i]; } } // required sum return sum; } // Driver program to test above public static void main (String[] args) { int arr[] = {5, 6, 12, 1, 18, 8}; int n = arr.length; System.out.println(\"Sum of even numbers\" + \" at even indices is \" + + sum_even_and_even_index(arr, n)); }} // This code is contributed by vt_m.", "e": 2407, "s": 1513, "text": null }, { "code": "# python 3 implementation to# find sum of even numbers# at even indices # Function to calculate sum# of even numbers at even indicesdef sum_even_and_even_index(arr,n): i = 0 sum = 0 # calculating sum of even# number at even index for i in range(0,n,2): if (arr[i] % 2 == 0) : sum += arr[i] # required sum return sum # Driver program to test abovearr = [5, 6, 12, 1, 18, 8]n = len(arr)print(\"Sum of even numbers at \", \"even indices is \", sum_even_and_even_index(arr, n)) # This code is contributed by Sam007", "e": 2984, "s": 2407, "text": null }, { "code": "// C# implementation to find sum of// even numbers at even indices using System; class GFG { // Function to calculate sum // of even numbers at even indices static int sum_even_and_even_index( int []arr, int n) { int i = 0, sum = 0; // calculating sum of even // number at even index for (i = 0; i < n; i+=2) { if (arr[i] % 2 == 0) { sum += arr[i]; } } // required sum return sum; } // Driver program to test above public static void Main () { int []arr = {5, 6, 12, 1, 18, 8}; int n = arr.Length; Console.WriteLine(\"Sum of even numbers\" + \" at even indices is \" + + sum_even_and_even_index(arr, n)); }} //This code is contributed by vt_m.", "e": 3868, "s": 2984, "text": null }, { "code": "<?php// PHP implementation to// find sum of even numbers// at even indices // Function to calculate sum// of even numbers at even indicesfunction sum_even_and_even_index($arr, $n){ $i = 0; $sum = 0; // calculating sum of even // number at even index for ($i = 0; $i < $n; $i=$i+2) { if ($arr[$i] % 2 == 0) { $sum += $arr[$i]; } } // required sum return $sum;} // Driver Code{ $arr = array(5, 6, 12, 1, 18, 8); $n = sizeof($arr) / sizeof($arr[0]); echo \"Sum of even numbers at \". \"even indices is \", sum_even_and_even_index($arr, $n); return 0;} // This code is contributed by nitin mittal.?>", "e": 4577, "s": 3868, "text": null }, { "code": "<script> // Javascript implementation to// find sum of even numbers// at even indices // Function to calculate sum// of even numbers at even indicesfunction sum_even_and_even_index( arr, n) { let i = 0, sum = 0; // calculating sum of even // number at even index for (i = 0; i < n; i += 2) { if (arr[i] % 2 == 0) { sum += arr[i]; } } // required sum return sum;} // Driver code let arr = [5, 6, 12, 1, 18, 8]; let n = arr.length; document.write(\"Sum of even numbers at even indices is \" + sum_even_and_even_index(arr, n)); // This code is contributed by Mayank Tyagi </script>", "e": 5259, "s": 4577, "text": null }, { "code": null, "e": 5269, "s": 5259, "text": "Output: " }, { "code": null, "e": 5312, "s": 5269, "text": " Sum of even numbers at even indices is 30" }, { "code": null, "e": 5334, "s": 5312, "text": "Time Complexity: O(n)" }, { "code": null, "e": 5357, "s": 5334, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 5370, "s": 5357, "text": "nitin mittal" }, { "code": null, "e": 5377, "s": 5370, "text": "Sam007" }, { "code": null, "e": 5390, "s": 5377, "text": "shashank2714" }, { "code": null, "e": 5406, "s": 5390, "text": "mayanktyagi1709" }, { "code": null, "e": 5413, "s": 5406, "text": "hasani" }, { "code": null, "e": 5420, "s": 5413, "text": "Arrays" }, { "code": null, "e": 5439, "s": 5420, "text": "School Programming" }, { "code": null, "e": 5446, "s": 5439, "text": "Arrays" }, { "code": null, "e": 5544, "s": 5446, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5612, "s": 5544, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 5656, "s": 5612, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 5688, "s": 5656, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 5736, "s": 5688, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 5750, "s": 5736, "text": "Linear Search" }, { "code": null, "e": 5768, "s": 5750, "text": "Python Dictionary" }, { "code": null, "e": 5793, "s": 5768, "text": "Reverse a string in Java" }, { "code": null, "e": 5816, "s": 5793, "text": "Introduction To PYTHON" }, { "code": null, "e": 5835, "s": 5816, "text": "Interfaces in Java" } ]
PyQt5 QListWidget – Getting Resize Mode Property
06 Aug, 2020 In this article we will see how we can get the resize mode property to the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. This property holds whether the items are laid out again when the view is resized. If this property is Adjust, the items will be laid out again when the view is resized. If the value is Fixed, the items will not be laid out when the view is resized. By default, this property is set to Fixed although it can be set with the help of setResizeMode method. In order to do this we will use resizeMode method with the list widget object. Syntax : list_widget.resizeMode() Argument : It takes no argument Return : It returns resize mode object, but when printed it shows the value associated with it. Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem("A") item2 = QListWidgetItem("B") item3 = QListWidgetItem("C") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting resize mode property list_widget.setResizeMode(QListView.Fixed) # creating a label label = QLabel("GeesforGeeks", self) # setting geometry to the label label.setGeometry(230, 80, 280, 80) # making label multi line label.setWordWrap(True) # getting resize mode property value = list_widget.resizeMode() # setting text to the label label.setText("Resize Mode Property : " + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt-QListWidget Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Aug, 2020" }, { "code": null, "e": 677, "s": 28, "text": "In this article we will see how we can get the resize mode property to the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. This property holds whether the items are laid out again when the view is resized. If this property is Adjust, the items will be laid out again when the view is resized. If the value is Fixed, the items will not be laid out when the view is resized. By default, this property is set to Fixed although it can be set with the help of setResizeMode method." }, { "code": null, "e": 756, "s": 677, "text": "In order to do this we will use resizeMode method with the list widget object." }, { "code": null, "e": 790, "s": 756, "text": "Syntax : list_widget.resizeMode()" }, { "code": null, "e": 822, "s": 790, "text": "Argument : It takes no argument" }, { "code": null, "e": 918, "s": 822, "text": "Return : It returns resize mode object, but when printed it shows the value associated with it." }, { "code": null, "e": 946, "s": 918, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem(\"A\") item2 = QListWidgetItem(\"B\") item3 = QListWidgetItem(\"C\") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting resize mode property list_widget.setResizeMode(QListView.Fixed) # creating a label label = QLabel(\"GeesforGeeks\", self) # setting geometry to the label label.setGeometry(230, 80, 280, 80) # making label multi line label.setWordWrap(True) # getting resize mode property value = list_widget.resizeMode() # setting text to the label label.setText(\"Resize Mode Property : \" + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 2543, "s": 946, "text": null }, { "code": null, "e": 2552, "s": 2543, "text": "Output :" }, { "code": null, "e": 2576, "s": 2552, "text": "Python PyQt-QListWidget" }, { "code": null, "e": 2587, "s": 2576, "text": "Python-gui" }, { "code": null, "e": 2599, "s": 2587, "text": "Python-PyQt" }, { "code": null, "e": 2606, "s": 2599, "text": "Python" } ]
Python | Add only numeric values present in a list
30 Jun, 2022 Given a list containing characters and numbers, the task is to add only numbers from a list. Given below are a few methods to complete a given task. Method #1: Using filter() and lambda Python3 # Python code to demonstrate# how to add only numbers present# in a list of characters and numbers # initialising listsini_list = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z'] # printing initial listprint ("initial list", str(ini_list)) # code to add numbers from listres = sum(filter(lambda i: isinstance(i, int), ini_list)) # printing resultprint ("resultant sum", res) initial list [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z'] resultant sum 15 Method #2: Using try and except Python3 # Python code to demonstrate# how to add only numbers present# in a list of characters and numbers # initialising listsini_list = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z'] # printing initial listprint ("initial list", str(ini_list)) # code to add numbers from listres = 0for item in ini_list: try: res+= int(item) except ValueError: pass # printing resultprint ("resultant sum", res) initial list [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z'] resultant sum 15 Method #3: Using isinstance and conditional statements Python3 # Python code to demonstrate# how to add only numbers present# in a list of characters and numbers # initialising listsini_list = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z'] # printing initial listprint ("initial list", str(ini_list)) # code to add numbers from listres = sum([x for x in ini_list if isinstance(x, int)]) # printing resultprint ("resultant sum", res) initial list [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z'] resultant sum 15 Method #4: Using type() and find() methods Python3 # Python code to demonstrate# how to add only numbers present# in a list of characters and numbers # initialising listsini_list = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z'] # printing initial listprint ("initial list", str(ini_list)) # code to add numbers from listres=0for i in ini_list: p=str(type(i)) if(p.find('int')!=-1): res+=int(i)# printing resultprint ("resultant sum", res) #contributed by Bhavya Koganti initial list [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z'] resultant sum 15 kogantibhavya Python list-programs python-list Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Split string into list of characters
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2022" }, { "code": null, "e": 215, "s": 28, "text": "Given a list containing characters and numbers, the task is to add only numbers from a list. Given below are a few methods to complete a given task. Method #1: Using filter() and lambda " }, { "code": null, "e": 223, "s": 215, "text": "Python3" }, { "code": "# Python code to demonstrate# how to add only numbers present# in a list of characters and numbers # initialising listsini_list = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z'] # printing initial listprint (\"initial list\", str(ini_list)) # code to add numbers from listres = sum(filter(lambda i: isinstance(i, int), ini_list)) # printing resultprint (\"resultant sum\", res)", "e": 585, "s": 223, "text": null }, { "code": null, "e": 651, "s": 585, "text": "initial list [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']\nresultant sum 15" }, { "code": null, "e": 686, "s": 651, "text": " Method #2: Using try and except " }, { "code": null, "e": 694, "s": 686, "text": "Python3" }, { "code": "# Python code to demonstrate# how to add only numbers present# in a list of characters and numbers # initialising listsini_list = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z'] # printing initial listprint (\"initial list\", str(ini_list)) # code to add numbers from listres = 0for item in ini_list: try: res+= int(item) except ValueError: pass # printing resultprint (\"resultant sum\", res)", "e": 1092, "s": 694, "text": null }, { "code": null, "e": 1158, "s": 1092, "text": "initial list [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']\nresultant sum 15" }, { "code": null, "e": 1216, "s": 1158, "text": " Method #3: Using isinstance and conditional statements " }, { "code": null, "e": 1224, "s": 1216, "text": "Python3" }, { "code": "# Python code to demonstrate# how to add only numbers present# in a list of characters and numbers # initialising listsini_list = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z'] # printing initial listprint (\"initial list\", str(ini_list)) # code to add numbers from listres = sum([x for x in ini_list if isinstance(x, int)]) # printing resultprint (\"resultant sum\", res)", "e": 1583, "s": 1224, "text": null }, { "code": null, "e": 1649, "s": 1583, "text": "initial list [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']\nresultant sum 15" }, { "code": null, "e": 1692, "s": 1649, "text": "Method #4: Using type() and find() methods" }, { "code": null, "e": 1700, "s": 1692, "text": "Python3" }, { "code": "# Python code to demonstrate# how to add only numbers present# in a list of characters and numbers # initialising listsini_list = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z'] # printing initial listprint (\"initial list\", str(ini_list)) # code to add numbers from listres=0for i in ini_list: p=str(type(i)) if(p.find('int')!=-1): res+=int(i)# printing resultprint (\"resultant sum\", res) #contributed by Bhavya Koganti", "e": 2121, "s": 1700, "text": null }, { "code": null, "e": 2187, "s": 2121, "text": "initial list [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']\nresultant sum 15" }, { "code": null, "e": 2201, "s": 2187, "text": "kogantibhavya" }, { "code": null, "e": 2222, "s": 2201, "text": "Python list-programs" }, { "code": null, "e": 2234, "s": 2222, "text": "python-list" }, { "code": null, "e": 2241, "s": 2234, "text": "Python" }, { "code": null, "e": 2257, "s": 2241, "text": "Python Programs" }, { "code": null, "e": 2269, "s": 2257, "text": "python-list" }, { "code": null, "e": 2367, "s": 2269, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2399, "s": 2367, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2426, "s": 2399, "text": "Python Classes and Objects" }, { "code": null, "e": 2447, "s": 2426, "text": "Python OOPs Concepts" }, { "code": null, "e": 2470, "s": 2447, "text": "Introduction To PYTHON" }, { "code": null, "e": 2526, "s": 2470, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2548, "s": 2526, "text": "Defaultdict in Python" }, { "code": null, "e": 2587, "s": 2548, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2625, "s": 2587, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2662, "s": 2625, "text": "Python Program for Fibonacci numbers" } ]
set::begin() and set::end() in C++ STL
17 Jun, 2022 Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. begin() function is used to return an iterator pointing to the first element of the set container. begin() function returns a bidirectional iterator to the first element of the container. Syntax: setname.begin() Parameters : No parameters are passed. Return Type: This function returns a bidirectional iterator pointing to the first element. Examples: Input : myset{1, 2, 3, 4, 5}; myset.begin(); Output : returns an iterator to the element 1 Input : myset{8, 7}; myset.end(); Output : returns an iterator to past-the-end element. Errors and Exceptions1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed. CPP // INTEGER SET EXAMPLE// CPP program to illustrate// Implementation of begin() function#include <iostream>#include <set>using namespace std; int main(){ // declaration of set container set<int> myset{ 1, 2, 3, 4, 5 }; // using begin() to print set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;} Output: 1 2 3 4 5 CPP // CHARACTER SET EXAMPLE// CPP program to illustrate// Implementation of begin() function#include <iostream>#include <set>using namespace std; int main(){ // declaration of set container set<char> myset{ 'a', 'c', 'g', 'z' }; // using begin() to print set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;} Output: a c g z CPP // STRING SET EXAMPLE// CPP program to illustrate// Implementation of begin() function#include <iostream>#include <set>#include <string>using namespace std; int main(){ // declaration of set container set<string> myset{ "This", "is", "Geeksforgeeks" }; // using begin() to print set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;} Output: Geeksforgeeks This is Time Complexity: O(1) It returns an iterator pointing to past the last element of the set container. Since it does not refer to a valid element, it cannot de-referenced end() function returns a bidirectional iterator.Syntax : setname.end() Parameters : No parameters are passed. Returns : This function returns a bidirectional iterator pointing to next of the last element. Examples: Input : myset{1, 2, 3, 4, 5}; myset.end(); Output : returns an iterator to next of 5 Errors and Exceptions1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed. CPP // INTEGER Example// CPP program to illustrate// Implementation of end() function#include <iostream>#include <set>using namespace std; int main(){ // declaration of set container set<int> myset{ 1, 2, 3, 4, 5 }; // using end() to print set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;} Output: 1 2 3 4 5 CPP // CHARACTER SET EXAMPLE// CPP program to illustrate// Implementation of begin() function#include <iostream>#include <set>using namespace std; int main(){ // declaration of set container set<char> myset{'a', 'c', 'g', 'z'}; // using begin() to print set for (auto it=myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;} Output: a c g z CPP // STRING SET EXAMPLE// CPP program to illustrate// Implementation of begin() function#include <iostream>#include <set>#include <string> using namespace std; int main(){ // declaration of set container set<string> myset{ "This", "is", "Geeksforgeeks" }; // using begin() to print set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;} Output: Geeksforgeeks This is Time Complexity: O(1) Let us see the differences in a tabular form -: Its syntax is -: iterator begin(); Its syntax is -: iterator end(); jai_balayya gauravkumarcs2828 dark_hunter mayank007rawa cpp-set STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL) Unordered Sets in C++ Standard Template Library List in C++ Standard Template Library (STL) std::find in C++ Inline Functions in C++
[ { "code": null, "e": 53, "s": 25, "text": "\n17 Jun, 2022" }, { "code": null, "e": 331, "s": 53, "text": "Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. " }, { "code": null, "e": 519, "s": 331, "text": "begin() function is used to return an iterator pointing to the first element of the set container. begin() function returns a bidirectional iterator to the first element of the container." }, { "code": null, "e": 528, "s": 519, "text": "Syntax: " }, { "code": null, "e": 676, "s": 528, "text": "setname.begin()\n\nParameters :\nNo parameters are passed.\n\nReturn Type:\nThis function returns a bidirectional\niterator pointing to the first element." }, { "code": null, "e": 688, "s": 676, "text": "Examples: " }, { "code": null, "e": 889, "s": 688, "text": "Input : myset{1, 2, 3, 4, 5};\n myset.begin();\nOutput : returns an iterator to the element 1\n\nInput : myset{8, 7};\n myset.end();\nOutput : returns an iterator to past-the-end element. " }, { "code": null, "e": 996, "s": 889, "text": "Errors and Exceptions1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed. " }, { "code": null, "e": 1000, "s": 996, "text": "CPP" }, { "code": "// INTEGER SET EXAMPLE// CPP program to illustrate// Implementation of begin() function#include <iostream>#include <set>using namespace std; int main(){ // declaration of set container set<int> myset{ 1, 2, 3, 4, 5 }; // using begin() to print set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;}", "e": 1385, "s": 1000, "text": null }, { "code": null, "e": 1394, "s": 1385, "text": "Output: " }, { "code": null, "e": 1404, "s": 1394, "text": "1 2 3 4 5" }, { "code": null, "e": 1408, "s": 1404, "text": "CPP" }, { "code": "// CHARACTER SET EXAMPLE// CPP program to illustrate// Implementation of begin() function#include <iostream>#include <set>using namespace std; int main(){ // declaration of set container set<char> myset{ 'a', 'c', 'g', 'z' }; // using begin() to print set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;}", "e": 1799, "s": 1408, "text": null }, { "code": null, "e": 1808, "s": 1799, "text": "Output: " }, { "code": null, "e": 1817, "s": 1808, "text": "a c g z " }, { "code": null, "e": 1821, "s": 1817, "text": "CPP" }, { "code": "// STRING SET EXAMPLE// CPP program to illustrate// Implementation of begin() function#include <iostream>#include <set>#include <string>using namespace std; int main(){ // declaration of set container set<string> myset{ \"This\", \"is\", \"Geeksforgeeks\" }; // using begin() to print set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;}", "e": 2270, "s": 1821, "text": null }, { "code": null, "e": 2279, "s": 2270, "text": "Output: " }, { "code": null, "e": 2302, "s": 2279, "text": "Geeksforgeeks This is " }, { "code": null, "e": 2325, "s": 2302, "text": "Time Complexity: O(1) " }, { "code": null, "e": 2531, "s": 2325, "text": "It returns an iterator pointing to past the last element of the set container. Since it does not refer to a valid element, it cannot de-referenced end() function returns a bidirectional iterator.Syntax : " }, { "code": null, "e": 2679, "s": 2531, "text": "setname.end()\nParameters :\nNo parameters are passed.\nReturns :\nThis function returns a bidirectional\niterator pointing to next of the last element." }, { "code": null, "e": 2691, "s": 2679, "text": "Examples: " }, { "code": null, "e": 2786, "s": 2691, "text": "Input : myset{1, 2, 3, 4, 5};\n myset.end();\nOutput : returns an iterator to next of 5" }, { "code": null, "e": 2893, "s": 2786, "text": "Errors and Exceptions1. It has a no exception throw guarantee. 2. Shows error when a parameter is passed. " }, { "code": null, "e": 2897, "s": 2893, "text": "CPP" }, { "code": "// INTEGER Example// CPP program to illustrate// Implementation of end() function#include <iostream>#include <set>using namespace std; int main(){ // declaration of set container set<int> myset{ 1, 2, 3, 4, 5 }; // using end() to print set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;}", "e": 3271, "s": 2897, "text": null }, { "code": null, "e": 3280, "s": 3271, "text": "Output: " }, { "code": null, "e": 3290, "s": 3280, "text": "1 2 3 4 5" }, { "code": null, "e": 3294, "s": 3290, "text": "CPP" }, { "code": "// CHARACTER SET EXAMPLE// CPP program to illustrate// Implementation of begin() function#include <iostream>#include <set>using namespace std; int main(){ // declaration of set container set<char> myset{'a', 'c', 'g', 'z'}; // using begin() to print set for (auto it=myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;}", "e": 3660, "s": 3294, "text": null }, { "code": null, "e": 3669, "s": 3660, "text": "Output: " }, { "code": null, "e": 3677, "s": 3669, "text": "a c g z" }, { "code": null, "e": 3681, "s": 3677, "text": "CPP" }, { "code": "// STRING SET EXAMPLE// CPP program to illustrate// Implementation of begin() function#include <iostream>#include <set>#include <string> using namespace std; int main(){ // declaration of set container set<string> myset{ \"This\", \"is\", \"Geeksforgeeks\" }; // using begin() to print set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;}", "e": 4074, "s": 3681, "text": null }, { "code": null, "e": 4083, "s": 4074, "text": "Output: " }, { "code": null, "e": 4106, "s": 4083, "text": "Geeksforgeeks This is " }, { "code": null, "e": 4129, "s": 4106, "text": "Time Complexity: O(1) " }, { "code": null, "e": 4177, "s": 4129, "text": "Let us see the differences in a tabular form -:" }, { "code": null, "e": 4194, "s": 4177, "text": "Its syntax is -:" }, { "code": null, "e": 4212, "s": 4194, "text": "iterator begin();" }, { "code": null, "e": 4229, "s": 4212, "text": "Its syntax is -:" }, { "code": null, "e": 4245, "s": 4229, "text": "iterator end();" }, { "code": null, "e": 4257, "s": 4245, "text": "jai_balayya" }, { "code": null, "e": 4275, "s": 4257, "text": "gauravkumarcs2828" }, { "code": null, "e": 4287, "s": 4275, "text": "dark_hunter" }, { "code": null, "e": 4301, "s": 4287, "text": "mayank007rawa" }, { "code": null, "e": 4309, "s": 4301, "text": "cpp-set" }, { "code": null, "e": 4313, "s": 4309, "text": "STL" }, { "code": null, "e": 4317, "s": 4313, "text": "C++" }, { "code": null, "e": 4321, "s": 4317, "text": "STL" }, { "code": null, "e": 4325, "s": 4321, "text": "CPP" }, { "code": null, "e": 4423, "s": 4325, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4447, "s": 4423, "text": "Sorting a vector in C++" }, { "code": null, "e": 4467, "s": 4447, "text": "Polymorphism in C++" }, { "code": null, "e": 4500, "s": 4467, "text": "Friend class and function in C++" }, { "code": null, "e": 4525, "s": 4500, "text": "std::string class in C++" }, { "code": null, "e": 4569, "s": 4525, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 4614, "s": 4569, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 4662, "s": 4614, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 4706, "s": 4662, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 4723, "s": 4706, "text": "std::find in C++" } ]
What is MORGAN in Node.js ?
05 Aug, 2021 Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside of the browser. It is widely used in developing APIs and microservices from small to large companies. It is a great tool as this enables developers to use JavaScript both on the server and client-side. In this article, We will discuss the MORGAN in Nodejs. Morgan: Morgan is an HTTP request level Middleware. It is a great tool that logs the requests along with some other information depending upon its configuration and the preset used. It proves to be very helpful while debugging and also if you want to create Log files. Prerequisites: Basic understanding of Nodejs. Creating Project and Module Installation: Step 1: Create a new folder for a project using the following command:mkdir morgan Step 1: Create a new folder for a project using the following command: mkdir morgan Step 2: Navigate to our folder using the following command:cd morgan Step 2: Navigate to our folder using the following command: cd morgan Step 3: Initialize npm using the following command and server file:npm init -y touch index.js Step 3: Initialize npm using the following command and server file: npm init -y touch index.js Step 4: Install required packages using the following command:npm i express morgan Step 4: Install required packages using the following command: npm i express morgan Project Structure: It will look like the following: Example 1: Using dev as a preset in morgan. Javascript const express = require('express');const logger = require('morgan');const port = 3000; const app = express();app.use(logger('dev')); app.get('/', (req, res) => { res.send('<h1>Front Page</h1>');}); app.listen(port, () => { console.log(`Started at ${port}`);}); Steps to run: Run the application using the following command. node index.js Output: To send the request, We use a browser, That request will be logged by our logger morgan. Then we will see the following output in our console. Information about the get request on the home route is logged with status code 200. Explanation: Basically in the above code, we set up morgan, and since it’s a middleware, So we used the .use() method to tell express to use that as a middleware in our app. Other than that we have used ‘dev’ as a preset. Some other presets available are combined, common, short, tiny. Each preset returns different information. Example 2: In this example tiny is used as a preset inside morgan instead of dev. Javascript const express = require('express');const logger = require('morgan');const port = 3000; const app = express();app.use(logger('tiny')); app.get('/', (req, res) => { res.send('<h1>Front Page</h1>');}); app.listen(port, () => { console.log(`Started at ${port}`);}); Steps to run: Run the application using the following command. node index.js Output: To send the request, We use a browser, That request will be logged by our logger morgan. Then we will see the following output in our console. Explanation: In this 304 code is there, the Reason is since it is a simple static webpage, So browser cached it and returned its previous instance instead of making a new request. NodeJS-Questions Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Aug, 2021" }, { "code": null, "e": 388, "s": 28, "text": "Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside of the browser. It is widely used in developing APIs and microservices from small to large companies. It is a great tool as this enables developers to use JavaScript both on the server and client-side. In this article, We will discuss the MORGAN in Nodejs." }, { "code": null, "e": 657, "s": 388, "text": "Morgan: Morgan is an HTTP request level Middleware. It is a great tool that logs the requests along with some other information depending upon its configuration and the preset used. It proves to be very helpful while debugging and also if you want to create Log files." }, { "code": null, "e": 703, "s": 657, "text": "Prerequisites: Basic understanding of Nodejs." }, { "code": null, "e": 747, "s": 705, "text": "Creating Project and Module Installation:" }, { "code": null, "e": 830, "s": 747, "text": "Step 1: Create a new folder for a project using the following command:mkdir morgan" }, { "code": null, "e": 901, "s": 830, "text": "Step 1: Create a new folder for a project using the following command:" }, { "code": null, "e": 914, "s": 901, "text": "mkdir morgan" }, { "code": null, "e": 983, "s": 914, "text": "Step 2: Navigate to our folder using the following command:cd morgan" }, { "code": null, "e": 1043, "s": 983, "text": "Step 2: Navigate to our folder using the following command:" }, { "code": null, "e": 1053, "s": 1043, "text": "cd morgan" }, { "code": null, "e": 1147, "s": 1053, "text": "Step 3: Initialize npm using the following command and server file:npm init -y\ntouch index.js" }, { "code": null, "e": 1215, "s": 1147, "text": "Step 3: Initialize npm using the following command and server file:" }, { "code": null, "e": 1242, "s": 1215, "text": "npm init -y\ntouch index.js" }, { "code": null, "e": 1325, "s": 1242, "text": "Step 4: Install required packages using the following command:npm i express morgan" }, { "code": null, "e": 1388, "s": 1325, "text": "Step 4: Install required packages using the following command:" }, { "code": null, "e": 1409, "s": 1388, "text": "npm i express morgan" }, { "code": null, "e": 1461, "s": 1409, "text": "Project Structure: It will look like the following:" }, { "code": null, "e": 1507, "s": 1463, "text": "Example 1: Using dev as a preset in morgan." }, { "code": null, "e": 1518, "s": 1507, "text": "Javascript" }, { "code": "const express = require('express');const logger = require('morgan');const port = 3000; const app = express();app.use(logger('dev')); app.get('/', (req, res) => { res.send('<h1>Front Page</h1>');}); app.listen(port, () => { console.log(`Started at ${port}`);});", "e": 1784, "s": 1518, "text": null }, { "code": null, "e": 1847, "s": 1784, "text": "Steps to run: Run the application using the following command." }, { "code": null, "e": 1861, "s": 1847, "text": "node index.js" }, { "code": null, "e": 1958, "s": 1861, "text": "Output: To send the request, We use a browser, That request will be logged by our logger morgan." }, { "code": null, "e": 2012, "s": 1958, "text": "Then we will see the following output in our console." }, { "code": null, "e": 2096, "s": 2012, "text": "Information about the get request on the home route is logged with status code 200." }, { "code": null, "e": 2426, "s": 2096, "text": "Explanation: Basically in the above code, we set up morgan, and since it’s a middleware, So we used the .use() method to tell express to use that as a middleware in our app. Other than that we have used ‘dev’ as a preset. Some other presets available are combined, common, short, tiny. Each preset returns different information. " }, { "code": null, "e": 2509, "s": 2426, "text": "Example 2: In this example tiny is used as a preset inside morgan instead of dev. " }, { "code": null, "e": 2520, "s": 2509, "text": "Javascript" }, { "code": "const express = require('express');const logger = require('morgan');const port = 3000; const app = express();app.use(logger('tiny')); app.get('/', (req, res) => { res.send('<h1>Front Page</h1>');}); app.listen(port, () => { console.log(`Started at ${port}`);});", "e": 2787, "s": 2520, "text": null }, { "code": null, "e": 2850, "s": 2787, "text": "Steps to run: Run the application using the following command." }, { "code": null, "e": 2864, "s": 2850, "text": "node index.js" }, { "code": null, "e": 2961, "s": 2864, "text": "Output: To send the request, We use a browser, That request will be logged by our logger morgan." }, { "code": null, "e": 3015, "s": 2961, "text": "Then we will see the following output in our console." }, { "code": null, "e": 3196, "s": 3015, "text": "Explanation: In this 304 code is there, the Reason is since it is a simple static webpage, So browser cached it and returned its previous instance instead of making a new request. " }, { "code": null, "e": 3213, "s": 3196, "text": "NodeJS-Questions" }, { "code": null, "e": 3220, "s": 3213, "text": "Picked" }, { "code": null, "e": 3228, "s": 3220, "text": "Node.js" }, { "code": null, "e": 3245, "s": 3228, "text": "Web Technologies" } ]
Map in JavaScript
31 May, 2022 In this article, we would be discussing Map object provided by ES6. Map is a collection of elements where each element is stored as a Key, value pair. Map object can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key, value pair in the same order as inserted. Syntax: new Map([it]) Parameter: it - It is any iterable object whose values are stored as key, value pair, If the parameter is not specified then a new map is created is Empty Returns: A new Map object Now lets create some Map using the Map object Javascript // map1 contains// 1 => 2// 2 => 3// 4 -> 5var map1 = new Map([[1 , 2], [2 ,3 ] ,[4, 5]]); console.log("Map1");console.log(map1); // map2 contains// firstname => sumit// lastname => ghosh// website => geeksforgeeksvar map2 = new Map([["firstname" ,"sumit"], ["lastname", "ghosh"], ["website", "geeksforgeeks"]]); console.log("Map2");console.log(map2); // map3 contains// Whole number => [1, 2, 3, 4]// Decimal number => [1.1, 1.2, 1.3, 1.4]// Negative number => [-1, -2, -3, -4]var map3 = new Map([["whole numbers", [1 ,2 ,3 ,4]], ["Decimal numbers" , [1.1, 1.2, 1.3, 1.4]], ["negative numbers", [-1, -2, -3, -4]]]); console.log("Map3");console.log(map3); // map 4 contains// storing arrays both as key and value// "first name ", "Last name" => "sumit", "ghosh"// "friend 1", "sourav" => "friend 2", "gourav"var map4 = new Map([[["first name", "last name"], ["sumit", "ghosh"]], [["friend 1", "friend 2"], ["sourav","gourav"]]]); console.log("Map4");console.log(map4); Output: Properties: Map.prototype.size – It returns the number of elements or the key-value pairs in the map. Methods: 1. Map.prototype.set() – It adds the key and value to the Map Object. Syntax: map1.set(k, v); Parameters: k - Key of the element to be added to the Map v - value of the element to be added to the Map Returns: It returns a Map object 2. Map.prototype.has() – It return a boolean value depending on whether the specified key is present or not. Syntax: map1.has(k); Parameters: k - Key of the element to checked Returns: true if the element with the specified key is present or else returns false. 3. Map.prototype.get() – It returns the value of the corresponding key. Syntax: map1.get(k); Parameters: k - Key, whose value is to be returned Returns: The value associated with the key, if it is present in Map, otherwise returns undefined 4. Map.prototype.delete() – It delete’s both the key as well as a value from the map. Syntax: map1.delete(k); Parameters: k - Key which is to be deleted from the map Returns: true if the value is found and deleted from the map otherwise, it returns false 5. Map.prototype.clear() – Removes all the elements from the Map object. Syntax: map1.clear(); Parameters: No parameters Returns: undefined Lets use all the methods described above: Example: Javascript // Using Map.prototype.set(k, v)// creating an empty mapvar map1 = new Map(); // adding some elements to the mapmap1.set("first name", "sumit");map1.set("last name", "ghosh");map1.set("website", "geeksforgeeks") .set("friend 1","gourav") .set("friend 2","sourav"); // map1 contains// "first name" => "sumit"// "last name" => "ghosh"// "website" => "geeksforgeeks"// "friend 1" => "gourav"// "friend 2" => "sourav"console.log(map1); // Using Map.prototype.has(k) // returns trueconsole.log("map1 has website ? "+ map1.has("website")); // return falseconsole.log("map1 has friend 3 ? " + map1.has("friend 3")); // Using Map.prototype.get(k) // returns geeksforgeeksconsole.log("get value for key website "+ map1.get("website")); // returns undefinedconsole.log("get value for key friend 3 "+ map1.get("friend 3")); // Using Map.prototype.delete(k) // removes key "website" and its value from// the map// it prints the value of the keyconsole.log("delete element with key website " + map1.delete("website")); // as the value is deleted from// the map hence it returns falseconsole.log("map1 has website ? "+ map1.has("website")); // returns false as this key is not in the listconsole.log("delete element with key website " + map1.delete("friend 3")); // Using Map.prototype.clear()// removing all values from map1map1.clear(); // map1 is emptyconsole.log(map1); Output: 6. Map.prototype.entries() – It returns an iterator object that contains key/value pair for each element present in the Map object. Syntax: map1.entries(); Parameters: No parameters Returns: It returns an iterator object 7. Map.prototype.keys() – It returns an iterator object which contains all the keys present in the Map Object. Syntax: map1.keys(); Parameters: No parameter Returns: An iterator object 8. Map.prototype.values() – It returns an iterator object which contains all the values present in the Map Object. Syntax: map1.values(); Parameters: No parameter Returns: An iterator object Lets use all the methods described above: Example: Javascript // creating an empty mapvar map1 = new Map(); // adding some elements to the mapmap1.set("first name", "sumit");map1.set("last name", "ghosh");map1.set("website", "geeksforgeeks") .set("friend 1","gourav") .set("friend 2","sourav"); // Using Map.prototype.entries() // getting all the entries of the mapvar get_entries = map1.entries(); // it prints// ["first name", "sumit"]// ["last name", "ghosh"]// ["website", "geeksforgeeks"]// ["friend 1", "gourav"]// ["friend 2", "sourav"]console.log("----------entries---------");for(var ele of get_entries)console.log(ele); // Using Map.prototype.keys() // getting all the keys of the mapvar get_keys = map1.keys(); // it prints// "first name", "last name",// "website", "friend 1", "friend 2"console.log("--------keys----------");for(var ele of get_keys)console.log(ele); // Using Map.prototype.values() // getting all the values of the mapvar get_values = map1.values(); // it prints all the values// "sumit", "ghosh", "geeksforgeeks"// "gourav", "sourav"console.log("----------values------------");for(var ele of get_values)console.log(ele); Output: 9. Map.prototype.forEach() – It executes the callback function once for each key/value pair in the Map, in the insertion order. Syntax: map1.forEach(callback, [thisArgument]); Parameters: callback - It is a function that is to be executed for each element of the Map. thisargument - Value to be used as this when executing the callback. Returns: undefined The callback function is provided with three parameters as follows: the element key the element value the Map object to be traversed Example: Javascript // using Map.prototype.forEach()// creating an empty mapvar map1 = new Map(); // adding some elements to the map map1.set("first name", "sumit");map1.set("last name", "ghosh");map1.set("website", "geeksforgeeks") .set("friend 1", "gourav") .set("friend 2", "sourav"); // Declaring a call back function// we are using only one parameter value// so it will ignore other two .function printOne(values) { console.log(values);} // It prints value of all the element // of the setconsole.log("-----one parameter-----");map1.forEach(printOne); // Declaring a call back function// we are using two parameter value// so it will ignore last one function printTwo(values, key) { console.log(key + " " + values);} // As key and values are same in set// so it will print values twiceconsole.log("-----two parameter-----");map1.forEach(printTwo); // Declaring a call back function// we are using all three parameter valuefunction printThree(values, key, map) { // it will print key and value // and the set object console.log(key + " " + values); console.log(map);} // It prints key and value of each // element and the entire Map objectconsole.log("-----three parameter-----");map1.forEach(printThree); Output: Note: In the above example we use a simple callback function which just print an element in the console, it can be designed to perform any complex operation as per requirement. 10. Map.prototype[@@iterator]() – It returns an Map iterator function which is entries() method of Map object by default. Syntax: map1[Symbol.iterator] Parameters: No parameters Returns: Returns an map iterator object and it is entries() by default Example: Javascript // using Map.prototype[@@iterator]()// creating an empty mapvar map1 = new Map(); // adding some elements to the mapmap1.set("first name", "sumit");map1.set("last name", "ghosh");map1.set("website", "geeksforgeeks") .set("friend 1", "gourav") .set("friend 2", "sourav"); // By default this method returns the// same iterator object return by entries methodsvar getit = map1[Symbol.iterator](); // it prints// ["first name", "sumit"]// ["last name", "ghosh"]// ["website", "geeksforgeeks"]// ["friend 1", "gourav"]// ["friend 2", "sourav"]for(var elem of getit) console.log(elem); Output: 11. Map used to iterate over arrays Syntax: arr.map(function(value,index){}) Parameters: value = array element index = index of array Return: Modified valueo of elements Example: Javascript let arr = [1,2,3,4,5] let arr1 = []; //iterate over array and store in arr1arr1 = arr.map((value,idx)=>{ console.log("value "+value,"idx "+idx); return value*2;}) console.log();//original arrayconsole.log("arr= "+arr);//modified arrayconsole.log("arr1= "+arr1); Output: Note:- We can create a user define iterable rather than using the default one. Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map 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. Akanksha_Rai surindertarika1234 varshagumber28 rajeev0719singh sagar0719kumar prachisoda1234 surbhikumaridav sweetyty JavaScript-ES JavaScript 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 Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Roadmap to Learn JavaScript For Beginners How to get character array from string in JavaScript? How do you run JavaScript script through the Terminal? JavaScript | console.log() with Examples
[ { "code": null, "e": 54, "s": 26, "text": "\n31 May, 2022" }, { "code": null, "e": 381, "s": 54, "text": "In this article, we would be discussing Map object provided by ES6. Map is a collection of elements where each element is stored as a Key, value pair. Map object can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key, value pair in the same order as inserted." }, { "code": null, "e": 390, "s": 381, "text": "Syntax: " }, { "code": null, "e": 604, "s": 390, "text": "new Map([it])\n\nParameter:\nit - It is any iterable object whose values are stored as \n key, value pair,\n If the parameter is not specified then a new map is created \n is Empty\n\nReturns:\nA new Map object" }, { "code": null, "e": 651, "s": 604, "text": "Now lets create some Map using the Map object " }, { "code": null, "e": 662, "s": 651, "text": "Javascript" }, { "code": "// map1 contains// 1 => 2// 2 => 3// 4 -> 5var map1 = new Map([[1 , 2], [2 ,3 ] ,[4, 5]]); console.log(\"Map1\");console.log(map1); // map2 contains// firstname => sumit// lastname => ghosh// website => geeksforgeeksvar map2 = new Map([[\"firstname\" ,\"sumit\"], [\"lastname\", \"ghosh\"], [\"website\", \"geeksforgeeks\"]]); console.log(\"Map2\");console.log(map2); // map3 contains// Whole number => [1, 2, 3, 4]// Decimal number => [1.1, 1.2, 1.3, 1.4]// Negative number => [-1, -2, -3, -4]var map3 = new Map([[\"whole numbers\", [1 ,2 ,3 ,4]], [\"Decimal numbers\" , [1.1, 1.2, 1.3, 1.4]], [\"negative numbers\", [-1, -2, -3, -4]]]); console.log(\"Map3\");console.log(map3); // map 4 contains// storing arrays both as key and value// \"first name \", \"Last name\" => \"sumit\", \"ghosh\"// \"friend 1\", \"sourav\" => \"friend 2\", \"gourav\"var map4 = new Map([[[\"first name\", \"last name\"], [\"sumit\", \"ghosh\"]], [[\"friend 1\", \"friend 2\"], [\"sourav\",\"gourav\"]]]); console.log(\"Map4\");console.log(map4);", "e": 1695, "s": 662, "text": null }, { "code": null, "e": 1704, "s": 1695, "text": "Output: " }, { "code": null, "e": 1717, "s": 1704, "text": "Properties: " }, { "code": null, "e": 1807, "s": 1717, "text": "Map.prototype.size – It returns the number of elements or the key-value pairs in the map." }, { "code": null, "e": 1819, "s": 1807, "text": " Methods: " }, { "code": null, "e": 1890, "s": 1819, "text": "1. Map.prototype.set() – It adds the key and value to the Map Object. " }, { "code": null, "e": 1899, "s": 1890, "text": "Syntax: " }, { "code": null, "e": 2056, "s": 1899, "text": "map1.set(k, v);\n\nParameters:\nk - Key of the element to be added to the Map\nv - value of the element to be added to the Map\n\nReturns:\nIt returns a Map object" }, { "code": null, "e": 2165, "s": 2056, "text": "2. Map.prototype.has() – It return a boolean value depending on whether the specified key is present or not." }, { "code": null, "e": 2174, "s": 2165, "text": "Syntax: " }, { "code": null, "e": 2324, "s": 2174, "text": "map1.has(k);\n\nParameters:\nk - Key of the element to checked \n\nReturns:\ntrue if the element with the specified key is present \nor else returns false. " }, { "code": null, "e": 2396, "s": 2324, "text": "3. Map.prototype.get() – It returns the value of the corresponding key." }, { "code": null, "e": 2405, "s": 2396, "text": "Syntax: " }, { "code": null, "e": 2569, "s": 2405, "text": "map1.get(k);\n\nParameters:\nk - Key, whose value is to be returned\n\nReturns:\nThe value associated with the key, if it is present \nin Map, otherwise returns undefined" }, { "code": null, "e": 2656, "s": 2569, "text": "4. Map.prototype.delete() – It delete’s both the key as well as a value from the map. " }, { "code": null, "e": 2665, "s": 2656, "text": "Syntax: " }, { "code": null, "e": 2830, "s": 2665, "text": "map1.delete(k);\n\nParameters:\nk - Key which is to be deleted from the map \n\nReturns:\ntrue if the value is found and deleted from \nthe map otherwise, it returns false" }, { "code": null, "e": 2903, "s": 2830, "text": "5. Map.prototype.clear() – Removes all the elements from the Map object." }, { "code": null, "e": 2912, "s": 2903, "text": "Syntax: " }, { "code": null, "e": 2973, "s": 2912, "text": "map1.clear();\n\nParameters:\nNo parameters\n\nReturns:\nundefined" }, { "code": null, "e": 3016, "s": 2973, "text": "Lets use all the methods described above: " }, { "code": null, "e": 3026, "s": 3016, "text": "Example: " }, { "code": null, "e": 3037, "s": 3026, "text": "Javascript" }, { "code": "// Using Map.prototype.set(k, v)// creating an empty mapvar map1 = new Map(); // adding some elements to the mapmap1.set(\"first name\", \"sumit\");map1.set(\"last name\", \"ghosh\");map1.set(\"website\", \"geeksforgeeks\") .set(\"friend 1\",\"gourav\") .set(\"friend 2\",\"sourav\"); // map1 contains// \"first name\" => \"sumit\"// \"last name\" => \"ghosh\"// \"website\" => \"geeksforgeeks\"// \"friend 1\" => \"gourav\"// \"friend 2\" => \"sourav\"console.log(map1); // Using Map.prototype.has(k) // returns trueconsole.log(\"map1 has website ? \"+ map1.has(\"website\")); // return falseconsole.log(\"map1 has friend 3 ? \" + map1.has(\"friend 3\")); // Using Map.prototype.get(k) // returns geeksforgeeksconsole.log(\"get value for key website \"+ map1.get(\"website\")); // returns undefinedconsole.log(\"get value for key friend 3 \"+ map1.get(\"friend 3\")); // Using Map.prototype.delete(k) // removes key \"website\" and its value from// the map// it prints the value of the keyconsole.log(\"delete element with key website \" + map1.delete(\"website\")); // as the value is deleted from// the map hence it returns falseconsole.log(\"map1 has website ? \"+ map1.has(\"website\")); // returns false as this key is not in the listconsole.log(\"delete element with key website \" + map1.delete(\"friend 3\")); // Using Map.prototype.clear()// removing all values from map1map1.clear(); // map1 is emptyconsole.log(map1);", "e": 4550, "s": 3037, "text": null }, { "code": null, "e": 4559, "s": 4550, "text": "Output: " }, { "code": null, "e": 4692, "s": 4559, "text": "6. Map.prototype.entries() – It returns an iterator object that contains key/value pair for each element present in the Map object. " }, { "code": null, "e": 4701, "s": 4692, "text": "Syntax: " }, { "code": null, "e": 4785, "s": 4701, "text": "map1.entries();\n\nParameters:\nNo parameters\n\nReturns:\nIt returns an iterator object " }, { "code": null, "e": 4897, "s": 4785, "text": "7. Map.prototype.keys() – It returns an iterator object which contains all the keys present in the Map Object. " }, { "code": null, "e": 4906, "s": 4897, "text": "Syntax: " }, { "code": null, "e": 4975, "s": 4906, "text": "map1.keys();\n\nParameters:\nNo parameter\n\nReturns:\nAn iterator object " }, { "code": null, "e": 5091, "s": 4975, "text": "8. Map.prototype.values() – It returns an iterator object which contains all the values present in the Map Object. " }, { "code": null, "e": 5100, "s": 5091, "text": "Syntax: " }, { "code": null, "e": 5172, "s": 5100, "text": "map1.values();\n\nParameters:\nNo parameter\n\nReturns: \nAn iterator object " }, { "code": null, "e": 5215, "s": 5172, "text": "Lets use all the methods described above: " }, { "code": null, "e": 5225, "s": 5215, "text": "Example: " }, { "code": null, "e": 5236, "s": 5225, "text": "Javascript" }, { "code": "// creating an empty mapvar map1 = new Map(); // adding some elements to the mapmap1.set(\"first name\", \"sumit\");map1.set(\"last name\", \"ghosh\");map1.set(\"website\", \"geeksforgeeks\") .set(\"friend 1\",\"gourav\") .set(\"friend 2\",\"sourav\"); // Using Map.prototype.entries() // getting all the entries of the mapvar get_entries = map1.entries(); // it prints// [\"first name\", \"sumit\"]// [\"last name\", \"ghosh\"]// [\"website\", \"geeksforgeeks\"]// [\"friend 1\", \"gourav\"]// [\"friend 2\", \"sourav\"]console.log(\"----------entries---------\");for(var ele of get_entries)console.log(ele); // Using Map.prototype.keys() // getting all the keys of the mapvar get_keys = map1.keys(); // it prints// \"first name\", \"last name\",// \"website\", \"friend 1\", \"friend 2\"console.log(\"--------keys----------\");for(var ele of get_keys)console.log(ele); // Using Map.prototype.values() // getting all the values of the mapvar get_values = map1.values(); // it prints all the values// \"sumit\", \"ghosh\", \"geeksforgeeks\"// \"gourav\", \"sourav\"console.log(\"----------values------------\");for(var ele of get_values)console.log(ele);", "e": 6333, "s": 5236, "text": null }, { "code": null, "e": 6342, "s": 6333, "text": "Output: " }, { "code": null, "e": 6471, "s": 6342, "text": "9. Map.prototype.forEach() – It executes the callback function once for each key/value pair in the Map, in the insertion order. " }, { "code": null, "e": 6480, "s": 6471, "text": "Syntax: " }, { "code": null, "e": 6703, "s": 6480, "text": "map1.forEach(callback, [thisArgument]);\n\nParameters:\ncallback - It is a function that is to be executed for each element of the Map.\nthisargument - Value to be used as this when executing the callback.\n\nReturns:\nundefined" }, { "code": null, "e": 6772, "s": 6703, "text": "The callback function is provided with three parameters as follows: " }, { "code": null, "e": 6788, "s": 6772, "text": "the element key" }, { "code": null, "e": 6806, "s": 6788, "text": "the element value" }, { "code": null, "e": 6837, "s": 6806, "text": "the Map object to be traversed" }, { "code": null, "e": 6846, "s": 6837, "text": "Example:" }, { "code": null, "e": 6857, "s": 6846, "text": "Javascript" }, { "code": "// using Map.prototype.forEach()// creating an empty mapvar map1 = new Map(); // adding some elements to the map map1.set(\"first name\", \"sumit\");map1.set(\"last name\", \"ghosh\");map1.set(\"website\", \"geeksforgeeks\") .set(\"friend 1\", \"gourav\") .set(\"friend 2\", \"sourav\"); // Declaring a call back function// we are using only one parameter value// so it will ignore other two .function printOne(values) { console.log(values);} // It prints value of all the element // of the setconsole.log(\"-----one parameter-----\");map1.forEach(printOne); // Declaring a call back function// we are using two parameter value// so it will ignore last one function printTwo(values, key) { console.log(key + \" \" + values);} // As key and values are same in set// so it will print values twiceconsole.log(\"-----two parameter-----\");map1.forEach(printTwo); // Declaring a call back function// we are using all three parameter valuefunction printThree(values, key, map) { // it will print key and value // and the set object console.log(key + \" \" + values); console.log(map);} // It prints key and value of each // element and the entire Map objectconsole.log(\"-----three parameter-----\");map1.forEach(printThree);", "e": 8082, "s": 6857, "text": null }, { "code": null, "e": 8090, "s": 8082, "text": "Output:" }, { "code": null, "e": 8267, "s": 8090, "text": "Note: In the above example we use a simple callback function which just print an element in the console, it can be designed to perform any complex operation as per requirement." }, { "code": null, "e": 8390, "s": 8267, "text": "10. Map.prototype[@@iterator]() – It returns an Map iterator function which is entries() method of Map object by default. " }, { "code": null, "e": 8399, "s": 8390, "text": "Syntax: " }, { "code": null, "e": 8521, "s": 8399, "text": "map1[Symbol.iterator]\n\nParameters:\nNo parameters\n\nReturns:\nReturns an map iterator object and it is \nentries() by default" }, { "code": null, "e": 8531, "s": 8521, "text": "Example: " }, { "code": null, "e": 8542, "s": 8531, "text": "Javascript" }, { "code": "// using Map.prototype[@@iterator]()// creating an empty mapvar map1 = new Map(); // adding some elements to the mapmap1.set(\"first name\", \"sumit\");map1.set(\"last name\", \"ghosh\");map1.set(\"website\", \"geeksforgeeks\") .set(\"friend 1\", \"gourav\") .set(\"friend 2\", \"sourav\"); // By default this method returns the// same iterator object return by entries methodsvar getit = map1[Symbol.iterator](); // it prints// [\"first name\", \"sumit\"]// [\"last name\", \"ghosh\"]// [\"website\", \"geeksforgeeks\"]// [\"friend 1\", \"gourav\"]// [\"friend 2\", \"sourav\"]for(var elem of getit) console.log(elem);", "e": 9131, "s": 8542, "text": null }, { "code": null, "e": 9140, "s": 9131, "text": "Output: " }, { "code": null, "e": 9176, "s": 9140, "text": "11. Map used to iterate over arrays" }, { "code": null, "e": 9184, "s": 9176, "text": "Syntax:" }, { "code": null, "e": 9335, "s": 9184, "text": "arr.map(function(value,index){})\n\nParameters: \nvalue = array element\n index = index of array\n \nReturn:\nModified valueo of elements" }, { "code": null, "e": 9344, "s": 9335, "text": "Example:" }, { "code": null, "e": 9355, "s": 9344, "text": "Javascript" }, { "code": "let arr = [1,2,3,4,5] let arr1 = []; //iterate over array and store in arr1arr1 = arr.map((value,idx)=>{ console.log(\"value \"+value,\"idx \"+idx); return value*2;}) console.log();//original arrayconsole.log(\"arr= \"+arr);//modified arrayconsole.log(\"arr1= \"+arr1);", "e": 9623, "s": 9355, "text": null }, { "code": null, "e": 9631, "s": 9623, "text": "Output:" }, { "code": null, "e": 9712, "s": 9633, "text": "Note:- We can create a user define iterable rather than using the default one." }, { "code": null, "e": 9724, "s": 9712, "text": "Reference: " }, { "code": null, "e": 9810, "s": 9724, "text": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map " }, { "code": null, "e": 10029, "s": 9810, "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": 10042, "s": 10029, "text": "Akanksha_Rai" }, { "code": null, "e": 10061, "s": 10042, "text": "surindertarika1234" }, { "code": null, "e": 10076, "s": 10061, "text": "varshagumber28" }, { "code": null, "e": 10092, "s": 10076, "text": "rajeev0719singh" }, { "code": null, "e": 10107, "s": 10092, "text": "sagar0719kumar" }, { "code": null, "e": 10122, "s": 10107, "text": "prachisoda1234" }, { "code": null, "e": 10138, "s": 10122, "text": "surbhikumaridav" }, { "code": null, "e": 10147, "s": 10138, "text": "sweetyty" }, { "code": null, "e": 10161, "s": 10147, "text": "JavaScript-ES" }, { "code": null, "e": 10172, "s": 10161, "text": "JavaScript" }, { "code": null, "e": 10270, "s": 10172, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10331, "s": 10270, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 10403, "s": 10331, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 10443, "s": 10403, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 10484, "s": 10443, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 10536, "s": 10484, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 10582, "s": 10536, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 10624, "s": 10582, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 10678, "s": 10624, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 10733, "s": 10678, "text": "How do you run JavaScript script through the Terminal?" } ]
GATE | GATE CS 1999 | Question 12
06 Oct, 2017 A sorting technique is called stable if: (A) It takes O(nlog n)time(B) It maintains the relative order of occurrence of non-distinct elements(C) It uses divide and conquer paradigm(D) It takes O(n) spaceAnswer: (B)Explanation:Quiz of this QuestionPlease comment below if you find anything wrong in the above post GATE CS 1999 GATE-GATE CS 1999 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE CS 2008 | Question 46 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2014-(Set-1) | Question 51 GATE | GATE CS 1996 | Question 63 GATE | GATE-CS-2015 (Set 2) | Question 55 GATE | GATE-CS-2004 | Question 31 GATE | GATE-CS-2001 | Question 50
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Oct, 2017" }, { "code": null, "e": 69, "s": 28, "text": "A sorting technique is called stable if:" }, { "code": null, "e": 341, "s": 69, "text": "(A) It takes O(nlog n)time(B) It maintains the relative order of occurrence of non-distinct elements(C) It uses divide and conquer paradigm(D) It takes O(n) spaceAnswer: (B)Explanation:Quiz of this QuestionPlease comment below if you find anything wrong in the above post" }, { "code": null, "e": 354, "s": 341, "text": "GATE CS 1999" }, { "code": null, "e": 372, "s": 354, "text": "GATE-GATE CS 1999" }, { "code": null, "e": 377, "s": 372, "text": "GATE" }, { "code": null, "e": 475, "s": 377, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 517, "s": 475, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 579, "s": 517, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 613, "s": 579, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 655, "s": 613, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 697, "s": 655, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 739, "s": 697, "text": "GATE | GATE-CS-2014-(Set-1) | Question 51" }, { "code": null, "e": 773, "s": 739, "text": "GATE | GATE CS 1996 | Question 63" }, { "code": null, "e": 815, "s": 773, "text": "GATE | GATE-CS-2015 (Set 2) | Question 55" }, { "code": null, "e": 849, "s": 815, "text": "GATE | GATE-CS-2004 | Question 31" } ]