title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
jQuery UI | draggable() and droppable() methods - GeeksforGeeks
27 Oct, 2021 jQuery UI is a mixture of methods and a set of user interface effects, widgets, interactions and themes which can be provided in the web page using jQuery methods. If you want to build up a powerful web application that includes various features such as dragging, dropping, date picker, tooltips, etc. then jQuery UI is a perfect choice to build up these effects. In this article, we are going to learn about various jQuery UI interactions. This method allows the elements to be dragged with the help of mouse. Using jQuery UI, we can make the DOM(Document Object Model) elements to drag anywhere within the view port. This can be done by clicking on the draggable object by mouse and dragging it anywhere within the view port. Syntax: The draggable() method has two forms and the use of each form depends on the requirement. These are as follows :- $(selector, context).draggable (options); $(selector, context).draggable ("action", [params]); The following table shows the different options that can be used with this method: Example: In this example, the <div> with id=”d1′′ can be dragged anywhere within the view port, <div> with id=”d2′′ can be dragged along X axis and <div> with id=”d3′′ can be dragged along Y axis. Code #1: HTML <!doctype html><html><head><title>jQuery UI Draggable</title><link rel="stylesheet" href="//code.jquery.com/ui/ 1.12.1/themes/base/jquery-ui.css"><link rel="stylesheet" href="/resources/demos/style.css"><style type="text/css">#d1 { width: 120px; height: 120px; background-color :aqua; padding:20px; float:left; margin:5px; }#d2 { width: 120px; height: 120px; background-color :orange; padding:20px; float:left; margin:5px; }#d3 { width: 120px; height: 120px; background-color :yellow; padding:20px; float:left; margin:5px; }</style><script src="https://code.jquery.com/jquery-1.12.4.js"></script><script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script></head><body><h1>Welcome to GeeksforGeeks</h1><div id="d1"> <p>Drag Me Anywhere</p> </div><div id="d2"> <p>Drag Me Horizontally</p> </div><div id="d3"> <p>Drag Me Vertically</p> </div><script type="text/javascript">$( function() { $("#d1").draggable();} );$( function() { $("#d2").draggable({axis:"x"});} );$( function() { $("#d3").draggable({axis :"y"});} );</script></body></html> Output: Before Dragging After Dragging This method allows the elements to be dropped with the help of mouse. Using jQuery UI, we can make the DOM(Document Object Model) elements to drop anywhere within the view port on the specified target. This can be done by clicking on the draggable object by mouse and drop it on the specified target. Syntax: The droppable() method has two forms and the use of each form depends on the requirement. These are as follows :- $(selector, context).droppable (options) $(selector, context).droppable ("action", params) The following table shows the different options that can be used with this method: Example : In this example, the <div> with id=”drag” is dragged and dropped over the <div> with id=”drop”. Code #1: HTML <!doctype html><html lang="en"><head><title>jQuery UI Droppable</title><link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/ themes/base/jquery-ui.css"><link rel="stylesheet" href="/resources/demos/style.css"><style type="text/css">#drag { width: 100px; height: 100px; float: left; margin: 10px; background-color :aqua; padding:10px; }#drop { width: 150px; height: 150px; float: left; margin: 10px; background-color:yellow; padding:10px; }</style><script src="https://code.jquery.com/jquery-1.12.4.js"></script><script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script><script>$( function() { $( "#drag" ).draggable(); $( "#drop" ).droppable( { drop :function() { alert("I am dropped"); } } ); } );</script></head><body><center><h1 align="center">Welcome to GeeksforGeeks</h1><div id="drag"> <p>Drag Me</p> </div><div id="drop"> <p>Drop On Me</p> </div></center></body></html> Output: Before Dropping After Dropping Code #2: In this example, the <div> with id=”drag” is dragged and dropped over the <div> with id=”drop” and it cannot be dropped over the <div> with id=”non-drop”. HTML <!doctype html><html lang="en"><head><title>jQuery UI Droppable</title><link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/ themes/base/jquery-ui.css"><link rel="stylesheet" href="/resources/demos/style.css"><style type="text/css">#drag { width: 100px; height: 100px; float: left; margin: 10px; background-color :aqua; padding:10px; }#non-drop { width: 100px; height: 100px; float: left; margin: 10px; background-color :orange; padding:10px; }#drop { width: 150px; height: 150px; float: left; margin: 10px; background-color:yellow; padding:10px; } </style><script src="https://code.jquery.com/jquery-1.12.4.js"></script><script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script><script>$( function() { $( "#drag" ).draggable(); $( "#non-drop" ).draggable(); $( "#drop" ).droppable( { accept:"#drag", drop :function() { alert("I am dropped"); } } ); } ); </script></head><body><center><h1 align="center">Welcome to GeeksforGeeks</h1><div id="drag"> <p>Drag Me</p> </div><div id="non-drop"> <p>Non droppable</p> </div><div id="drop"> <p>Drop On Me</p> </div></center></body></html> Output: Before Dropping After Dropping jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”. You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. nidhi_biet surinderdawra388 simmytarika5 jQuery-Basics JavaScript JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to change the background color after clicking the button in JavaScript ? How to fetch data from JSON file and display in HTML table using jQuery ?
[ { "code": null, "e": 26288, "s": 26260, "text": "\n27 Oct, 2021" }, { "code": null, "e": 26731, "s": 26288, "text": "jQuery UI is a mixture of methods and a set of user interface effects, widgets, interactions and themes which can be provided in the web page using jQuery methods. If you want to build up a powerful web application that includes various features such as dragging, dropping, date picker, tooltips, etc. then jQuery UI is a perfect choice to build up these effects. In this article, we are going to learn about various jQuery UI interactions. " }, { "code": null, "e": 27019, "s": 26731, "text": "This method allows the elements to be dragged with the help of mouse. Using jQuery UI, we can make the DOM(Document Object Model) elements to drag anywhere within the view port. This can be done by clicking on the draggable object by mouse and dragging it anywhere within the view port. " }, { "code": null, "e": 27143, "s": 27019, "text": "Syntax: The draggable() method has two forms and the use of each form depends on the requirement. These are as follows :- " }, { "code": null, "e": 27185, "s": 27143, "text": "$(selector, context).draggable (options);" }, { "code": null, "e": 27238, "s": 27185, "text": "$(selector, context).draggable (\"action\", [params]);" }, { "code": null, "e": 27322, "s": 27238, "text": "The following table shows the different options that can be used with this method: " }, { "code": null, "e": 27520, "s": 27322, "text": "Example: In this example, the <div> with id=”d1′′ can be dragged anywhere within the view port, <div> with id=”d2′′ can be dragged along X axis and <div> with id=”d3′′ can be dragged along Y axis. " }, { "code": null, "e": 27530, "s": 27520, "text": "Code #1: " }, { "code": null, "e": 27535, "s": 27530, "text": "HTML" }, { "code": "<!doctype html><html><head><title>jQuery UI Draggable</title><link rel=\"stylesheet\" href=\"//code.jquery.com/ui/ 1.12.1/themes/base/jquery-ui.css\"><link rel=\"stylesheet\" href=\"/resources/demos/style.css\"><style type=\"text/css\">#d1 { width: 120px; height: 120px; background-color :aqua; padding:20px; float:left; margin:5px; }#d2 { width: 120px; height: 120px; background-color :orange; padding:20px; float:left; margin:5px; }#d3 { width: 120px; height: 120px; background-color :yellow; padding:20px; float:left; margin:5px; }</style><script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script><script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script></head><body><h1>Welcome to GeeksforGeeks</h1><div id=\"d1\"> <p>Drag Me Anywhere</p> </div><div id=\"d2\"> <p>Drag Me Horizontally</p> </div><div id=\"d3\"> <p>Drag Me Vertically</p> </div><script type=\"text/javascript\">$( function() { $(\"#d1\").draggable();} );$( function() { $(\"#d2\").draggable({axis:\"x\"});} );$( function() { $(\"#d3\").draggable({axis :\"y\"});} );</script></body></html> ", "e": 28725, "s": 27535, "text": null }, { "code": null, "e": 28734, "s": 28725, "text": "Output: " }, { "code": null, "e": 28751, "s": 28734, "text": "Before Dragging " }, { "code": null, "e": 28768, "s": 28751, "text": "After Dragging " }, { "code": null, "e": 29072, "s": 28770, "text": "This method allows the elements to be dropped with the help of mouse. Using jQuery UI, we can make the DOM(Document Object Model) elements to drop anywhere within the view port on the specified target. This can be done by clicking on the draggable object by mouse and drop it on the specified target. " }, { "code": null, "e": 29081, "s": 29072, "text": "Syntax: " }, { "code": null, "e": 29197, "s": 29081, "text": "The droppable() method has two forms and the use of each form depends on the requirement. These are as follows :- " }, { "code": null, "e": 29238, "s": 29197, "text": "$(selector, context).droppable (options)" }, { "code": null, "e": 29288, "s": 29238, "text": "$(selector, context).droppable (\"action\", params)" }, { "code": null, "e": 29373, "s": 29288, "text": "The following table shows the different options that can be used with this method: " }, { "code": null, "e": 29480, "s": 29373, "text": "Example : In this example, the <div> with id=”drag” is dragged and dropped over the <div> with id=”drop”. " }, { "code": null, "e": 29491, "s": 29480, "text": "Code #1: " }, { "code": null, "e": 29496, "s": 29491, "text": "HTML" }, { "code": "<!doctype html><html lang=\"en\"><head><title>jQuery UI Droppable</title><link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/ themes/base/jquery-ui.css\"><link rel=\"stylesheet\" href=\"/resources/demos/style.css\"><style type=\"text/css\">#drag { width: 100px; height: 100px; float: left; margin: 10px; background-color :aqua; padding:10px; }#drop { width: 150px; height: 150px; float: left; margin: 10px; background-color:yellow; padding:10px; }</style><script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script><script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script><script>$( function() { $( \"#drag\" ).draggable(); $( \"#drop\" ).droppable( { drop :function() { alert(\"I am dropped\"); } } ); } );</script></head><body><center><h1 align=\"center\">Welcome to GeeksforGeeks</h1><div id=\"drag\"> <p>Drag Me</p> </div><div id=\"drop\"> <p>Drop On Me</p> </div></center></body></html> ", "e": 30551, "s": 29496, "text": null }, { "code": null, "e": 30560, "s": 30551, "text": "Output: " }, { "code": null, "e": 30577, "s": 30560, "text": "Before Dropping " }, { "code": null, "e": 30594, "s": 30577, "text": "After Dropping " }, { "code": null, "e": 30759, "s": 30594, "text": "Code #2: In this example, the <div> with id=”drag” is dragged and dropped over the <div> with id=”drop” and it cannot be dropped over the <div> with id=”non-drop”. " }, { "code": null, "e": 30764, "s": 30759, "text": "HTML" }, { "code": "<!doctype html><html lang=\"en\"><head><title>jQuery UI Droppable</title><link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/ themes/base/jquery-ui.css\"><link rel=\"stylesheet\" href=\"/resources/demos/style.css\"><style type=\"text/css\">#drag { width: 100px; height: 100px; float: left; margin: 10px; background-color :aqua; padding:10px; }#non-drop { width: 100px; height: 100px; float: left; margin: 10px; background-color :orange; padding:10px; }#drop { width: 150px; height: 150px; float: left; margin: 10px; background-color:yellow; padding:10px; } </style><script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script><script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script><script>$( function() { $( \"#drag\" ).draggable(); $( \"#non-drop\" ).draggable(); $( \"#drop\" ).droppable( { accept:\"#drag\", drop :function() { alert(\"I am dropped\"); } } ); } ); </script></head><body><center><h1 align=\"center\">Welcome to GeeksforGeeks</h1><div id=\"drag\"> <p>Drag Me</p> </div><div id=\"non-drop\"> <p>Non droppable</p> </div><div id=\"drop\"> <p>Drop On Me</p> </div></center></body></html> ", "e": 32071, "s": 30764, "text": null }, { "code": null, "e": 32080, "s": 32071, "text": "Output: " }, { "code": null, "e": 32097, "s": 32080, "text": "Before Dropping " }, { "code": null, "e": 32114, "s": 32097, "text": "After Dropping " }, { "code": null, "e": 32289, "s": 32114, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”. " }, { "code": null, "e": 32384, "s": 32289, "text": "You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 32397, "s": 32386, "text": "nidhi_biet" }, { "code": null, "e": 32414, "s": 32397, "text": "surinderdawra388" }, { "code": null, "e": 32427, "s": 32414, "text": "simmytarika5" }, { "code": null, "e": 32441, "s": 32427, "text": "jQuery-Basics" }, { "code": null, "e": 32452, "s": 32441, "text": "JavaScript" }, { "code": null, "e": 32459, "s": 32452, "text": "JQuery" }, { "code": null, "e": 32476, "s": 32459, "text": "Web Technologies" }, { "code": null, "e": 32574, "s": 32476, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32614, "s": 32574, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32659, "s": 32614, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32720, "s": 32659, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 32792, "s": 32720, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 32844, "s": 32792, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 32890, "s": 32844, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 32919, "s": 32890, "text": "Form validation using jQuery" }, { "code": null, "e": 32982, "s": 32919, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 33059, "s": 32982, "text": "How to change the background color after clicking the button in JavaScript ?" } ]
PHP | Loops - GeeksforGeeks
09 Mar, 2018 Like any other language, loop in PHP is used to execute a statement or a block of statements, multiple times until and unless a specific condition is met. This helps the user to save both time and effort of writing the same code multiple times. PHP supports four types of looping techniques; for loopwhile loopdo-while loopforeach loop for loop while loop do-while loop foreach loop Let us now learn about each of the above mentioned loops in details: for loop: This type of loops is used when the user knows in advance, how many times the block needs to execute. That is, the number of iterations is known beforehand. These type of loops are also known as entry-controlled loops. There are three main parameters to the code, namely the initialization, the test condition and the counter.Syntax:for (initialization expression; test condition; update expression) { // code to be executed } In for loop, a loop variable is used to control the loop. First initialize this loop variable to some value, then check whether this variable is less than or greater than counter value. If statement is true, then loop body is executed and loop variable gets updated . Steps are repeated till exit condition comes.Initialization Expression: In this expression we have to initialize the loop counter to some value. for example: $num = 1;Test Expression: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of loop and go to update expression otherwise we will exit from the for loop. For example: $num <= 10;Update Expression: After executing loop body this expression increments/decrements the loop variable by some value. for example: $num += 2;Example:<?php // code to illustrate for loopfor ($num = 1; $num <= 10; $num += 2) { echo "$num \n";} ?>Output:1 3 5 7 9 Flow Diagram:while loop: The while loop is also an entry control loop like for loops i.e., it first checks the condition at the start of the loop and if its true then it enters the loop and executes the block of statements, and goes on executing it as long as the condition holds true.Syntax:while (if the condition is true) { // code is executed } Example:<?php // PHP code to illustrate while loops$num = 2; while ($num < 12) { $num += 2; echo $num, "\n";} ?>Output:4 6 8 10 12 Flowchart:do-while loop: This is an exit control loop which means that it first enters the loop, executes the statements, and then checks the condition. Therefore, a statement is executed at least once on using the do...while loop. After executing once, the program is executed as long as the condition holds true.Syntax:do { //code is executed } while (if condition is true); Example:<?php // PHP code to illustrate do...while loops$num = 2;do { $num += 2; echo $num, "\n";} while ($num < 12); ?>Output:4 6 8 10 12 This code would show the difference between while and do...while loop.<?php // PHP code to illustrate the difference of two loops$num = 2; // In case of whilewhile ($num != 2) { echo "In case of while the code is skipped"; echo $num, "\n"; }// In case of do...whiledo { $num++; echo "The do...while code is executed atleast once "; } while($num == 2); ?>Output:The code is executed at least once Flowchart:foreach loop: This loop is used to iterate over arrays. For every counter of loop, an array element is assigned and the next counter is shifted to the next element.Syntax:foreach (array_element as value) { //code to be executed } Example:<?php $arr = array (10, 20, 30, 40, 50, 60); foreach ($arr as $val) { echo "$val \n"; } $arr = array ("Ram", "Laxman", "Sita"); foreach ($arr as $val) { echo "$val \n"; } ?>Output:10 20 30 40 50 60 Ram Laxman Sita for loop: This type of loops is used when the user knows in advance, how many times the block needs to execute. That is, the number of iterations is known beforehand. These type of loops are also known as entry-controlled loops. There are three main parameters to the code, namely the initialization, the test condition and the counter.Syntax:for (initialization expression; test condition; update expression) { // code to be executed } In for loop, a loop variable is used to control the loop. First initialize this loop variable to some value, then check whether this variable is less than or greater than counter value. If statement is true, then loop body is executed and loop variable gets updated . Steps are repeated till exit condition comes.Initialization Expression: In this expression we have to initialize the loop counter to some value. for example: $num = 1;Test Expression: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of loop and go to update expression otherwise we will exit from the for loop. For example: $num <= 10;Update Expression: After executing loop body this expression increments/decrements the loop variable by some value. for example: $num += 2;Example:<?php // code to illustrate for loopfor ($num = 1; $num <= 10; $num += 2) { echo "$num \n";} ?>Output:1 3 5 7 9 Flow Diagram: Syntax: for (initialization expression; test condition; update expression) { // code to be executed } In for loop, a loop variable is used to control the loop. First initialize this loop variable to some value, then check whether this variable is less than or greater than counter value. If statement is true, then loop body is executed and loop variable gets updated . Steps are repeated till exit condition comes. Initialization Expression: In this expression we have to initialize the loop counter to some value. for example: $num = 1; Test Expression: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of loop and go to update expression otherwise we will exit from the for loop. For example: $num <= 10; Update Expression: After executing loop body this expression increments/decrements the loop variable by some value. for example: $num += 2; Example: <?php // code to illustrate for loopfor ($num = 1; $num <= 10; $num += 2) { echo "$num \n";} ?> Output: 1 3 5 7 9 Flow Diagram: while loop: The while loop is also an entry control loop like for loops i.e., it first checks the condition at the start of the loop and if its true then it enters the loop and executes the block of statements, and goes on executing it as long as the condition holds true.Syntax:while (if the condition is true) { // code is executed } Example:<?php // PHP code to illustrate while loops$num = 2; while ($num < 12) { $num += 2; echo $num, "\n";} ?>Output:4 6 8 10 12 Flowchart: Syntax: while (if the condition is true) { // code is executed } Example: <?php // PHP code to illustrate while loops$num = 2; while ($num < 12) { $num += 2; echo $num, "\n";} ?> Output: 4 6 8 10 12 Flowchart: do-while loop: This is an exit control loop which means that it first enters the loop, executes the statements, and then checks the condition. Therefore, a statement is executed at least once on using the do...while loop. After executing once, the program is executed as long as the condition holds true.Syntax:do { //code is executed } while (if condition is true); Example:<?php // PHP code to illustrate do...while loops$num = 2;do { $num += 2; echo $num, "\n";} while ($num < 12); ?>Output:4 6 8 10 12 This code would show the difference between while and do...while loop.<?php // PHP code to illustrate the difference of two loops$num = 2; // In case of whilewhile ($num != 2) { echo "In case of while the code is skipped"; echo $num, "\n"; }// In case of do...whiledo { $num++; echo "The do...while code is executed atleast once "; } while($num == 2); ?>Output:The code is executed at least once Flowchart: Syntax: do { //code is executed } while (if condition is true); Example: <?php // PHP code to illustrate do...while loops$num = 2;do { $num += 2; echo $num, "\n";} while ($num < 12); ?> Output: 4 6 8 10 12 This code would show the difference between while and do...while loop. <?php // PHP code to illustrate the difference of two loops$num = 2; // In case of whilewhile ($num != 2) { echo "In case of while the code is skipped"; echo $num, "\n"; }// In case of do...whiledo { $num++; echo "The do...while code is executed atleast once "; } while($num == 2); ?> Output: The code is executed at least once Flowchart: foreach loop: This loop is used to iterate over arrays. For every counter of loop, an array element is assigned and the next counter is shifted to the next element.Syntax:foreach (array_element as value) { //code to be executed } Example:<?php $arr = array (10, 20, 30, 40, 50, 60); foreach ($arr as $val) { echo "$val \n"; } $arr = array ("Ram", "Laxman", "Sita"); foreach ($arr as $val) { echo "$val \n"; } ?>Output:10 20 30 40 50 60 Ram Laxman Sita foreach (array_element as value) { //code to be executed } Example: <?php $arr = array (10, 20, 30, 40, 50, 60); foreach ($arr as $val) { echo "$val \n"; } $arr = array ("Ram", "Laxman", "Sita"); foreach ($arr as $val) { echo "$val \n"; } ?> Output: 10 20 30 40 50 60 Ram Laxman Sita This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. PHP-basics PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? PHP in_array() Function How to pop an alert message box using PHP ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 42164, "s": 42136, "text": "\n09 Mar, 2018" }, { "code": null, "e": 42409, "s": 42164, "text": "Like any other language, loop in PHP is used to execute a statement or a block of statements, multiple times until and unless a specific condition is met. This helps the user to save both time and effort of writing the same code multiple times." }, { "code": null, "e": 42456, "s": 42409, "text": "PHP supports four types of looping techniques;" }, { "code": null, "e": 42500, "s": 42456, "text": "for loopwhile loopdo-while loopforeach loop" }, { "code": null, "e": 42509, "s": 42500, "text": "for loop" }, { "code": null, "e": 42520, "s": 42509, "text": "while loop" }, { "code": null, "e": 42534, "s": 42520, "text": "do-while loop" }, { "code": null, "e": 42547, "s": 42534, "text": "foreach loop" }, { "code": null, "e": 42616, "s": 42547, "text": "Let us now learn about each of the above mentioned loops in details:" }, { "code": null, "e": 45963, "s": 42616, "text": "for loop: This type of loops is used when the user knows in advance, how many times the block needs to execute. That is, the number of iterations is known beforehand. These type of loops are also known as entry-controlled loops. There are three main parameters to the code, namely the initialization, the test condition and the counter.Syntax:for (initialization expression; test condition; update expression) {\n // code to be executed\n}\nIn for loop, a loop variable is used to control the loop. First initialize this loop variable to some value, then check whether this variable is less than or greater than counter value. If statement is true, then loop body is executed and loop variable gets updated . Steps are repeated till exit condition comes.Initialization Expression: In this expression we have to initialize the loop counter to some value. for example: $num = 1;Test Expression: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of loop and go to update expression otherwise we will exit from the for loop. For example: $num <= 10;Update Expression: After executing loop body this expression increments/decrements the loop variable by some value. for example: $num += 2;Example:<?php // code to illustrate for loopfor ($num = 1; $num <= 10; $num += 2) { echo \"$num \\n\";} ?>Output:1\n3\n5\n7\n9\nFlow Diagram:while loop: The while loop is also an entry control loop like for loops i.e., it first checks the condition at the start of the loop and if its true then it enters the loop and executes the block of statements, and goes on executing it as long as the condition holds true.Syntax:while (if the condition is true) {\n // code is executed\n}\nExample:<?php // PHP code to illustrate while loops$num = 2; while ($num < 12) { $num += 2; echo $num, \"\\n\";} ?>Output:4\n6\n8\n10\n12\nFlowchart:do-while loop: This is an exit control loop which means that it first enters the loop, executes the statements, and then checks the condition. Therefore, a statement is executed at least once on using the do...while loop. After executing once, the program is executed as long as the condition holds true.Syntax:do {\n\n //code is executed\n\n} while (if condition is true);\nExample:<?php // PHP code to illustrate do...while loops$num = 2;do { $num += 2; echo $num, \"\\n\";} while ($num < 12); ?>Output:4\n6\n8\n10\n12\nThis code would show the difference between while and do...while loop.<?php // PHP code to illustrate the difference of two loops$num = 2; // In case of whilewhile ($num != 2) { echo \"In case of while the code is skipped\"; echo $num, \"\\n\"; }// In case of do...whiledo { $num++; echo \"The do...while code is executed atleast once \"; } while($num == 2); ?>Output:The code is executed at least once \nFlowchart:foreach loop: This loop is used to iterate over arrays. For every counter of loop, an array element is assigned and the next counter is shifted to the next element.Syntax:foreach (array_element as value) {\n //code to be executed\n}\nExample:<?php $arr = array (10, 20, 30, 40, 50, 60); foreach ($arr as $val) { echo \"$val \\n\"; } $arr = array (\"Ram\", \"Laxman\", \"Sita\"); foreach ($arr as $val) { echo \"$val \\n\"; } ?>Output:10 \n20 \n30 \n40 \n50 \n60 \nRam \nLaxman \nSita \n" }, { "code": null, "e": 47353, "s": 45963, "text": "for loop: This type of loops is used when the user knows in advance, how many times the block needs to execute. That is, the number of iterations is known beforehand. These type of loops are also known as entry-controlled loops. There are three main parameters to the code, namely the initialization, the test condition and the counter.Syntax:for (initialization expression; test condition; update expression) {\n // code to be executed\n}\nIn for loop, a loop variable is used to control the loop. First initialize this loop variable to some value, then check whether this variable is less than or greater than counter value. If statement is true, then loop body is executed and loop variable gets updated . Steps are repeated till exit condition comes.Initialization Expression: In this expression we have to initialize the loop counter to some value. for example: $num = 1;Test Expression: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of loop and go to update expression otherwise we will exit from the for loop. For example: $num <= 10;Update Expression: After executing loop body this expression increments/decrements the loop variable by some value. for example: $num += 2;Example:<?php // code to illustrate for loopfor ($num = 1; $num <= 10; $num += 2) { echo \"$num \\n\";} ?>Output:1\n3\n5\n7\n9\nFlow Diagram:" }, { "code": null, "e": 47361, "s": 47353, "text": "Syntax:" }, { "code": null, "e": 47460, "s": 47361, "text": "for (initialization expression; test condition; update expression) {\n // code to be executed\n}\n" }, { "code": null, "e": 47774, "s": 47460, "text": "In for loop, a loop variable is used to control the loop. First initialize this loop variable to some value, then check whether this variable is less than or greater than counter value. If statement is true, then loop body is executed and loop variable gets updated . Steps are repeated till exit condition comes." }, { "code": null, "e": 47897, "s": 47774, "text": "Initialization Expression: In this expression we have to initialize the loop counter to some value. for example: $num = 1;" }, { "code": null, "e": 48132, "s": 47897, "text": "Test Expression: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of loop and go to update expression otherwise we will exit from the for loop. For example: $num <= 10;" }, { "code": null, "e": 48272, "s": 48132, "text": "Update Expression: After executing loop body this expression increments/decrements the loop variable by some value. for example: $num += 2;" }, { "code": null, "e": 48281, "s": 48272, "text": "Example:" }, { "code": "<?php // code to illustrate for loopfor ($num = 1; $num <= 10; $num += 2) { echo \"$num \\n\";} ?>", "e": 48384, "s": 48281, "text": null }, { "code": null, "e": 48392, "s": 48384, "text": "Output:" }, { "code": null, "e": 48403, "s": 48392, "text": "1\n3\n5\n7\n9\n" }, { "code": null, "e": 48417, "s": 48403, "text": "Flow Diagram:" }, { "code": null, "e": 48908, "s": 48417, "text": "while loop: The while loop is also an entry control loop like for loops i.e., it first checks the condition at the start of the loop and if its true then it enters the loop and executes the block of statements, and goes on executing it as long as the condition holds true.Syntax:while (if the condition is true) {\n // code is executed\n}\nExample:<?php // PHP code to illustrate while loops$num = 2; while ($num < 12) { $num += 2; echo $num, \"\\n\";} ?>Output:4\n6\n8\n10\n12\nFlowchart:" }, { "code": null, "e": 48916, "s": 48908, "text": "Syntax:" }, { "code": null, "e": 48978, "s": 48916, "text": "while (if the condition is true) {\n // code is executed\n}\n" }, { "code": null, "e": 48987, "s": 48978, "text": "Example:" }, { "code": "<?php // PHP code to illustrate while loops$num = 2; while ($num < 12) { $num += 2; echo $num, \"\\n\";} ?>", "e": 49101, "s": 48987, "text": null }, { "code": null, "e": 49109, "s": 49101, "text": "Output:" }, { "code": null, "e": 49122, "s": 49109, "text": "4\n6\n8\n10\n12\n" }, { "code": null, "e": 49133, "s": 49122, "text": "Flowchart:" }, { "code": null, "e": 50094, "s": 49133, "text": "do-while loop: This is an exit control loop which means that it first enters the loop, executes the statements, and then checks the condition. Therefore, a statement is executed at least once on using the do...while loop. After executing once, the program is executed as long as the condition holds true.Syntax:do {\n\n //code is executed\n\n} while (if condition is true);\nExample:<?php // PHP code to illustrate do...while loops$num = 2;do { $num += 2; echo $num, \"\\n\";} while ($num < 12); ?>Output:4\n6\n8\n10\n12\nThis code would show the difference between while and do...while loop.<?php // PHP code to illustrate the difference of two loops$num = 2; // In case of whilewhile ($num != 2) { echo \"In case of while the code is skipped\"; echo $num, \"\\n\"; }// In case of do...whiledo { $num++; echo \"The do...while code is executed atleast once \"; } while($num == 2); ?>Output:The code is executed at least once \nFlowchart:" }, { "code": null, "e": 50102, "s": 50094, "text": "Syntax:" }, { "code": null, "e": 50165, "s": 50102, "text": "do {\n\n //code is executed\n\n} while (if condition is true);\n" }, { "code": null, "e": 50174, "s": 50165, "text": "Example:" }, { "code": "<?php // PHP code to illustrate do...while loops$num = 2;do { $num += 2; echo $num, \"\\n\";} while ($num < 12); ?>", "e": 50295, "s": 50174, "text": null }, { "code": null, "e": 50303, "s": 50295, "text": "Output:" }, { "code": null, "e": 50316, "s": 50303, "text": "4\n6\n8\n10\n12\n" }, { "code": null, "e": 50387, "s": 50316, "text": "This code would show the difference between while and do...while loop." }, { "code": "<?php // PHP code to illustrate the difference of two loops$num = 2; // In case of whilewhile ($num != 2) { echo \"In case of while the code is skipped\"; echo $num, \"\\n\"; }// In case of do...whiledo { $num++; echo \"The do...while code is executed atleast once \"; } while($num == 2); ?>", "e": 50705, "s": 50387, "text": null }, { "code": null, "e": 50713, "s": 50705, "text": "Output:" }, { "code": null, "e": 50750, "s": 50713, "text": "The code is executed at least once \n" }, { "code": null, "e": 50761, "s": 50750, "text": "Flowchart:" }, { "code": null, "e": 51269, "s": 50761, "text": "foreach loop: This loop is used to iterate over arrays. For every counter of loop, an array element is assigned and the next counter is shifted to the next element.Syntax:foreach (array_element as value) {\n //code to be executed\n}\nExample:<?php $arr = array (10, 20, 30, 40, 50, 60); foreach ($arr as $val) { echo \"$val \\n\"; } $arr = array (\"Ram\", \"Laxman\", \"Sita\"); foreach ($arr as $val) { echo \"$val \\n\"; } ?>Output:10 \n20 \n30 \n40 \n50 \n60 \nRam \nLaxman \nSita \n" }, { "code": null, "e": 51332, "s": 51269, "text": "foreach (array_element as value) {\n //code to be executed\n}\n" }, { "code": null, "e": 51341, "s": 51332, "text": "Example:" }, { "code": "<?php $arr = array (10, 20, 30, 40, 50, 60); foreach ($arr as $val) { echo \"$val \\n\"; } $arr = array (\"Ram\", \"Laxman\", \"Sita\"); foreach ($arr as $val) { echo \"$val \\n\"; } ?>", "e": 51558, "s": 51341, "text": null }, { "code": null, "e": 51566, "s": 51558, "text": "Output:" }, { "code": null, "e": 51610, "s": 51566, "text": "10 \n20 \n30 \n40 \n50 \n60 \nRam \nLaxman \nSita \n" }, { "code": null, "e": 51911, "s": 51610, "text": "This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 52036, "s": 51911, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 52047, "s": 52036, "text": "PHP-basics" }, { "code": null, "e": 52051, "s": 52047, "text": "PHP" }, { "code": null, "e": 52068, "s": 52051, "text": "Web Technologies" }, { "code": null, "e": 52072, "s": 52068, "text": "PHP" }, { "code": null, "e": 52170, "s": 52072, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 52215, "s": 52170, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 52265, "s": 52215, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 52305, "s": 52265, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 52329, "s": 52305, "text": "PHP in_array() Function" }, { "code": null, "e": 52373, "s": 52329, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 52413, "s": 52373, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 52446, "s": 52413, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 52491, "s": 52446, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 52534, "s": 52491, "text": "How to fetch data from an API in ReactJS ?" } ]
Most frequent word in an array of strings - GeeksforGeeks
25 Feb, 2022 Given an array of words find the most occurring word in itExamples: Input : arr[] = {"geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks"} Output : Geeks "geeks" is the most frequent word as it occurs 3 times A simple solution is to run two loops and count occurrences of every word. Time complexity of this solution is O(n * n * MAX_WORD_LEN).An efficient solution is to use Trie data structure. The idea is simple first we will insert in trie. In trie, we keep counts of words ending at a node. We do preorder traversal and compare count present at each node and find the maximum occurring word CPP // CPP code to find most frequent word in// an array of strings#include <bits/stdc++.h>using namespace std; /*structing the trie*/struct Trie { string key; int cnt; unordered_map<char, Trie*> map;}; /* Function to return a new Trie node */Trie* getNewTrieNode(){ Trie* node = new Trie; node->cnt = 0; return node;} /* function to insert a string */void insert(Trie*& root, string& str){ // start from root node Trie* temp = root; for (int i = 0; i < str.length(); i++) { char x = str[i]; /*a new node if path doesn't exists*/ if (temp->map.find(x) == temp->map.end()) temp->map[x] = getNewTrieNode(); // go to next node temp = temp->map[x]; } // store key and its count in leaf nodes temp->key = str; temp->cnt += 1;} /* function for preorder traversal */bool preorder(Trie* temp, int& maxcnt, string& key){ if (temp == NULL) return false; for (auto it : temp->map) { /*leaf node will have non-zero count*/ if (maxcnt < it.second->cnt) { key = it.second->key; maxcnt = it.second->cnt; } // recurse for current node children preorder(it.second, maxcnt, key); }} void mostFrequentWord(string arr[], int n){ // Insert all words in a Trie Trie* root = getNewTrieNode(); for (int i = 0; i < n; i++) insert(root, arr[i]); // Do preorder traversal to find the // most frequent word string key; int cnt = 0; preorder(root, cnt, key); cout << "The word that occurs most is : " << key << endl; cout << "No of times: " << cnt << endl;} // Driver codeint main(){ // given set of keys string arr[] = { "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks" }; int n = sizeof(arr) / sizeof(arr[0]); mostFrequentWord(arr, n); return 0;} The word that occurs most is : geeks No of times: 3 Time Complexity: O(n * MAX_WORD_LEN)Another efficient solution is to use hashing. Please refer Find winner of an election where votes are represented as candidate names for details.More simple solution is to use HashMap. Approach: Using HashMap, one can keep track of word and it’s frequency. Next step includes iterate over it and find out the word with maximum frequency. Below is the implementation of the above approach. Java C# Javascript // Java implementationimport java.util.*; class GKG { // Function returns word with highest frequency static String findWord(String[] arr) { // Create HashMap to store word and it's frequency HashMap<String, Integer> hs = new HashMap<String, Integer>(); // Iterate through array of words for (int i = 0; i < arr.length; i++) { // If word already exist in HashMap then increase it's count by 1 if (hs.containsKey(arr[i])) { hs.put(arr[i], hs.get(arr[i]) + 1); } // Otherwise add word to HashMap else { hs.put(arr[i], 1); } } // Create set to iterate over HashMap Set<Map.Entry<String, Integer> > set = hs.entrySet(); String key = ""; int value = 0; for (Map.Entry<String, Integer> me : set) { // Check for word having highest frequency if (me.getValue() > value) { value = me.getValue(); key = me.getKey(); } } // Return word having highest frequency return key; } // Driver code public static void main(String[] args) { String arr[] = { "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks" }; String sol = findWord(arr); // Print word having highest frequency System.out.println(sol); }} // This code is contributed by Divyank Sheth // C# implementationusing System;using System.Collections.Generic; class GFG{ // Function returns word with highest frequency static String findWord(String[] arr) { // Create Dictionary to store word // and it's frequency Dictionary<String, int> hs = new Dictionary<String, int>(); // Iterate through array of words for (int i = 0; i < arr.Length; i++) { // If word already exist in Dictionary // then increase it's count by 1 if (hs.ContainsKey(arr[i])) { hs[arr[i]] = hs[arr[i]] + 1; } // Otherwise add word to Dictionary else { hs.Add(arr[i], 1); } } // Create set to iterate over Dictionary String key = ""; int value = 0; foreach(KeyValuePair<String, int> me in hs) { // Check for word having highest frequency if (me.Value > value) { value = me.Value; key = me.Key; } } // Return word having highest frequency return key; } // Driver code public static void Main(String[] args) { String []arr = { "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks" }; String sol = findWord(arr); // Print word having highest frequency Console.WriteLine(sol); }} // This code is contributed by Rajput-Ji <script> // JavaScript implementation // Function returns word with highest frequency function findWord(arr) { // Create Dictionary to store word // and it's frequency var hs = {}; // Iterate through array of words for (var i = 0; i < arr.length; i++) { // If word already exist in Dictionary // then increase it's count by 1 if (hs.hasOwnProperty(arr[i])) { hs[arr[i]] = hs[arr[i]] + 1; } // Otherwise add word to Dictionary else { hs[arr[i]] = 1; } } // Create set to iterate over Dictionary var Key = ""; var Value = 0; for (const [key, value] of Object.entries(hs)) { // Check for word having highest frequency if (value > Value) { Value = value; Key = key; } } // Return word having highest frequency return Key; } // Driver code var arr = [ "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks", ]; var sol = findWord(arr); // Print word having highest frequency document.write(sol); </script> geeks Another Efficient Approach( Using Trie Data Structure) Maintain a counter while inserting a word in Trie would avoid traversing Trie again Java C# import java.util.HashMap;import java.util.Map; public class TrieTest { class TrieNode { Map<Character, TrieNode> children; boolean endOfWord; int count; public TrieNode() { children = new HashMap<>(); endOfWord = false; count = 0; } } private TrieNode root = new TrieNode(); private int maxCount = Integer.MIN_VALUE; private String mostFrequentString; public void insert(String word) { TrieNode current = root; for(int i=0; i<word.length(); i++) { Character ch = word.charAt(i); if(current.children.size() == 0 || (!current.children.containsKey(ch))) { current.children.put(ch, new TrieNode()); } TrieNode child = current.children.get(ch); current = child; } current.endOfWord = true; current.count++; if (maxCount < current.count) { maxCount = current.count; mostFrequentString = word; } } public static void main(String[] args) { String [] words = { "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks" }; TrieTest test = new TrieTest(); for (String word : words) { test.insert(word); }// print max count and System.out.println(test.maxCount); System.out.println(test.mostFrequentString); }} using System;using System.Collections.Generic; public class TrieTest{ public class TrieNode { public Dictionary<char, TrieNode> children; public bool endOfWord; public int count; public TrieNode() { children = new Dictionary<char, TrieNode>(); endOfWord = false; count = 0; } } private TrieNode root = new TrieNode(); private int maxCount = int.MinValue; private String mostFrequentString; public void insert(String word) { TrieNode current = root; for (int i = 0; i < word.Length; i++) { char ch = word[i]; if (current.children.Count == 0 || (!current.children.ContainsKey(ch))) { current.children.Add(ch, new TrieNode()); } TrieNode child = current.children[ch]; current = child; } current.endOfWord = true; current.count++; if (maxCount < current.count) { maxCount = current.count; mostFrequentString = word; } } public static void Main(String[] args) { String[] words = { "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks" }; TrieTest test = new TrieTest(); foreach (String word in words) { test.insert(word); } // print max count and Console.WriteLine(test.maxCount); Console.WriteLine(test.mostFrequentString); }} // This code is contributed by Rajput-Ji 3 geeks Time complexity – time to insert words in Trie O(W*L) W – no of words, L – avg length of Strings Another Efficient Approach( Using Hash map in c++) C++ Java C# #include <bits/stdc++.h>using namespace std; // User function template for C++ class Solution {public: // Function to find most frequent word in an array of // strings. string mostFrequentWord(string arr[], int n) { unordered_map<string, int> m; unordered_map<string, int> m1; int max = 0; string result; int k = 1; for (int i = 0; i < n; i++) { if (m1.count(arr[i]) > 0) { continue; } m1[arr[i]] = k; k++; } for (int i = 0; i < n; i++) { m[arr[i]]++; if (max <= m[arr[i]]) { if (max < m[arr[i]]) { max = m[arr[i]]; result = arr[i]; } else { if (m1[result] < m1[arr[i]]) { max = m[arr[i]]; result = arr[i]; } } } } return result; }}; int main(){ string arr[] = { "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks" }; int n = sizeof(arr) / sizeof(arr[0]); Solution obj; cout << obj.mostFrequentWord(arr, n) << endl; return 0;} import java.util.*;class GFG { // User function template for Java // Function to find most frequent word in an array of // Strings. String mostFrequentWord(String arr[], int n) { HashMap<String, Integer> m = new HashMap<>(); HashMap<String, Integer> m1 = new HashMap<>(); int max = 0; String result=""; int k = 1; for (int i = 0; i < n; i++) { if (m1.containsKey(arr[i])) { continue; } m1.put(arr[i], k); k++; } for (int i = 0; i < n; i++) { if (m.containsKey(arr[i])) { m.put(arr[i], m.get(arr[i])+1); } else m.put(arr[i], +1); if (max <= m.get(arr[i])) { if (max < m.get(arr[i])) { max = m.get(arr[i]); result = arr[i]; } else { if (m1.get(result) < m1.get(arr[i])) { max = m.get(arr[i]); result = arr[i]; } } } } return result; } public static void main(String[] args) { String arr[] = { "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks" }; int n = arr.length; GFG obj = new GFG(); System.out.print(obj.mostFrequentWord(arr, n) + "\n"); }} // This code is contributed by Rajput-Ji // C# Program for the above approach using System;using System.Collections;using System.Collections.Generic; class Solution { // Function to find most frequent word in an array of // strings. static string mostFrequentWord(string []arr, int n) { Dictionary<string, int> m = new Dictionary<string, int>(); Dictionary<string, int> m1 = new Dictionary<string, int>(); int max = 0; string result = ""; int k = 1; for (int i = 0; i < n; i++) { if (m1.ContainsKey(arr[i])) { continue; } m1[arr[i]] = k; k++; } for (int i = 0; i < n; i++) { if(m.ContainsKey(arr[i])) { m[arr[i]] = m[arr[i]] + 1; } else { m.Add(arr[i], 1); } if (max <= m[arr[i]]) { if (max < m[arr[i]]) { max = m[arr[i]]; result = arr[i]; } else { if (m1[result] < m1[arr[i]]) { max = m[arr[i]]; result = arr[i]; } } } } return result; } public static void Main(){ string []arr = { "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks" }; int n = arr.Length; Console.Write(mostFrequentWord(arr, n)); }} // This code is contributed by Samim Hossain Mondal. geeks Time complexity : O(n) This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Divyank_Sheth 29AjayKumar rdtank abhijeet patwari ajaykadoula samim2000 Rajput-Ji Adobe Trie Arrays Hash Sorting Strings Adobe Arrays Hash Strings Sorting Trie Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Count pairs with given sum Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing)
[ { "code": null, "e": 26309, "s": 26281, "text": "\n25 Feb, 2022" }, { "code": null, "e": 26379, "s": 26309, "text": "Given an array of words find the most occurring word in itExamples: " }, { "code": null, "e": 26680, "s": 26379, "text": "Input : arr[] = {\"geeks\", \"for\", \"geeks\", \"a\", \n \"portal\", \"to\", \"learn\", \"can\",\n \"be\", \"computer\", \"science\", \n \"zoom\", \"yup\", \"fire\", \"in\", \n \"be\", \"data\", \"geeks\"}\nOutput : Geeks \n\"geeks\" is the most frequent word as it \noccurs 3 times" }, { "code": null, "e": 27071, "s": 26682, "text": "A simple solution is to run two loops and count occurrences of every word. Time complexity of this solution is O(n * n * MAX_WORD_LEN).An efficient solution is to use Trie data structure. The idea is simple first we will insert in trie. In trie, we keep counts of words ending at a node. We do preorder traversal and compare count present at each node and find the maximum occurring word " }, { "code": null, "e": 27075, "s": 27071, "text": "CPP" }, { "code": "// CPP code to find most frequent word in// an array of strings#include <bits/stdc++.h>using namespace std; /*structing the trie*/struct Trie { string key; int cnt; unordered_map<char, Trie*> map;}; /* Function to return a new Trie node */Trie* getNewTrieNode(){ Trie* node = new Trie; node->cnt = 0; return node;} /* function to insert a string */void insert(Trie*& root, string& str){ // start from root node Trie* temp = root; for (int i = 0; i < str.length(); i++) { char x = str[i]; /*a new node if path doesn't exists*/ if (temp->map.find(x) == temp->map.end()) temp->map[x] = getNewTrieNode(); // go to next node temp = temp->map[x]; } // store key and its count in leaf nodes temp->key = str; temp->cnt += 1;} /* function for preorder traversal */bool preorder(Trie* temp, int& maxcnt, string& key){ if (temp == NULL) return false; for (auto it : temp->map) { /*leaf node will have non-zero count*/ if (maxcnt < it.second->cnt) { key = it.second->key; maxcnt = it.second->cnt; } // recurse for current node children preorder(it.second, maxcnt, key); }} void mostFrequentWord(string arr[], int n){ // Insert all words in a Trie Trie* root = getNewTrieNode(); for (int i = 0; i < n; i++) insert(root, arr[i]); // Do preorder traversal to find the // most frequent word string key; int cnt = 0; preorder(root, cnt, key); cout << \"The word that occurs most is : \" << key << endl; cout << \"No of times: \" << cnt << endl;} // Driver codeint main(){ // given set of keys string arr[] = { \"geeks\", \"for\", \"geeks\", \"a\", \"portal\", \"to\", \"learn\", \"can\", \"be\", \"computer\", \"science\", \"zoom\", \"yup\", \"fire\", \"in\", \"be\", \"data\", \"geeks\" }; int n = sizeof(arr) / sizeof(arr[0]); mostFrequentWord(arr, n); return 0;}", "e": 29074, "s": 27075, "text": null }, { "code": null, "e": 29126, "s": 29074, "text": "The word that occurs most is : geeks\nNo of times: 3" }, { "code": null, "e": 29553, "s": 29126, "text": "Time Complexity: O(n * MAX_WORD_LEN)Another efficient solution is to use hashing. Please refer Find winner of an election where votes are represented as candidate names for details.More simple solution is to use HashMap. Approach: Using HashMap, one can keep track of word and it’s frequency. Next step includes iterate over it and find out the word with maximum frequency. Below is the implementation of the above approach. " }, { "code": null, "e": 29558, "s": 29553, "text": "Java" }, { "code": null, "e": 29561, "s": 29558, "text": "C#" }, { "code": null, "e": 29572, "s": 29561, "text": "Javascript" }, { "code": "// Java implementationimport java.util.*; class GKG { // Function returns word with highest frequency static String findWord(String[] arr) { // Create HashMap to store word and it's frequency HashMap<String, Integer> hs = new HashMap<String, Integer>(); // Iterate through array of words for (int i = 0; i < arr.length; i++) { // If word already exist in HashMap then increase it's count by 1 if (hs.containsKey(arr[i])) { hs.put(arr[i], hs.get(arr[i]) + 1); } // Otherwise add word to HashMap else { hs.put(arr[i], 1); } } // Create set to iterate over HashMap Set<Map.Entry<String, Integer> > set = hs.entrySet(); String key = \"\"; int value = 0; for (Map.Entry<String, Integer> me : set) { // Check for word having highest frequency if (me.getValue() > value) { value = me.getValue(); key = me.getKey(); } } // Return word having highest frequency return key; } // Driver code public static void main(String[] args) { String arr[] = { \"geeks\", \"for\", \"geeks\", \"a\", \"portal\", \"to\", \"learn\", \"can\", \"be\", \"computer\", \"science\", \"zoom\", \"yup\", \"fire\", \"in\", \"be\", \"data\", \"geeks\" }; String sol = findWord(arr); // Print word having highest frequency System.out.println(sol); }} // This code is contributed by Divyank Sheth", "e": 31176, "s": 29572, "text": null }, { "code": "// C# implementationusing System;using System.Collections.Generic; class GFG{ // Function returns word with highest frequency static String findWord(String[] arr) { // Create Dictionary to store word // and it's frequency Dictionary<String, int> hs = new Dictionary<String, int>(); // Iterate through array of words for (int i = 0; i < arr.Length; i++) { // If word already exist in Dictionary // then increase it's count by 1 if (hs.ContainsKey(arr[i])) { hs[arr[i]] = hs[arr[i]] + 1; } // Otherwise add word to Dictionary else { hs.Add(arr[i], 1); } } // Create set to iterate over Dictionary String key = \"\"; int value = 0; foreach(KeyValuePair<String, int> me in hs) { // Check for word having highest frequency if (me.Value > value) { value = me.Value; key = me.Key; } } // Return word having highest frequency return key; } // Driver code public static void Main(String[] args) { String []arr = { \"geeks\", \"for\", \"geeks\", \"a\", \"portal\", \"to\", \"learn\", \"can\", \"be\", \"computer\", \"science\", \"zoom\", \"yup\", \"fire\", \"in\", \"be\", \"data\", \"geeks\" }; String sol = findWord(arr); // Print word having highest frequency Console.WriteLine(sol); }} // This code is contributed by Rajput-Ji", "e": 32820, "s": 31176, "text": null }, { "code": "<script> // JavaScript implementation // Function returns word with highest frequency function findWord(arr) { // Create Dictionary to store word // and it's frequency var hs = {}; // Iterate through array of words for (var i = 0; i < arr.length; i++) { // If word already exist in Dictionary // then increase it's count by 1 if (hs.hasOwnProperty(arr[i])) { hs[arr[i]] = hs[arr[i]] + 1; } // Otherwise add word to Dictionary else { hs[arr[i]] = 1; } } // Create set to iterate over Dictionary var Key = \"\"; var Value = 0; for (const [key, value] of Object.entries(hs)) { // Check for word having highest frequency if (value > Value) { Value = value; Key = key; } } // Return word having highest frequency return Key; } // Driver code var arr = [ \"geeks\", \"for\", \"geeks\", \"a\", \"portal\", \"to\", \"learn\", \"can\", \"be\", \"computer\", \"science\", \"zoom\", \"yup\", \"fire\", \"in\", \"be\", \"data\", \"geeks\", ]; var sol = findWord(arr); // Print word having highest frequency document.write(sol); </script>", "e": 34223, "s": 32820, "text": null }, { "code": null, "e": 34229, "s": 34223, "text": "geeks" }, { "code": null, "e": 34284, "s": 34229, "text": "Another Efficient Approach( Using Trie Data Structure)" }, { "code": null, "e": 34368, "s": 34284, "text": "Maintain a counter while inserting a word in Trie would avoid traversing Trie again" }, { "code": null, "e": 34373, "s": 34368, "text": "Java" }, { "code": null, "e": 34376, "s": 34373, "text": "C#" }, { "code": "import java.util.HashMap;import java.util.Map; public class TrieTest { class TrieNode { Map<Character, TrieNode> children; boolean endOfWord; int count; public TrieNode() { children = new HashMap<>(); endOfWord = false; count = 0; } } private TrieNode root = new TrieNode(); private int maxCount = Integer.MIN_VALUE; private String mostFrequentString; public void insert(String word) { TrieNode current = root; for(int i=0; i<word.length(); i++) { Character ch = word.charAt(i); if(current.children.size() == 0 || (!current.children.containsKey(ch))) { current.children.put(ch, new TrieNode()); } TrieNode child = current.children.get(ch); current = child; } current.endOfWord = true; current.count++; if (maxCount < current.count) { maxCount = current.count; mostFrequentString = word; } } public static void main(String[] args) { String [] words = { \"geeks\", \"for\", \"geeks\", \"a\", \"portal\", \"to\", \"learn\", \"can\", \"be\", \"computer\", \"science\", \"zoom\", \"yup\", \"fire\", \"in\", \"be\", \"data\", \"geeks\" }; TrieTest test = new TrieTest(); for (String word : words) { test.insert(word); }// print max count and System.out.println(test.maxCount); System.out.println(test.mostFrequentString); }}", "e": 35761, "s": 34376, "text": null }, { "code": "using System;using System.Collections.Generic; public class TrieTest{ public class TrieNode { public Dictionary<char, TrieNode> children; public bool endOfWord; public int count; public TrieNode() { children = new Dictionary<char, TrieNode>(); endOfWord = false; count = 0; } } private TrieNode root = new TrieNode(); private int maxCount = int.MinValue; private String mostFrequentString; public void insert(String word) { TrieNode current = root; for (int i = 0; i < word.Length; i++) { char ch = word[i]; if (current.children.Count == 0 || (!current.children.ContainsKey(ch))) { current.children.Add(ch, new TrieNode()); } TrieNode child = current.children[ch]; current = child; } current.endOfWord = true; current.count++; if (maxCount < current.count) { maxCount = current.count; mostFrequentString = word; } } public static void Main(String[] args) { String[] words = { \"geeks\", \"for\", \"geeks\", \"a\", \"portal\", \"to\", \"learn\", \"can\", \"be\", \"computer\", \"science\", \"zoom\", \"yup\", \"fire\", \"in\", \"be\", \"data\", \"geeks\" }; TrieTest test = new TrieTest(); foreach (String word in words) { test.insert(word); } // print max count and Console.WriteLine(test.maxCount); Console.WriteLine(test.mostFrequentString); }} // This code is contributed by Rajput-Ji", "e": 37189, "s": 35761, "text": null }, { "code": null, "e": 37197, "s": 37189, "text": "3\ngeeks" }, { "code": null, "e": 37294, "s": 37197, "text": "Time complexity – time to insert words in Trie O(W*L) W – no of words, L – avg length of Strings" }, { "code": null, "e": 37347, "s": 37294, "text": "Another Efficient Approach( Using Hash map in c++) " }, { "code": null, "e": 37351, "s": 37347, "text": "C++" }, { "code": null, "e": 37356, "s": 37351, "text": "Java" }, { "code": null, "e": 37359, "s": 37356, "text": "C#" }, { "code": "#include <bits/stdc++.h>using namespace std; // User function template for C++ class Solution {public: // Function to find most frequent word in an array of // strings. string mostFrequentWord(string arr[], int n) { unordered_map<string, int> m; unordered_map<string, int> m1; int max = 0; string result; int k = 1; for (int i = 0; i < n; i++) { if (m1.count(arr[i]) > 0) { continue; } m1[arr[i]] = k; k++; } for (int i = 0; i < n; i++) { m[arr[i]]++; if (max <= m[arr[i]]) { if (max < m[arr[i]]) { max = m[arr[i]]; result = arr[i]; } else { if (m1[result] < m1[arr[i]]) { max = m[arr[i]]; result = arr[i]; } } } } return result; }}; int main(){ string arr[] = { \"geeks\", \"for\", \"geeks\", \"a\", \"portal\", \"to\", \"learn\", \"can\", \"be\", \"computer\", \"science\", \"zoom\", \"yup\", \"fire\", \"in\", \"be\", \"data\", \"geeks\" }; int n = sizeof(arr) / sizeof(arr[0]); Solution obj; cout << obj.mostFrequentWord(arr, n) << endl; return 0;}", "e": 38725, "s": 37359, "text": null }, { "code": "import java.util.*;class GFG { // User function template for Java // Function to find most frequent word in an array of // Strings. String mostFrequentWord(String arr[], int n) { HashMap<String, Integer> m = new HashMap<>(); HashMap<String, Integer> m1 = new HashMap<>(); int max = 0; String result=\"\"; int k = 1; for (int i = 0; i < n; i++) { if (m1.containsKey(arr[i])) { continue; } m1.put(arr[i], k); k++; } for (int i = 0; i < n; i++) { if (m.containsKey(arr[i])) { m.put(arr[i], m.get(arr[i])+1); } else m.put(arr[i], +1); if (max <= m.get(arr[i])) { if (max < m.get(arr[i])) { max = m.get(arr[i]); result = arr[i]; } else { if (m1.get(result) < m1.get(arr[i])) { max = m.get(arr[i]); result = arr[i]; } } } } return result; } public static void main(String[] args) { String arr[] = { \"geeks\", \"for\", \"geeks\", \"a\", \"portal\", \"to\", \"learn\", \"can\", \"be\", \"computer\", \"science\", \"zoom\", \"yup\", \"fire\", \"in\", \"be\", \"data\", \"geeks\" }; int n = arr.length; GFG obj = new GFG(); System.out.print(obj.mostFrequentWord(arr, n) + \"\\n\"); }} // This code is contributed by Rajput-Ji", "e": 40035, "s": 38725, "text": null }, { "code": "// C# Program for the above approach using System;using System.Collections;using System.Collections.Generic; class Solution { // Function to find most frequent word in an array of // strings. static string mostFrequentWord(string []arr, int n) { Dictionary<string, int> m = new Dictionary<string, int>(); Dictionary<string, int> m1 = new Dictionary<string, int>(); int max = 0; string result = \"\"; int k = 1; for (int i = 0; i < n; i++) { if (m1.ContainsKey(arr[i])) { continue; } m1[arr[i]] = k; k++; } for (int i = 0; i < n; i++) { if(m.ContainsKey(arr[i])) { m[arr[i]] = m[arr[i]] + 1; } else { m.Add(arr[i], 1); } if (max <= m[arr[i]]) { if (max < m[arr[i]]) { max = m[arr[i]]; result = arr[i]; } else { if (m1[result] < m1[arr[i]]) { max = m[arr[i]]; result = arr[i]; } } } } return result; } public static void Main(){ string []arr = { \"geeks\", \"for\", \"geeks\", \"a\", \"portal\", \"to\", \"learn\", \"can\", \"be\", \"computer\", \"science\", \"zoom\", \"yup\", \"fire\", \"in\", \"be\", \"data\", \"geeks\" }; int n = arr.Length; Console.Write(mostFrequentWord(arr, n)); }} // This code is contributed by Samim Hossain Mondal.", "e": 41669, "s": 40035, "text": null }, { "code": null, "e": 41675, "s": 41669, "text": "geeks" }, { "code": null, "e": 41698, "s": 41675, "text": "Time complexity : O(n)" }, { "code": null, "e": 42113, "s": 41698, "text": "This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 42127, "s": 42113, "text": "Divyank_Sheth" }, { "code": null, "e": 42139, "s": 42127, "text": "29AjayKumar" }, { "code": null, "e": 42146, "s": 42139, "text": "rdtank" }, { "code": null, "e": 42163, "s": 42146, "text": "abhijeet patwari" }, { "code": null, "e": 42175, "s": 42163, "text": "ajaykadoula" }, { "code": null, "e": 42185, "s": 42175, "text": "samim2000" }, { "code": null, "e": 42195, "s": 42185, "text": "Rajput-Ji" }, { "code": null, "e": 42201, "s": 42195, "text": "Adobe" }, { "code": null, "e": 42206, "s": 42201, "text": "Trie" }, { "code": null, "e": 42213, "s": 42206, "text": "Arrays" }, { "code": null, "e": 42218, "s": 42213, "text": "Hash" }, { "code": null, "e": 42226, "s": 42218, "text": "Sorting" }, { "code": null, "e": 42234, "s": 42226, "text": "Strings" }, { "code": null, "e": 42240, "s": 42234, "text": "Adobe" }, { "code": null, "e": 42247, "s": 42240, "text": "Arrays" }, { "code": null, "e": 42252, "s": 42247, "text": "Hash" }, { "code": null, "e": 42260, "s": 42252, "text": "Strings" }, { "code": null, "e": 42268, "s": 42260, "text": "Sorting" }, { "code": null, "e": 42273, "s": 42268, "text": "Trie" }, { "code": null, "e": 42371, "s": 42273, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42439, "s": 42371, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 42483, "s": 42439, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 42531, "s": 42483, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 42554, "s": 42531, "text": "Introduction to Arrays" }, { "code": null, "e": 42586, "s": 42554, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 42671, "s": 42586, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 42707, "s": 42671, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 42734, "s": 42707, "text": "Count pairs with given sum" }, { "code": null, "e": 42765, "s": 42734, "text": "Hashing | Set 1 (Introduction)" } ]
Python calendar module : formatmonth() method - GeeksforGeeks
04 Dec, 2020 Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. class calendar.TextCalendar(firstweekday=0) can be used to generate plain text calendars. formatmonth() method is one of the methods of TextCalendar instance. formatmonth() method in Python is used to get month’s calendar in a multi-line string. Syntax: formatmonth(year, month, width=0, lines=0) Parameter:year: year of the calendarmonth: month of the calendarwidth: [optional] Specifies the width of the date columns, which are centeredline: [optional] Specifies the number of lines that each week will use. Returns: Return a month’s calendar. Code #1: # Python program to demonstrate working of formatmonth() method # importing calendar moduleimport calendar text_cal = calendar.TextCalendar(firstweekday = 0) year = 2018month = 9# default value of width is 0 # printing formatmonthprint(text_cal.formatmonth(year, month)) Output: September 2018 Mo Tu We Th Fr Sa Su 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 28 29 30 Code #2: With parameter width # Python program to demonstrate working of formatmonth() method # importing calendar moduleimport calendar text_cal = calendar.TextCalendar(firstweekday = 0) # default value of width is 0 # printing formatmonthprint(text_cal.formatmonth(2018, 9, w = 5)) Output: September 2018 Mon Tue Wed Thu Fri Sat Sun 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 28 29 30 Code #3: # Python program to demonstrate working of formatmonth() method # importing calendar moduleimport calendar text_cal = calendar.TextCalendar(firstweekday = 0) # giving value of width = 6, line = 2 # printing formatmonthprint(text_cal.formatmonth(2018, 10, 6, 2)) Output: October 2018 Mon Tue Wed Thu Fri Sat Sun 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 28 29 30 31 Python Calander-module python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26419, "s": 26391, "text": "\n04 Dec, 2020" }, { "code": null, "e": 26691, "s": 26419, "text": "Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions." }, { "code": null, "e": 26850, "s": 26691, "text": "class calendar.TextCalendar(firstweekday=0) can be used to generate plain text calendars. formatmonth() method is one of the methods of TextCalendar instance." }, { "code": null, "e": 26937, "s": 26850, "text": "formatmonth() method in Python is used to get month’s calendar in a multi-line string." }, { "code": null, "e": 26988, "s": 26937, "text": "Syntax: formatmonth(year, month, width=0, lines=0)" }, { "code": null, "e": 27201, "s": 26988, "text": "Parameter:year: year of the calendarmonth: month of the calendarwidth: [optional] Specifies the width of the date columns, which are centeredline: [optional] Specifies the number of lines that each week will use." }, { "code": null, "e": 27237, "s": 27201, "text": "Returns: Return a month’s calendar." }, { "code": null, "e": 27246, "s": 27237, "text": "Code #1:" }, { "code": "# Python program to demonstrate working of formatmonth() method # importing calendar moduleimport calendar text_cal = calendar.TextCalendar(firstweekday = 0) year = 2018month = 9# default value of width is 0 # printing formatmonthprint(text_cal.formatmonth(year, month))", "e": 27521, "s": 27246, "text": null }, { "code": null, "e": 27529, "s": 27521, "text": "Output:" }, { "code": null, "e": 27674, "s": 27529, "text": " September 2018\nMo Tu We Th Fr Sa Su\n 1 2\n 3 4 5 6 7 8 9\n10 11 12 13 14 15 16\n17 18 19 20 21 22 23\n24 25 26 27 28 29 30\n" }, { "code": null, "e": 27706, "s": 27676, "text": "Code #2: With parameter width" }, { "code": "# Python program to demonstrate working of formatmonth() method # importing calendar moduleimport calendar text_cal = calendar.TextCalendar(firstweekday = 0) # default value of width is 0 # printing formatmonthprint(text_cal.formatmonth(2018, 9, w = 5))", "e": 27966, "s": 27706, "text": null }, { "code": null, "e": 27974, "s": 27966, "text": "Output:" }, { "code": null, "e": 28249, "s": 27974, "text": " September 2018\n Mon Tue Wed Thu Fri Sat Sun\n 1 2\n 3 4 5 6 7 8 9\n 10 11 12 13 14 15 16\n 17 18 19 20 21 22 23\n 24 25 26 27 28 29 30" }, { "code": null, "e": 28259, "s": 28249, "text": " Code #3:" }, { "code": "# Python program to demonstrate working of formatmonth() method # importing calendar moduleimport calendar text_cal = calendar.TextCalendar(firstweekday = 0) # giving value of width = 6, line = 2 # printing formatmonthprint(text_cal.formatmonth(2018, 10, 6, 2))", "e": 28527, "s": 28259, "text": null }, { "code": null, "e": 28535, "s": 28527, "text": "Output:" }, { "code": null, "e": 28826, "s": 28535, "text": " October 2018\n\n Mon Tue Wed Thu Fri Sat Sun\n\n 1 2 3 4 5 6 7\n\n 8 9 10 11 12 13 14\n\n 15 16 17 18 19 20 21\n\n 22 23 24 25 26 27 28\n\n 29 30 31" }, { "code": null, "e": 28849, "s": 28826, "text": "Python Calander-module" }, { "code": null, "e": 28864, "s": 28849, "text": "python-modules" }, { "code": null, "e": 28871, "s": 28864, "text": "Python" }, { "code": null, "e": 28969, "s": 28871, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28987, "s": 28969, "text": "Python Dictionary" }, { "code": null, "e": 29022, "s": 28987, "text": "Read a file line by line in Python" }, { "code": null, "e": 29054, "s": 29022, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29076, "s": 29054, "text": "Enumerate() in Python" }, { "code": null, "e": 29118, "s": 29076, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29148, "s": 29118, "text": "Iterate over a list in Python" }, { "code": null, "e": 29174, "s": 29148, "text": "Python String | replace()" }, { "code": null, "e": 29203, "s": 29174, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29247, "s": 29203, "text": "Reading and Writing to text files in Python" } ]
Matplotlib.axes.Axes.set_aspect() in Python - GeeksforGeeks
19 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.#Sample Code # Implementation of matplotlib function import matplotlib.pyplot as pltimport numpy as np # make an agg figurefig, ax = plt.subplots()ax.plot([1, 2, 3])ax.set_title('matplotlib.axes.Axes function')fig.canvas.draw()plt.show() Output: The Axes.set_aspect() function in axes module of matplotlib library is used to set the aspect of the axis scaling, i.e. the ratio of y-unit to x-unit. Syntax: Axes.set_aspect(self, aspect, adjustable=None, anchor=None, share=False) Parameters: This method accepts the following parameters. aspect : This parameter accepts the following value {‘auto’, ‘equal’} or num. adjustable : This defines which parameter will be adjusted to meet the required aspect. anchor : This parameter is used to define where the Axes will be drawn if there is extra space due to aspect constraints. share: This parameter is used to apply the settings to all shared Axes. Return value: This method does not return any value. Below examples illustrate the matplotlib.axes.Axes.set_aspect() function in matplotlib.axes: Example-1: # ImpleIn Reviewtation of matplotlib function import matplotlib.pyplot as plt fig, (ax1, ax2) = plt.subplots(1, 2)ax1.set_xscale("log")ax1.set_yscale("log")ax1.set_adjustable("datalim")ax1.plot([1, 3, 34, 4, 46, 3, 7, 45, 10], [1, 9, 27, 8, 29, 84, 78, 19, 48], "o-", color ="green")ax1.set_xlim(1e-1, 1e2)ax1.set_ylim(1, 1e2)ax1.set_title("No set_aspect") ax2.set_xscale("log")ax2.set_yscale("log")ax2.set_adjustable("datalim")ax2.plot([1, 3, 34, 4, 46, 3, 7, 45, 10], [1, 9, 27, 8, 29, 84, 78, 19, 48], "o-", color ="green") ax2.set_xlim(1e-1, 1e2)ax2.set_ylim(1, 1e2)ax2.set_aspect(2)ax2.set_title("set_aspect value = 2") fig.suptitle('matplotlib.axes.Axes.set_aspect() \function Example\n', fontweight ="bold")fig.canvas.draw()plt.show() Output: Example-2: # ImpleIn Reviewtation of matplotlib function import matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np n_angles = 20n_radii = 10min_radius = 2radii = np.linspace(min_radius, 0.95, n_radii) angles = np.linspace(0, 4 * np.pi, n_angles, endpoint = False)angles = np.repeat(angles[..., np.newaxis], n_radii, axis = 1)angles[:, 1::2] += np.pi / n_angles x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten() triang = tri.Triangulation(x, y) triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1), y[triang.triangles].mean(axis = 1)) < min_radius)fig, (ax, ax1) = plt.subplots(1, 2) ax.triplot(triang, 'bo-', lw = 1, color = "green")ax.set_title("No set_aspect") ax1.set_aspect('equal')ax1.triplot(triang, 'bo-', lw = 1, color = "green")ax1.set_title("set_aspect value ='equal'") fig.suptitle('matplotlib.axes.Axes.set_aspect() \function Example\n', fontweight ="bold")fig.canvas.draw()plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Convert integer to string in Python
[ { "code": null, "e": 26095, "s": 26067, "text": "\n19 Apr, 2020" }, { "code": null, "e": 26193, "s": 26095, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library." }, { "code": null, "e": 26407, "s": 26193, "text": "The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.#Sample Code" }, { "code": "# Implementation of matplotlib function import matplotlib.pyplot as pltimport numpy as np # make an agg figurefig, ax = plt.subplots()ax.plot([1, 2, 3])ax.set_title('matplotlib.axes.Axes function')fig.canvas.draw()plt.show()", "e": 26640, "s": 26407, "text": null }, { "code": null, "e": 26648, "s": 26640, "text": "Output:" }, { "code": null, "e": 26799, "s": 26648, "text": "The Axes.set_aspect() function in axes module of matplotlib library is used to set the aspect of the axis scaling, i.e. the ratio of y-unit to x-unit." }, { "code": null, "e": 26807, "s": 26799, "text": "Syntax:" }, { "code": null, "e": 26880, "s": 26807, "text": "Axes.set_aspect(self, aspect, adjustable=None, anchor=None, share=False)" }, { "code": null, "e": 26938, "s": 26880, "text": "Parameters: This method accepts the following parameters." }, { "code": null, "e": 27016, "s": 26938, "text": "aspect : This parameter accepts the following value {‘auto’, ‘equal’} or num." }, { "code": null, "e": 27104, "s": 27016, "text": "adjustable : This defines which parameter will be adjusted to meet the required aspect." }, { "code": null, "e": 27226, "s": 27104, "text": "anchor : This parameter is used to define where the Axes will be drawn if there is extra space due to aspect constraints." }, { "code": null, "e": 27298, "s": 27226, "text": "share: This parameter is used to apply the settings to all shared Axes." }, { "code": null, "e": 27351, "s": 27298, "text": "Return value: This method does not return any value." }, { "code": null, "e": 27444, "s": 27351, "text": "Below examples illustrate the matplotlib.axes.Axes.set_aspect() function in matplotlib.axes:" }, { "code": null, "e": 27455, "s": 27444, "text": "Example-1:" }, { "code": "# ImpleIn Reviewtation of matplotlib function import matplotlib.pyplot as plt fig, (ax1, ax2) = plt.subplots(1, 2)ax1.set_xscale(\"log\")ax1.set_yscale(\"log\")ax1.set_adjustable(\"datalim\")ax1.plot([1, 3, 34, 4, 46, 3, 7, 45, 10], [1, 9, 27, 8, 29, 84, 78, 19, 48], \"o-\", color =\"green\")ax1.set_xlim(1e-1, 1e2)ax1.set_ylim(1, 1e2)ax1.set_title(\"No set_aspect\") ax2.set_xscale(\"log\")ax2.set_yscale(\"log\")ax2.set_adjustable(\"datalim\")ax2.plot([1, 3, 34, 4, 46, 3, 7, 45, 10], [1, 9, 27, 8, 29, 84, 78, 19, 48], \"o-\", color =\"green\") ax2.set_xlim(1e-1, 1e2)ax2.set_ylim(1, 1e2)ax2.set_aspect(2)ax2.set_title(\"set_aspect value = 2\") fig.suptitle('matplotlib.axes.Axes.set_aspect() \\function Example\\n', fontweight =\"bold\")fig.canvas.draw()plt.show()", "e": 28234, "s": 27455, "text": null }, { "code": null, "e": 28242, "s": 28234, "text": "Output:" }, { "code": null, "e": 28253, "s": 28242, "text": "Example-2:" }, { "code": "# ImpleIn Reviewtation of matplotlib function import matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np n_angles = 20n_radii = 10min_radius = 2radii = np.linspace(min_radius, 0.95, n_radii) angles = np.linspace(0, 4 * np.pi, n_angles, endpoint = False)angles = np.repeat(angles[..., np.newaxis], n_radii, axis = 1)angles[:, 1::2] += np.pi / n_angles x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten() triang = tri.Triangulation(x, y) triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1), y[triang.triangles].mean(axis = 1)) < min_radius)fig, (ax, ax1) = plt.subplots(1, 2) ax.triplot(triang, 'bo-', lw = 1, color = \"green\")ax.set_title(\"No set_aspect\") ax1.set_aspect('equal')ax1.triplot(triang, 'bo-', lw = 1, color = \"green\")ax1.set_title(\"set_aspect value ='equal'\") fig.suptitle('matplotlib.axes.Axes.set_aspect() \\function Example\\n', fontweight =\"bold\")fig.canvas.draw()plt.show()", "e": 29279, "s": 28253, "text": null }, { "code": null, "e": 29287, "s": 29279, "text": "Output:" }, { "code": null, "e": 29305, "s": 29287, "text": "Python-matplotlib" }, { "code": null, "e": 29312, "s": 29305, "text": "Python" }, { "code": null, "e": 29410, "s": 29312, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29428, "s": 29410, "text": "Python Dictionary" }, { "code": null, "e": 29463, "s": 29428, "text": "Read a file line by line in Python" }, { "code": null, "e": 29495, "s": 29463, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29517, "s": 29495, "text": "Enumerate() in Python" }, { "code": null, "e": 29559, "s": 29517, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29589, "s": 29559, "text": "Iterate over a list in Python" }, { "code": null, "e": 29615, "s": 29589, "text": "Python String | replace()" }, { "code": null, "e": 29644, "s": 29615, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29688, "s": 29644, "text": "Reading and Writing to text files in Python" } ]
How to convert uppercase string to lowercase using PHP ? - GeeksforGeeks
19 May, 2021 The best way to convert uppercase string to lowercase in PHP is by using the strtolower() function. It takes the string as the input and converts it’s all characters to the lower case and returns the string value. Syntax: string strtolower( $string ) Return value: It returns the string converted into lower string. Example 1: PHP <?php echo strtolower("GeeksForGeeks")?> geeksforgeeks Example 2: PHP <?php $str = "Geeks For Geeks"; $lowerStr = strtolower($str); echo $lowerStr?> geeks for geeks Example 3: PHP <?php $str = "HelLo GeeKs hAve A wonDERful DaY"; echo strtolower($str);?> hello geeks have a wonderful day PHP-function PHP-Questions PHP-string Picked PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? PHP in_array() Function How to pop an alert message box using PHP ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 32651, "s": 32623, "text": "\n19 May, 2021" }, { "code": null, "e": 32865, "s": 32651, "text": "The best way to convert uppercase string to lowercase in PHP is by using the strtolower() function. It takes the string as the input and converts it’s all characters to the lower case and returns the string value." }, { "code": null, "e": 32873, "s": 32865, "text": "Syntax:" }, { "code": null, "e": 32902, "s": 32873, "text": "string strtolower( $string )" }, { "code": null, "e": 32967, "s": 32902, "text": "Return value: It returns the string converted into lower string." }, { "code": null, "e": 32978, "s": 32967, "text": "Example 1:" }, { "code": null, "e": 32982, "s": 32978, "text": "PHP" }, { "code": "<?php echo strtolower(\"GeeksForGeeks\")?>", "e": 33024, "s": 32982, "text": null }, { "code": null, "e": 33038, "s": 33024, "text": "geeksforgeeks" }, { "code": null, "e": 33049, "s": 33038, "text": "Example 2:" }, { "code": null, "e": 33053, "s": 33049, "text": "PHP" }, { "code": "<?php $str = \"Geeks For Geeks\"; $lowerStr = strtolower($str); echo $lowerStr?>", "e": 33141, "s": 33053, "text": null }, { "code": null, "e": 33157, "s": 33141, "text": "geeks for geeks" }, { "code": null, "e": 33168, "s": 33157, "text": "Example 3:" }, { "code": null, "e": 33172, "s": 33168, "text": "PHP" }, { "code": "<?php $str = \"HelLo GeeKs hAve A wonDERful DaY\"; echo strtolower($str);?>", "e": 33252, "s": 33172, "text": null }, { "code": null, "e": 33285, "s": 33252, "text": "hello geeks have a wonderful day" }, { "code": null, "e": 33298, "s": 33285, "text": "PHP-function" }, { "code": null, "e": 33312, "s": 33298, "text": "PHP-Questions" }, { "code": null, "e": 33323, "s": 33312, "text": "PHP-string" }, { "code": null, "e": 33330, "s": 33323, "text": "Picked" }, { "code": null, "e": 33334, "s": 33330, "text": "PHP" }, { "code": null, "e": 33351, "s": 33334, "text": "Web Technologies" }, { "code": null, "e": 33355, "s": 33351, "text": "PHP" }, { "code": null, "e": 33453, "s": 33355, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33498, "s": 33453, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 33548, "s": 33498, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 33588, "s": 33548, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 33612, "s": 33588, "text": "PHP in_array() Function" }, { "code": null, "e": 33656, "s": 33612, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 33696, "s": 33656, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33729, "s": 33696, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33774, "s": 33729, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33817, "s": 33774, "text": "How to fetch data from an API in ReactJS ?" } ]
Java Program for Number of pairs with maximum sum - GeeksforGeeks
13 Jan, 2022 Given an array arr[], count number of pairs arr[i], arr[j] such that arr[i] + arr[j] is maximum and i < j. Example : Input : arr[] = {1, 1, 1, 2, 2, 2} Output : 3 Explanation: The maximum possible pair sum where i Recommended: Please try your approach on {IDE} first, before moving on to the solution. Method 1 (Naive) Traverse a loop i from 0 to n, i.e length of the array and another loop j from i+1 to n to find all possible pairs with i Java Java // Java program to count pairs // with maximum sum. class GFG { // function to find the number of // maximum pair sums static int sum(int a[], int n) { // traverse through all the pairs int maxSum = Integer.MIN_VALUE; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) maxSum = Math.max(maxSum, a[i] + a[j]); // traverse through all pairs and // keep a count of the number of // maximum pairs int c = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (a[i] + a[j] == maxSum) c++; return c; } // driver program to test the above function public static void main(String[] args) { int array[] = { 1, 1, 1, 2, 2, 2 }; int n = array.length; System.out.println(sum(array, n)); } } // This code is contributed by Prerna Saini Output : 3Time complexity:O(n^2)Method 2 (Efficient) If we take a closer look, we can notice following facts. Maximum element is always part of solutionIf maximum element appears more than once, then result is maxCount * (maxCount - 1)/2. We basically need to choose 2 elements from maxCount (maxCountC2).If maximum element appears once, then result is equal to count of second maximum element. We can form a pair with every second max and maxJavaJava// Java program to count pairs // with maximum sum.import java.io.*;class GFG { // function to find the number // of maximum pair sumsstatic int sum(int a[], int n){ // Find maximum and second maximum // elements. Also find their counts. int maxVal = a[0], maxCount = 1; int secondMax = Integer.MIN_VALUE, secondMaxCount = 0; for (int i = 1; i < n; i++) { if (a[i] == maxVal) maxCount++; else if (a[i] > maxVal) { secondMax = maxVal; secondMaxCount = maxCount; maxVal = a[i]; maxCount = 1; } else if (a[i] == secondMax) { secondMax = a[i]; secondMaxCount++; } else if (a[i] > secondMax) { secondMax = a[i]; secondMaxCount = 1; } } // If maximum element appears // more than once. if (maxCount > 1) return maxCount * (maxCount - 1) / 2; // If maximum element appears // only once. return secondMaxCount;} // driver program public static void main(String[] args){ int array[] = { 1, 1, 1, 2, 2, 2, 3 }; int n = array.length; System.out.println(sum(array, n));}} // This code is contributed by Prerna SainiOutput : 3Time complexity:O(n) Please refer complete article on Number of pairs with maximum sum for more details!My Personal Notes arrow_drop_upSave Method 1 (Naive) Traverse a loop i from 0 to n, i.e length of the array and another loop j from i+1 to n to find all possible pairs with i Java // Java program to count pairs // with maximum sum. class GFG { // function to find the number of // maximum pair sums static int sum(int a[], int n) { // traverse through all the pairs int maxSum = Integer.MIN_VALUE; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) maxSum = Math.max(maxSum, a[i] + a[j]); // traverse through all pairs and // keep a count of the number of // maximum pairs int c = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (a[i] + a[j] == maxSum) c++; return c; } // driver program to test the above function public static void main(String[] args) { int array[] = { 1, 1, 1, 2, 2, 2 }; int n = array.length; System.out.println(sum(array, n)); } } // This code is contributed by Prerna Saini Output : 3 Time complexity:O(n^2) Method 2 (Efficient) If we take a closer look, we can notice following facts. Maximum element is always part of solutionIf maximum element appears more than once, then result is maxCount * (maxCount - 1)/2. We basically need to choose 2 elements from maxCount (maxCountC2).If maximum element appears once, then result is equal to count of second maximum element. We can form a pair with every second max and max Maximum element is always part of solution If maximum element appears more than once, then result is maxCount * (maxCount - 1)/2. We basically need to choose 2 elements from maxCount (maxCountC2). If maximum element appears once, then result is equal to count of second maximum element. We can form a pair with every second max and max Java // Java program to count pairs // with maximum sum.import java.io.*;class GFG { // function to find the number // of maximum pair sumsstatic int sum(int a[], int n){ // Find maximum and second maximum // elements. Also find their counts. int maxVal = a[0], maxCount = 1; int secondMax = Integer.MIN_VALUE, secondMaxCount = 0; for (int i = 1; i < n; i++) { if (a[i] == maxVal) maxCount++; else if (a[i] > maxVal) { secondMax = maxVal; secondMaxCount = maxCount; maxVal = a[i]; maxCount = 1; } else if (a[i] == secondMax) { secondMax = a[i]; secondMaxCount++; } else if (a[i] > secondMax) { secondMax = a[i]; secondMaxCount = 1; } } // If maximum element appears // more than once. if (maxCount > 1) return maxCount * (maxCount - 1) / 2; // If maximum element appears // only once. return secondMaxCount;} // driver program public static void main(String[] args){ int array[] = { 1, 1, 1, 2, 2, 2, 3 }; int n = array.length; System.out.println(sum(array, n));}} // This code is contributed by Prerna Saini Output : 3 Time complexity:O(n) Please refer complete article on Number of pairs with maximum sum for more details! Arrays Java Java Programs Searching Arrays Searching Java 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 Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples HashMap in Java with Examples
[ { "code": null, "e": 26041, "s": 26013, "text": "\n13 Jan, 2022" }, { "code": null, "e": 26148, "s": 26041, "text": "Given an array arr[], count number of pairs arr[i], arr[j] such that arr[i] + arr[j] is maximum and i < j." }, { "code": null, "e": 29593, "s": 26148, "text": "Example :\nInput : arr[] = {1, 1, 1, 2, 2, 2}\nOutput : 3\nExplanation: The maximum possible pair \nsum where i\nRecommended: Please try your approach on {IDE} first, before moving on to the solution.\nMethod 1 (Naive) Traverse a loop i from 0 to n, i.e length of the array and another loop j from i+1 to n to find all possible pairs with i\nJava\nJava\n\n\n\n\n\n\n\n \n\n \n \n\n \n\n \n \n \n \n\n\n\n\n\n\n\n\n\n\n// Java program to count pairs \n// with maximum sum. \nclass GFG { \n \n// function to find the number of \n// maximum pair sums \nstatic int sum(int a[], int n) \n{ \n // traverse through all the pairs \n int maxSum = Integer.MIN_VALUE; \n for (int i = 0; i < n; i++) \n for (int j = i + 1; j < n; j++) \n maxSum = Math.max(maxSum, a[i] + \n a[j]); \n \n // traverse through all pairs and \n // keep a count of the number of \n // maximum pairs \n int c = 0; \n for (int i = 0; i < n; i++) \n for (int j = i + 1; j < n; j++) \n if (a[i] + a[j] == maxSum) \n c++; \n return c; \n} \n \n// driver program to test the above function \npublic static void main(String[] args) \n{ \n int array[] = { 1, 1, 1, 2, 2, 2 }; \n int n = array.length; \n System.out.println(sum(array, n)); \n} \n} \n \n// This code is contributed by Prerna Saini \n\n\n\n\n\n\n\n\n\n\n \nOutput : 3Time complexity:O(n^2)Method 2 (Efficient) If we take a closer look, we can notice following facts. Maximum element is always part of solutionIf maximum element appears more than once, then result is maxCount * (maxCount - 1)/2. We basically need to choose 2 elements from maxCount (maxCountC2).If maximum element appears once, then result is equal to count of second maximum element. We can form a pair with every second max and maxJavaJava// Java program to count pairs // with maximum sum.import java.io.*;class GFG { // function to find the number // of maximum pair sumsstatic int sum(int a[], int n){ // Find maximum and second maximum // elements. Also find their counts. int maxVal = a[0], maxCount = 1; int secondMax = Integer.MIN_VALUE, secondMaxCount = 0; for (int i = 1; i < n; i++) { if (a[i] == maxVal) maxCount++; else if (a[i] > maxVal) { secondMax = maxVal; secondMaxCount = maxCount; maxVal = a[i]; maxCount = 1; } else if (a[i] == secondMax) { secondMax = a[i]; secondMaxCount++; } else if (a[i] > secondMax) { secondMax = a[i]; secondMaxCount = 1; } } // If maximum element appears // more than once. if (maxCount > 1) return maxCount * (maxCount - 1) / 2; // If maximum element appears // only once. return secondMaxCount;} // driver program public static void main(String[] args){ int array[] = { 1, 1, 1, 2, 2, 2, 3 }; int n = array.length; System.out.println(sum(array, n));}} // This code is contributed by Prerna SainiOutput : 3Time complexity:O(n) Please refer complete article on Number of pairs with maximum sum for more details!My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 29733, "s": 29593, "text": "Method 1 (Naive) Traverse a loop i from 0 to n, i.e length of the array and another loop j from i+1 to n to find all possible pairs with i\n" }, { "code": null, "e": 29738, "s": 29733, "text": "Java" }, { "code": "\n\n\n\n\n\n\n// Java program to count pairs \n// with maximum sum. \nclass GFG { \n \n// function to find the number of \n// maximum pair sums \nstatic int sum(int a[], int n) \n{ \n // traverse through all the pairs \n int maxSum = Integer.MIN_VALUE; \n for (int i = 0; i < n; i++) \n for (int j = i + 1; j < n; j++) \n maxSum = Math.max(maxSum, a[i] + \n a[j]); \n \n // traverse through all pairs and \n // keep a count of the number of \n // maximum pairs \n int c = 0; \n for (int i = 0; i < n; i++) \n for (int j = i + 1; j < n; j++) \n if (a[i] + a[j] == maxSum) \n c++; \n return c; \n} \n \n// driver program to test the above function \npublic static void main(String[] args) \n{ \n int array[] = { 1, 1, 1, 2, 2, 2 }; \n int n = array.length; \n System.out.println(sum(array, n)); \n} \n} \n \n// This code is contributed by Prerna Saini \n\n\n\n\n\n", "e": 30936, "s": 29995, "text": null }, { "code": null, "e": 30946, "s": 30936, "text": "Output : " }, { "code": null, "e": 30948, "s": 30946, "text": "3" }, { "code": null, "e": 30971, "s": 30948, "text": "Time complexity:O(n^2)" }, { "code": null, "e": 31050, "s": 30971, "text": "Method 2 (Efficient) If we take a closer look, we can notice following facts. " }, { "code": null, "e": 31384, "s": 31050, "text": "Maximum element is always part of solutionIf maximum element appears more than once, then result is maxCount * (maxCount - 1)/2. We basically need to choose 2 elements from maxCount (maxCountC2).If maximum element appears once, then result is equal to count of second maximum element. We can form a pair with every second max and max" }, { "code": null, "e": 31427, "s": 31384, "text": "Maximum element is always part of solution" }, { "code": null, "e": 31581, "s": 31427, "text": "If maximum element appears more than once, then result is maxCount * (maxCount - 1)/2. We basically need to choose 2 elements from maxCount (maxCountC2)." }, { "code": null, "e": 31720, "s": 31581, "text": "If maximum element appears once, then result is equal to count of second maximum element. We can form a pair with every second max and max" }, { "code": null, "e": 31725, "s": 31720, "text": "Java" }, { "code": "// Java program to count pairs // with maximum sum.import java.io.*;class GFG { // function to find the number // of maximum pair sumsstatic int sum(int a[], int n){ // Find maximum and second maximum // elements. Also find their counts. int maxVal = a[0], maxCount = 1; int secondMax = Integer.MIN_VALUE, secondMaxCount = 0; for (int i = 1; i < n; i++) { if (a[i] == maxVal) maxCount++; else if (a[i] > maxVal) { secondMax = maxVal; secondMaxCount = maxCount; maxVal = a[i]; maxCount = 1; } else if (a[i] == secondMax) { secondMax = a[i]; secondMaxCount++; } else if (a[i] > secondMax) { secondMax = a[i]; secondMaxCount = 1; } } // If maximum element appears // more than once. if (maxCount > 1) return maxCount * (maxCount - 1) / 2; // If maximum element appears // only once. return secondMaxCount;} // driver program public static void main(String[] args){ int array[] = { 1, 1, 1, 2, 2, 2, 3 }; int n = array.length; System.out.println(sum(array, n));}} // This code is contributed by Prerna Saini", "e": 32948, "s": 31725, "text": null }, { "code": null, "e": 32959, "s": 32948, "text": "Output : " }, { "code": null, "e": 32961, "s": 32959, "text": "3" }, { "code": null, "e": 32983, "s": 32961, "text": "Time complexity:O(n) " }, { "code": null, "e": 33067, "s": 32983, "text": "Please refer complete article on Number of pairs with maximum sum for more details!" }, { "code": null, "e": 33074, "s": 33067, "text": "Arrays" }, { "code": null, "e": 33079, "s": 33074, "text": "Java" }, { "code": null, "e": 33093, "s": 33079, "text": "Java Programs" }, { "code": null, "e": 33103, "s": 33093, "text": "Searching" }, { "code": null, "e": 33110, "s": 33103, "text": "Arrays" }, { "code": null, "e": 33120, "s": 33110, "text": "Searching" }, { "code": null, "e": 33125, "s": 33120, "text": "Java" }, { "code": null, "e": 33223, "s": 33125, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33250, "s": 33223, "text": "Count pairs with given sum" }, { "code": null, "e": 33281, "s": 33250, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 33306, "s": 33281, "text": "Window Sliding Technique" }, { "code": null, "e": 33344, "s": 33306, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 33365, "s": 33344, "text": "Next Greater Element" }, { "code": null, "e": 33409, "s": 33365, "text": "Split() String method in Java with examples" }, { "code": null, "e": 33431, "s": 33409, "text": "For-each loop in Java" }, { "code": null, "e": 33482, "s": 33431, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 33518, "s": 33482, "text": "Arrays.sort() in Java with examples" } ]
Windows Forensic Analysis - GeeksforGeeks
28 Oct, 2021 When doing Windows Forensic Analysis, it can be quite overwhelming to see a large amount of data that one needs to collect, assuming you know what you are looking for. In case you don’t know what are you looking for, the entire process becomes twice as hard. In this article we will be discussing following topics: What is Windows Forensic Analysis?What are Forensic Artifacts?Top Open-Source Tools for Windows Forensic Analysis What is Windows Forensic Analysis? What are Forensic Artifacts? Top Open-Source Tools for Windows Forensic Analysis Windows Forensic Analysis focuses on 2 things: In-depth analysis of Windows Operating System.Analysis of Windows System Artifacts. In-depth analysis of Windows Operating System. Analysis of Windows System Artifacts. Windows artifacts are the objects which hold information about the activities that are performed by the Windows user. The type of information and the location of the artifact varies from one operating system to another. Windows artifacts contain sensitive information that is collected and analyzed at the time of forensic analysis. Forensic artifacts are the forensic objects that have some forensic value. Any object that contains some data or evidence of something that has occurred like logs, register, hives, and many more. In this section, we will be going through some of the forensic artifacts that a forensic investigator look for while performing a Forensic analysis in Windows. 1. Recylce Bin: The windows recycle bin contains some great artifacts like: $1 file containing the metadata. You can find this file under the path C:\$Recycle.Bin\SID*\$Ixxxxxx $R file containing the contents of the deleted files. This file can be located under the path C:\$Recycle.Bin\SID*\$Rxxxxxx $1 file can be parsed using a tool $1 Parse. 2. Browsers: Web browsers contain a lot of information like: Cookies. Cached website data. Downloaded files. 3. Windows Error Reporting: This features enables user to inform Microsoft about application faults, kernel faults, unresponsive application, and other application specific problems. This feature provides us with various artifacts like: Program Execution, if a malicious program crashes during program execution. You can locate these artifacts at the following locations:C:\ProgramData\Microsoft\Windows\WER\ReportArchive C:\Users\XXX\AppData\Local\Microsoft\Windows\WER\ReportArchive C:\ProgramData\Microsoft\Windows\WER\ReportQueue C:\Users\XXX\AppData\Local\Microsoft\Windows\WER\ReportQueue C:\ProgramData\Microsoft\Windows\WER\ReportArchive C:\Users\XXX\AppData\Local\Microsoft\Windows\WER\ReportArchive C:\ProgramData\Microsoft\Windows\WER\ReportQueue C:\Users\XXX\AppData\Local\Microsoft\Windows\WER\ReportQueue 4. Remote Desktop Protocol Cache: When using the “mstc” client that is provided by the Windows, RDP can be used to move laterally through the network. Cache files are created containing the sections of the screen of the machine to which we are connected to and that is rarely changing. These cache files can be located in the directory: C:\Users\XXX\AppData\Local\Microsoft\Terminal Server Client\Cache Tools like BMC-Tools can be used to extract images stored in these cache files. 5. LNK Files: .lnk files are the windows shortcut files. LNK files link or point to other files or executables for ease of access. You can find following information in these files: The original path of the target file. Timestamp of both the target files and the .lnk files. File Attributes like System, Hidden, etc. Details about the disk. Remote or local execution. MAC address of the machines. You can use tools like Windows LNK Parsing Library or LECmd to parse the contents of these files. 6. Jump Lists: They contain information about the recently accessed applications and files. This feature was introduced with Windows 7. Two types of Jump Lists can be created in Windows: AUTOMATICDESTINATIONS-MS: These jump lists are created automatically when a user opens a file or an application. They are located under the path:C:\Users\xxx\AppData\Roaming\Microsoft\Windows\Recent\AutomaticDestinations CUSTOMDESTINATIONS-MS: These jump lists are custom made and are created when a user pins a file or an application. They are located under the directory C:\Users\xxx\AppData\Roaming\Microsoft\Windows\Recent\CustomDestinations You can use tools like JumpList Explorer, JLECmd, or Windows JumpList Parser to parse Jump lists. 7. Prefetch Files: These files contain a wealth of information like: Application Name. Application path. Last execution timestamp. Creation timestamp. These files can be located under the directory: C:\Windows\Prefetch\. You can use tools like Windows Prefetch Parser, WinPrefetchView, or PECmd. In this section, we will be discussing some of the open-source tools that are available for conducting Forensic Analysis in the Windows Operating System. 1. Magnet Encrypted Disk Detector: This tool is used to check the encrypted physical drives. This tool supports PGP, Safe boot encrypted volumes, Bitlocker, etc. You can download it from here. 2. Magnet RAM Capture: This tool is used to analyze the physical memory of the system. You can download it from here. 3. Wireshark: This is a network analyzer tool and a capture tool that is used to see what traffic is going in your network. You can download it from here. 4. RAM Capture: As the name suggests, this is a free tool that is used to extract the entire contents of the volatile memory i.e. RAM. You can download it from here. 5. NMAP: This is the most popular tool that is used to find open ports on the target machine. Using this tool you can find the vulnerability of any target to hack. You can download it from here. 6. Network Miner: This tool is used as a passive network sniffer to capture or to detect the operating systems ports, sessions, hostnames, etc. You can download it from here. 7. Autopsy: This is the GUI based tool, that is used to analyze hard disks and smartphones. You can download it from here. 8. Forensic Investigator: This is a Splunk toolkit which is used in HEX conversion, Base64 conversion, metascan lookups, and many more other features that are essential in forensic analysis. You can download it from here. 9. HashMyFiles: This tool is used to calculate the SHA1 and MD5 hashes. It works on all the latest websites. You can download it from here. 10. Crowd Response: This tool is used to gather the system information for incident response. You can download it from here. 11. ExifTool: This tool is used to read, write, and edit meta information from a number of files. You can download it from here. 12. FAW (Forensic Acquisition of Websites): This tool is used to acquire web pages image, HTML, source code of the web page. This tool can be integrated with Wireshark. You can download it from here. There is such a large variety of forensic tools available in the market. Some are free and open-source and some tools charge annual or monthly fees. You just need to identify your requirements and choose a tool that best suits your requirements. simmytarika5 Cyber-security Information-Security GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar GET and POST requests using Python Top 10 Projects For Beginners To Practice HTML and CSS Skills Types of Software Testing Working with csv files in Python How to Start Learning DSA? Supervised and Unsupervised learning Differences between Procedural and Object Oriented Programming Introduction to Recurrent Neural Network 12 pip Commands For Python Developers
[ { "code": null, "e": 25579, "s": 25551, "text": "\n28 Oct, 2021" }, { "code": null, "e": 25838, "s": 25579, "text": "When doing Windows Forensic Analysis, it can be quite overwhelming to see a large amount of data that one needs to collect, assuming you know what you are looking for. In case you don’t know what are you looking for, the entire process becomes twice as hard." }, { "code": null, "e": 25894, "s": 25838, "text": "In this article we will be discussing following topics:" }, { "code": null, "e": 26008, "s": 25894, "text": "What is Windows Forensic Analysis?What are Forensic Artifacts?Top Open-Source Tools for Windows Forensic Analysis" }, { "code": null, "e": 26043, "s": 26008, "text": "What is Windows Forensic Analysis?" }, { "code": null, "e": 26072, "s": 26043, "text": "What are Forensic Artifacts?" }, { "code": null, "e": 26124, "s": 26072, "text": "Top Open-Source Tools for Windows Forensic Analysis" }, { "code": null, "e": 26171, "s": 26124, "text": "Windows Forensic Analysis focuses on 2 things:" }, { "code": null, "e": 26255, "s": 26171, "text": "In-depth analysis of Windows Operating System.Analysis of Windows System Artifacts." }, { "code": null, "e": 26302, "s": 26255, "text": "In-depth analysis of Windows Operating System." }, { "code": null, "e": 26340, "s": 26302, "text": "Analysis of Windows System Artifacts." }, { "code": null, "e": 26673, "s": 26340, "text": "Windows artifacts are the objects which hold information about the activities that are performed by the Windows user. The type of information and the location of the artifact varies from one operating system to another. Windows artifacts contain sensitive information that is collected and analyzed at the time of forensic analysis." }, { "code": null, "e": 27029, "s": 26673, "text": "Forensic artifacts are the forensic objects that have some forensic value. Any object that contains some data or evidence of something that has occurred like logs, register, hives, and many more. In this section, we will be going through some of the forensic artifacts that a forensic investigator look for while performing a Forensic analysis in Windows." }, { "code": null, "e": 27105, "s": 27029, "text": "1. Recylce Bin: The windows recycle bin contains some great artifacts like:" }, { "code": null, "e": 27206, "s": 27105, "text": "$1 file containing the metadata. You can find this file under the path C:\\$Recycle.Bin\\SID*\\$Ixxxxxx" }, { "code": null, "e": 27330, "s": 27206, "text": "$R file containing the contents of the deleted files. This file can be located under the path C:\\$Recycle.Bin\\SID*\\$Rxxxxxx" }, { "code": null, "e": 27375, "s": 27330, "text": "$1 file can be parsed using a tool $1 Parse." }, { "code": null, "e": 27436, "s": 27375, "text": "2. Browsers: Web browsers contain a lot of information like:" }, { "code": null, "e": 27445, "s": 27436, "text": "Cookies." }, { "code": null, "e": 27466, "s": 27445, "text": "Cached website data." }, { "code": null, "e": 27484, "s": 27466, "text": "Downloaded files." }, { "code": null, "e": 27721, "s": 27484, "text": "3. Windows Error Reporting: This features enables user to inform Microsoft about application faults, kernel faults, unresponsive application, and other application specific problems. This feature provides us with various artifacts like:" }, { "code": null, "e": 27797, "s": 27721, "text": "Program Execution, if a malicious program crashes during program execution." }, { "code": null, "e": 28080, "s": 27797, "text": "You can locate these artifacts at the following locations:C:\\ProgramData\\Microsoft\\Windows\\WER\\ReportArchive\nC:\\Users\\XXX\\AppData\\Local\\Microsoft\\Windows\\WER\\ReportArchive\nC:\\ProgramData\\Microsoft\\Windows\\WER\\ReportQueue\nC:\\Users\\XXX\\AppData\\Local\\Microsoft\\Windows\\WER\\ReportQueue\n" }, { "code": null, "e": 28305, "s": 28080, "text": "C:\\ProgramData\\Microsoft\\Windows\\WER\\ReportArchive\nC:\\Users\\XXX\\AppData\\Local\\Microsoft\\Windows\\WER\\ReportArchive\nC:\\ProgramData\\Microsoft\\Windows\\WER\\ReportQueue\nC:\\Users\\XXX\\AppData\\Local\\Microsoft\\Windows\\WER\\ReportQueue\n" }, { "code": null, "e": 28642, "s": 28305, "text": "4. Remote Desktop Protocol Cache: When using the “mstc” client that is provided by the Windows, RDP can be used to move laterally through the network. Cache files are created containing the sections of the screen of the machine to which we are connected to and that is rarely changing. These cache files can be located in the directory:" }, { "code": null, "e": 28708, "s": 28642, "text": "C:\\Users\\XXX\\AppData\\Local\\Microsoft\\Terminal Server Client\\Cache" }, { "code": null, "e": 28788, "s": 28708, "text": "Tools like BMC-Tools can be used to extract images stored in these cache files." }, { "code": null, "e": 28970, "s": 28788, "text": "5. LNK Files: .lnk files are the windows shortcut files. LNK files link or point to other files or executables for ease of access. You can find following information in these files:" }, { "code": null, "e": 29008, "s": 28970, "text": "The original path of the target file." }, { "code": null, "e": 29063, "s": 29008, "text": "Timestamp of both the target files and the .lnk files." }, { "code": null, "e": 29105, "s": 29063, "text": "File Attributes like System, Hidden, etc." }, { "code": null, "e": 29129, "s": 29105, "text": "Details about the disk." }, { "code": null, "e": 29156, "s": 29129, "text": "Remote or local execution." }, { "code": null, "e": 29185, "s": 29156, "text": "MAC address of the machines." }, { "code": null, "e": 29283, "s": 29185, "text": "You can use tools like Windows LNK Parsing Library or LECmd to parse the contents of these files." }, { "code": null, "e": 29470, "s": 29283, "text": "6. Jump Lists: They contain information about the recently accessed applications and files. This feature was introduced with Windows 7. Two types of Jump Lists can be created in Windows:" }, { "code": null, "e": 29691, "s": 29470, "text": "AUTOMATICDESTINATIONS-MS: These jump lists are created automatically when a user opens a file or an application. They are located under the path:C:\\Users\\xxx\\AppData\\Roaming\\Microsoft\\Windows\\Recent\\AutomaticDestinations" }, { "code": null, "e": 29916, "s": 29691, "text": "CUSTOMDESTINATIONS-MS: These jump lists are custom made and are created when a user pins a file or an application. They are located under the directory C:\\Users\\xxx\\AppData\\Roaming\\Microsoft\\Windows\\Recent\\CustomDestinations" }, { "code": null, "e": 30014, "s": 29916, "text": "You can use tools like JumpList Explorer, JLECmd, or Windows JumpList Parser to parse Jump lists." }, { "code": null, "e": 30083, "s": 30014, "text": "7. Prefetch Files: These files contain a wealth of information like:" }, { "code": null, "e": 30101, "s": 30083, "text": "Application Name." }, { "code": null, "e": 30119, "s": 30101, "text": "Application path." }, { "code": null, "e": 30145, "s": 30119, "text": "Last execution timestamp." }, { "code": null, "e": 30165, "s": 30145, "text": "Creation timestamp." }, { "code": null, "e": 30310, "s": 30165, "text": "These files can be located under the directory: C:\\Windows\\Prefetch\\. You can use tools like Windows Prefetch Parser, WinPrefetchView, or PECmd." }, { "code": null, "e": 30464, "s": 30310, "text": "In this section, we will be discussing some of the open-source tools that are available for conducting Forensic Analysis in the Windows Operating System." }, { "code": null, "e": 30657, "s": 30464, "text": "1. Magnet Encrypted Disk Detector: This tool is used to check the encrypted physical drives. This tool supports PGP, Safe boot encrypted volumes, Bitlocker, etc. You can download it from here." }, { "code": null, "e": 30775, "s": 30657, "text": "2. Magnet RAM Capture: This tool is used to analyze the physical memory of the system. You can download it from here." }, { "code": null, "e": 30930, "s": 30775, "text": "3. Wireshark: This is a network analyzer tool and a capture tool that is used to see what traffic is going in your network. You can download it from here." }, { "code": null, "e": 31096, "s": 30930, "text": "4. RAM Capture: As the name suggests, this is a free tool that is used to extract the entire contents of the volatile memory i.e. RAM. You can download it from here." }, { "code": null, "e": 31291, "s": 31096, "text": "5. NMAP: This is the most popular tool that is used to find open ports on the target machine. Using this tool you can find the vulnerability of any target to hack. You can download it from here." }, { "code": null, "e": 31466, "s": 31291, "text": "6. Network Miner: This tool is used as a passive network sniffer to capture or to detect the operating systems ports, sessions, hostnames, etc. You can download it from here." }, { "code": null, "e": 31589, "s": 31466, "text": "7. Autopsy: This is the GUI based tool, that is used to analyze hard disks and smartphones. You can download it from here." }, { "code": null, "e": 31811, "s": 31589, "text": "8. Forensic Investigator: This is a Splunk toolkit which is used in HEX conversion, Base64 conversion, metascan lookups, and many more other features that are essential in forensic analysis. You can download it from here." }, { "code": null, "e": 31951, "s": 31811, "text": "9. HashMyFiles: This tool is used to calculate the SHA1 and MD5 hashes. It works on all the latest websites. You can download it from here." }, { "code": null, "e": 32076, "s": 31951, "text": "10. Crowd Response: This tool is used to gather the system information for incident response. You can download it from here." }, { "code": null, "e": 32205, "s": 32076, "text": "11. ExifTool: This tool is used to read, write, and edit meta information from a number of files. You can download it from here." }, { "code": null, "e": 32405, "s": 32205, "text": "12. FAW (Forensic Acquisition of Websites): This tool is used to acquire web pages image, HTML, source code of the web page. This tool can be integrated with Wireshark. You can download it from here." }, { "code": null, "e": 32651, "s": 32405, "text": "There is such a large variety of forensic tools available in the market. Some are free and open-source and some tools charge annual or monthly fees. You just need to identify your requirements and choose a tool that best suits your requirements." }, { "code": null, "e": 32664, "s": 32651, "text": "simmytarika5" }, { "code": null, "e": 32679, "s": 32664, "text": "Cyber-security" }, { "code": null, "e": 32700, "s": 32679, "text": "Information-Security" }, { "code": null, "e": 32706, "s": 32700, "text": "GBlog" }, { "code": null, "e": 32804, "s": 32706, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32829, "s": 32804, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 32864, "s": 32829, "text": "GET and POST requests using Python" }, { "code": null, "e": 32926, "s": 32864, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 32952, "s": 32926, "text": "Types of Software Testing" }, { "code": null, "e": 32985, "s": 32952, "text": "Working with csv files in Python" }, { "code": null, "e": 33012, "s": 32985, "text": "How to Start Learning DSA?" }, { "code": null, "e": 33049, "s": 33012, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 33112, "s": 33049, "text": "Differences between Procedural and Object Oriented Programming" }, { "code": null, "e": 33153, "s": 33112, "text": "Introduction to Recurrent Neural Network" } ]
Django Migrations | Python - GeeksforGeeks
03 Jul, 2019 Prerequisite: Django Models The class defined in product/models.py is the mere idea of what our database is going to look like but it didn’t create any table in the database. We can assume class Phone as conceptual schema. Before the creation of any table, if we try to access the table before creation, it will throw an error like this. OperationalError at /admin/product/phone/ no such table: product_phone Python provides certain commands for user convenience so that without going into details of SQL,a user can interact with the database. Now, we have created the class (conceptual schema of the database), we can use migrate command to create the actual schema in the database. Stop the server using CTRL+C if running and run the following command in the database. python manage.py makemigrations Above command will let the project know that we want to make changes in the database. You will see following quoting that Create model Phone.what does this command do? This command will generate SQL statements that are supposed to be executed if we wish to make changes in the database.If you want to see the generated commands, navigate to product/migrations/0001_initial.py. You will see file contentIf you try to run the server now using command python manage.py runserver you will see You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): product. Run ‘python manage.py migrate’ to apply them. As written in warning, run python manage.py migrate in your terminal. This will result in creation of table in database. Python Django Web technologies Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26165, "s": 26137, "text": "\n03 Jul, 2019" }, { "code": null, "e": 26193, "s": 26165, "text": "Prerequisite: Django Models" }, { "code": null, "e": 26503, "s": 26193, "text": "The class defined in product/models.py is the mere idea of what our database is going to look like but it didn’t create any table in the database. We can assume class Phone as conceptual schema. Before the creation of any table, if we try to access the table before creation, it will throw an error like this." }, { "code": null, "e": 26574, "s": 26503, "text": "OperationalError at /admin/product/phone/\nno such table: product_phone" }, { "code": null, "e": 26936, "s": 26574, "text": "Python provides certain commands for user convenience so that without going into details of SQL,a user can interact with the database. Now, we have created the class (conceptual schema of the database), we can use migrate command to create the actual schema in the database. Stop the server using CTRL+C if running and run the following command in the database." }, { "code": null, "e": 26968, "s": 26936, "text": "python manage.py makemigrations" }, { "code": null, "e": 27417, "s": 26968, "text": "Above command will let the project know that we want to make changes in the database. You will see following quoting that Create model Phone.what does this command do? This command will generate SQL statements that are supposed to be executed if we wish to make changes in the database.If you want to see the generated commands, navigate to product/migrations/0001_initial.py. You will see file contentIf you try to run the server now using command" }, { "code": null, "e": 27444, "s": 27417, "text": "python manage.py runserver" }, { "code": null, "e": 27457, "s": 27444, "text": "you will see" }, { "code": null, "e": 27625, "s": 27457, "text": "You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): product. Run ‘python manage.py migrate’ to apply them." }, { "code": null, "e": 27652, "s": 27625, "text": "As written in warning, run" }, { "code": null, "e": 27677, "s": 27652, "text": "python manage.py migrate" }, { "code": null, "e": 27746, "s": 27677, "text": "in your terminal. This will result in creation of table in database." }, { "code": null, "e": 27760, "s": 27746, "text": "Python Django" }, { "code": null, "e": 27777, "s": 27760, "text": "Web technologies" }, { "code": null, "e": 27784, "s": 27777, "text": "Python" }, { "code": null, "e": 27882, "s": 27784, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27900, "s": 27882, "text": "Python Dictionary" }, { "code": null, "e": 27935, "s": 27900, "text": "Read a file line by line in Python" }, { "code": null, "e": 27967, "s": 27935, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27989, "s": 27967, "text": "Enumerate() in Python" }, { "code": null, "e": 28031, "s": 27989, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28061, "s": 28031, "text": "Iterate over a list in Python" }, { "code": null, "e": 28087, "s": 28061, "text": "Python String | replace()" }, { "code": null, "e": 28116, "s": 28087, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28160, "s": 28116, "text": "Reading and Writing to text files in Python" } ]
Python program to crawl a web page and get most frequent words
18 Nov, 2021 The task is to count the most frequent words, which extracts data from dynamic sources.First, create a web crawler or scraper with the help of the requests module and a beautiful soup module, which will extract data from the web pages and store them in a list. There might be some undesired words or symbols (like special symbols, blank spaces), which can be filtered in order to ease the counts and get the desired results. After counting each word, we also can have the count of most (say 10 or 20) frequent words.Modules and Library functions used : requests : Will allow you to send HTTP/1.1 requests and many more. beautifulsoup4 : Used for parsing HTML/XML to extract data out of HTML and XML files. operator : Exports a set of efficient functions corresponding to the intrinsic operators. collections : Implements high-performance container datatypes. Below is an implementation of the idea discussed above : Python3 # Python3 program for a word frequency# counter after crawling/scraping a web-pageimport requestsfrom bs4 import BeautifulSoupimport operatorfrom collections import Counter '''Function defining the web-crawler/corespider, which will fetch information froma given website, and push the contents tothe second function clean_wordlist()''' def start(url): # empty list to store the contents of # the website fetched from our web-crawler wordlist = [] source_code = requests.get(url).text # BeautifulSoup object which will # ping the requested url for data soup = BeautifulSoup(source_code, 'html.parser') # Text in given web-page is stored under # the <div> tags with class <entry-content> for each_text in soup.findAll('div', {'class': 'entry-content'}): content = each_text.text # use split() to break the sentence into # words and convert them into lowercase words = content.lower().split() for each_word in words: wordlist.append(each_word) clean_wordlist(wordlist) # Function removes any unwanted symbols def clean_wordlist(wordlist): clean_list = [] for word in wordlist: symbols = "!@#$%^&*()_-+={[}]|\;:\"<>?/., " for i in range(len(symbols)): word = word.replace(symbols[i], '') if len(word) > 0: clean_list.append(word) create_dictionary(clean_list) # Creates a dictionary containing each word's# count and top_20 occurring words def create_dictionary(clean_list): word_count = {} for word in clean_list: if word in word_count: word_count[word] += 1 else: word_count[word] = 1 ''' To get the count of each word in the crawled page --> # operator.itemgetter() takes one # parameter either 1(denotes keys) # or 0 (denotes corresponding values) for key, value in sorted(word_count.items(), key = operator.itemgetter(1)): print ("% s : % s " % (key, value)) <-- ''' c = Counter(word_count) # returns the most occurring elements top = c.most_common(10) print(top) # Driver codeif __name__ == '__main__': url = "https://www.geeksforgeeks.org/programming-language-choose/" # starts crawling and prints output start(url) [('to', 10), ('in', 7), ('is', 6), ('language', 6), ('the', 5), ('programming', 5), ('a', 5), ('c', 5), ('you', 5), ('of', 4)] shubham_singh kumarv456 varshagumber28 kumaripunam984122 surindertarika1234 Python-projects python-utility Python Technical Scripter Web Technologies 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 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Nov, 2021" }, { "code": null, "e": 480, "s": 54, "text": "The task is to count the most frequent words, which extracts data from dynamic sources.First, create a web crawler or scraper with the help of the requests module and a beautiful soup module, which will extract data from the web pages and store them in a list. There might be some undesired words or symbols (like special symbols, blank spaces), which can be filtered in order to ease the counts and get the desired results. " }, { "code": null, "e": 609, "s": 480, "text": "After counting each word, we also can have the count of most (say 10 or 20) frequent words.Modules and Library functions used : " }, { "code": null, "e": 915, "s": 609, "text": "requests : Will allow you to send HTTP/1.1 requests and many more. beautifulsoup4 : Used for parsing HTML/XML to extract data out of HTML and XML files. operator : Exports a set of efficient functions corresponding to the intrinsic operators. collections : Implements high-performance container datatypes." }, { "code": null, "e": 974, "s": 915, "text": "Below is an implementation of the idea discussed above : " }, { "code": null, "e": 982, "s": 974, "text": "Python3" }, { "code": "# Python3 program for a word frequency# counter after crawling/scraping a web-pageimport requestsfrom bs4 import BeautifulSoupimport operatorfrom collections import Counter '''Function defining the web-crawler/corespider, which will fetch information froma given website, and push the contents tothe second function clean_wordlist()''' def start(url): # empty list to store the contents of # the website fetched from our web-crawler wordlist = [] source_code = requests.get(url).text # BeautifulSoup object which will # ping the requested url for data soup = BeautifulSoup(source_code, 'html.parser') # Text in given web-page is stored under # the <div> tags with class <entry-content> for each_text in soup.findAll('div', {'class': 'entry-content'}): content = each_text.text # use split() to break the sentence into # words and convert them into lowercase words = content.lower().split() for each_word in words: wordlist.append(each_word) clean_wordlist(wordlist) # Function removes any unwanted symbols def clean_wordlist(wordlist): clean_list = [] for word in wordlist: symbols = \"!@#$%^&*()_-+={[}]|\\;:\\\"<>?/., \" for i in range(len(symbols)): word = word.replace(symbols[i], '') if len(word) > 0: clean_list.append(word) create_dictionary(clean_list) # Creates a dictionary containing each word's# count and top_20 occurring words def create_dictionary(clean_list): word_count = {} for word in clean_list: if word in word_count: word_count[word] += 1 else: word_count[word] = 1 ''' To get the count of each word in the crawled page --> # operator.itemgetter() takes one # parameter either 1(denotes keys) # or 0 (denotes corresponding values) for key, value in sorted(word_count.items(), key = operator.itemgetter(1)): print (\"% s : % s \" % (key, value)) <-- ''' c = Counter(word_count) # returns the most occurring elements top = c.most_common(10) print(top) # Driver codeif __name__ == '__main__': url = \"https://www.geeksforgeeks.org/programming-language-choose/\" # starts crawling and prints output start(url)", "e": 3270, "s": 982, "text": null }, { "code": null, "e": 3398, "s": 3270, "text": "[('to', 10), ('in', 7), ('is', 6), ('language', 6), ('the', 5),\n ('programming', 5), ('a', 5), ('c', 5), ('you', 5), ('of', 4)]" }, { "code": null, "e": 3412, "s": 3398, "text": "shubham_singh" }, { "code": null, "e": 3422, "s": 3412, "text": "kumarv456" }, { "code": null, "e": 3437, "s": 3422, "text": "varshagumber28" }, { "code": null, "e": 3455, "s": 3437, "text": "kumaripunam984122" }, { "code": null, "e": 3474, "s": 3455, "text": "surindertarika1234" }, { "code": null, "e": 3490, "s": 3474, "text": "Python-projects" }, { "code": null, "e": 3505, "s": 3490, "text": "python-utility" }, { "code": null, "e": 3512, "s": 3505, "text": "Python" }, { "code": null, "e": 3531, "s": 3512, "text": "Technical Scripter" }, { "code": null, "e": 3548, "s": 3531, "text": "Web Technologies" }, { "code": null, "e": 3646, "s": 3548, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3678, "s": 3646, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3705, "s": 3678, "text": "Python Classes and Objects" }, { "code": null, "e": 3726, "s": 3705, "text": "Python OOPs Concepts" }, { "code": null, "e": 3749, "s": 3726, "text": "Introduction To PYTHON" }, { "code": null, "e": 3805, "s": 3749, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3838, "s": 3805, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3900, "s": 3838, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3961, "s": 3900, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4011, "s": 3961, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Program to Convert Radian to Degree in C
If input is in radian convert it to degree else input will be in radian convert it to degree. There are formulas that can be used for this conversion. Radian is the standard unit for measuring angles whereas the complete angle of circle is divided into 360 degree. Also, radian is the smaller value as 1 degree = 180 radians. Conversion Formulas − degree = radian * (180/pi) where, pi=3.14 or 22/7 Example Input-: radian = 9.0 Output-: degree is : 515.92357 Start Step 1 -> define macro as #define pi 3.14 Step 2 -> declare function for converting radian to degree double convert(double radian) return(radian * (180/pi)) Step 3 -> In main() Declare variable as double radian = 9.0 Declare and set double degree = convert(radian) Print degree Stop #include <stdio.h> #define pi 3.14 // Function for converting radian to degree double convert(double radian){ return(radian * (180/pi)); } int main(){ double radian = 9.0; double degree = convert(radian); printf("degree is : %.5lf", degree); return 0; } degree is : 515.92357
[ { "code": null, "e": 1338, "s": 1187, "text": "If input is in radian convert it to degree else input will be in radian convert it to degree. There are formulas that can be used for this conversion." }, { "code": null, "e": 1513, "s": 1338, "text": "Radian is the standard unit for measuring angles whereas the complete angle of circle is divided into 360 degree. Also, radian is the smaller value as 1 degree = 180 radians." }, { "code": null, "e": 1535, "s": 1513, "text": "Conversion Formulas −" }, { "code": null, "e": 1585, "s": 1535, "text": "degree = radian * (180/pi)\nwhere, pi=3.14 or 22/7" }, { "code": null, "e": 1593, "s": 1585, "text": "Example" }, { "code": null, "e": 1645, "s": 1593, "text": "Input-: radian = 9.0\nOutput-: degree is : 515.92357" }, { "code": null, "e": 1952, "s": 1645, "text": "Start\nStep 1 -> define macro as #define pi 3.14\nStep 2 -> declare function for converting radian to degree\n double convert(double radian)\n return(radian * (180/pi))\nStep 3 -> In main()\n Declare variable as double radian = 9.0\n Declare and set double degree = convert(radian)\n Print degree\nStop" }, { "code": null, "e": 2224, "s": 1952, "text": "#include <stdio.h>\n#define pi 3.14\n// Function for converting radian to degree\ndouble convert(double radian){\n return(radian * (180/pi));\n}\n int main(){\n double radian = 9.0;\n double degree = convert(radian);\n printf(\"degree is : %.5lf\", degree);\n return 0;\n}" }, { "code": null, "e": 2246, "s": 2224, "text": "degree is : 515.92357" } ]
CSS elevation Property
01 Oct, 2020 The CSS elevation property is used to set the sound source on the vertical axis depending on the listener’s environment. Syntax: elevation: angle: Parameters: This property accepts single value as mentioned above and described below: angle: This parameter holds the angle of the source, where the sound is generated. There are few possible values that is accepted by this parameter in the range of 90deg to -90deg. Name of the positions is acceptable. above = 90deg level = 0deg below = -90deg higher = shifted upwards by 10deg compare to initial(0deg) lower = shifted downwards by 10deg compare to initial(0deg) Example 1: HTML <!DOCTYPE html><html> <head> <style> audio { elevation: above; } </style></head> <body style="text-align: center;"> <h1 style="color: green;">GeeksforGeeks</h1> <p>CSS elevation Property</p> <audio controls> <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3" type="audio/mp3"> </audio></body> </html> Output: Example 2: HTML <!DOCTYPE html><html> <head> <style> audio { elevation: below; } </style></head> <body style="text-align: center;"> <h1 style="color: green;"> GeeksforGeeks </h1> <p>CSS elevation Property</p> <audio controls> <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3" type="audio/mp3"> </audio></body> </html> Output: Supported Browsers: This property is deprecated in CSS3 so the major browsers are not supported by this property CSS-Properties CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Oct, 2020" }, { "code": null, "e": 149, "s": 28, "text": "The CSS elevation property is used to set the sound source on the vertical axis depending on the listener’s environment." }, { "code": null, "e": 158, "s": 149, "text": " Syntax:" }, { "code": null, "e": 177, "s": 158, "text": "elevation: angle:\n" }, { "code": null, "e": 264, "s": 177, "text": "Parameters: This property accepts single value as mentioned above and described below:" }, { "code": null, "e": 482, "s": 264, "text": "angle: This parameter holds the angle of the source, where the sound is generated. There are few possible values that is accepted by this parameter in the range of 90deg to -90deg. Name of the positions is acceptable." }, { "code": null, "e": 645, "s": 482, "text": "above = 90deg\nlevel = 0deg\nbelow = -90deg\nhigher = shifted upwards by 10deg compare to initial(0deg)\nlower = shifted downwards by 10deg compare to initial(0deg)\n\n" }, { "code": null, "e": 656, "s": 645, "text": "Example 1:" }, { "code": null, "e": 661, "s": 656, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> audio { elevation: above; } </style></head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\">GeeksforGeeks</h1> <p>CSS elevation Property</p> <audio controls> <source src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3\" type=\"audio/mp3\"> </audio></body> </html>", "e": 1064, "s": 661, "text": null }, { "code": null, "e": 1072, "s": 1064, "text": "Output:" }, { "code": null, "e": 1083, "s": 1072, "text": "Example 2:" }, { "code": null, "e": 1088, "s": 1083, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> audio { elevation: below; } </style></head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <p>CSS elevation Property</p> <audio controls> <source src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3\" type=\"audio/mp3\"> </audio></body> </html>", "e": 1503, "s": 1088, "text": null }, { "code": null, "e": 1511, "s": 1503, "text": "Output:" }, { "code": null, "e": 1624, "s": 1511, "text": "Supported Browsers: This property is deprecated in CSS3 so the major browsers are not supported by this property" }, { "code": null, "e": 1639, "s": 1624, "text": "CSS-Properties" }, { "code": null, "e": 1643, "s": 1639, "text": "CSS" }, { "code": null, "e": 1660, "s": 1643, "text": "Web Technologies" } ]
FIRST Set in Syntax Analysis
31 Jul, 2021 FIRST(X) for a grammar symbol X is the set of terminals that begin the strings derivable from X. Rules to compute FIRST set: If x is a terminal, then FIRST(x) = { ‘x’ }If x-> Є, is a production rule, then add Є to FIRST(x).If X->Y1 Y2 Y3....Yn is a production, FIRST(X) = FIRST(Y1)If FIRST(Y1) contains Є then FIRST(X) = { FIRST(Y1) – Є } U { FIRST(Y2) }If FIRST (Yi) contains Є for all i = 1 to n, then add Є to FIRST(X). If x is a terminal, then FIRST(x) = { ‘x’ } If x-> Є, is a production rule, then add Є to FIRST(x). If X->Y1 Y2 Y3....Yn is a production, FIRST(X) = FIRST(Y1)If FIRST(Y1) contains Є then FIRST(X) = { FIRST(Y1) – Є } U { FIRST(Y2) }If FIRST (Yi) contains Є for all i = 1 to n, then add Є to FIRST(X). FIRST(X) = FIRST(Y1)If FIRST(Y1) contains Є then FIRST(X) = { FIRST(Y1) – Є } U { FIRST(Y2) }If FIRST (Yi) contains Є for all i = 1 to n, then add Є to FIRST(X). FIRST(X) = FIRST(Y1) If FIRST(Y1) contains Є then FIRST(X) = { FIRST(Y1) – Є } U { FIRST(Y2) } If FIRST (Yi) contains Є for all i = 1 to n, then add Є to FIRST(X). Example 1: Production Rules of Grammar E -> TE’ E’ -> +T E’|Є T -> F T’ T’ -> *F T’ | Є F -> (E) | id FIRST sets FIRST(E) = FIRST(T) = { ( , id } FIRST(E’) = { +, Є } FIRST(T) = FIRST(F) = { ( , id } FIRST(T’) = { *, Є } FIRST(F) = { ( , id } Example 2: Production Rules of Grammar S -> ACB | Cbb | Ba A -> da | BC B -> g | Є C -> h | Є FIRST sets FIRST(S) = FIRST(ACB) U FIRST(Cbb) U FIRST(Ba) = { d, g, h, b, a, Є} FIRST(A) = { d } U FIRST(BC) = { d, g, h, Є } FIRST(B) = { g , Є } FIRST(C) = { h , Є } Notes: The grammar used above is Context-Free Grammar (CFG). Syntax of most of the programming language can be specified using CFG.CFG is of the form A -> B , where A is a single Non-Terminal, and B can be a set of grammar symbols ( i.e. Terminals as well as Non-Terminals) The grammar used above is Context-Free Grammar (CFG). Syntax of most of the programming language can be specified using CFG. CFG is of the form A -> B , where A is a single Non-Terminal, and B can be a set of grammar symbols ( i.e. Terminals as well as Non-Terminals) In the next article “FOLLOW sets in Compiler Design” we will see how to compute Follow sets. This article is compiled by Vaibhav Bajpai. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. VaibhavRai3 1watyd6bxgvi21srkng09kmrlpsl0yb4pdr2dyx9 alvinshaita Compiler Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n31 Jul, 2021" }, { "code": null, "e": 152, "s": 54, "text": "FIRST(X) for a grammar symbol X is the set of terminals that begin the strings derivable from X. " }, { "code": null, "e": 181, "s": 152, "text": "Rules to compute FIRST set: " }, { "code": null, "e": 479, "s": 181, "text": "If x is a terminal, then FIRST(x) = { ‘x’ }If x-> Є, is a production rule, then add Є to FIRST(x).If X->Y1 Y2 Y3....Yn is a production, FIRST(X) = FIRST(Y1)If FIRST(Y1) contains Є then FIRST(X) = { FIRST(Y1) – Є } U { FIRST(Y2) }If FIRST (Yi) contains Є for all i = 1 to n, then add Є to FIRST(X)." }, { "code": null, "e": 523, "s": 479, "text": "If x is a terminal, then FIRST(x) = { ‘x’ }" }, { "code": null, "e": 579, "s": 523, "text": "If x-> Є, is a production rule, then add Є to FIRST(x)." }, { "code": null, "e": 779, "s": 579, "text": "If X->Y1 Y2 Y3....Yn is a production, FIRST(X) = FIRST(Y1)If FIRST(Y1) contains Є then FIRST(X) = { FIRST(Y1) – Є } U { FIRST(Y2) }If FIRST (Yi) contains Є for all i = 1 to n, then add Є to FIRST(X)." }, { "code": null, "e": 941, "s": 779, "text": "FIRST(X) = FIRST(Y1)If FIRST(Y1) contains Є then FIRST(X) = { FIRST(Y1) – Є } U { FIRST(Y2) }If FIRST (Yi) contains Є for all i = 1 to n, then add Є to FIRST(X)." }, { "code": null, "e": 962, "s": 941, "text": "FIRST(X) = FIRST(Y1)" }, { "code": null, "e": 1036, "s": 962, "text": "If FIRST(Y1) contains Є then FIRST(X) = { FIRST(Y1) – Є } U { FIRST(Y2) }" }, { "code": null, "e": 1105, "s": 1036, "text": "If FIRST (Yi) contains Є for all i = 1 to n, then add Є to FIRST(X)." }, { "code": null, "e": 1117, "s": 1105, "text": "Example 1: " }, { "code": null, "e": 1353, "s": 1117, "text": "Production Rules of Grammar\nE -> TE’\nE’ -> +T E’|Є\nT -> F T’\nT’ -> *F T’ | Є\nF -> (E) | id\n\nFIRST sets\nFIRST(E) = FIRST(T) = { ( , id }\nFIRST(E’) = { +, Є }\nFIRST(T) = FIRST(F) = { ( , id }\nFIRST(T’) = { *, Є }\nFIRST(F) = { ( , id }" }, { "code": null, "e": 1365, "s": 1353, "text": "Example 2: " }, { "code": null, "e": 1636, "s": 1365, "text": "Production Rules of Grammar\nS -> ACB | Cbb | Ba\nA -> da | BC\nB -> g | Є\nC -> h | Є\n\nFIRST sets\nFIRST(S) = FIRST(ACB) U FIRST(Cbb) U FIRST(Ba)\n = { d, g, h, b, a, Є}\nFIRST(A) = { d } U FIRST(BC) \n = { d, g, h, Є }\nFIRST(B) = { g , Є }\nFIRST(C) = { h , Є }" }, { "code": null, "e": 1644, "s": 1636, "text": "Notes: " }, { "code": null, "e": 1911, "s": 1644, "text": "The grammar used above is Context-Free Grammar (CFG). Syntax of most of the programming language can be specified using CFG.CFG is of the form A -> B , where A is a single Non-Terminal, and B can be a set of grammar symbols ( i.e. Terminals as well as Non-Terminals)" }, { "code": null, "e": 2036, "s": 1911, "text": "The grammar used above is Context-Free Grammar (CFG). Syntax of most of the programming language can be specified using CFG." }, { "code": null, "e": 2179, "s": 2036, "text": "CFG is of the form A -> B , where A is a single Non-Terminal, and B can be a set of grammar symbols ( i.e. Terminals as well as Non-Terminals)" }, { "code": null, "e": 2273, "s": 2179, "text": "In the next article “FOLLOW sets in Compiler Design” we will see how to compute Follow sets. " }, { "code": null, "e": 2442, "s": 2273, "text": "This article is compiled by Vaibhav Bajpai. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2454, "s": 2442, "text": "VaibhavRai3" }, { "code": null, "e": 2495, "s": 2454, "text": "1watyd6bxgvi21srkng09kmrlpsl0yb4pdr2dyx9" }, { "code": null, "e": 2507, "s": 2495, "text": "alvinshaita" }, { "code": null, "e": 2523, "s": 2507, "text": "Compiler Design" }, { "code": null, "e": 2531, "s": 2523, "text": "GATE CS" } ]
Python | Pandas MultiIndex.from_arrays()
24 Dec, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas MultiIndex.from_arrays() function is used to convert arrays into MultiIndex. It is one of the several ways in which we construct a MultiIndex. Syntax: MultiIndex.from_arrays(arrays, sortorder=None, names=None) Parameters :arrays : Each array-like gives one level’s value for each data point. len(arrays) is the number of levelssortorder : Level of sortedness (must be lexicographically sorted by that level) Returns: index : MultiIndex Example #1: Use MultiIndex.from_arrays() function to construct a MultiIndex from arrays. # importing pandas as pdimport pandas as pd # Creating the arrayarray =[[1, 2, 3], ['Sharon', 'Nick', 'Bailey']] # Print the arrayprint(array) Output : Now let’s create the MultiIndex using this array # Creating the MultiIndexmidx = pd.MultiIndex.from_arrays(array, names =('Number', 'Names')) # Print the MultiIndexprint(midx) Output :As we can see in the output, the function has created a MultiIndex object using the arrays. Example #2: Use MultiIndex.from_arrays() function to construct a MultiIndex from arrays. # importing pandas as pdimport pandas as pd # Creating the arrayarray =[[1, 2, 3], ['Sharon', 'Nick', 'Bailey'], ['Doctor', 'Scientist', 'Physicist']] # Print the arrayprint(array) Output : Now let’s create the MultiIndex using this array # Creating the MultiIndexmidx = pd.MultiIndex.from_arrays(array, names =('Ranking', 'Names', 'Profession')) # Print the MultiIndexprint(midx) Output :As we can see in the output, the function has created a MultiIndex using the passed arrays. Python pandas-multiIndex Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Dec, 2018" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 392, "s": 242, "text": "Pandas MultiIndex.from_arrays() function is used to convert arrays into MultiIndex. It is one of the several ways in which we construct a MultiIndex." }, { "code": null, "e": 459, "s": 392, "text": "Syntax: MultiIndex.from_arrays(arrays, sortorder=None, names=None)" }, { "code": null, "e": 657, "s": 459, "text": "Parameters :arrays : Each array-like gives one level’s value for each data point. len(arrays) is the number of levelssortorder : Level of sortedness (must be lexicographically sorted by that level)" }, { "code": null, "e": 685, "s": 657, "text": "Returns: index : MultiIndex" }, { "code": null, "e": 774, "s": 685, "text": "Example #1: Use MultiIndex.from_arrays() function to construct a MultiIndex from arrays." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the arrayarray =[[1, 2, 3], ['Sharon', 'Nick', 'Bailey']] # Print the arrayprint(array)", "e": 919, "s": 774, "text": null }, { "code": null, "e": 928, "s": 919, "text": "Output :" }, { "code": null, "e": 977, "s": 928, "text": "Now let’s create the MultiIndex using this array" }, { "code": "# Creating the MultiIndexmidx = pd.MultiIndex.from_arrays(array, names =('Number', 'Names')) # Print the MultiIndexprint(midx)", "e": 1116, "s": 977, "text": null }, { "code": null, "e": 1305, "s": 1116, "text": "Output :As we can see in the output, the function has created a MultiIndex object using the arrays. Example #2: Use MultiIndex.from_arrays() function to construct a MultiIndex from arrays." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the arrayarray =[[1, 2, 3], ['Sharon', 'Nick', 'Bailey'], ['Doctor', 'Scientist', 'Physicist']] # Print the arrayprint(array)", "e": 1498, "s": 1305, "text": null }, { "code": null, "e": 1507, "s": 1498, "text": "Output :" }, { "code": null, "e": 1556, "s": 1507, "text": "Now let’s create the MultiIndex using this array" }, { "code": "# Creating the MultiIndexmidx = pd.MultiIndex.from_arrays(array, names =('Ranking', 'Names', 'Profession')) # Print the MultiIndexprint(midx)", "e": 1702, "s": 1556, "text": null }, { "code": null, "e": 1802, "s": 1702, "text": "Output :As we can see in the output, the function has created a MultiIndex using the passed arrays." }, { "code": null, "e": 1827, "s": 1802, "text": "Python pandas-multiIndex" }, { "code": null, "e": 1841, "s": 1827, "text": "Python-pandas" }, { "code": null, "e": 1848, "s": 1841, "text": "Python" }, { "code": null, "e": 1946, "s": 1848, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1964, "s": 1946, "text": "Python Dictionary" }, { "code": null, "e": 2006, "s": 1964, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2028, "s": 2006, "text": "Enumerate() in Python" }, { "code": null, "e": 2063, "s": 2028, "text": "Read a file line by line in Python" }, { "code": null, "e": 2095, "s": 2063, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2124, "s": 2095, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2151, "s": 2124, "text": "Python Classes and Objects" }, { "code": null, "e": 2181, "s": 2151, "text": "Iterate over a list in Python" }, { "code": null, "e": 2202, "s": 2181, "text": "Python OOPs Concepts" } ]
Java protected Keyword
❮ Java Keywords The Student subclass accesses a Person class with protected attributes: class Person { protected String fname = "John"; protected String lname = "Doe"; protected String email = "john@doe.com"; protected int age = 24; } class Student extends Person { private int graduationYear = 2018; public static void main(String[] args) { Student myObj = new Student(); System.out.println("Name: " + myObj.fname + " " + myObj.lname); System.out.println("Email: " + myObj.email); System.out.println("Age: " + myObj.age); System.out.println("Graduation Year: " + myObj.graduationYear); } } Try it Yourself » The protected keyword is an access modifier used for attributes, methods and constructors, making them accessible in the same package and subclasses. Read more about modifiers in our Java Modifiers Tutorial. ❮ Java Keywords We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 18, "s": 0, "text": "\n❮ Java Keywords\n" }, { "code": null, "e": 90, "s": 18, "text": "The Student subclass accesses a Person class with protected attributes:" }, { "code": null, "e": 629, "s": 90, "text": "class Person {\n protected String fname = \"John\";\n protected String lname = \"Doe\";\n protected String email = \"john@doe.com\";\n protected int age = 24;\n}\n\nclass Student extends Person {\n private int graduationYear = 2018;\n public static void main(String[] args) {\n Student myObj = new Student();\n System.out.println(\"Name: \" + myObj.fname + \" \" + myObj.lname);\n System.out.println(\"Email: \" + myObj.email);\n System.out.println(\"Age: \" + myObj.age);\n System.out.println(\"Graduation Year: \" + myObj.graduationYear);\n }\n}\n" }, { "code": null, "e": 649, "s": 629, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 799, "s": 649, "text": "The protected keyword is an access modifier used for attributes, methods and constructors, making them accessible in the same package and subclasses." }, { "code": null, "e": 857, "s": 799, "text": "Read more about modifiers in our Java Modifiers Tutorial." }, { "code": null, "e": 875, "s": 857, "text": "\n❮ Java Keywords\n" }, { "code": null, "e": 908, "s": 875, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 950, "s": 908, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1057, "s": 950, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1076, "s": 1057, "text": "help@w3schools.com" } ]
Instanceof operator in JavaScript
The instance of operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object. In a simpler languange, it tests if a variable is of a certain type. But it has a few caveats. Let us look at some examples. Strings and numbers are primitive values, not objects and therefore don't have a [[Prototype]], so it'll only work if you wrap them in regular objects. console.log(1 instanceof Number) console.log(new Number(1) instanceof Number) console.log("" instanceof String) console.log(new String("") instanceof String) false true false true Functions that return their objects(JS Classes) can have their objects checked using the instanceof operator. function Person(name) { this.name = name } let john = new Person("John"); console.log(john instanceof Person) true JS supports prototypical inheritence, so if you check for instanceof for any class in the hierarchy, it'll return true. class Person {} class Student extends Person { constructor(name) { super() this.name = name } } let john = new Student("John"); console.log(john instanceof Person) console.log(john instanceof Student) true true
[ { "code": null, "e": 1320, "s": 1062, "text": "The instance of operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object. In a simpler languange, it tests if a variable is of a certain type. But it has a few caveats. Let us look at some examples." }, { "code": null, "e": 1472, "s": 1320, "text": "Strings and numbers are primitive values, not objects and therefore don't have a [[Prototype]], so it'll only work if you wrap them in regular objects." }, { "code": null, "e": 1630, "s": 1472, "text": "console.log(1 instanceof Number)\nconsole.log(new Number(1) instanceof Number)\nconsole.log(\"\" instanceof String)\nconsole.log(new String(\"\") instanceof String)" }, { "code": null, "e": 1652, "s": 1630, "text": "false\ntrue\nfalse\ntrue" }, { "code": null, "e": 1762, "s": 1652, "text": "Functions that return their objects(JS Classes) can have their objects checked using the instanceof operator." }, { "code": null, "e": 1875, "s": 1762, "text": "function Person(name) {\n this.name = name\n}\nlet john = new Person(\"John\");\nconsole.log(john instanceof Person)" }, { "code": null, "e": 1880, "s": 1875, "text": "true" }, { "code": null, "e": 2000, "s": 1880, "text": "JS supports prototypical inheritence, so if you check for instanceof for any class in the hierarchy, it'll return true." }, { "code": null, "e": 2219, "s": 2000, "text": "class Person {}\nclass Student extends Person {\n constructor(name) {\n super()\n this.name = name\n }\n}\nlet john = new Student(\"John\");\nconsole.log(john instanceof Person)\nconsole.log(john instanceof Student)" }, { "code": null, "e": 2229, "s": 2219, "text": "true\ntrue" } ]
How to build a wide-and-deep model using Keras in TensorFlow 2.0 | by Lak Lakshmanan | Towards Data Science
In TensorFlow 2.0, Keras has support for feature columns, opening up the ability to represent structured data using standard feature engineering techniques like embedding, bucketizing, and feature crosses. In this article, I will first show you a simple example of using the Functional API to build a model that uses features columns. Then, I will update the code to build out a full wide-and-deep model. To keep the article short, I am focusing on just the model, but you can see the full notebook (including reading data using tf.data) on GitHub. The code here assumes you are using TensorFlow 2.0. pip install it in Colab using: !pip install -q tensorflow==2.0.0-alpha0` or use Cloud AI Platform (CAIP) Notebooks to get a TensorFlow 2.0 Jupyter instance: Create feature columns for each of the fields in your input: real = { colname : fc.numeric_column(colname) \ for colname in \ (’dep_delay,taxiout,distance’).split(’,’)}sparse = { 'origin' : fc.categorical_column_with_hash_bucket(’origin’, hash_bucket_size=1000), 'dest' : fc.categorical_column_with_hash_bucket(’dest’, hash_bucket_size=1000)} Here, I’m creating numeric columns for the float fields and hashed-categorical columns for the categorical fields. For each of the inputs, also create a Keras Input layer, making sure to set the dtype and name for each of the input fields: inputs = { colname : tf.keras.layers.Input(name=colname, shape=(), dtype='float32') \ for colname in real.keys()}inputs.update({ colname : tf.keras.layers.Input(name=colname, shape=(), dtype='string') \ for colname in sparse.keys()}) In order to use a categorical variable in a deep learning model, we have to encode it. A sparse variable will have to be either embedded or one-hot encoded. So, let’s do both: embed = { 'embed_{}'.format(colname) : fc.embedding_column(col, 10) \ for colname, col in sparse.items()}real.update(embed)# one-hot encode the sparse columnssparse = { colname : fc.indicator_column(col) \ for colname, col in sparse.items()} The key thing is to create a DenseFeatures layer to transform the inputs using the feature columns: deep = tf.keras.layers.DenseFeatures(real.values())(inputs)deep = tf.keras.layers.Dense(64, activation='relu')(deep)deep = tf.keras.layers.Dense(16, activation='relu')(deep)output = tf.keras.layers.Dense(1, activation='sigmoid')(deep)model = tf.keras.Model(inputs, output) That’s it! Call model.fit() etc. as usual. If you want to build a wide-and-deep network, you want to wire the sparse features directly to the output node, but pass the real features through a set of dense layers. Here’s a model architecture that will do that: def wide_and_deep_classifier(inputs, linear_feature_columns, dnn_feature_columns, dnn_hidden_units): deep = tf.keras.layers.DenseFeatures(dnn_feature_columns)(inputs) for numnodes in dnn_hidden_units: deep = tf.keras.layers.Dense(numnodes, activation='relu')(deep) wide = tf.keras.layers.DenseFeatures(linear_feature_columns)(inputs) both = tf.keras.layers.concatenate([deep, wide]) output = tf.keras.layers.Dense(1, activation='sigmoid')(both) model = tf.keras.Model(inputs, output) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) return modelmodel = wide_and_deep_classifier(inputs, sparse.values(), real.values(), [64, 16]) Of course, this being Keras, you can easily sprinkle in dropout, batch normalization, etc. into the model. Enjoy! See the full notebook on GitHub.Read my book on doing Data Science on GCP See the full notebook on GitHub. Read my book on doing Data Science on GCP
[ { "code": null, "e": 577, "s": 172, "text": "In TensorFlow 2.0, Keras has support for feature columns, opening up the ability to represent structured data using standard feature engineering techniques like embedding, bucketizing, and feature crosses. In this article, I will first show you a simple example of using the Functional API to build a model that uses features columns. Then, I will update the code to build out a full wide-and-deep model." }, { "code": null, "e": 721, "s": 577, "text": "To keep the article short, I am focusing on just the model, but you can see the full notebook (including reading data using tf.data) on GitHub." }, { "code": null, "e": 804, "s": 721, "text": "The code here assumes you are using TensorFlow 2.0. pip install it in Colab using:" }, { "code": null, "e": 846, "s": 804, "text": "!pip install -q tensorflow==2.0.0-alpha0`" }, { "code": null, "e": 930, "s": 846, "text": "or use Cloud AI Platform (CAIP) Notebooks to get a TensorFlow 2.0 Jupyter instance:" }, { "code": null, "e": 991, "s": 930, "text": "Create feature columns for each of the fields in your input:" }, { "code": null, "e": 1308, "s": 991, "text": "real = { colname : fc.numeric_column(colname) \\ for colname in \\ (’dep_delay,taxiout,distance’).split(’,’)}sparse = { 'origin' : fc.categorical_column_with_hash_bucket(’origin’, hash_bucket_size=1000), 'dest' : fc.categorical_column_with_hash_bucket(’dest’, hash_bucket_size=1000)}" }, { "code": null, "e": 1423, "s": 1308, "text": "Here, I’m creating numeric columns for the float fields and hashed-categorical columns for the categorical fields." }, { "code": null, "e": 1548, "s": 1423, "text": "For each of the inputs, also create a Keras Input layer, making sure to set the dtype and name for each of the input fields:" }, { "code": null, "e": 1806, "s": 1548, "text": "inputs = { colname : tf.keras.layers.Input(name=colname, shape=(), dtype='float32') \\ for colname in real.keys()}inputs.update({ colname : tf.keras.layers.Input(name=colname, shape=(), dtype='string') \\ for colname in sparse.keys()})" }, { "code": null, "e": 1982, "s": 1806, "text": "In order to use a categorical variable in a deep learning model, we have to encode it. A sparse variable will have to be either embedded or one-hot encoded. So, let’s do both:" }, { "code": null, "e": 2251, "s": 1982, "text": "embed = { 'embed_{}'.format(colname) : fc.embedding_column(col, 10) \\ for colname, col in sparse.items()}real.update(embed)# one-hot encode the sparse columnssparse = { colname : fc.indicator_column(col) \\ for colname, col in sparse.items()}" }, { "code": null, "e": 2351, "s": 2251, "text": "The key thing is to create a DenseFeatures layer to transform the inputs using the feature columns:" }, { "code": null, "e": 2624, "s": 2351, "text": "deep = tf.keras.layers.DenseFeatures(real.values())(inputs)deep = tf.keras.layers.Dense(64, activation='relu')(deep)deep = tf.keras.layers.Dense(16, activation='relu')(deep)output = tf.keras.layers.Dense(1, activation='sigmoid')(deep)model = tf.keras.Model(inputs, output)" }, { "code": null, "e": 2667, "s": 2624, "text": "That’s it! Call model.fit() etc. as usual." }, { "code": null, "e": 2884, "s": 2667, "text": "If you want to build a wide-and-deep network, you want to wire the sparse features directly to the output node, but pass the real features through a set of dense layers. Here’s a model architecture that will do that:" }, { "code": null, "e": 3618, "s": 2884, "text": "def wide_and_deep_classifier(inputs, linear_feature_columns, dnn_feature_columns, dnn_hidden_units): deep = tf.keras.layers.DenseFeatures(dnn_feature_columns)(inputs) for numnodes in dnn_hidden_units: deep = tf.keras.layers.Dense(numnodes, activation='relu')(deep) wide = tf.keras.layers.DenseFeatures(linear_feature_columns)(inputs) both = tf.keras.layers.concatenate([deep, wide]) output = tf.keras.layers.Dense(1, activation='sigmoid')(both) model = tf.keras.Model(inputs, output) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) return modelmodel = wide_and_deep_classifier(inputs, sparse.values(), real.values(), [64, 16])" }, { "code": null, "e": 3725, "s": 3618, "text": "Of course, this being Keras, you can easily sprinkle in dropout, batch normalization, etc. into the model." }, { "code": null, "e": 3732, "s": 3725, "text": "Enjoy!" }, { "code": null, "e": 3806, "s": 3732, "text": "See the full notebook on GitHub.Read my book on doing Data Science on GCP" }, { "code": null, "e": 3839, "s": 3806, "text": "See the full notebook on GitHub." } ]
Concat a field in MySQL SELECT?
To concat a field in MySQL SELECT, use the CONCAT() function as shown in the below syntax. SELECT CONCAT(yourColumnName1,’anyConcatenationString’),CONCAT(yourColumnName2,’anyC oncatenationString’),....N from yourTableName; To understand the above syntax, let us first create a table. The query to create a table is as follows. mysql> create table selectConcat -> ( -> StudentId int, -> StudentName varchar(100), -> StudentAge int -> ); Query OK, 0 rows affected (1.32 sec) Insert some records in the table using insert command. The query is as follows − mysql> insert into selectConcat values(1,'Carol',23); Query OK, 1 row affected (0.19 sec) mysql> insert into selectConcat values(2,'John',24); Query OK, 1 row affected (0.25 sec) mysql> insert into selectConcat values(3,'Adam',25); Query OK, 1 row affected (0.14 sec) mysql> insert into selectConcat values(4,'Bob',21); Query OK, 1 row affected (0.20 sec) mysql> insert into selectConcat values(5,'Sam',22); Query OK, 1 row affected (0.16 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from selectConcat; The following is the output. +-----------+-------------+------------+ | StudentId | StudentName | StudentAge | +-----------+-------------+------------+ | 1 | Carol | 23 | | 2 | John | 24 | | 3 | Adam | 25 | | 4 | Bob | 21 | | 5 | Sam | 22 | +-----------+-------------+------------+ 5 rows in set (0.00 sec) Contact the field in select statement. The query is as follows. mysql> select concat(StudentId,' as an Id'),concat(StudentName,' as a Name') from selectConcat; The following is the output. +-------------------------------+----------------------------------+ | concat(StudentId,' as an Id') | concat(StudentName,' as a Name') | +-------------------------------+----------------------------------+ | 1 as an Id | Carol as a Name | | 2 as an Id | John as a Name | | 3 as an Id | Adam as a Name | | 4 as an Id | Bob as a Name | | 5 as an Id | Sam as a Name | +-------------------------------+----------------------------------+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1153, "s": 1062, "text": "To concat a field in MySQL SELECT, use the CONCAT() function as shown in the below syntax." }, { "code": null, "e": 1288, "s": 1153, "text": "SELECT CONCAT(yourColumnName1,’anyConcatenationString’),CONCAT(yourColumnName2,’anyC\n oncatenationString’),....N from yourTableName;" }, { "code": null, "e": 1392, "s": 1288, "text": "To understand the above syntax, let us first create a table. The query to create a table is as follows." }, { "code": null, "e": 1538, "s": 1392, "text": "mysql> create table selectConcat\n-> (\n-> StudentId int,\n-> StudentName varchar(100),\n-> StudentAge int\n-> );\nQuery OK, 0 rows affected (1.32 sec)" }, { "code": null, "e": 1619, "s": 1538, "text": "Insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2067, "s": 1619, "text": "mysql> insert into selectConcat values(1,'Carol',23);\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into selectConcat values(2,'John',24);\nQuery OK, 1 row affected (0.25 sec)\n\nmysql> insert into selectConcat values(3,'Adam',25);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into selectConcat values(4,'Bob',21);\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into selectConcat values(5,'Sam',22);\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 2152, "s": 2067, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2186, "s": 2152, "text": "mysql> select *from selectConcat;" }, { "code": null, "e": 2215, "s": 2186, "text": "The following is the output." }, { "code": null, "e": 2609, "s": 2215, "text": "+-----------+-------------+------------+\n| StudentId | StudentName | StudentAge |\n+-----------+-------------+------------+\n| 1 | Carol | 23 |\n| 2 | John | 24 |\n| 3 | Adam | 25 |\n| 4 | Bob | 21 |\n| 5 | Sam | 22 |\n+-----------+-------------+------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2673, "s": 2609, "text": "Contact the field in select statement. The query is as follows." }, { "code": null, "e": 2769, "s": 2673, "text": "mysql> select concat(StudentId,' as an Id'),concat(StudentName,' as a Name') from selectConcat;" }, { "code": null, "e": 2798, "s": 2769, "text": "The following is the output." }, { "code": null, "e": 3444, "s": 2798, "text": "+-------------------------------+----------------------------------+\n| concat(StudentId,' as an Id') | concat(StudentName,' as a Name') |\n+-------------------------------+----------------------------------+\n| 1 as an Id | Carol as a Name |\n| 2 as an Id | John as a Name |\n| 3 as an Id | Adam as a Name |\n| 4 as an Id | Bob as a Name |\n| 5 as an Id | Sam as a Name |\n+-------------------------------+----------------------------------+\n5 rows in set (0.00 sec)" } ]
Python | Stack using Doubly Linked List - GeeksforGeeks
30 Dec, 2020 A stack is a collection of objects that are inserted and removed using Last in First out Principle(LIFO). User can insert elements into the stack, and can only access or remove the recently inserted object on top of the stack. The main advantage of using LinkedList over array for implementing stack is the dynamic allocation of data whereas in the array, the size of the stack is restricted and there is a chance of stack overflow error when the size of the stack is exceeded the maximum size. 1. push() : Insert the element into Stack and assign the top pointer to the element.2. pop() : Return top element from the Stack and move the top pointer to thesecond element of the Stack.3. top() : Return the top element.4. size() : Return the Size of the Stack.5. isEmpty() : Return True if Stack is Empty else return False.6. printstack() : Print all elements of the stack. # A complete working Python program to demonstrate all # stack operations using a doubly linked list # Node class class Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null self.prev = None # Initialize prev as null # Stack class contains a Node objectclass Stack: # Function to initialize head def __init__(self): self.head = None # Function to add an element data in the stack def push(self, data): if self.head is None: self.head = Node(data) else: new_node = Node(data) self.head.prev = new_node new_node.next = self.head new_node.prev = None self.head = new_node # Function to pop top element and return the element from the stack def pop(self): if self.head is None: return None elif self.head.next is None: temp = self.head.data self.head = None return temp else: temp = self.head.data self.head = self.head.next self.head.prev = None return temp # Function to return top element in the stack def top(self): return self.head.data # Function to return the size of the stack def size(self): temp = self.head count = 0 while temp is not None: count = count + 1 temp = temp.next return count # Function to check if the stack is empty or not def isEmpty(self): if self.head is None: return True else: return False # Function to print the stack def printstack(self): print("stack elements are:") temp = self.head while temp is not None: print(temp.data, end ="->") temp = temp.next # Code execution starts here if __name__=='__main__': # Start with the empty stack stack = Stack() # Insert 4 at the beginning. So stack becomes 4->None print("Stack operations using Doubly LinkedList") stack.push(4) # Insert 5 at the beginning. So stack becomes 4->5->None stack.push(5) # Insert 6 at the beginning. So stack becomes 4->5->6->None stack.push(6) # Insert 7 at the beginning. So stack becomes 4->5->6->7->None stack.push(7) # Print the stack stack.printstack() # Print the top element print("\nTop element is ", stack.top()) # Print the stack size print("Size of the stack is ", stack.size()) # pop the top element stack.pop() # pop the top element stack.pop() # two elements are popped# Print the stack stack.printstack() # Print True if the stack is empty else False print("\nstack is empty:", stack.isEmpty()) #This code is added by Suparna Raut Stack operations using Doubly LinkedList stack elements are: 7->6->5->4-> Top element is 7 Size of the stack is 4 stack elements are: 5->4-> stack is empty: False SuparnaRaut Python DSA-exercises Python LinkedList-exercises Linked List Python Stack Linked List Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Circular Linked List | Set 2 (Traversal) Swap nodes in a linked list without swapping data Circular Singly Linked List | Insertion Given a linked list which is sorted, how will you insert in sorted way Real-time application of Data Structures Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 26315, "s": 26287, "text": "\n30 Dec, 2020" }, { "code": null, "e": 26810, "s": 26315, "text": "A stack is a collection of objects that are inserted and removed using Last in First out Principle(LIFO). User can insert elements into the stack, and can only access or remove the recently inserted object on top of the stack. The main advantage of using LinkedList over array for implementing stack is the dynamic allocation of data whereas in the array, the size of the stack is restricted and there is a chance of stack overflow error when the size of the stack is exceeded the maximum size." }, { "code": null, "e": 27187, "s": 26810, "text": "1. push() : Insert the element into Stack and assign the top pointer to the element.2. pop() : Return top element from the Stack and move the top pointer to thesecond element of the Stack.3. top() : Return the top element.4. size() : Return the Size of the Stack.5. isEmpty() : Return True if Stack is Empty else return False.6. printstack() : Print all elements of the stack." }, { "code": "# A complete working Python program to demonstrate all # stack operations using a doubly linked list # Node class class Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null self.prev = None # Initialize prev as null # Stack class contains a Node objectclass Stack: # Function to initialize head def __init__(self): self.head = None # Function to add an element data in the stack def push(self, data): if self.head is None: self.head = Node(data) else: new_node = Node(data) self.head.prev = new_node new_node.next = self.head new_node.prev = None self.head = new_node # Function to pop top element and return the element from the stack def pop(self): if self.head is None: return None elif self.head.next is None: temp = self.head.data self.head = None return temp else: temp = self.head.data self.head = self.head.next self.head.prev = None return temp # Function to return top element in the stack def top(self): return self.head.data # Function to return the size of the stack def size(self): temp = self.head count = 0 while temp is not None: count = count + 1 temp = temp.next return count # Function to check if the stack is empty or not def isEmpty(self): if self.head is None: return True else: return False # Function to print the stack def printstack(self): print(\"stack elements are:\") temp = self.head while temp is not None: print(temp.data, end =\"->\") temp = temp.next # Code execution starts here if __name__=='__main__': # Start with the empty stack stack = Stack() # Insert 4 at the beginning. So stack becomes 4->None print(\"Stack operations using Doubly LinkedList\") stack.push(4) # Insert 5 at the beginning. So stack becomes 4->5->None stack.push(5) # Insert 6 at the beginning. So stack becomes 4->5->6->None stack.push(6) # Insert 7 at the beginning. So stack becomes 4->5->6->7->None stack.push(7) # Print the stack stack.printstack() # Print the top element print(\"\\nTop element is \", stack.top()) # Print the stack size print(\"Size of the stack is \", stack.size()) # pop the top element stack.pop() # pop the top element stack.pop() # two elements are popped# Print the stack stack.printstack() # Print True if the stack is empty else False print(\"\\nstack is empty:\", stack.isEmpty()) #This code is added by Suparna Raut", "e": 30090, "s": 27187, "text": null }, { "code": null, "e": 30256, "s": 30090, "text": "Stack operations using Doubly LinkedList\nstack elements are:\n7->6->5->4->\nTop element is 7\nSize of the stack is 4\nstack elements are:\n5->4->\nstack is empty: False\n" }, { "code": null, "e": 30268, "s": 30256, "text": "SuparnaRaut" }, { "code": null, "e": 30289, "s": 30268, "text": "Python DSA-exercises" }, { "code": null, "e": 30317, "s": 30289, "text": "Python LinkedList-exercises" }, { "code": null, "e": 30329, "s": 30317, "text": "Linked List" }, { "code": null, "e": 30336, "s": 30329, "text": "Python" }, { "code": null, "e": 30342, "s": 30336, "text": "Stack" }, { "code": null, "e": 30354, "s": 30342, "text": "Linked List" }, { "code": null, "e": 30360, "s": 30354, "text": "Stack" }, { "code": null, "e": 30458, "s": 30360, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30499, "s": 30458, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 30549, "s": 30499, "text": "Swap nodes in a linked list without swapping data" }, { "code": null, "e": 30589, "s": 30549, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 30660, "s": 30589, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 30701, "s": 30660, "text": "Real-time application of Data Structures" }, { "code": null, "e": 30729, "s": 30701, "text": "Read JSON file using Python" }, { "code": null, "e": 30779, "s": 30729, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 30801, "s": 30779, "text": "Python map() function" } ]
How to call a stored procedure using select statement in MySQL?
In MySQL, it is not possible to use select from procedure in FROM clause. You can use CALL command and after that the SELECT statement can be executed. Let us first create a table: mysql> create table DemoTable2 -> ( -> CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> CustomerName varchar(100), -> ShippingDateTime datetime -> ); Query OK, 0 rows affected (0.66 sec) Following is the query to create stored procedure: mysql> DELIMITER // mysql> CREATE PROCEDURE insert_information(Name varchar(100),shippingtime datetime) -> BEGIN -> -> INSERT INTO DemoTable2(CustomerName,ShippingDateTime) VALUES(Name,shippingtime); -> END -> // Query OK, 0 rows affected (0.16 sec) mysql> DELIMITER ; Now you can call the stored procedure using call command: mysql> call insert_information('Chris',NOW()); Query OK, 1 row affected, 1 warning (0.15 sec) Here is the query to display records from the table using select statement after calling stored procedure. mysql> select *from DemoTable2; This will produce the following output +------------+--------------+---------------------+ | CustomerId | CustomerName | ShippingDateTime | +------------+--------------+---------------------+ | 1 | Chris | 2019-04-08 15:03:07 | +------------+--------------+---------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1214, "s": 1062, "text": "In MySQL, it is not possible to use select from procedure in FROM clause. You can use CALL command and after that the SELECT statement can be executed." }, { "code": null, "e": 1243, "s": 1214, "text": "Let us first create a table:" }, { "code": null, "e": 1451, "s": 1243, "text": "mysql> create table DemoTable2\n -> (\n -> CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> CustomerName varchar(100),\n -> ShippingDateTime datetime\n -> );\nQuery OK, 0 rows affected (0.66 sec)" }, { "code": null, "e": 1502, "s": 1451, "text": "Following is the query to create stored procedure:" }, { "code": null, "e": 1787, "s": 1502, "text": "mysql> DELIMITER //\nmysql> CREATE PROCEDURE insert_information(Name varchar(100),shippingtime datetime)\n -> BEGIN\n ->\n -> INSERT INTO DemoTable2(CustomerName,ShippingDateTime) VALUES(Name,shippingtime);\n -> END\n -> //\nQuery OK, 0 rows affected (0.16 sec)\n\nmysql> DELIMITER ;" }, { "code": null, "e": 1845, "s": 1787, "text": "Now you can call the stored procedure using call command:" }, { "code": null, "e": 1939, "s": 1845, "text": "mysql> call insert_information('Chris',NOW());\nQuery OK, 1 row affected, 1 warning (0.15 sec)" }, { "code": null, "e": 2046, "s": 1939, "text": "Here is the query to display records from the table using select statement after calling stored procedure." }, { "code": null, "e": 2078, "s": 2046, "text": "mysql> select *from DemoTable2;" }, { "code": null, "e": 2117, "s": 2078, "text": "This will produce the following output" }, { "code": null, "e": 2401, "s": 2117, "text": "+------------+--------------+---------------------+\n| CustomerId | CustomerName | ShippingDateTime |\n+------------+--------------+---------------------+\n| 1 | Chris | 2019-04-08 15:03:07 |\n+------------+--------------+---------------------+\n1 row in set (0.00 sec)" } ]
Angular 10 I18nPluralPipe API - GeeksforGeeks
04 Aug, 2021 In this article, we are going to see what is I18nPluralPipe in Angular 10 and how to use it. The I18nPluralPipe is a map that takes a string value that pluralizes according to given rules. Syntax: {{ value | i18nPlural : map [ : rule]}} NgModule: Module used by I18nPluralPipe is: CommonModule Approach: Create an angular app to be used. There is no need for any import for the I18nPluralPipe to be used. In app.component.ts define the variables that takes the I18nPluralPipe value. In app.component.html use the above syntax with ‘|’ symbol to make I18nPluralPipe element. Serve the angular app using ng serve to see the output. Input value: value: it takes a number value. Parameters: pluralMap: It takes an object value. locale: It takes a string value. Example 1: app.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { // Color array colors: any[] = ['red','green','blue']; // Map from which I18nPluralPipe takes the value gfg: {[k: string]: string} = { '=0': 'No color', '=1': 'one color', 'other': '# colors' };} app.component.html <!-- In Below Code I18nPluralPipe is used --><div>there are: {{ colors.length | i18nPlural: gfg }}</div> Output: Example 2: app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { // Language array language: any[] = []; // Map from which I18nPluralPipe // takes the value gfg: {[k: string]: string} = { '=0': 'zero languages', '=1': 'one language', 'other': '# languages' };} app.component.html <!-- In Below Code I18nPluralPipe is used --><div>there are: {{ language.length | i18nPlural: gfg }}</div> Output: Reference: https://angular.io/api/common/I18nPluralPipe bunnyram19 Angular10 AngularJS-API AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Angular Libraries For Web Developers How to use <mat-chip-list> and <mat-chip> in Angular Material ? How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular 10 (blur) Event Angular PrimeNG Dropdown Component Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25109, "s": 25081, "text": "\n04 Aug, 2021" }, { "code": null, "e": 25298, "s": 25109, "text": "In this article, we are going to see what is I18nPluralPipe in Angular 10 and how to use it. The I18nPluralPipe is a map that takes a string value that pluralizes according to given rules." }, { "code": null, "e": 25306, "s": 25298, "text": "Syntax:" }, { "code": null, "e": 25347, "s": 25306, "text": "{{ value | i18nPlural : map [ : rule]}}" }, { "code": null, "e": 25391, "s": 25347, "text": "NgModule: Module used by I18nPluralPipe is:" }, { "code": null, "e": 25404, "s": 25391, "text": "CommonModule" }, { "code": null, "e": 25415, "s": 25404, "text": "Approach: " }, { "code": null, "e": 25449, "s": 25415, "text": "Create an angular app to be used." }, { "code": null, "e": 25516, "s": 25449, "text": "There is no need for any import for the I18nPluralPipe to be used." }, { "code": null, "e": 25594, "s": 25516, "text": "In app.component.ts define the variables that takes the I18nPluralPipe value." }, { "code": null, "e": 25685, "s": 25594, "text": "In app.component.html use the above syntax with ‘|’ symbol to make I18nPluralPipe element." }, { "code": null, "e": 25741, "s": 25685, "text": "Serve the angular app using ng serve to see the output." }, { "code": null, "e": 25756, "s": 25743, "text": "Input value:" }, { "code": null, "e": 25788, "s": 25756, "text": "value: it takes a number value." }, { "code": null, "e": 25800, "s": 25788, "text": "Parameters:" }, { "code": null, "e": 25837, "s": 25800, "text": "pluralMap: It takes an object value." }, { "code": null, "e": 25870, "s": 25837, "text": "locale: It takes a string value." }, { "code": null, "e": 25881, "s": 25870, "text": "Example 1:" }, { "code": null, "e": 25898, "s": 25881, "text": "app.component.ts" }, { "code": "import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { // Color array colors: any[] = ['red','green','blue']; // Map from which I18nPluralPipe takes the value gfg: {[k: string]: string} = { '=0': 'No color', '=1': 'one color', 'other': '# colors' };}", "e": 26318, "s": 25898, "text": null }, { "code": null, "e": 26337, "s": 26318, "text": "app.component.html" }, { "code": "<!-- In Below Code I18nPluralPipe is used --><div>there are: {{ colors.length | i18nPlural: gfg }}</div>", "e": 26442, "s": 26337, "text": null }, { "code": null, "e": 26450, "s": 26442, "text": "Output:" }, { "code": null, "e": 26461, "s": 26450, "text": "Example 2:" }, { "code": null, "e": 26478, "s": 26461, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { // Language array language: any[] = []; // Map from which I18nPluralPipe // takes the value gfg: {[k: string]: string} = { '=0': 'zero languages', '=1': 'one language', 'other': '# languages' };}", "e": 26891, "s": 26478, "text": null }, { "code": null, "e": 26910, "s": 26891, "text": "app.component.html" }, { "code": "<!-- In Below Code I18nPluralPipe is used --><div>there are: {{ language.length | i18nPlural: gfg }}</div>", "e": 27017, "s": 26910, "text": null }, { "code": null, "e": 27025, "s": 27017, "text": "Output:" }, { "code": null, "e": 27081, "s": 27025, "text": "Reference: https://angular.io/api/common/I18nPluralPipe" }, { "code": null, "e": 27092, "s": 27081, "text": "bunnyram19" }, { "code": null, "e": 27102, "s": 27092, "text": "Angular10" }, { "code": null, "e": 27116, "s": 27102, "text": "AngularJS-API" }, { "code": null, "e": 27126, "s": 27116, "text": "AngularJS" }, { "code": null, "e": 27143, "s": 27126, "text": "Web Technologies" }, { "code": null, "e": 27241, "s": 27143, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27250, "s": 27241, "text": "Comments" }, { "code": null, "e": 27263, "s": 27250, "text": "Old Comments" }, { "code": null, "e": 27307, "s": 27263, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 27371, "s": 27307, "text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?" }, { "code": null, "e": 27424, "s": 27371, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 27448, "s": 27424, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 27483, "s": 27448, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 27525, "s": 27483, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27558, "s": 27525, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27601, "s": 27558, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27663, "s": 27601, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Continuous Integration - Version Control
Version control systems, also known as source control, source code management systems, or revision control systems, are a mechanism for keeping multiple versions of your files, so that when you modify a file you can still access the previous revisions. The first popular version control system was a proprietary UNIX tool called SCCS (Source Code Control System) which dates back to the 1970s. This was superseded by RCS, the Revision Control System, and later CVS, Concurrent Versions System. Now the most popular version control system used are Subversion and Git. Let’s first look at why we need to use a versioning control system and next let’s look at putting our source code in Git source code repository system. One reason that we use the term version control in preference to source control is that version control isn’t just for source code. Every single artifact related to the creation of your software should be under version control. Developers should use it for source code − By default all source code needs to be stored in the versioning control system Related artefacts − Every system would be having related artefacts to the source code such as database scripts, build and deployment scripts, documentation, libraries and configuration files for your application, your compiler and collection of tools, and so on. All of these compliment the entire development and deployment process and also needs to be stored in the versioning control system. By storing all the information for the application in source control, it becomes easier to re-create the testing and production environments that your application runs on. This should include configuration information for your application’s software stack and the operating systems that comprise the environment, DNS Zone Files, Firewall Configuration, and so forth. At the bare minimum, you need everything required to re-create your application’s binaries and the environments in which they run. The objective is to have everything that can possibly change at any point in the life of the project stored in a controlled manner. This allows you to recover an exact snapshot of the state of the entire system, from development environment to production environment, at any point in the project’s history. It is even helpful to keep the configuration files for the development team’s development environments in version control since it makes it easy for everyone on the team to use the same settings. Analysts should store requirements documents. Testers should keep their test scripts and procedures in version control. Project managers should save their release plans, progress charts, and risk logs here. In short, every member of the team should store any document or file related to the project in version control. This section will now focus on how Git can be used as a versioning control system. It will focus on how you can upload your code to the versioning control system and manage changes in it. For the purpose of this entire tutorial we are going to look at a simple Web ASP.Net application which will be used for the entire Continuous Integration Process. We don’t need to focus on the entire code details for this exercise, just having an overview of what the project does is sufficient for understanding the entire continuous integration process. This .Net application was built using the Visual Studio Integrated Development Environment. The following screenshot is the structure of the solution in the Visual Studio environment. It is a very simple Web application which has the main code in the Demo.aspx file. The code in the Demo.aspx file is shown in the following program − <html xmlns = "http://www.w3.org/1999/xhtml"> <head runat = "server"> <title>TutorialsPoint</title> </head> <body> <form id = "form1" runat="server"> <div><%Response.Write("Continuous Integration"); %></div> </form> </body> </html> The code is very simple and just outputs the string “Continuous Integration” to the browser. When you run the project in Google Chrome, the output will be as shown in the following screenshot. We are going to show how to move the source code to Git from the command line interface, so that the knowledge of how Git can be used is clearer to the end user. Step 1 − Initialize the Git Repository. Go to the command prompt, go to your project folder and issue the command git init. This command will add the necessary Git files to the project folder, so that it can be recognized by Git when it needs to be uploaded to the repository. Step 2 − Adding your files which need to be added to the Git repository. This can be done by issuing the git add command. The dot option tells Git that all files in the project folder need to be added to the Git repository. Step 3 − The final step is to commit the project files to the Git repository. This step is required to ensure all files are now a part of Git. The command to be issued is given in the following screenshot. The –m option is to provide a comment to the upload of files. Your solution is now available in Git. 16 Lectures 1.5 hours Christopher Frewin 67 Lectures 8 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2239, "s": 1986, "text": "Version control systems, also known as source control, source code management systems, or revision control systems, are a mechanism for keeping multiple versions of your files, so that when you modify a file you can still access the previous revisions." }, { "code": null, "e": 2480, "s": 2239, "text": "The first popular version control system was a proprietary UNIX tool called SCCS (Source Code Control System) which dates back to the 1970s. This was superseded by RCS, the Revision Control System, and later CVS, Concurrent Versions System." }, { "code": null, "e": 2705, "s": 2480, "text": "Now the most popular version control system used are Subversion and Git. Let’s first look at why we need to use a versioning control system and next let’s look at putting our source code in Git source code repository system." }, { "code": null, "e": 2933, "s": 2705, "text": "One reason that we use the term version control in preference to source control is that version control isn’t just for source code. Every single artifact related to the creation of your software should be under version control." }, { "code": null, "e": 3055, "s": 2933, "text": "Developers should use it for source code − By default all source code needs to be stored in the versioning control system" }, { "code": null, "e": 3450, "s": 3055, "text": "Related artefacts − Every system would be having related artefacts to the source code such as database scripts, build and deployment scripts, documentation, libraries and configuration files for your application, your compiler and collection of tools, and so on. All of these compliment the entire development and deployment process and also needs to be stored in the versioning control system." }, { "code": null, "e": 3817, "s": 3450, "text": "By storing all the information for the application in source control, it becomes easier to re-create the testing and production environments that your application runs on. This should include configuration information for your application’s software stack and the operating systems that comprise the environment, DNS Zone Files, Firewall Configuration, and so forth." }, { "code": null, "e": 4255, "s": 3817, "text": "At the bare minimum, you need everything required to re-create your application’s binaries and the environments in which they run. The objective is to have everything that can possibly change at any point in the life of the project stored in a controlled manner. This allows you to recover an exact snapshot of the state of the entire system, from development environment to production environment, at any point in the project’s history." }, { "code": null, "e": 4658, "s": 4255, "text": "It is even helpful to keep the configuration files for the development team’s development environments in version control since it makes it easy for everyone on the team to use the same settings. Analysts should store requirements documents. Testers should keep their test scripts and procedures in version control. Project managers should save their release plans, progress charts, and risk logs here." }, { "code": null, "e": 4770, "s": 4658, "text": "In short, every member of the team should store any document or file related to the project in version control." }, { "code": null, "e": 4958, "s": 4770, "text": "This section will now focus on how Git can be used as a versioning control system. It will focus on how you can upload your code to the versioning control system and manage changes in it." }, { "code": null, "e": 5406, "s": 4958, "text": "For the purpose of this entire tutorial we are going to look at a simple Web ASP.Net application which will be used for the entire Continuous Integration Process. We don’t need to focus on the entire code details for this exercise, just having an overview of what the project does is sufficient for understanding the entire continuous integration process. This .Net application was built using the Visual Studio Integrated Development Environment." }, { "code": null, "e": 5581, "s": 5406, "text": "The following screenshot is the structure of the solution in the Visual Studio environment. It is a very simple Web application which has the main code in the Demo.aspx file." }, { "code": null, "e": 5648, "s": 5581, "text": "The code in the Demo.aspx file is shown in the following program −" }, { "code": null, "e": 5927, "s": 5648, "text": "<html xmlns = \"http://www.w3.org/1999/xhtml\">\n <head runat = \"server\">\n <title>TutorialsPoint</title>\n </head>\n \n <body>\n <form id = \"form1\" runat=\"server\">\n <div><%Response.Write(\"Continuous Integration\"); %></div>\n </form>\n </body>\n \n</html>" }, { "code": null, "e": 6020, "s": 5927, "text": "The code is very simple and just outputs the string “Continuous Integration” to the browser." }, { "code": null, "e": 6120, "s": 6020, "text": "When you run the project in Google Chrome, the output will be as shown in the following screenshot." }, { "code": null, "e": 6282, "s": 6120, "text": "We are going to show how to move the source code to Git from the command line interface, so that the knowledge of how Git can be used is clearer to the end user." }, { "code": null, "e": 6559, "s": 6282, "text": "Step 1 − Initialize the Git Repository. Go to the command prompt, go to your project folder and issue the command git init. This command will add the necessary Git files to the project folder, so that it can be recognized by Git when it needs to be uploaded to the repository." }, { "code": null, "e": 6783, "s": 6559, "text": "Step 2 − Adding your files which need to be added to the Git repository. This can be done by issuing the git add command. The dot option tells Git that all files in the project folder need to be added to the Git repository." }, { "code": null, "e": 7051, "s": 6783, "text": "Step 3 − The final step is to commit the project files to the Git repository. This step is required to ensure all files are now a part of Git. The command to be issued is given in the following screenshot. The –m option is to provide a comment to the upload of files." }, { "code": null, "e": 7090, "s": 7051, "text": "Your solution is now available in Git." }, { "code": null, "e": 7125, "s": 7090, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7145, "s": 7125, "text": " Christopher Frewin" }, { "code": null, "e": 7178, "s": 7145, "text": "\n 67 Lectures \n 8 hours \n" }, { "code": null, "e": 7196, "s": 7178, "text": " Packt Publishing" }, { "code": null, "e": 7203, "s": 7196, "text": " Print" }, { "code": null, "e": 7214, "s": 7203, "text": " Add Notes" } ]
Shortest Common Supersequence | Practice | GeeksforGeeks
Given two strings X and Y of lengths m and n respectively, find the length of the smallest string which has both, X and Y as its sub-sequences. Note: X and Y can have both uppercase and lowercase letters. Example 1 Input: X = abcd, Y = xycd Output: 6 Explanation: Shortest Common Supersequence would be abxycd which is of length 6 and has both the strings as its subsequences. Example 2 Input: X = efgh, Y = jghi Output: 6 Explanation: Shortest Common Supersequence would be ejfghi which is of length 6 and has both the strings as its subsequences. Your Task: Complete shortestCommonSupersequence() function that takes X, Y, m, and n as arguments and returns the length of the required string. Expected Time Complexity: O(Length(X) * Length(Y)). Expected Auxiliary Space: O(Length(X) * Length(Y)). Constraints: 1<= |X|, |Y| <= 100 0 vinamrajha1 week ago int shortestCommonSupersequence(string X, string Y, int m, int n) { //code here //LCS_variation int dp[m+1][n+1]; for(int i =0; i<=m; ++i)dp[i][0] = 0; for(int i =0; i<=n; ++i)dp[0][i] = 0; for(int i =1; i<=m; ++i){ for(int j =1; j<=n; ++j){ if(X[i-1]==Y[j-1]) dp[i][j] = 1+dp[i-1][j-1]; else dp[i][j] = max(dp[i-1][j], dp[i][j-1]); } } return(m+n-dp[m][n]); } 0 uratabhi3 weeks ago #include <bits/stdc++.h> using ll = int64_t; using iii = std::tuple<int, int, int>; void sum(int a); signed main() { std::string X, Y; std::cin >> X >> Y; int n = X.size(); int m = Y.size(); std::vector<std::vector<int>> dp(n + 1, std::vector<int>(m + 1, 0)); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (X[i - 1] == Y[j - 1]) { dp[i][j] = 1 + dp[i - 1][j - 1]; } else { dp[i][j] = std::max(dp[i - 1][j], dp[i][j - 1]); } } } std::cout<<m+n-dp[n][m]<<'\n'; } void sum(int a) { std::cout << ++a << '\n'; } 0 hamidnourashraf1 month ago class Solution: #find longest common subsequent and then return m+n - len(LC_subsequence) def shortestCommonSupersequence(self, X, Y, m, n): dp = [[0] * (n+1) for i in range(m+1)] for i in range(1, m+1): for j in range(1, n+1): if X[i-1] == Y[j-1]: dp[i][j] = 1 + dp[i-1][j-1] else: dp[i][j] = max(dp[i-1][j], dp[i][j-1]) return m+n - dp[m][n] 0 adityasingh1091 month ago private: int lcs(string s1, string s2 , int m , int n ){ int dp[m+1][n+1]; for(int i = 0; i<m+1; i++){ for(int j = 0; j<n+1; j++){ if(i == 0 || j ==0) dp[i][j] = 0; } } for(int i = 1; i<m+1; i++){ for(int j = 1; j<n+1; j++){ if(s1[i-1] == s2[j-1] ) dp[i][j] = 1+dp[i-1][j-1]; else dp[i][j] = max(dp[i-1][j], dp[i][j-1] ); } } return dp[m][n]; } public: int shortestCommonSupersequence(string X, string Y, int m, int n) { return m+n - lcs(X, Y, m , n); } 0 ayushkumar54511 month ago int dp[1001][1001]; int lcs(string &a,string &b,int n,int m){ for(int i=0;i<=n;i++){ for(int j=0;j<=m;j++){ if(i==0 or j==0) dp[i][j]=0; } } for(int i=1;i<n+1;i++){ for(int j=1;j<m+1;j++){ if(a[i-1]==b[j-1]){ dp[i][j]=1+dp[i-1][j-1]; } else{ dp[i][j]=max(dp[i][j-1],dp[i-1][j]); } } } return dp[n][m]; } int shortestCommonSupersequence(string X, string Y, int m, int n) { int x=n-lcs(X,Y,m,n); int y=m-lcs(X,Y,m,n); return x+y+lcs(X,Y,m,n); } +1 shishankrawt937741 month ago This is my solution with a different, but intiutive approach. I hope it is helpful: This is the code: // { Driver Code Starts //Initial template for C++ #include<bits/stdc++.h> using namespace std; // } Driver Code Ends //User function template for C++ class Solution { public: //Function to find length of shortest common supersequence of two strings. int shortestCommonSupersequence(string a, string b, int n1, int n2) { //code here int dp[n1+1][n2+1]; memset(dp, 0, sizeof(dp)); dp[0][0] = 0; for(int i = 1; i<=n1; i++)dp[i][0] = i; // Base Case for(int i = 1; i<=n2; i++)dp[0][i] = i; // Base Case for(int i = 1; i<=n1; i++){ for(int j = 1; j<=n2; j++){ if(a[i-1] == b[j-1]){ dp[i][j] = dp[i-1][j-1] + 1; // If both chars are same, add only 1. continue; } dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + 1; // Give the min + 1 to the ans. } } return dp[n1][n2]; } }; // { Driver Code Starts. int main() { int t; //taking total testcases cin >> t; while(t--){ string X, Y; //taking String X and Y cin >> X >> Y; //calling function shortestCommonSupersequence() Solution obj; cout << obj.shortestCommonSupersequence(X, Y, X.size(), Y.size())<< endl; } return 0; } // } Driver Code Ends 0 anandkumarsatapathy1 month ago // { Driver Code Starts//Initial template for C++ #include<bits/stdc++.h>using namespace std; // } Driver Code Ends//User function template for C++ class Solution{ public: int lcs(string w1,string w2) { int n = w1.length(); int m = w2.length(); vector<vector<int>>dp(n+1,vector<int>(m+1,0)); for(int i =0;i<=n;i++)dp[i][0]=0; for(int j =0;j<=m;j++)dp[0][j]=0; for(int i = 1;i<=n;i++){ for(int j = 1;j<=m;j++){ if(w1[i-1]==w2[j-1]) dp[i][j]=1+dp[i-1][j-1]; else dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } return dp[n][m]; } //Function to find length of shortest common supersequence of two strings. int shortestCommonSupersequence(string X, string Y, int m, int n) { int x = n-lcs(X,Y); int y = m-lcs(X,Y); return x+y+lcs(X,); }}; // { Driver Code Starts. int main(){ int t; //taking total testcases cin >> t; while(t--){ string X, Y; //taking String X and Ycin >> X >> Y;//calling function shortestCommonSupersequence()Solution obj;cout << obj.shortestCommonSupersequence(X, Y, X.size(), Y.size())<< endl; }return 0;} // } Driver Code Ends 0 amish987652 months ago gfg ques are a cup of tea for me JAVA Solution: public static int shortestCommonSupersequence(String X,String Y,int m,int n) { //Your code here int[][] t=new int[m+1][n+1]; int ans=0; for(int i=1;i<=m;i++){ for(int j=1;j<=n;j++){ if(X.charAt(i-1)==Y.charAt(j-1)){ t[i][j]=1+t[i-1][j-1]; } else{ t[i][j]=Math.max(t[i-1][j],t[i][j-1]); } } } ans=(m+n)-t[m][n]; return ans; } 0 annanyamathur2 months ago int dp[101][101]; int shortestCommonSupersequence(string x, string y, int n, int m) { for(int i=0;i<=m;i++) dp[i][0]=0; for(int j=0;j<=n;j++) dp[0][j]=0; for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { if(x[i-1]==y[j-1]) dp[i][j]=1+dp[i-1][j-1]; else dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } int res=n+m-dp[n][m]; return res; } +1 madhukartemba2 months ago JAVA SOLUTION: class Solution { private static int LCS(String X, String Y, int n1, int n2) { int dp[][] = new int[n1+1][n2+1]; for(int i=1; i<=n1; i++) { for(int j=1; j<=n2; j++) { if(X.charAt(i-1)==Y.charAt(j-1)) { dp[i][j] = dp[i-1][j-1] + 1; } else { dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]); } } } return dp[n1][n2]; } //Function to find length of shortest common supersequence of two strings. public static int shortestCommonSupersequence(String X,String Y,int m,int n) { int lcs = LCS(X, Y, m, n); return lcs + (m-lcs) + (n-lcs); } } 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": 443, "s": 238, "text": "Given two strings X and Y of lengths m and n respectively, find the length of the smallest string which has both, X and Y as its sub-sequences.\nNote: X and Y can have both uppercase and lowercase letters." }, { "code": null, "e": 453, "s": 443, "text": "Example 1" }, { "code": null, "e": 616, "s": 453, "text": "Input:\nX = abcd, Y = xycd\nOutput: 6\nExplanation: Shortest Common Supersequence\nwould be abxycd which is of length 6 and\nhas both the strings as its subsequences.\n" }, { "code": null, "e": 626, "s": 616, "text": "Example 2" }, { "code": null, "e": 788, "s": 626, "text": "Input:\nX = efgh, Y = jghi\nOutput: 6\nExplanation: Shortest Common Supersequence\nwould be ejfghi which is of length 6 and\nhas both the strings as its subsequences." }, { "code": null, "e": 933, "s": 788, "text": "Your Task:\nComplete shortestCommonSupersequence() function that takes X, Y, m, and n as arguments and returns the length of the required string." }, { "code": null, "e": 1037, "s": 933, "text": "Expected Time Complexity: O(Length(X) * Length(Y)).\nExpected Auxiliary Space: O(Length(X) * Length(Y))." }, { "code": null, "e": 1070, "s": 1037, "text": "Constraints:\n1<= |X|, |Y| <= 100" }, { "code": null, "e": 1074, "s": 1072, "text": "0" }, { "code": null, "e": 1095, "s": 1074, "text": "vinamrajha1 week ago" }, { "code": null, "e": 1570, "s": 1095, "text": "int shortestCommonSupersequence(string X, string Y, int m, int n)\n {\n //code here\n //LCS_variation\n int dp[m+1][n+1];\n for(int i =0; i<=m; ++i)dp[i][0] = 0;\n for(int i =0; i<=n; ++i)dp[0][i] = 0;\n for(int i =1; i<=m; ++i){\n for(int j =1; j<=n; ++j){\n if(X[i-1]==Y[j-1]) dp[i][j] = 1+dp[i-1][j-1];\n else dp[i][j] = max(dp[i-1][j], dp[i][j-1]);\n }\n }\n return(m+n-dp[m][n]);\n }" }, { "code": null, "e": 1572, "s": 1570, "text": "0" }, { "code": null, "e": 1592, "s": 1572, "text": "uratabhi3 weeks ago" }, { "code": null, "e": 1617, "s": 1592, "text": "#include <bits/stdc++.h>" }, { "code": null, "e": 1637, "s": 1617, "text": "using ll = int64_t;" }, { "code": null, "e": 1676, "s": 1637, "text": "using iii = std::tuple<int, int, int>;" }, { "code": null, "e": 1693, "s": 1676, "text": "void sum(int a);" }, { "code": null, "e": 1707, "s": 1693, "text": "signed main()" }, { "code": null, "e": 1709, "s": 1707, "text": "{" }, { "code": null, "e": 1731, "s": 1709, "text": " std::string X, Y;" }, { "code": null, "e": 1755, "s": 1731, "text": " std::cin >> X >> Y;" }, { "code": null, "e": 1777, "s": 1755, "text": " int n = X.size();" }, { "code": null, "e": 1799, "s": 1777, "text": " int m = Y.size();" }, { "code": null, "e": 1872, "s": 1799, "text": " std::vector<std::vector<int>> dp(n + 1, std::vector<int>(m + 1, 0));" }, { "code": null, "e": 1907, "s": 1874, "text": " for (int i = 1; i <= n; i++)" }, { "code": null, "e": 1913, "s": 1907, "text": " {" }, { "code": null, "e": 1950, "s": 1913, "text": " for (int j = 1; j <= m; j++)" }, { "code": null, "e": 1960, "s": 1950, "text": " {" }, { "code": null, "e": 1998, "s": 1960, "text": " if (X[i - 1] == Y[j - 1])" }, { "code": null, "e": 2012, "s": 1998, "text": " {" }, { "code": null, "e": 2061, "s": 2012, "text": " dp[i][j] = 1 + dp[i - 1][j - 1];" }, { "code": null, "e": 2075, "s": 2061, "text": " }" }, { "code": null, "e": 2092, "s": 2075, "text": " else" }, { "code": null, "e": 2106, "s": 2092, "text": " {" }, { "code": null, "e": 2171, "s": 2106, "text": " dp[i][j] = std::max(dp[i - 1][j], dp[i][j - 1]);" }, { "code": null, "e": 2185, "s": 2171, "text": " }" }, { "code": null, "e": 2195, "s": 2185, "text": " }" }, { "code": null, "e": 2201, "s": 2195, "text": " }" }, { "code": null, "e": 2236, "s": 2201, "text": " std::cout<<m+n-dp[n][m]<<'\\n';" }, { "code": null, "e": 2238, "s": 2236, "text": "}" }, { "code": null, "e": 2256, "s": 2240, "text": "void sum(int a)" }, { "code": null, "e": 2258, "s": 2256, "text": "{" }, { "code": null, "e": 2288, "s": 2258, "text": " std::cout << ++a << '\\n';" }, { "code": null, "e": 2290, "s": 2288, "text": "}" }, { "code": null, "e": 2292, "s": 2290, "text": "0" }, { "code": null, "e": 2319, "s": 2292, "text": "hamidnourashraf1 month ago" }, { "code": null, "e": 2784, "s": 2319, "text": "class Solution:\n \n #find longest common subsequent and then return m+n - len(LC_subsequence)\n def shortestCommonSupersequence(self, X, Y, m, n):\n dp = [[0] * (n+1) for i in range(m+1)]\n for i in range(1, m+1):\n for j in range(1, n+1):\n if X[i-1] == Y[j-1]:\n dp[i][j] = 1 + dp[i-1][j-1]\n else:\n dp[i][j] = max(dp[i-1][j], dp[i][j-1])\n return m+n - dp[m][n]" }, { "code": null, "e": 2786, "s": 2784, "text": "0" }, { "code": null, "e": 2812, "s": 2786, "text": "adityasingh1091 month ago" }, { "code": null, "e": 3584, "s": 2812, "text": " private:\n int lcs(string s1, string s2 , int m , int n ){\n int dp[m+1][n+1];\n \n for(int i = 0; i<m+1; i++){\n for(int j = 0; j<n+1; j++){\n if(i == 0 || j ==0)\n dp[i][j] = 0;\n }\n }\n \n for(int i = 1; i<m+1; i++){\n for(int j = 1; j<n+1; j++){\n if(s1[i-1] == s2[j-1] )\n dp[i][j] = 1+dp[i-1][j-1];\n else \n dp[i][j] = max(dp[i-1][j], dp[i][j-1] );\n }\n \n }\n \n return dp[m][n];\n \n \n }\npublic: \n int shortestCommonSupersequence(string X, string Y, int m, int n)\n {\n return m+n - lcs(X, Y, m , n);\n }" }, { "code": null, "e": 3586, "s": 3584, "text": "0" }, { "code": null, "e": 3612, "s": 3586, "text": "ayushkumar54511 month ago" }, { "code": null, "e": 4257, "s": 3612, "text": " int dp[1001][1001]; int lcs(string &a,string &b,int n,int m){ for(int i=0;i<=n;i++){ for(int j=0;j<=m;j++){ if(i==0 or j==0) dp[i][j]=0; } } for(int i=1;i<n+1;i++){ for(int j=1;j<m+1;j++){ if(a[i-1]==b[j-1]){ dp[i][j]=1+dp[i-1][j-1]; } else{ dp[i][j]=max(dp[i][j-1],dp[i-1][j]); } } } return dp[n][m]; } int shortestCommonSupersequence(string X, string Y, int m, int n) { int x=n-lcs(X,Y,m,n); int y=m-lcs(X,Y,m,n); return x+y+lcs(X,Y,m,n); }" }, { "code": null, "e": 4260, "s": 4257, "text": "+1" }, { "code": null, "e": 4289, "s": 4260, "text": "shishankrawt937741 month ago" }, { "code": null, "e": 4352, "s": 4289, "text": "This is my solution with a different, but intiutive approach. " }, { "code": null, "e": 4374, "s": 4352, "text": "I hope it is helpful:" }, { "code": null, "e": 4394, "s": 4376, "text": "This is the code:" }, { "code": null, "e": 5739, "s": 4394, "text": "// { Driver Code Starts\n//Initial template for C++\n\n#include<bits/stdc++.h>\nusing namespace std;\n\n\n // } Driver Code Ends\n//User function template for C++\n\n\nclass Solution\n{\n public:\n //Function to find length of shortest common supersequence of two strings.\n int shortestCommonSupersequence(string a, string b, int n1, int n2)\n {\n //code here\n int dp[n1+1][n2+1];\n memset(dp, 0, sizeof(dp));\n dp[0][0] = 0;\n for(int i = 1; i<=n1; i++)dp[i][0] = i; // Base Case\n for(int i = 1; i<=n2; i++)dp[0][i] = i; // Base Case\n for(int i = 1; i<=n1; i++){\n for(int j = 1; j<=n2; j++){\n if(a[i-1] == b[j-1]){\n dp[i][j] = dp[i-1][j-1] + 1; // If both chars are same, add only 1.\n continue;\n }\n dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + 1; // Give the min + 1 to the ans.\n }\n }\n return dp[n1][n2];\n }\n};\n\n// { Driver Code Starts.\n\nint main()\n{ \n \n int t;\n \n //taking total testcases\n cin >> t;\n while(t--){\n string X, Y;\n //taking String X and Y\n\tcin >> X >> Y;\n\t\n\t//calling function shortestCommonSupersequence()\n\tSolution obj;\n\tcout << obj.shortestCommonSupersequence(X, Y, X.size(), Y.size())<< endl;\n }\n\treturn 0;\n}\n\n // } Driver Code Ends" }, { "code": null, "e": 5741, "s": 5739, "text": "0" }, { "code": null, "e": 5772, "s": 5741, "text": "anandkumarsatapathy1 month ago" }, { "code": null, "e": 5822, "s": 5772, "text": "// { Driver Code Starts//Initial template for C++" }, { "code": null, "e": 5866, "s": 5822, "text": "#include<bits/stdc++.h>using namespace std;" }, { "code": null, "e": 5920, "s": 5866, "text": "// } Driver Code Ends//User function template for C++" }, { "code": null, "e": 6666, "s": 5920, "text": "class Solution{ public: int lcs(string w1,string w2) { int n = w1.length(); int m = w2.length(); vector<vector<int>>dp(n+1,vector<int>(m+1,0)); for(int i =0;i<=n;i++)dp[i][0]=0; for(int j =0;j<=m;j++)dp[0][j]=0; for(int i = 1;i<=n;i++){ for(int j = 1;j<=m;j++){ if(w1[i-1]==w2[j-1]) dp[i][j]=1+dp[i-1][j-1]; else dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } return dp[n][m]; } //Function to find length of shortest common supersequence of two strings. int shortestCommonSupersequence(string X, string Y, int m, int n) { int x = n-lcs(X,Y); int y = m-lcs(X,Y); return x+y+lcs(X,); }};" }, { "code": null, "e": 6691, "s": 6666, "text": "// { Driver Code Starts." }, { "code": null, "e": 6977, "s": 6691, "text": "int main(){ int t; //taking total testcases cin >> t; while(t--){ string X, Y; //taking String X and Ycin >> X >> Y;//calling function shortestCommonSupersequence()Solution obj;cout << obj.shortestCommonSupersequence(X, Y, X.size(), Y.size())<< endl; }return 0;}" }, { "code": null, "e": 7000, "s": 6977, "text": " // } Driver Code Ends" }, { "code": null, "e": 7002, "s": 7000, "text": "0" }, { "code": null, "e": 7025, "s": 7002, "text": "amish987652 months ago" }, { "code": null, "e": 7059, "s": 7025, "text": "gfg ques are a cup of tea for me " }, { "code": null, "e": 7074, "s": 7059, "text": "JAVA Solution:" }, { "code": null, "e": 7557, "s": 7074, "text": "public static int shortestCommonSupersequence(String X,String Y,int m,int n) { //Your code here int[][] t=new int[m+1][n+1]; int ans=0; for(int i=1;i<=m;i++){ for(int j=1;j<=n;j++){ if(X.charAt(i-1)==Y.charAt(j-1)){ t[i][j]=1+t[i-1][j-1]; } else{ t[i][j]=Math.max(t[i-1][j],t[i][j-1]); } } } ans=(m+n)-t[m][n]; return ans; }" }, { "code": null, "e": 7559, "s": 7557, "text": "0" }, { "code": null, "e": 7585, "s": 7559, "text": "annanyamathur2 months ago" }, { "code": null, "e": 8059, "s": 7585, "text": "int dp[101][101]; int shortestCommonSupersequence(string x, string y, int n, int m) { for(int i=0;i<=m;i++) dp[i][0]=0; for(int j=0;j<=n;j++) dp[0][j]=0; for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { if(x[i-1]==y[j-1]) dp[i][j]=1+dp[i-1][j-1]; else dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } int res=n+m-dp[n][m]; return res; }" }, { "code": null, "e": 8062, "s": 8059, "text": "+1" }, { "code": null, "e": 8088, "s": 8062, "text": "madhukartemba2 months ago" }, { "code": null, "e": 8103, "s": 8088, "text": "JAVA SOLUTION:" }, { "code": null, "e": 8978, "s": 8103, "text": "class Solution\n{\n \n private static int LCS(String X, String Y, int n1, int n2)\n {\n int dp[][] = new int[n1+1][n2+1];\n \n for(int i=1; i<=n1; i++)\n {\n for(int j=1; j<=n2; j++)\n {\n if(X.charAt(i-1)==Y.charAt(j-1))\n {\n dp[i][j] = dp[i-1][j-1] + 1;\n }\n else\n {\n dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);\n }\n }\n }\n \n return dp[n1][n2];\n \n \n }\n \n //Function to find length of shortest common supersequence of two strings.\n public static int shortestCommonSupersequence(String X,String Y,int m,int n)\n {\n \n int lcs = LCS(X, Y, m, n);\n \n return lcs + (m-lcs) + (n-lcs);\n \n \n \n }\n}" }, { "code": null, "e": 9124, "s": 8978, "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": 9160, "s": 9124, "text": " Login to access your submissions. " }, { "code": null, "e": 9170, "s": 9160, "text": "\nProblem\n" }, { "code": null, "e": 9180, "s": 9170, "text": "\nContest\n" }, { "code": null, "e": 9243, "s": 9180, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9391, "s": 9243, "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": 9599, "s": 9391, "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": 9705, "s": 9599, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Timeit in Python with Examples?
Python provides many ways to measure the time of execution for a piece of python code. One way is to use the python inbuilt time module and save the time before and after the execution of the program? When some program is running, many processes also run in the background to make that code executable. The time module doesn’t count background processes execution time, however if you need precise time performance measurements timeit is the module to go for it. The timeit module runs the code approximately 1 million times (default value) and take into account the minimum amount of time it took to run that piece of code. We can use timeit module in many ways. One of the simplest ways is to use directly on the python CLI. We will start using python CLI with timeit module first. When CLI is used, we’ll notice that the module itself decides the number of repetitions performed for the same piece of code. C:\Users\rajesh>python -m timeit "'-'.join(str(n) for n in range(200))" 1000 loops, best of 3: 290 usec per loop C:\Users\rajesh>python -m timeit "'-'.join(str(n) for n in range(200))" 1000 loops, best of 3: 292 usec per loop C:\Users\rajesh>python -m timeit "'-'.join(str(n) for n in range(200))" 1000 loops, best of 3: 294 usec per loop Next we introduce timeit with another simple example but first we must import timeit module with “import timeit” statement. This is required incase we are not using command-line syntax like above. #Import timeit module import timeit # The instructions being timed. print('x' * 5) print('x' + 'x' + 'x' + 'x' + 'x') # Call timeit on the statements and print the time returned. # ... Specify optional number of iterations. print(timeit.timeit("y = 'x' * 3", number=10000000)) print(timeit.timeit("xy = 'x' + 'x' + 'x' + 'x' + 'x'", number = 10000000)) Above we pass the statements in quoted strings to the timeit.timeit method and then we increase the iterations by specifying a number argument. First time on running above program, output generated: xxxxx xxxxx 0.9041136896626635 0.7712796073957123 Second time on running above program, output generated: xxxxx xxxxx 0.7317015874427751 0.7312688195585995 Third time on running above program, output generated: xxxxx xxxxx 0.7240862411172824 0.7255863890794246 We performed our above program multiple times(3 times) and see there is reduction is execution time. One instead of doing it manually, let’s do the repetition through program: #Import timeit module import timeit # Call timeit on the statements and print the time returned. # ... Specify optional number of iterations. print(timeit.repeat("y = 'x' * 3", number=10000000, repeat = 5)) print() print(timeit.repeat("xy= 'x' + 'x' + 'x' + 'x' + 'x'", number = 10000000, repeat = 5)) [0.7303736343436382, 0.7213687552991258, 0.7362311105941466, 0.7293136666273243, 0.7278277732068212] [0.7388334197158559, 0.7378481457977326, 0.9486733868277772, 0.735295442480929, 0.7398226849056382] Running Multiple statements using timeit module: We can use multiple statements with timeit module. We separate each statements using a semicolon. Though it’s not the best way to write code but helps in specifying longer code fragments. #Import timeit module import timeit # Use semicolon for multiple statements. print(timeit.repeat("x = 2; x *= 2", number=100000000)) print(timeit.repeat("x = 1; x *= 4", number=100000000)) [24.859605879029118, 23.58795536845994, 23.95826726353284] [22.70639977603264, 21.380195994245724, 20.71523588130414] Using Methods, setup in Timeit module: We can use the custom methods in timeit by specifying a setup argument. In this argument, we specify an import statement that indicates the methods we invoke. #Import timeit module import timeit def func1(): return 1 def func2(): return sum([-1, 0, 1, 1]) # Test methods. print(func1()) print(func2()) # Pass setup argument to call methods. print(timeit.repeat("func1()", setup="from __main__ import func1")) print(timeit.repeat("func2()", setup="from __main__ import func2")) In above program we benchmark the func1() method against the func2() method. 1 1 [0.44798489246658874, 0.4411512652046069, 0.44570416580426686] [1.583622557983199, 1.5712399227517881, 1.5469479030713984] As func1() is doing less work, executed much faster. Above we saw how we can measure the performance of small piece of python code using the timeit module using CLI and scripts as well.
[ { "code": null, "e": 1263, "s": 1062, "text": "Python provides many ways to measure the time of execution for a piece of python code. One way is to use the python inbuilt time module and save the time before and after the execution of the program?" }, { "code": null, "e": 1525, "s": 1263, "text": "When some program is running, many processes also run in the background to make that code executable. The time module doesn’t count background processes execution time, however if you need precise time performance measurements timeit is the module to go for it." }, { "code": null, "e": 1687, "s": 1525, "text": "The timeit module runs the code approximately 1 million times (default value) and take into account the minimum amount of time it took to run that piece of code." }, { "code": null, "e": 1789, "s": 1687, "text": "We can use timeit module in many ways. One of the simplest ways is to use directly on the python CLI." }, { "code": null, "e": 1972, "s": 1789, "text": "We will start using python CLI with timeit module first. When CLI is used, we’ll notice that the module itself decides the number of repetitions performed for the same piece of code." }, { "code": null, "e": 2313, "s": 1972, "text": "C:\\Users\\rajesh>python -m timeit \"'-'.join(str(n) for n in range(200))\"\n1000 loops, best of 3: 290 usec per loop\n\nC:\\Users\\rajesh>python -m timeit \"'-'.join(str(n) for n in range(200))\"\n1000 loops, best of 3: 292 usec per loop\n\nC:\\Users\\rajesh>python -m timeit \"'-'.join(str(n) for n in range(200))\"\n1000 loops, best of 3: 294 usec per loop" }, { "code": null, "e": 2510, "s": 2313, "text": "Next we introduce timeit with another simple example but first we must import timeit module with “import timeit” statement. This is required incase we are not using command-line syntax like above." }, { "code": null, "e": 2865, "s": 2510, "text": "#Import timeit module\nimport timeit\n\n# The instructions being timed.\nprint('x' * 5)\nprint('x' + 'x' + 'x' + 'x' + 'x')\n\n# Call timeit on the statements and print the time returned.\n# ... Specify optional number of iterations.\nprint(timeit.timeit(\"y = 'x' * 3\", number=10000000))\nprint(timeit.timeit(\"xy = 'x' + 'x' + 'x' + 'x' + 'x'\", number = 10000000))" }, { "code": null, "e": 3009, "s": 2865, "text": "Above we pass the statements in quoted strings to the timeit.timeit method and then we increase the iterations by specifying a number argument." }, { "code": null, "e": 3064, "s": 3009, "text": "First time on running above program, output generated:" }, { "code": null, "e": 3114, "s": 3064, "text": "xxxxx\nxxxxx\n0.9041136896626635\n0.7712796073957123" }, { "code": null, "e": 3170, "s": 3114, "text": "Second time on running above program, output generated:" }, { "code": null, "e": 3220, "s": 3170, "text": "xxxxx\nxxxxx\n0.7317015874427751\n0.7312688195585995" }, { "code": null, "e": 3275, "s": 3220, "text": "Third time on running above program, output generated:" }, { "code": null, "e": 3325, "s": 3275, "text": "xxxxx\nxxxxx\n0.7240862411172824\n0.7255863890794246" }, { "code": null, "e": 3501, "s": 3325, "text": "We performed our above program multiple times(3 times) and see there is reduction is execution time. One instead of doing it manually, let’s do the repetition through program:" }, { "code": null, "e": 3803, "s": 3501, "text": "#Import timeit module\nimport timeit\n# Call timeit on the statements and print the time returned.\n# ... Specify optional number of iterations.\nprint(timeit.repeat(\"y = 'x' * 3\", number=10000000, repeat = 5))\nprint()\nprint(timeit.repeat(\"xy= 'x' + 'x' + 'x' + 'x' + 'x'\", number = 10000000, repeat = 5))" }, { "code": null, "e": 4005, "s": 3803, "text": "[0.7303736343436382, 0.7213687552991258, 0.7362311105941466, 0.7293136666273243, 0.7278277732068212]\n\n[0.7388334197158559, 0.7378481457977326, 0.9486733868277772, 0.735295442480929, 0.7398226849056382]" }, { "code": null, "e": 4054, "s": 4005, "text": "Running Multiple statements using timeit module:" }, { "code": null, "e": 4242, "s": 4054, "text": "We can use multiple statements with timeit module. We separate each statements using a semicolon. Though it’s not the best way to write code but helps in specifying longer code fragments." }, { "code": null, "e": 4432, "s": 4242, "text": "#Import timeit module\nimport timeit\n\n# Use semicolon for multiple statements.\nprint(timeit.repeat(\"x = 2; x *= 2\", number=100000000))\nprint(timeit.repeat(\"x = 1; x *= 4\", number=100000000))" }, { "code": null, "e": 4550, "s": 4432, "text": "[24.859605879029118, 23.58795536845994, 23.95826726353284]\n[22.70639977603264, 21.380195994245724, 20.71523588130414]" }, { "code": null, "e": 4589, "s": 4550, "text": "Using Methods, setup in Timeit module:" }, { "code": null, "e": 4748, "s": 4589, "text": "We can use the custom methods in timeit by specifying a setup argument. In this argument, we specify an import statement that indicates the methods we invoke." }, { "code": null, "e": 5076, "s": 4748, "text": "#Import timeit module\nimport timeit\n\ndef func1():\n return 1\n\ndef func2():\n return sum([-1, 0, 1, 1])\n\n# Test methods.\nprint(func1())\nprint(func2())\n\n# Pass setup argument to call methods.\nprint(timeit.repeat(\"func1()\", setup=\"from __main__ import func1\"))\nprint(timeit.repeat(\"func2()\", setup=\"from __main__ import func2\"))" }, { "code": null, "e": 5153, "s": 5076, "text": "In above\nprogram we benchmark the func1() method against the func2() method." }, { "code": null, "e": 5280, "s": 5153, "text": "1\n1\n[0.44798489246658874, 0.4411512652046069, 0.44570416580426686]\n[1.583622557983199, 1.5712399227517881, 1.5469479030713984]" }, { "code": null, "e": 5333, "s": 5280, "text": "As func1() is doing less work, executed much faster." }, { "code": null, "e": 5466, "s": 5333, "text": "Above we saw how we can measure the performance of small piece of python code using the timeit module using CLI and scripts as well." } ]
How to horizontal align text content into center in HTML ? - GeeksforGeeks
25 Dec, 2020 In this article, we will align the text content into center using HTML. We use align=”center” attribute to set the text content into center. Syntax: <element_name align="center"> Contents... <element_name> The align=”center” attribute is used to set the text content into center. Example 1: HTML <!DOCTYPE html><html> <head> <title> How to horizontal align text content into center in HTML? </title> <style> h1 { color: green; } </style></head> <body> <h1 align="center"> GeeksforGeeks </h1> <h3 align="center"> How to horizontal align text content into center in HTML? </h3> <p align="center"> GeeksforGeeks: A computer science portal for geeks </p> </body> </html> Output: Example 2: Use CSS text-align=”center” property to set the text content into center. HTML <!DOCTYPE html><html> <head> <title> How to horizontal align text content into center in HTML? </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3> How to horizontal align text content into center in HTML? </h3> <p> GeeksforGeeks: A computer science portal for geeks </p> </body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 25376, "s": 25348, "text": "\n25 Dec, 2020" }, { "code": null, "e": 25517, "s": 25376, "text": "In this article, we will align the text content into center using HTML. We use align=”center” attribute to set the text content into center." }, { "code": null, "e": 25525, "s": 25517, "text": "Syntax:" }, { "code": null, "e": 25582, "s": 25525, "text": "<element_name align=\"center\"> Contents... <element_name>" }, { "code": null, "e": 25656, "s": 25582, "text": "The align=”center” attribute is used to set the text content into center." }, { "code": null, "e": 25667, "s": 25656, "text": "Example 1:" }, { "code": null, "e": 25672, "s": 25667, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to horizontal align text content into center in HTML? </title> <style> h1 { color: green; } </style></head> <body> <h1 align=\"center\"> GeeksforGeeks </h1> <h3 align=\"center\"> How to horizontal align text content into center in HTML? </h3> <p align=\"center\"> GeeksforGeeks: A computer science portal for geeks </p> </body> </html>", "e": 26157, "s": 25672, "text": null }, { "code": null, "e": 26165, "s": 26157, "text": "Output:" }, { "code": null, "e": 26250, "s": 26165, "text": "Example 2: Use CSS text-align=”center” property to set the text content into center." }, { "code": null, "e": 26255, "s": 26250, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to horizontal align text content into center in HTML? </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3> How to horizontal align text content into center in HTML? </h3> <p> GeeksforGeeks: A computer science portal for geeks </p> </body> </html>", "e": 26745, "s": 26255, "text": null }, { "code": null, "e": 26753, "s": 26745, "text": "Output:" }, { "code": null, "e": 26890, "s": 26753, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 26899, "s": 26890, "text": "CSS-Misc" }, { "code": null, "e": 26909, "s": 26899, "text": "HTML-Misc" }, { "code": null, "e": 26913, "s": 26909, "text": "CSS" }, { "code": null, "e": 26918, "s": 26913, "text": "HTML" }, { "code": null, "e": 26935, "s": 26918, "text": "Web Technologies" }, { "code": null, "e": 26962, "s": 26935, "text": "Web technologies Questions" }, { "code": null, "e": 26967, "s": 26962, "text": "HTML" }, { "code": null, "e": 27065, "s": 26967, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27102, "s": 27065, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27131, "s": 27102, "text": "Form validation using jQuery" }, { "code": null, "e": 27170, "s": 27131, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 27212, "s": 27170, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 27247, "s": 27212, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 27307, "s": 27247, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 27368, "s": 27307, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 27421, "s": 27368, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 27471, "s": 27421, "text": "How to Insert Form Data into Database using PHP ?" } ]
HTML <textarea> cols Attribute
The cols attribute of the <textarea> element is used to set the width of the textarea. The cols set it and the width is visible under the textarea itself. Following is the syntax − <textarea cols="num"> Above, num is the width of the textarea. The default value is 20. Let us now see an example to implement the cols attribute of the <textarea> element − Live Demo <!DOCTYPE html> <html> <body> <h2>Interview Questions</h2> <p>Why do you want go for the Editor Job Profile? (100 words)</p> <textarea rows="6" cols="70"> Write the answer in 100 words only... </textarea> <p>What are your weaknesses? (50 words)</p> <textarea rows="4" cols="70"> Write the answer in 50 words only... </textarea> </body> </html> In the above example, we have set two textarea − <textarea rows="6" cols="70"> Write the answer in 100 words only... </textarea> <p>What are your weaknesses? (50 words)</p> <textarea rows="4" cols="70"> Write the answer in 50 words only... </textarea> The width of the textarea is set with the cols attribute − <textare arows="6" cols="70" autofocus>
[ { "code": null, "e": 1217, "s": 1062, "text": "The cols attribute of the <textarea> element is used to set the width of the textarea. The cols set it and the width is visible under the textarea itself." }, { "code": null, "e": 1243, "s": 1217, "text": "Following is the syntax −" }, { "code": null, "e": 1265, "s": 1243, "text": "<textarea cols=\"num\">" }, { "code": null, "e": 1331, "s": 1265, "text": "Above, num is the width of the textarea. The default value is 20." }, { "code": null, "e": 1417, "s": 1331, "text": "Let us now see an example to implement the cols attribute of the <textarea> element −" }, { "code": null, "e": 1428, "s": 1417, "text": " Live Demo" }, { "code": null, "e": 1790, "s": 1428, "text": "<!DOCTYPE html>\n<html>\n<body>\n<h2>Interview Questions</h2>\n<p>Why do you want go for the Editor Job Profile? (100 words)</p>\n <textarea rows=\"6\" cols=\"70\">\n Write the answer in 100 words only...\n </textarea>\n <p>What are your weaknesses? (50 words)</p>\n <textarea rows=\"4\" cols=\"70\">\nWrite the answer in 50 words only...\n</textarea>\n</body>\n</html>" }, { "code": null, "e": 1839, "s": 1790, "text": "In the above example, we have set two textarea −" }, { "code": null, "e": 2042, "s": 1839, "text": "<textarea rows=\"6\" cols=\"70\">\nWrite the answer in 100 words only...\n</textarea>\n<p>What are your weaknesses? (50 words)</p>\n<textarea rows=\"4\" cols=\"70\">\nWrite the answer in 50 words only...\n</textarea>" }, { "code": null, "e": 2101, "s": 2042, "text": "The width of the textarea is set with the cols attribute −" }, { "code": null, "e": 2141, "s": 2101, "text": "<textare arows=\"6\" cols=\"70\" autofocus>" } ]
How to select only numeric columns from an R data frame?
The easiest way to do it is by using select_if function of dplyr package but we can also do it through lapply. Using dplyr > df <- data.frame(X1=1:10,X2=11:20,X3=21:30,X4=letters[1:10], X5=letters[11:20]) > df X1 X2 X3 X4 X5 1 1 11 21 a k 2 2 12 22 b l 3 3 13 23 c m 4 4 14 24 d n 5 5 15 25 e o 6 6 16 26 f p 7 7 17 27 g q 8 8 18 28 h r 9 9 19 29 i s 10 10 20 30 j t >library("dplyr") > select_if(df, is.numeric) X1 X2 X3 1 1 11 21 2 2 12 22 3 3 13 23 4 4 14 24 5 5 15 25 6 6 16 26 7 7 17 27 8 8 18 28 9 9 19 29 10 10 20 30 Using lapply > numeric_only <- unlist(lapply(df, is.numeric)) > df[ , numeric_only] X1 X2 X3 1 1 11 21 2 2 12 22 3 3 13 23 4 4 14 24 5 5 15 25 6 6 16 26 7 7 17 27 8 8 18 28 9 9 19 29 10 10 20 30
[ { "code": null, "e": 1173, "s": 1062, "text": "The easiest way to do it is by using select_if function of dplyr package but we can also do\nit through lapply." }, { "code": null, "e": 1185, "s": 1173, "text": "Using dplyr" }, { "code": null, "e": 1586, "s": 1185, "text": "> df <- data.frame(X1=1:10,X2=11:20,X3=21:30,X4=letters[1:10], X5=letters[11:20])\n> df\nX1 X2 X3 X4 X5\n1 1 11 21 a k\n2 2 12 22 b l\n3 3 13 23 c m\n4 4 14 24 d n\n5 5 15 25 e o\n6 6 16 26 f p\n7 7 17 27 g q\n8 8 18 28 h r\n9 9 19 29 i s\n10 10 20 30 j t\n>library(\"dplyr\")\n> select_if(df, is.numeric)\nX1 X2 X3\n1 1 11 21\n2 2 12 22\n3 3 13 23\n4 4 14 24\n5 5 15 25\n6 6 16 26\n7 7 17 27\n8 8 18 28\n9 9 19 29\n10 10 20 30" }, { "code": null, "e": 1599, "s": 1586, "text": "Using lapply" }, { "code": null, "e": 1783, "s": 1599, "text": "> numeric_only <- unlist(lapply(df, is.numeric))\n> df[ , numeric_only]\n X1 X2 X3\n1 1 11 21\n2 2 12 22\n3 3 13 23\n4 4 14 24\n5 5 15 25\n6 6 16 26\n7 7 17 27\n8 8 18 28\n9 9 19 29\n10 10 20 30" } ]
XML - Processing
This chapter describes the Processing Instructions (PIs). As defined by the XML 1.0 Recommendation, Processing instructions (PIs) can be used to pass information to applications. PIs can appear anywhere in the document outside the markup. They can appear in the prolog, including the document type definition (DTD), in textual content, or after the document. Following is the syntax of PI − <?target instructions?> Where target − Identifies the application to which the instruction is directed. target − Identifies the application to which the instruction is directed. instruction − A character that describes the information for the application to process. instruction − A character that describes the information for the application to process. A PI starts with a special tag <? and ends with ?>. Processing of the contents ends immediately after the string ?> is encountered. PIs are rarely used. They are mostly used to link XML document to a style sheet. Following is an example − <?xml-stylesheet href = "tutorialspointstyle.css" type = "text/css"?> Here, the target is xml-stylesheet. href="tutorialspointstyle.css" and type="text/css" are data or instructions the target application will use at the time of processing the given XML document. In this case, a browser recognizes the target by indicating that the XML should be transformed before being shown; the first attribute states that the type of the transform is XSL and the second attribute points to its location. A PI can contain any data except the combination ?>, which is interpreted as the closing delimiter. Here are two examples of valid PIs − <?welcome to pg = 10 of tutorials point?> <?welcome?> 84 Lectures 6 hours Frahaan Hussain 29 Lectures 2 hours YouAccel 27 Lectures 1 hours Jordan Stanchev 16 Lectures 2 hours Simon Sez IT Print Add Notes Bookmark this page
[ { "code": null, "e": 2061, "s": 1961, "text": "This chapter describes the Processing Instructions (PIs). As defined by the XML 1.0 Recommendation," }, { "code": null, "e": 2320, "s": 2061, "text": "Processing instructions (PIs) can be used to pass information to applications. PIs can appear anywhere in the document outside the markup. They can appear in the prolog, including the document type definition (DTD), in textual content, or after the document." }, { "code": null, "e": 2352, "s": 2320, "text": "Following is the syntax of PI −" }, { "code": null, "e": 2377, "s": 2352, "text": "<?target instructions?>\n" }, { "code": null, "e": 2383, "s": 2377, "text": "Where" }, { "code": null, "e": 2457, "s": 2383, "text": "target − Identifies the application to which the instruction is directed." }, { "code": null, "e": 2531, "s": 2457, "text": "target − Identifies the application to which the instruction is directed." }, { "code": null, "e": 2620, "s": 2531, "text": "instruction − A character that describes the information for the application to process." }, { "code": null, "e": 2709, "s": 2620, "text": "instruction − A character that describes the information for the application to process." }, { "code": null, "e": 2842, "s": 2709, "text": "A PI starts with a special tag <? and ends with ?>. Processing of the contents ends immediately after the string ?> is encountered." }, { "code": null, "e": 2949, "s": 2842, "text": "PIs are rarely used. They are mostly used to link XML document to a style sheet. Following is an example −" }, { "code": null, "e": 3020, "s": 2949, "text": "<?xml-stylesheet href = \"tutorialspointstyle.css\" type = \"text/css\"?>\n" }, { "code": null, "e": 3214, "s": 3020, "text": "Here, the target is xml-stylesheet. href=\"tutorialspointstyle.css\" and type=\"text/css\" are data or instructions the target application will use at the time of processing the given XML document." }, { "code": null, "e": 3443, "s": 3214, "text": "In this case, a browser recognizes the target by indicating that the XML should be transformed before being shown; the first attribute states that the type of the transform is XSL and the second attribute points to its location." }, { "code": null, "e": 3580, "s": 3443, "text": "A PI can contain any data except the combination ?>, which is interpreted as the closing delimiter. Here are two examples of valid PIs −" }, { "code": null, "e": 3635, "s": 3580, "text": "<?welcome to pg = 10 of tutorials point?>\n\n<?welcome?>" }, { "code": null, "e": 3668, "s": 3635, "text": "\n 84 Lectures \n 6 hours \n" }, { "code": null, "e": 3685, "s": 3668, "text": " Frahaan Hussain" }, { "code": null, "e": 3718, "s": 3685, "text": "\n 29 Lectures \n 2 hours \n" }, { "code": null, "e": 3728, "s": 3718, "text": " YouAccel" }, { "code": null, "e": 3761, "s": 3728, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 3778, "s": 3761, "text": " Jordan Stanchev" }, { "code": null, "e": 3811, "s": 3778, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3825, "s": 3811, "text": " Simon Sez IT" }, { "code": null, "e": 3832, "s": 3825, "text": " Print" }, { "code": null, "e": 3843, "s": 3832, "text": " Add Notes" } ]
Containerize your whole Data Science Environment (or anything you want) with Docker-Compose | by Donny Hanz | Towards Data Science
In this article I want to explore with you how you can create a containerized data science environment or whatever other systems you might want, that you can quickly deploy to any machine running Docker, may it be your laptop or a cloud computer. The tool I want to demonstrate to you for that purpose is Docker-Compose, an addition to Docker to build and run applications made from multiple containers. The example system I want to build with you in this article will be comprised of three components: a Jupyter Notebook server to conduct experiments in, an MLflow Tracking Server to record and organize experiment parameters and metrics, and a Postgres Database as the backend for the MLflow server and as a handy datastore for your structured datasets. I mostly aim to give you an idea of Docker-Compose and how to use it and will assume that you have at least a basic understanding of Docker or maybe a first idea what it is used for and how it works. If not, let’s take a quick look at why you should bother with yet another technology. Why use Docker you might ask yourself when you’ve got everything installed and set up just fine. In a nutshell and without much buzzword-bingo: For me, the motivation to really start trying to get my head around Docker and Compose was the drive to set up a similar environment to what I will show you in this article, hosted somewhere on a server so that I can access it from anywhere. Because I’m not naturally gifted at configuring and setting things up I wanted to try it all out in the comfort of my laptop and a Docker container where I can’t break anything, and then put it up in the cloud when I’m ready. I’m also still not sure about cloud providers so I really liked the idea of being able to quickly pick up and move my setup somewhere else. When I told a coworker about this little project, he was also interested because he thought it was a great thing to have when giving seminars for students or hosting workshops, when you maybe need to get your setup suddenly running on many computers or maybe you just want it kicking around to deploy it on demand. Another thing I also found to make my life a lot easier is how reliable you can reproduce results with containers. If you’re working in software there is a good chance that earlier or later you’ve encountered the famous sentence “it works on my machine”, when running into any sort of issue with a setup. Containers make this a thing of the past as their behavior is very predictable, you get the same result wherever you deploy and run them, when it “works on my machine” it will also work on yours most likely. The motivation to add Compose to the toolbox for me was, that as soon as you want to start wiring multiple containers together to interact with each other things become a bit less trivial. Docker-Compose is simply a tool that allows you to describe a collection of multiple containers that can interact via their own network in a very straight forward way, which was exactly what I needed. You can just specify everything in a little YAML formatted file, define containers as services, define volumes to store data, set port forwards and make things even easier than with Docker alone. Even when you’re only working with a single container I find it to be quite handy and I’m almost exclusively using it now. Compose is included in all desktop distributions of Docker so if you have one running you can try things out right away. As a starting point, we will create a simple system made up of a single container. Let's begin with the Jupyter notebook and define a Dockerfile containing the notebook server and a docker-compose.yml file that describes how to build and run the Docker image and expose the notebook server port to the host machine so that we can connect to it. Jupyter is easy to get started with since the team behind it already provides great images, just add the tools you might need and off you go. With Docker-Compose you can use ready-made images from a repository like Docker HUB or build a local image from a Dockerfile. Let's start with the project structure, we have a docker-compose.yml file in which we will specify our system and we have a Dockerfile, at the moment just for our notebook, in a separate folder that we want to build and run. data-toolbox|- jupyter-notebook-docker| |- Dockerfile|- docker-compose.yml The notebooks Dockerfile is a simple extension of the scipy image the Jupyter team published on Docker HUB. The scipy-notebook image already contains many useful libraries like numpy, pandas, matloblib, seaborn, dask and so on and has Jupyter Lab enabled as well. We are just going to add two libraries to the image, mlflow because we want to the client-part of the library that we will use to connect to the MLfLow Tracking Server, which we will set up next, as well as psycopg2, a library that will allow us to easily connect to the Postgres Database that we will set up last. To do so we simply add a RUN command to have the conda package manager add mlflow and psycopg2 to the environment. If you would be interested in building a setup with Spark for example (which you can also completely containerize even in cluster setup with Docker Swarm or Kubernetes) there is also a Spark Notebook image available by the Jupyter team to extend from. And last but not least the docker-compose.yml file, not very exciting yet. The section services describes the Docker images that our system is made of, and at the moment we have just added one entry that we called notebook in which we specify which Dockerfile will be used. In this case, the instruction says: “build the Dockerfile in the jupyter-notebook-docker folder and use the resulting image”. Also we specify that we want the notebook servers port 8888 forwarded to the same port on the host machine so that we can connect to our notebook. The order for the port specification is host:container. In case you don’t care for adding any library and want to just use a premade image you can use the image command instead of build and specify an image like jupyter/scipy-notebook. I recommend having a look at the docker-compose file reference to get a better understanding of what commands are available. Now, all there is left to do is to build and run the project. In order to have Docker-Compose build you local images you simply punch the following into the command line when you’re in the same folder as your docker-compose.yml file. docker-compose build If everything works out fine and the build succeeds you can finally start your system with the compose command up. docker-compose up If that works out as well, you should now be able to connect to your new Jupyter notebook by visiting localhost:8888 in your browser. In the Jupyter images authentication is enabled by default so make sure to copy the token from the log when starting the container. As you can see Compose can make it easier to run even just a single container since you can specify the port forwarding etc. in the compose file and just run it with a much shorter command and without the need to write a script file. Now it gets a bit more interesting, we add the MLflow tracking server into the mix so that we can log experiment runs, parameters and metrics, and organize our model artifacts. For that, the Jupyter notebook server needs to be able to talk to the MLfLow server which will run in a different container. First, let’s add another folder for the new Dockerfile so that your project structure now looks like the following. data-toolbox|- jupyter-notebook-docker| |- Dockerfile|- ml-flow-docker| |- Dockerfile|- docker-compose.yml First, we create a simple docker image again, this time running the MLflow tracking server. For that, we extend from the python:3.7.0 Docker image which comes with Python 3.7 preinstalled and is a good go-to starting point for creating any Python-related images like this one. All we have to do to make it an MLflow server is to install mlflow via pip, make a directory for it to write all the data to and then start the server with the command mlflow server. That’s basically it. You can see the option backend-store-uri which is used to tell MLflow where to store the data, here we use a folder, but the option also accepts database URIs and other things, which we will use later. Check out the tracking server documentation to find out more details about the configuration. Now to a slightly more interesting docker-compose file. We add a second service that we call mlflow and have it point to the Dockerfile in the ml-flow-docker folder, we expose the port 5000 of the container in the “systems internal network” and also forward it to the same port of the host machine again, so that we can inspect our experiment runs and look at cool graphs of our metrics and so on. The command expose only exposes the port in the systems internal network created by Compose were as ports as we know forwards the port to the host. Since we also have MLflow installed in the container that is running the notebook server we can set an environment variable that tells the MLflow client where to track experiments by default. When we set this variable right we don’t have to set it in the notebook via the python API every time we want to use tracking. Compose allows you to set those variables from the compose file. Here we set the environment variable MLFLOW_TRACKING_URI to the address of our MLflow tracking server. Since Compose automatically creates a network with domain names for our services we can simply refer to the tracking URI as the service name and the relevant port — mlflow:5000 — since we named the service for the tracking server mlflow. If we now punch our trusty docker-compose commands build and up into the command line again, we will be able to connect to localhost:8888 and connect to our Jupyter notebook, create a new experiment with mlflow and log some stuff. We should also be able to connect to localhost:5000 and see our MLflow UI and the experiment we just created. Now to the trickiest part, we will add a database backend for the tracking server, since support for logging to databases was added in 0.9.1 and is promised to be so much more performant in tracking and querying speed than a filestore. Databases are also cool and it's helpful to have one around to store and query tabular datasets efficiently. Storing the tracking data in a database also has the benefit that we can query and analyze experiment metrics directly from it which might be necessary if you want to do anything the MLflow UI doesn't offer, which at the moment is still quite a lot. Adding the database image itself is not hard, the Postgres alpine image is all you really need, a very lean image running a PostgresDB. Still, we’re going to extend from the Postgres image and make our own Dockerfile, mostly because we want to copy an initialization script into a folder in the image so that Postgres will initialize the mlflow database on startup. In the compose file we add a new service again as usual and call it postgres, we also specify environment variables for Postgres to create a super-user with a given name and password on startup, which we will need when we add the database URI to the tracking server. Since the Postgres image already exposes the database port by default, we don’t need to add an expose command to the compose file, but we can forward the port to the host again to inspect the database. The project structure, the Dockerfile, and the compose file now look like the following. data-toolbox|- jupyter-notebook-docker| |- Dockerfile|- ml-flow-docker| |- Dockerfile|- postgres-docker| |- Dockerfile| |- init.sql|- docker-compose.yml In order to use the Postgres Database as a backend for MLflow, we need to configure the databases URI as the backend-store-uri when starting the MLflow server. Also, since the backend-store-uri is now pointing to a database MLflow will complain that it cannot store artifacts there, so you also need to provide a default-artifact-root to specify where artifacts are stored. Keep in mind though that if you provide a file path instead of an address to an NFS or a cloud storage solution like AWS S3 the artifacts will be stored on the client-side, so in the container running the notebook under the folder we specify here, since it basically just tells the client where to store the artifacts. The tracking server documentation gives an overview of what is possible at the moment for artifact storage. Even though you can tell Docker-Compose in which order to start the services with the depends command, it’s not always enough. Compose will see that a container starts but will not wait for it to be ready, since this means something else for every container, and in case of the database we regard the container as ready as soon as the PostgresDB accepts connections. Unfortunately, the database takes a moment to start up and the MLflow server immediately checks the database connection, finds no open port that accepts a connection under the specified URI and shuts down. Great, what now? Thanks to people much smarter than me you can, for example, get a very handy shell script wait-for-it.sh that allows you to wait for any service to accept a TCP connection and then executes any other command. Obviously, this is just one way to achieve this, feel free to leave other methods that you find in the comments as I’m curious about how others have solved this. To incorporate the script we just download it, put it into the folder with the tracking servers Dockerfile and change the Dockerfile slightly to copy the script into the image, set the execution flag so that it has the permission to be run and then we start the MLflow server with the script, given that Postgres accepts connections. The script will by default try to connect once a second for 15 seconds, which is more than enough. Tip: something that took me a while to figure out, when you’re on Windows and copying the file into the image make sure it has LF as line endings and not CRLF which will cause bash in the container to “not find the file”. The funny thing about Docker containers is that if you shut them down your data is gone, your Jupyter notebooks, your metrics in MLFlow and everything in the database. Every time you start your compose environment you get a clean slate. That's great but not always what you want, more often than not people seem to prefer to not start their work from scratch every time they turn on their computer. That’s why we have to make the Docker containers write their data to a persistent storage, most often the host machines disk. Then when you start the containers again your data will still be there. There are two general ways to achieve this, one is to directly bind a file path of the host machine to the file path in the container, the other and also recommended, as well as sligthly easier way, is to use Docker volumes. Volumes are spaces on the host machines file system that are managed by Docker, and that have some advantages over binding a file path, for example, that they are independent of the host machines files structure which means you don’t need to change anything when moving to a new machine, and with different volume drivers you can also write to a remote storage location instead of the host machine for example. Another great thing I found is that they also seamlessly work on Windows hosts which you otherwise often run into issues with when trying to simply share access to a local folder with Docker. The only thing you have to figure out regardless of which option you choose is which directory the container writes its data to and then mount a volume at that point. For the notebook server, for example, the notebook starts in and writes its data to the folder /home/jovyan. If we mount a volume at that point the data gets written into the volume which is somewhere outside the container and remains persistent. In order to have Docker Compose create volumes, we simply add a section called volumes and then specify some names that the volumes should have, and then bind them to the right path in the containers under the respective service section in the file. In the end, the final compose file with volume mounts for the containers looks like the following. If you’re wondering where your data ends up when you let Docker manage it with volumes, you can inspect them with the following docker command. Note that the name of the volume you create will not be exactly the name you specify in the compose file. Instead, when Compose creates the volumes it prepends the name of the project, which by default is the name of the directory containing the compose file. In our case the project directory is called data-toolbox so to inspect the file-store volume, for example, we’ll use the following command. docker volume inspect data-toolbox_file-store What you’ll get will be something like the following, where under Mountpoint you can see where on the host machine the data for that volume will be parked. [ { "CreatedAt": "2019-06-17T18:51:53Z", "Driver": "local", "Labels": { "com.docker.compose.project": "data-toolbox", "com.docker.compose.version": "1.23.2", "com.docker.compose.volume": "file-store" }, "Mountpoint": "/var/lib/docker/volumes/data-toolbox_file-store/_data", "Name": "data-toolbox_file-store", "Options": null, "Scope": "local" }] I hope I was able to demonstrate with this little example how you can easily create a system made up of multiple containers, that can interact via a network and can share data in volumes. If you’ve followed along, you should now have a small containerized environment that you can use on your laptop to play around with or maybe even to put on a server and seriously work with if you wish to. You also should be able to extend it to add more things you might need in your environment, like different databases, dashboards, message queues and streaming servers, Spark, build tools, or who knows what, your imagination is the limit and I encourage you to experiment a bit. The good thing about playing around with Docker containers is that you can’t really break anything. You might run out of disk space at some point though since images and containers can get big and they pile up if you don’t run some commands to clean them up and shut them down every now and then. Once you get acquainted with it I found it becomes almost fun to have things up and running quickly. I don’t install local databases on my laptop for development anymore, I pull a Docker image and run it, and if I want to keep the data I add a volume, and if not then I don’t. There is a lot more to it if you want to get deeper into the matter, Docker containers can make a lot of things easier and faster, from build pipelines to distributed systems and software testing to only name a few. Some things like microservice architectures are only really feasible with the use of containers. There is probably something in it for you that can make your life easier or streamline your productivity. Thank you very much for reading.
[ { "code": null, "e": 1214, "s": 172, "text": "In this article I want to explore with you how you can create a containerized data science environment or whatever other systems you might want, that you can quickly deploy to any machine running Docker, may it be your laptop or a cloud computer. The tool I want to demonstrate to you for that purpose is Docker-Compose, an addition to Docker to build and run applications made from multiple containers. The example system I want to build with you in this article will be comprised of three components: a Jupyter Notebook server to conduct experiments in, an MLflow Tracking Server to record and organize experiment parameters and metrics, and a Postgres Database as the backend for the MLflow server and as a handy datastore for your structured datasets. I mostly aim to give you an idea of Docker-Compose and how to use it and will assume that you have at least a basic understanding of Docker or maybe a first idea what it is used for and how it works. If not, let’s take a quick look at why you should bother with yet another technology." }, { "code": null, "e": 2281, "s": 1214, "text": "Why use Docker you might ask yourself when you’ve got everything installed and set up just fine. In a nutshell and without much buzzword-bingo: For me, the motivation to really start trying to get my head around Docker and Compose was the drive to set up a similar environment to what I will show you in this article, hosted somewhere on a server so that I can access it from anywhere. Because I’m not naturally gifted at configuring and setting things up I wanted to try it all out in the comfort of my laptop and a Docker container where I can’t break anything, and then put it up in the cloud when I’m ready. I’m also still not sure about cloud providers so I really liked the idea of being able to quickly pick up and move my setup somewhere else. When I told a coworker about this little project, he was also interested because he thought it was a great thing to have when giving seminars for students or hosting workshops, when you maybe need to get your setup suddenly running on many computers or maybe you just want it kicking around to deploy it on demand." }, { "code": null, "e": 2794, "s": 2281, "text": "Another thing I also found to make my life a lot easier is how reliable you can reproduce results with containers. If you’re working in software there is a good chance that earlier or later you’ve encountered the famous sentence “it works on my machine”, when running into any sort of issue with a setup. Containers make this a thing of the past as their behavior is very predictable, you get the same result wherever you deploy and run them, when it “works on my machine” it will also work on yours most likely." }, { "code": null, "e": 3624, "s": 2794, "text": "The motivation to add Compose to the toolbox for me was, that as soon as you want to start wiring multiple containers together to interact with each other things become a bit less trivial. Docker-Compose is simply a tool that allows you to describe a collection of multiple containers that can interact via their own network in a very straight forward way, which was exactly what I needed. You can just specify everything in a little YAML formatted file, define containers as services, define volumes to store data, set port forwards and make things even easier than with Docker alone. Even when you’re only working with a single container I find it to be quite handy and I’m almost exclusively using it now. Compose is included in all desktop distributions of Docker so if you have one running you can try things out right away." }, { "code": null, "e": 4237, "s": 3624, "text": "As a starting point, we will create a simple system made up of a single container. Let's begin with the Jupyter notebook and define a Dockerfile containing the notebook server and a docker-compose.yml file that describes how to build and run the Docker image and expose the notebook server port to the host machine so that we can connect to it. Jupyter is easy to get started with since the team behind it already provides great images, just add the tools you might need and off you go. With Docker-Compose you can use ready-made images from a repository like Docker HUB or build a local image from a Dockerfile." }, { "code": null, "e": 4462, "s": 4237, "text": "Let's start with the project structure, we have a docker-compose.yml file in which we will specify our system and we have a Dockerfile, at the moment just for our notebook, in a separate folder that we want to build and run." }, { "code": null, "e": 4540, "s": 4462, "text": "data-toolbox|- jupyter-notebook-docker| |- Dockerfile|- docker-compose.yml" }, { "code": null, "e": 5486, "s": 4540, "text": "The notebooks Dockerfile is a simple extension of the scipy image the Jupyter team published on Docker HUB. The scipy-notebook image already contains many useful libraries like numpy, pandas, matloblib, seaborn, dask and so on and has Jupyter Lab enabled as well. We are just going to add two libraries to the image, mlflow because we want to the client-part of the library that we will use to connect to the MLfLow Tracking Server, which we will set up next, as well as psycopg2, a library that will allow us to easily connect to the Postgres Database that we will set up last. To do so we simply add a RUN command to have the conda package manager add mlflow and psycopg2 to the environment. If you would be interested in building a setup with Spark for example (which you can also completely containerize even in cluster setup with Docker Swarm or Kubernetes) there is also a Spark Notebook image available by the Jupyter team to extend from." }, { "code": null, "e": 6394, "s": 5486, "text": "And last but not least the docker-compose.yml file, not very exciting yet. The section services describes the Docker images that our system is made of, and at the moment we have just added one entry that we called notebook in which we specify which Dockerfile will be used. In this case, the instruction says: “build the Dockerfile in the jupyter-notebook-docker folder and use the resulting image”. Also we specify that we want the notebook servers port 8888 forwarded to the same port on the host machine so that we can connect to our notebook. The order for the port specification is host:container. In case you don’t care for adding any library and want to just use a premade image you can use the image command instead of build and specify an image like jupyter/scipy-notebook. I recommend having a look at the docker-compose file reference to get a better understanding of what commands are available." }, { "code": null, "e": 6628, "s": 6394, "text": "Now, all there is left to do is to build and run the project. In order to have Docker-Compose build you local images you simply punch the following into the command line when you’re in the same folder as your docker-compose.yml file." }, { "code": null, "e": 6649, "s": 6628, "text": "docker-compose build" }, { "code": null, "e": 6764, "s": 6649, "text": "If everything works out fine and the build succeeds you can finally start your system with the compose command up." }, { "code": null, "e": 6782, "s": 6764, "text": "docker-compose up" }, { "code": null, "e": 7048, "s": 6782, "text": "If that works out as well, you should now be able to connect to your new Jupyter notebook by visiting localhost:8888 in your browser. In the Jupyter images authentication is enabled by default so make sure to copy the token from the log when starting the container." }, { "code": null, "e": 7282, "s": 7048, "text": "As you can see Compose can make it easier to run even just a single container since you can specify the port forwarding etc. in the compose file and just run it with a much shorter command and without the need to write a script file." }, { "code": null, "e": 7700, "s": 7282, "text": "Now it gets a bit more interesting, we add the MLflow tracking server into the mix so that we can log experiment runs, parameters and metrics, and organize our model artifacts. For that, the Jupyter notebook server needs to be able to talk to the MLfLow server which will run in a different container. First, let’s add another folder for the new Dockerfile so that your project structure now looks like the following." }, { "code": null, "e": 7813, "s": 7700, "text": "data-toolbox|- jupyter-notebook-docker| |- Dockerfile|- ml-flow-docker| |- Dockerfile|- docker-compose.yml" }, { "code": null, "e": 8590, "s": 7813, "text": "First, we create a simple docker image again, this time running the MLflow tracking server. For that, we extend from the python:3.7.0 Docker image which comes with Python 3.7 preinstalled and is a good go-to starting point for creating any Python-related images like this one. All we have to do to make it an MLflow server is to install mlflow via pip, make a directory for it to write all the data to and then start the server with the command mlflow server. That’s basically it. You can see the option backend-store-uri which is used to tell MLflow where to store the data, here we use a folder, but the option also accepts database URIs and other things, which we will use later. Check out the tracking server documentation to find out more details about the configuration." }, { "code": null, "e": 9136, "s": 8590, "text": "Now to a slightly more interesting docker-compose file. We add a second service that we call mlflow and have it point to the Dockerfile in the ml-flow-docker folder, we expose the port 5000 of the container in the “systems internal network” and also forward it to the same port of the host machine again, so that we can inspect our experiment runs and look at cool graphs of our metrics and so on. The command expose only exposes the port in the systems internal network created by Compose were as ports as we know forwards the port to the host." }, { "code": null, "e": 9861, "s": 9136, "text": "Since we also have MLflow installed in the container that is running the notebook server we can set an environment variable that tells the MLflow client where to track experiments by default. When we set this variable right we don’t have to set it in the notebook via the python API every time we want to use tracking. Compose allows you to set those variables from the compose file. Here we set the environment variable MLFLOW_TRACKING_URI to the address of our MLflow tracking server. Since Compose automatically creates a network with domain names for our services we can simply refer to the tracking URI as the service name and the relevant port — mlflow:5000 — since we named the service for the tracking server mlflow." }, { "code": null, "e": 10202, "s": 9861, "text": "If we now punch our trusty docker-compose commands build and up into the command line again, we will be able to connect to localhost:8888 and connect to our Jupyter notebook, create a new experiment with mlflow and log some stuff. We should also be able to connect to localhost:5000 and see our MLflow UI and the experiment we just created." }, { "code": null, "e": 10797, "s": 10202, "text": "Now to the trickiest part, we will add a database backend for the tracking server, since support for logging to databases was added in 0.9.1 and is promised to be so much more performant in tracking and querying speed than a filestore. Databases are also cool and it's helpful to have one around to store and query tabular datasets efficiently. Storing the tracking data in a database also has the benefit that we can query and analyze experiment metrics directly from it which might be necessary if you want to do anything the MLflow UI doesn't offer, which at the moment is still quite a lot." }, { "code": null, "e": 11721, "s": 10797, "text": "Adding the database image itself is not hard, the Postgres alpine image is all you really need, a very lean image running a PostgresDB. Still, we’re going to extend from the Postgres image and make our own Dockerfile, mostly because we want to copy an initialization script into a folder in the image so that Postgres will initialize the mlflow database on startup. In the compose file we add a new service again as usual and call it postgres, we also specify environment variables for Postgres to create a super-user with a given name and password on startup, which we will need when we add the database URI to the tracking server. Since the Postgres image already exposes the database port by default, we don’t need to add an expose command to the compose file, but we can forward the port to the host again to inspect the database. The project structure, the Dockerfile, and the compose file now look like the following." }, { "code": null, "e": 11886, "s": 11721, "text": "data-toolbox|- jupyter-notebook-docker| |- Dockerfile|- ml-flow-docker| |- Dockerfile|- postgres-docker| |- Dockerfile| |- init.sql|- docker-compose.yml" }, { "code": null, "e": 12687, "s": 11886, "text": "In order to use the Postgres Database as a backend for MLflow, we need to configure the databases URI as the backend-store-uri when starting the MLflow server. Also, since the backend-store-uri is now pointing to a database MLflow will complain that it cannot store artifacts there, so you also need to provide a default-artifact-root to specify where artifacts are stored. Keep in mind though that if you provide a file path instead of an address to an NFS or a cloud storage solution like AWS S3 the artifacts will be stored on the client-side, so in the container running the notebook under the folder we specify here, since it basically just tells the client where to store the artifacts. The tracking server documentation gives an overview of what is possible at the moment for artifact storage." }, { "code": null, "e": 13277, "s": 12687, "text": "Even though you can tell Docker-Compose in which order to start the services with the depends command, it’s not always enough. Compose will see that a container starts but will not wait for it to be ready, since this means something else for every container, and in case of the database we regard the container as ready as soon as the PostgresDB accepts connections. Unfortunately, the database takes a moment to start up and the MLflow server immediately checks the database connection, finds no open port that accepts a connection under the specified URI and shuts down. Great, what now?" }, { "code": null, "e": 13648, "s": 13277, "text": "Thanks to people much smarter than me you can, for example, get a very handy shell script wait-for-it.sh that allows you to wait for any service to accept a TCP connection and then executes any other command. Obviously, this is just one way to achieve this, feel free to leave other methods that you find in the comments as I’m curious about how others have solved this." }, { "code": null, "e": 14303, "s": 13648, "text": "To incorporate the script we just download it, put it into the folder with the tracking servers Dockerfile and change the Dockerfile slightly to copy the script into the image, set the execution flag so that it has the permission to be run and then we start the MLflow server with the script, given that Postgres accepts connections. The script will by default try to connect once a second for 15 seconds, which is more than enough. Tip: something that took me a while to figure out, when you’re on Windows and copying the file into the image make sure it has LF as line endings and not CRLF which will cause bash in the container to “not find the file”." }, { "code": null, "e": 14900, "s": 14303, "text": "The funny thing about Docker containers is that if you shut them down your data is gone, your Jupyter notebooks, your metrics in MLFlow and everything in the database. Every time you start your compose environment you get a clean slate. That's great but not always what you want, more often than not people seem to prefer to not start their work from scratch every time they turn on their computer. That’s why we have to make the Docker containers write their data to a persistent storage, most often the host machines disk. Then when you start the containers again your data will still be there." }, { "code": null, "e": 15728, "s": 14900, "text": "There are two general ways to achieve this, one is to directly bind a file path of the host machine to the file path in the container, the other and also recommended, as well as sligthly easier way, is to use Docker volumes. Volumes are spaces on the host machines file system that are managed by Docker, and that have some advantages over binding a file path, for example, that they are independent of the host machines files structure which means you don’t need to change anything when moving to a new machine, and with different volume drivers you can also write to a remote storage location instead of the host machine for example. Another great thing I found is that they also seamlessly work on Windows hosts which you otherwise often run into issues with when trying to simply share access to a local folder with Docker." }, { "code": null, "e": 16491, "s": 15728, "text": "The only thing you have to figure out regardless of which option you choose is which directory the container writes its data to and then mount a volume at that point. For the notebook server, for example, the notebook starts in and writes its data to the folder /home/jovyan. If we mount a volume at that point the data gets written into the volume which is somewhere outside the container and remains persistent. In order to have Docker Compose create volumes, we simply add a section called volumes and then specify some names that the volumes should have, and then bind them to the right path in the containers under the respective service section in the file. In the end, the final compose file with volume mounts for the containers looks like the following." }, { "code": null, "e": 17035, "s": 16491, "text": "If you’re wondering where your data ends up when you let Docker manage it with volumes, you can inspect them with the following docker command. Note that the name of the volume you create will not be exactly the name you specify in the compose file. Instead, when Compose creates the volumes it prepends the name of the project, which by default is the name of the directory containing the compose file. In our case the project directory is called data-toolbox so to inspect the file-store volume, for example, we’ll use the following command." }, { "code": null, "e": 17081, "s": 17035, "text": "docker volume inspect data-toolbox_file-store" }, { "code": null, "e": 17237, "s": 17081, "text": "What you’ll get will be something like the following, where under Mountpoint you can see where on the host machine the data for that volume will be parked." }, { "code": null, "e": 17678, "s": 17237, "text": "[ { \"CreatedAt\": \"2019-06-17T18:51:53Z\", \"Driver\": \"local\", \"Labels\": { \"com.docker.compose.project\": \"data-toolbox\", \"com.docker.compose.version\": \"1.23.2\", \"com.docker.compose.volume\": \"file-store\" }, \"Mountpoint\": \"/var/lib/docker/volumes/data-toolbox_file-store/_data\", \"Name\": \"data-toolbox_file-store\", \"Options\": null, \"Scope\": \"local\" }]" }, { "code": null, "e": 18646, "s": 17678, "text": "I hope I was able to demonstrate with this little example how you can easily create a system made up of multiple containers, that can interact via a network and can share data in volumes. If you’ve followed along, you should now have a small containerized environment that you can use on your laptop to play around with or maybe even to put on a server and seriously work with if you wish to. You also should be able to extend it to add more things you might need in your environment, like different databases, dashboards, message queues and streaming servers, Spark, build tools, or who knows what, your imagination is the limit and I encourage you to experiment a bit. The good thing about playing around with Docker containers is that you can’t really break anything. You might run out of disk space at some point though since images and containers can get big and they pile up if you don’t run some commands to clean them up and shut them down every now and then." }, { "code": null, "e": 19342, "s": 18646, "text": "Once you get acquainted with it I found it becomes almost fun to have things up and running quickly. I don’t install local databases on my laptop for development anymore, I pull a Docker image and run it, and if I want to keep the data I add a volume, and if not then I don’t. There is a lot more to it if you want to get deeper into the matter, Docker containers can make a lot of things easier and faster, from build pipelines to distributed systems and software testing to only name a few. Some things like microservice architectures are only really feasible with the use of containers. There is probably something in it for you that can make your life easier or streamline your productivity." } ]
LINQ - ASP.Net
As a set of .NET framework extensions, LINQ is the preferred mechanism for data access by ASP.NET developers. ASP.NET 3.5 has a built-in tool LINQDataSource control that enables usage of LINQ easily in ASP.NET. ASP.NET uses the above-mentioned control as a data source. Real life projects mostly encompass websites or windows applications and so to understand better the concept of LINQ with ASP.NET, let’s start with creating a ASP.NET website that make use of the LINQ features. For this, it is essential to get installed Visual Studio and .NET framework on your system. Once you have opened Visual Studio, go to File → New → Website. A pop up window will open as shown in below figure. Now, under the templates in the left hand side, there will be two language options to create the website. Choose Visual C# and select ASP.NET Empty Web Site. Select the folder where you want to save new website on your system. Then press OK and soon Solution Explorer appears on your screen containing all the web files. Right click on Default.aspx in the Solution Explorer and choose View in Browser to view the default ASP.NET website in the browser. Soon your new ASP.NET website will open in the web browser, as shown in the following screenshot. .aspx is in fact the major file extension used in ASP.NET websites. Visual Studio by default creates all the necessary pages for a basic website like Home page and About Us page where you can place your content conveniently. The code for the website is generated automatically here and can be viewed too. It is possible to UPDATE, INSERT and DELETE data in the pages of ASP.NET website with the help of LINQDataSource control. There is absolutely no need for specification of SQL commands as LINQDataSource control employs dynamically created commands for such operations. The control enables a user to make use of LINQ in an ASP.NET web page conveniently by property setting in the markup text. LINQDataSource is very similar to that of controls like SqlDataSource as well as ObjectDataSource as it can be used in binding other ASP.NET controls present on a page to a data source. So, we must have a database to explain the various functions invoked by the LINQDataSource Control. Before going to start explanation of the control usage in ASP.NET web page form, it is essential to open the Microsoft Visual Studio Toolbox and drag and drop LINQDataSource control to .aspx page of ASP.NET website like below figure. The next step is to configure LINQDataSource by selecting all the columns for the employee record. Now add a GridView Control to the .aspx page and configure it like shown in below figure. The GridView control is powerful and offers flexibility to work with the data. Soon after configuring the control, it will appear in the browser. The coding that can be viewed now on your screen for the .aspx page will be − <!DOCTYPE html> <html> <head runat = "server"> <title></title> </head> <body> <form id = "form1" runat = "server"> <div> <asp:GridView ID = "GridView1" runat = "server" AutoGenerateColumns = "False" DataKeyNames = "ContactID" DataSourceID = "LINQDataSource1"> <Columns> <asp:BoundField DataField = "ContactID" HeaderText = "ContactID" InsertVisible = "False" ReadOnly="True" SortExpression = "ContactID" /> <asp:CheckBoxField DataField = "NameStyle" HeaderText = "NameStyle" SortExpression = "NameStyle" /> <asp:BoundField DataField = "Title" HeaderText = "Title" SortExpression = "Title" /> <asp:BoundField DataField = "FirstName" HeaderText = "FirstName" SortExpression="FirstName" /> <asp:BoundField DataField = "MiddleName" HeaderText = "MiddleName" SortExpression = "MiddleName" /> <asp:BoundField DataField = "LastName" HeaderText = "LastName" SortExpression = "LastName" /> <asp:BoundField DataField = "Suffix" HeaderText = "Suffix" SortExpression = "Suffix" /> <asp:BoundField DataField = "EmailAddress" HeaderText = "EmailAddress" SortExpression = "EmailAddress" /> </Columns> </asp:GridView> <br /> </div> <asp:LINQDataSource ID = "LINQDataSource1" runat = "server" ContextTypeName = "LINQWebApp1.AdventureWorksDataContext" EntityTypeName = "" TableName = "Contacts"> </asp:LINQDataSource> </form> </body> </html> Here it should be noted that it is vital to set the property ContextTypeName to that of the class representing the database. For example, here it is given as LINQWebApp1.AdventureWorksDataContext as this action will make the needed connection between LINQDataSource and the database. After completing all the above steps rigorously, choose the LINQDataSource Tasks from the LINQDataSource Control and choose all the three boxes for enable insert, enable update and enable delete from the same, as shown in the following screenshot. Soon the declarative markup will get displayed on your screen as the following one. <asp:LINQDataSource ContextTypeName = "LINQWebApp1.AdventureWorksDataContext" TableName = "Contacts" EnableUpdate = "true" EnableInsert = "true" EnableDelete = "true" ID = "LINQDataSource1" runat = "server"> </asp:LINQDataSource> Now since there are multiple rows and columns, it is better to add another control on your .aspx form named as Detail View or Master control below the Grid View control to display only the details of a selected row of the grid. Choose the Detail View Tasks from the Detail View control and select the check boxes as shown below. Now, just save the changes and press Ctrl + F5 to view the page in your browser where it is now possible to delete, update, insert any record on the detail view control. 23 Lectures 1.5 hours Anadi Sharma 37 Lectures 13 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2217, "s": 1736, "text": "As a set of .NET framework extensions, LINQ is the preferred mechanism for data access by ASP.NET developers. ASP.NET 3.5 has a built-in tool LINQDataSource control that enables usage of LINQ easily in ASP.NET. ASP.NET uses the above-mentioned control as a data source. Real life projects mostly encompass websites or windows applications and so to understand better the concept of LINQ with ASP.NET, let’s start with creating a ASP.NET website that make use of the LINQ features." }, { "code": null, "e": 2425, "s": 2217, "text": "For this, it is essential to get installed Visual Studio and .NET framework on your system. Once you have opened Visual Studio, go to File → New → Website. A pop up window will open as shown in below figure." }, { "code": null, "e": 2583, "s": 2425, "text": "Now, under the templates in the left hand side, there will be two language options to create the website. Choose Visual C# and select ASP.NET Empty Web Site." }, { "code": null, "e": 2976, "s": 2583, "text": "Select the folder where you want to save new website on your system. Then press OK and soon Solution Explorer appears on your screen containing all the web files. Right click on Default.aspx in the Solution Explorer and choose View in Browser to view the default ASP.NET website in the browser. Soon your new ASP.NET website will open in the web browser, as shown in the following screenshot." }, { "code": null, "e": 3281, "s": 2976, "text": ".aspx is in fact the major file extension used in ASP.NET websites. Visual Studio by default creates all the necessary pages for a basic website like Home page and About Us page where you can place your content conveniently. The code for the website is generated automatically here and can be viewed too." }, { "code": null, "e": 3549, "s": 3281, "text": "It is possible to UPDATE, INSERT and DELETE data in the pages of ASP.NET website with the help of LINQDataSource control. There is absolutely no need for specification of SQL commands as LINQDataSource control employs dynamically created commands for such operations." }, { "code": null, "e": 3958, "s": 3549, "text": "The control enables a user to make use of LINQ in an ASP.NET web page conveniently by property setting in the markup text. LINQDataSource is very similar to that of controls like SqlDataSource as well as ObjectDataSource as it can be used in binding other ASP.NET controls present on a page to a data source. So, we must have a database to explain the various functions invoked by the LINQDataSource Control." }, { "code": null, "e": 4192, "s": 3958, "text": "Before going to start explanation of the control usage in ASP.NET web page form, it is essential to open the Microsoft Visual Studio Toolbox and drag and drop LINQDataSource control to .aspx page of ASP.NET website like below figure." }, { "code": null, "e": 4291, "s": 4192, "text": "The next step is to configure LINQDataSource by selecting all the columns for the employee record." }, { "code": null, "e": 4527, "s": 4291, "text": "Now add a GridView Control to the .aspx page and configure it like shown in below figure. The GridView control is powerful and offers flexibility to work with the data. Soon after configuring the control, it will appear in the browser." }, { "code": null, "e": 4605, "s": 4527, "text": "The coding that can be viewed now on your screen for the .aspx page will be −" }, { "code": null, "e": 6413, "s": 4605, "text": "<!DOCTYPE html>\n\n<html>\n <head runat = \"server\">\n <title></title>\n </head>\n\n <body>\n <form id = \"form1\" runat = \"server\">\n <div>\n <asp:GridView ID = \"GridView1\" runat = \"server\" AutoGenerateColumns = \"False\"\n\t\t\t\n DataKeyNames = \"ContactID\" DataSourceID = \"LINQDataSource1\">\n <Columns>\n\t\t\t \n <asp:BoundField DataField = \"ContactID\" HeaderText = \"ContactID\"\n InsertVisible = \"False\" ReadOnly=\"True\" SortExpression = \"ContactID\" />\n <asp:CheckBoxField DataField = \"NameStyle\" HeaderText = \"NameStyle\"\n SortExpression = \"NameStyle\" />\n <asp:BoundField DataField = \"Title\" HeaderText = \"Title\" SortExpression = \"Title\" />\n <asp:BoundField DataField = \"FirstName\" HeaderText = \"FirstName\"\n SortExpression=\"FirstName\" />\n <asp:BoundField DataField = \"MiddleName\" HeaderText = \"MiddleName\"\n SortExpression = \"MiddleName\" />\n <asp:BoundField DataField = \"LastName\" HeaderText = \"LastName\"\n SortExpression = \"LastName\" />\n <asp:BoundField DataField = \"Suffix\" HeaderText = \"Suffix\"\n SortExpression = \"Suffix\" />\n <asp:BoundField DataField = \"EmailAddress\" HeaderText = \"EmailAddress\"\n SortExpression = \"EmailAddress\" />\n </Columns>\n\n </asp:GridView>\n\n <br />\n\n </div>\n\n <asp:LINQDataSource ID = \"LINQDataSource1\" runat = \"server\"\n\n ContextTypeName = \"LINQWebApp1.AdventureWorksDataContext\" EntityTypeName = \"\"\n TableName = \"Contacts\">\n\n </asp:LINQDataSource>\n </form>\n </body>\n</html>" }, { "code": null, "e": 6697, "s": 6413, "text": "Here it should be noted that it is vital to set the property ContextTypeName to that of the class representing the database. For example, here it is given as LINQWebApp1.AdventureWorksDataContext as this action will make the needed connection between LINQDataSource and the database." }, { "code": null, "e": 6945, "s": 6697, "text": "After completing all the above steps rigorously, choose the LINQDataSource Tasks from the LINQDataSource Control and choose all the three boxes for enable insert, enable update and enable delete from the same, as shown in the following screenshot." }, { "code": null, "e": 7029, "s": 6945, "text": "Soon the declarative markup will get displayed on your screen as the following one." }, { "code": null, "e": 7287, "s": 7029, "text": "<asp:LINQDataSource \n ContextTypeName = \"LINQWebApp1.AdventureWorksDataContext\" \n TableName = \"Contacts\" \n EnableUpdate = \"true\" \n EnableInsert = \"true\" \n EnableDelete = \"true\" \n ID = \"LINQDataSource1\" \n runat = \"server\">\n</asp:LINQDataSource>" }, { "code": null, "e": 7616, "s": 7287, "text": "Now since there are multiple rows and columns, it is better to add another control on your .aspx form named as Detail View or Master control below the Grid View control to display only the details of a selected row of the grid. Choose the Detail View Tasks from the Detail View control and select the check boxes as shown below." }, { "code": null, "e": 7786, "s": 7616, "text": "Now, just save the changes and press Ctrl + F5 to view the page in your browser where it is now possible to delete, update, insert any record on the detail view control." }, { "code": null, "e": 7821, "s": 7786, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7835, "s": 7821, "text": " Anadi Sharma" }, { "code": null, "e": 7869, "s": 7835, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 7887, "s": 7869, "text": " Trevoir Williams" }, { "code": null, "e": 7894, "s": 7887, "text": " Print" }, { "code": null, "e": 7905, "s": 7894, "text": " Add Notes" } ]
HTM5 checkValidity() method
The HTML5 checkValidity() works in Google Chrome and Opera as well. This works as well: <!DOCTYPE html> <html> <body> <style> .valid { color: #0B7866; } .invalid { color: #0B6877; } </style> <div id="result"></div> <script> function check(input) { var out = document.getElementById('result'); if (input.validity) { if (input.validity.valid === true) { out.innerHTML = "<span class='valid'>" + input.id + " valid</span>"; } else { out.innerHTML = "<span class='invalid'>" + input.id + " not valid</span>"; } } console.log(input.checkValidity()); }; </script> <form id="testform" onsubmit="return false;"> <label>Minimum: <input oninput="check(this)" id="min_input" type=number min=4 /> </label><br> </form> </body> </html>
[ { "code": null, "e": 1150, "s": 1062, "text": "The HTML5 checkValidity() works in Google Chrome and Opera as well. This works as well:" }, { "code": null, "e": 2038, "s": 1150, "text": "<!DOCTYPE html>\n<html>\n <body>\n <style>\n .valid { color: #0B7866; }\n .invalid { color: #0B6877; }\n </style>\n <div id=\"result\"></div>\n <script>\n function check(input) {\n var out = document.getElementById('result');\n \n if (input.validity) {\n if (input.validity.valid === true) {\n out.innerHTML = \"<span class='valid'>\" + input.id + \" valid</span>\";\n } else {\n out.innerHTML = \"<span class='invalid'>\" + input.id + \" not valid</span>\";\n }\n }\n console.log(input.checkValidity());\n };\n </script>\n <form id=\"testform\" onsubmit=\"return false;\">\n <label>Minimum:\n <input oninput=\"check(this)\" id=\"min_input\" type=number min=4 />\n </label><br>\n </form>\n </body>\n</html>" } ]
How to read a 2d array from a file in java?
A 2d array is an array of one dimensional arrays to read the contents of a file to a 2d array – Instantiate Scanner or other relevant class to read data from a file. Create an array to store the contents. To copy contents, you need two loops one nested within the other. the outer loop is to traverse through the array of one dimensional arrays and, the inner loop is to traverse through the elements of a particular one dimensional array. Create an outer loop starting from 0 up to the length of the array. Within this loop read each line trim and split it using nextLine(), trim(), and split() methods respectively. Create the second loop starting from 0 up to the length of the line. Within this loop convert each element of the string array to integer and assign to the array created in the previous step. import java.io.BufferedReader; import java.io.FileReader; import java.util.Arrays; import java.util.Scanner; public class Reading2DArrayFromFile { public static void main(String args[]) throws Exception { Scanner sc = new Scanner(new BufferedReader(new FileReader("sample.txt"))); int rows = 4; int columns = 4; int [][] myArray = new int[rows][columns]; while(sc.hasNextLine()) { for (int i=0; i<myArray.length; i++) { String[] line = sc.nextLine().trim().split(" "); for (int j=0; j<line.length; j++) { myArray[i][j] = Integer.parseInt(line[j]); } } } System.out.println(Arrays.deepToString(myArray)); } } [[2, 2, 2, 2], [6, 6, 6, 6], [2, 2, 2, 2], [4, 4, 4, 4]]
[ { "code": null, "e": 1158, "s": 1062, "text": "A 2d array is an array of one dimensional arrays to read the contents of a file to a 2d array –" }, { "code": null, "e": 1228, "s": 1158, "text": "Instantiate Scanner or other relevant class to read data from a file." }, { "code": null, "e": 1268, "s": 1228, "text": " Create an array to store the contents." }, { "code": null, "e": 1503, "s": 1268, "text": "To copy contents, you need two loops one nested within the other. the outer loop is to traverse through the array of one dimensional arrays and, the inner loop is to traverse through the elements of a particular one dimensional array." }, { "code": null, "e": 1681, "s": 1503, "text": "Create an outer loop starting from 0 up to the length of the array. Within this loop read each line trim and split it using nextLine(), trim(), and split() methods respectively." }, { "code": null, "e": 1873, "s": 1681, "text": "Create the second loop starting from 0 up to the length of the line. Within this loop convert each element of the string array to integer and assign to the array created in the previous step." }, { "code": null, "e": 2600, "s": 1873, "text": "import java.io.BufferedReader;\nimport java.io.FileReader;\n\nimport java.util.Arrays;\nimport java.util.Scanner;\n\npublic class Reading2DArrayFromFile {\n public static void main(String args[]) throws Exception {\n Scanner sc = new Scanner(new BufferedReader(new FileReader(\"sample.txt\")));\n int rows = 4;\n int columns = 4;\n int [][] myArray = new int[rows][columns];\n while(sc.hasNextLine()) {\n for (int i=0; i<myArray.length; i++) {\n String[] line = sc.nextLine().trim().split(\" \");\n for (int j=0; j<line.length; j++) {\n myArray[i][j] = Integer.parseInt(line[j]);\n }\n }\n }\n System.out.println(Arrays.deepToString(myArray));\n }\n}" }, { "code": null, "e": 2657, "s": 2600, "text": "[[2, 2, 2, 2], [6, 6, 6, 6], [2, 2, 2, 2], [4, 4, 4, 4]]" } ]
AtomicLong set() method in Java with examples - GeeksforGeeks
29 Jan, 2019 The Java.util.concurrent.atomic.AtomicLong.set() is an inbuilt method in java that updates the previous value and sets it to a new value which is passed in the parameter. Syntax: public final void set(long newVal) Parameters: The function accepts a single mandatory parameter newVal which is to be updated. Return value: The function does not returns anything. Below programs illustrate the above method: Program 1: // Java program that demonstrates// the set() function import java.util.concurrent.atomic.AtomicLong; public class GFG { public static void main(String args[]) { // Initially value as 0 AtomicLong val = new AtomicLong(0); System.out.println("Previous value: " + val); val.set(10); // Prints the updated value System.out.println("Current value: " + val); }} Previous value: 0 Current value: 10 Program 2: // Java program that demonstrates// the set() function import java.util.concurrent.atomic.AtomicLong; public class GFG { public static void main(String args[]) { // Initially value as 18 AtomicLong val = new AtomicLong(18); System.out.println("Previous value: " + val); val.set(200); // Prints the updated value System.out.println("Current value: " + val); }} Previous value: 18 Current value: 200 Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicLong.html#set– Java - util package Java-AtomicLong Java-Functions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java Stream In Java Set in Java Overriding in Java LinkedList in Java
[ { "code": null, "e": 24532, "s": 24504, "text": "\n29 Jan, 2019" }, { "code": null, "e": 24703, "s": 24532, "text": "The Java.util.concurrent.atomic.AtomicLong.set() is an inbuilt method in java that updates the previous value and sets it to a new value which is passed in the parameter." }, { "code": null, "e": 24711, "s": 24703, "text": "Syntax:" }, { "code": null, "e": 24747, "s": 24711, "text": "public final void set(long newVal)\n" }, { "code": null, "e": 24840, "s": 24747, "text": "Parameters: The function accepts a single mandatory parameter newVal which is to be updated." }, { "code": null, "e": 24894, "s": 24840, "text": "Return value: The function does not returns anything." }, { "code": null, "e": 24938, "s": 24894, "text": "Below programs illustrate the above method:" }, { "code": null, "e": 24949, "s": 24938, "text": "Program 1:" }, { "code": "// Java program that demonstrates// the set() function import java.util.concurrent.atomic.AtomicLong; public class GFG { public static void main(String args[]) { // Initially value as 0 AtomicLong val = new AtomicLong(0); System.out.println(\"Previous value: \" + val); val.set(10); // Prints the updated value System.out.println(\"Current value: \" + val); }}", "e": 25419, "s": 24949, "text": null }, { "code": null, "e": 25456, "s": 25419, "text": "Previous value: 0\nCurrent value: 10\n" }, { "code": null, "e": 25467, "s": 25456, "text": "Program 2:" }, { "code": "// Java program that demonstrates// the set() function import java.util.concurrent.atomic.AtomicLong; public class GFG { public static void main(String args[]) { // Initially value as 18 AtomicLong val = new AtomicLong(18); System.out.println(\"Previous value: \" + val); val.set(200); // Prints the updated value System.out.println(\"Current value: \" + val); }}", "e": 25940, "s": 25467, "text": null }, { "code": null, "e": 25979, "s": 25940, "text": "Previous value: 18\nCurrent value: 200\n" }, { "code": null, "e": 26081, "s": 25979, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicLong.html#set–" }, { "code": null, "e": 26101, "s": 26081, "text": "Java - util package" }, { "code": null, "e": 26117, "s": 26101, "text": "Java-AtomicLong" }, { "code": null, "e": 26132, "s": 26117, "text": "Java-Functions" }, { "code": null, "e": 26137, "s": 26132, "text": "Java" }, { "code": null, "e": 26142, "s": 26137, "text": "Java" }, { "code": null, "e": 26240, "s": 26142, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26272, "s": 26240, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26291, "s": 26272, "text": "Interfaces in Java" }, { "code": null, "e": 26309, "s": 26291, "text": "ArrayList in Java" }, { "code": null, "e": 26341, "s": 26309, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26361, "s": 26341, "text": "Stack Class in Java" }, { "code": null, "e": 26385, "s": 26361, "text": "Singleton Class in Java" }, { "code": null, "e": 26400, "s": 26385, "text": "Stream In Java" }, { "code": null, "e": 26412, "s": 26400, "text": "Set in Java" }, { "code": null, "e": 26431, "s": 26412, "text": "Overriding in Java" } ]
Sieve of Eratosthenes | Practice | GeeksforGeeks
Given a number N, calculate the prime numbers up to N using Sieve of Eratosthenes. Example 1: Input: N = 10 Output: 2 3 5 7 Explanation: Prime numbers less than equal to N are 2 3 5 and 7. Example 2: Input: N = 35 Output: 2 3 5 7 11 13 17 19 23 29 31 Explanation: Prime numbers less than equal to 35 are 2 3 5 7 11 13 17 19 23 29 and 31. Your Task: You don't need to read input or print anything. Your task is to complete the function sieveOfEratosthenes() which takes an integer N as an input parameter and return the list of prime numbers less than equal to N. Expected Time Complexity: O(NloglogN) Expected Auxiliary Space: O(N) Constraints: 1<= N <= 104 0 pranavkhandare45452 weeks ago JAVA SOLUTION static ArrayList<Integer> sieveOfEratosthenes(int N){ ArrayList<Integer> al=new ArrayList<>(); boolean isprime[]=new boolean[N+1]; Arrays.fill(isprime,true); for(int i=2;i*i<=N;i++){ if(isprime[i]){ for(int j=2*i;j<=N;j=j+i){ isprime[j]=false; } } } for (int i=2;i<=N;i++){ if(isprime[i]==true){ al.add(i); } } return al; } 0 mail2rajab011 month ago // Simple Java Solution Total Time Taken: 0.6/1.5 class Solution{ static ArrayList<Integer> sieveOfEratosthenes(int N){ // code here ArrayList<Integer> al=new ArrayList<> (); boolean arr[]=new boolean[N+1]; Arrays.fill(arr,true); arr[0]=false; arr[1]=false; for(int i=2;i*i<=N;i++){ for(int j=2*i;j<=N;j +=i){ arr[j]=false; } } for(int i=0;i<arr.length;i++){ if(arr[i]==true){ al.add(i); } } return al; }} 0 sharmanitish1832 months ago static ArrayList<Integer> sieveOfEratosthenes(int N){ ArrayList<Integer> a=new ArrayList<>(); boolean prime[]=isPrime(N); for(int i=2;i<=N;i++){ if(prime[i]) a.add(i); } return a; } public static boolean[] isPrime(int n){ boolean a[]=new boolean[n+1]; Arrays.fill(a,true); a[0]=false; a[1]=false; for(int i=2;i<=Math.sqrt(n);i++){ for(int j=2*i;j<=n;j+=i) a[j]=false; } return a; } 0 deepakkoshta8063 months ago vector<int> sieveOfEratosthenes(int N) { int i,j; vector<int> v; for(i=2;i<=N;i++) { for(j=2;j<=i/2;j++) if(i%j==0) break; if(j==(i/2)+1) v.push_back(i); } return v; } 0 akashjoy5983 months ago Simple Code:- class Solution{ static ArrayList<Integer> sieveOfEratosthenes(int N){ // code here ArrayList<Integer>prime = new ArrayList<>(); for(int i = 2;i<=N;i++){ boolean isprime = true; int div = 2; while(div*div<=i){ if(i%div==0){ isprime = false; break; } div++; } if(isprime==true){ prime.add(i); } } // System.out.println(N); return prime; }} 0 puspdev4 months ago class Solution: def sieveOfEratosthenes(self, N): #code here res = [0]*(N+1) i = 2 ans = [] while (i*i <=N): if not res[i]: for j in range(i*i, N+1, i): res[j]=1 i+=1 for j in range(2, N+1): if not res[j]: ans.append(j) return ans 0 puspdev This comment was deleted. +1 princeagrawal6174 months ago vector<int>primes; bool arr[N+1]={false}; arr[0]=arr[1]=true; for(int i=2;i*i<=N;i++){ if(arr[i]==false){ for(int j=i*i;j<=N;j+=i) arr[j]=true; } } for(int i=2;i<=N;i++){ if(!arr[i]) primes.push_back(i); } return primes; } 0 xixo5 months ago //User function Template for Javaclass Solution{ static ArrayList<Integer> sieveOfEratosthenes(int N){ boolean[] criba = new boolean[N+1]; ArrayList<Integer> primes = new ArrayList<Integer>(); primes.add(2); for(int i=3; i<=N; i+=2){ if(!criba[i]){ primes.add(i); for(int j=i*i;j<=N;j+=2*i){ criba[j]=true; } } } return primes; }} +1 krishanu2020ca0355 months ago vector<int> sieveOfEratosthenes(int n) { // Write Your Code here if(n <= 1) return {}; bool isPrime[n + 1]; fill(isPrime, isPrime + n + 1, true); for(int i=2; i*i <= n; i++) { if(isPrime[i]) { for(int j = 2*i; j <= n; j = j+i) { isPrime[j] = false; } } } vector<int> Primes; for(int i = 2; i <= n; i++) { if(isPrime[i]) Primes.push_back(i); } return Primes; } 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": 323, "s": 238, "text": "Given a number N, calculate the prime numbers up to N using Sieve of Eratosthenes. " }, { "code": null, "e": 334, "s": 323, "text": "Example 1:" }, { "code": null, "e": 432, "s": 334, "text": "Input:\nN = 10\n\nOutput:\n2 3 5 7\n\nExplanation:\nPrime numbers less than equal to N \nare 2 3 5 and 7." }, { "code": null, "e": 443, "s": 432, "text": "Example 2:" }, { "code": null, "e": 583, "s": 443, "text": "Input:\nN = 35\n\nOutput:\n2 3 5 7 11 13 17 19 23 29 31\n\nExplanation:\nPrime numbers less than equal to 35 are\n2 3 5 7 11 13 17 19 23 29 and 31." }, { "code": null, "e": 810, "s": 583, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function sieveOfEratosthenes() which takes an integer N as an input parameter and return the list of prime numbers less than equal to N." }, { "code": null, "e": 879, "s": 810, "text": "Expected Time Complexity: O(NloglogN)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 905, "s": 879, "text": "Constraints:\n1<= N <= 104" }, { "code": null, "e": 907, "s": 905, "text": "0" }, { "code": null, "e": 937, "s": 907, "text": "pranavkhandare45452 weeks ago" }, { "code": null, "e": 951, "s": 937, "text": "JAVA SOLUTION" }, { "code": null, "e": 1434, "s": 953, "text": "static ArrayList<Integer> sieveOfEratosthenes(int N){ ArrayList<Integer> al=new ArrayList<>(); boolean isprime[]=new boolean[N+1]; Arrays.fill(isprime,true); for(int i=2;i*i<=N;i++){ if(isprime[i]){ for(int j=2*i;j<=N;j=j+i){ isprime[j]=false; } } } for (int i=2;i<=N;i++){ if(isprime[i]==true){ al.add(i); } } return al; }" }, { "code": null, "e": 1462, "s": 1460, "text": "0" }, { "code": null, "e": 1486, "s": 1462, "text": "mail2rajab011 month ago" }, { "code": null, "e": 1510, "s": 1486, "text": "// Simple Java Solution" }, { "code": null, "e": 1536, "s": 1510, "text": "Total Time Taken: 0.6/1.5" }, { "code": null, "e": 2046, "s": 1538, "text": "class Solution{ static ArrayList<Integer> sieveOfEratosthenes(int N){ // code here ArrayList<Integer> al=new ArrayList<> (); boolean arr[]=new boolean[N+1]; Arrays.fill(arr,true); arr[0]=false; arr[1]=false; for(int i=2;i*i<=N;i++){ for(int j=2*i;j<=N;j +=i){ arr[j]=false; } } for(int i=0;i<arr.length;i++){ if(arr[i]==true){ al.add(i); } } return al; }}" }, { "code": null, "e": 2048, "s": 2046, "text": "0" }, { "code": null, "e": 2076, "s": 2048, "text": "sharmanitish1832 months ago" }, { "code": null, "e": 2589, "s": 2076, "text": "static ArrayList<Integer> sieveOfEratosthenes(int N){ ArrayList<Integer> a=new ArrayList<>(); boolean prime[]=isPrime(N); for(int i=2;i<=N;i++){ if(prime[i]) a.add(i); } return a; } public static boolean[] isPrime(int n){ boolean a[]=new boolean[n+1]; Arrays.fill(a,true); a[0]=false; a[1]=false; for(int i=2;i<=Math.sqrt(n);i++){ for(int j=2*i;j<=n;j+=i) a[j]=false; } return a; }" }, { "code": null, "e": 2591, "s": 2589, "text": "0" }, { "code": null, "e": 2619, "s": 2591, "text": "deepakkoshta8063 months ago" }, { "code": null, "e": 2906, "s": 2619, "text": "vector<int> sieveOfEratosthenes(int N)\n {\n int i,j;\n vector<int> v;\n for(i=2;i<=N;i++)\n {\n for(j=2;j<=i/2;j++)\n if(i%j==0)\n break;\n if(j==(i/2)+1)\n v.push_back(i);\n }\n return v;\n }" }, { "code": null, "e": 2908, "s": 2906, "text": "0" }, { "code": null, "e": 2932, "s": 2908, "text": "akashjoy5983 months ago" }, { "code": null, "e": 2947, "s": 2932, "text": "Simple Code:- " }, { "code": null, "e": 3477, "s": 2947, "text": "class Solution{ static ArrayList<Integer> sieveOfEratosthenes(int N){ // code here ArrayList<Integer>prime = new ArrayList<>(); for(int i = 2;i<=N;i++){ boolean isprime = true; int div = 2; while(div*div<=i){ if(i%div==0){ isprime = false; break; } div++; } if(isprime==true){ prime.add(i); } } // System.out.println(N); return prime; }}" }, { "code": null, "e": 3479, "s": 3477, "text": "0" }, { "code": null, "e": 3499, "s": 3479, "text": "puspdev4 months ago" }, { "code": null, "e": 3852, "s": 3499, "text": "class Solution: def sieveOfEratosthenes(self, N): #code here res = [0]*(N+1) i = 2 ans = [] while (i*i <=N): if not res[i]: for j in range(i*i, N+1, i): res[j]=1 i+=1 for j in range(2, N+1): if not res[j]: ans.append(j) return ans" }, { "code": null, "e": 3854, "s": 3852, "text": "0" }, { "code": null, "e": 3862, "s": 3854, "text": "puspdev" }, { "code": null, "e": 3888, "s": 3862, "text": "This comment was deleted." }, { "code": null, "e": 3891, "s": 3888, "text": "+1" }, { "code": null, "e": 3920, "s": 3891, "text": "princeagrawal6174 months ago" }, { "code": null, "e": 3986, "s": 3920, "text": "vector<int>primes; bool arr[N+1]={false}; arr[0]=arr[1]=true;" }, { "code": null, "e": 4109, "s": 3986, "text": " for(int i=2;i*i<=N;i++){ if(arr[i]==false){ for(int j=i*i;j<=N;j+=i) arr[j]=true; } }" }, { "code": null, "e": 4205, "s": 4109, "text": " for(int i=2;i<=N;i++){ if(!arr[i]) primes.push_back(i); } return primes; }" }, { "code": null, "e": 4207, "s": 4205, "text": "0" }, { "code": null, "e": 4224, "s": 4207, "text": "xixo5 months ago" }, { "code": null, "e": 4675, "s": 4224, "text": "//User function Template for Javaclass Solution{ static ArrayList<Integer> sieveOfEratosthenes(int N){ boolean[] criba = new boolean[N+1]; ArrayList<Integer> primes = new ArrayList<Integer>(); primes.add(2); for(int i=3; i<=N; i+=2){ if(!criba[i]){ primes.add(i); for(int j=i*i;j<=N;j+=2*i){ criba[j]=true; } } } return primes; }}" }, { "code": null, "e": 4678, "s": 4675, "text": "+1" }, { "code": null, "e": 4708, "s": 4678, "text": "krishanu2020ca0355 months ago" }, { "code": null, "e": 5270, "s": 4708, "text": " vector<int> sieveOfEratosthenes(int n)\n {\n // Write Your Code here\n if(n <= 1)\n\t\treturn {};\n\t\t\n bool isPrime[n + 1];\n fill(isPrime, isPrime + n + 1, true);\n \n for(int i=2; i*i <= n; i++)\n \t{\n \t\tif(isPrime[i])\n \t\t{\n \t\t\tfor(int j = 2*i; j <= n; j = j+i)\n \t\t\t{\n \t\t\t\tisPrime[j] = false;\n \t\t\t}\n \t\t}\n \t}\n \n vector<int> Primes;\n for(int i = 2; i <= n; i++)\n {\n if(isPrime[i])\n Primes.push_back(i);\n }\n \n return Primes;\n }" }, { "code": null, "e": 5416, "s": 5270, "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": 5452, "s": 5416, "text": " Login to access your submissions. " }, { "code": null, "e": 5462, "s": 5452, "text": "\nProblem\n" }, { "code": null, "e": 5472, "s": 5462, "text": "\nContest\n" }, { "code": null, "e": 5535, "s": 5472, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5683, "s": 5535, "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": 5891, "s": 5683, "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": 5997, "s": 5891, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to traverse Hierarchical data in Oracle?
Problem Statement: You need to traverse the hierarchy data from top to bottom marking the level of each row in the hierarchy. Solution: Oracle provides CONNECT BY clause to specify a hierarchical query i.e. how to connect the parent nodes and child nodes and the PRIOR operator to define the join condition/s between the parent nodes, and the LEVEL pseudo-column to indicate how far from the root/parent row the current row is. Additionally, we can use the START WITH clause to indicate where to start the tree navigation. We must use the PRIOR operator to specify the column/s in the parent row that have the same values as the linking columns in the child row. In order to loop through the entire hieratchy, remove the START WITH clause. This will fetch all the students with their professor and their professor’s professor(i.e. Dean), and so on, until the top manager/director of the institute. /* Function - Identify the hierarchical/structure for the professor_id = 102 Tables Used - students Data - documented below */ SELECT student_id, level, lpad('-',(level-1)*3) || first_name || ' ' || last_name AS full_name FROM students START WITH professor_id = 102 CONNECT BY professor_id = PRIOR student_id; 103 1 BROWN MICHAEL 104 2 -JONES WILLIAM 105 2 -MILLER DAVID 106 2 -DAVIS RICHARD 107 2 -GARCIA CHARLES 103 1 BROWN MICHAEL 104 2 -JONES WILLIAM 105 2 -MILLER DAVID 106 2 -DAVIS RICHARD 107 2 -GARCIA CHARLES /* Function - Identify the hierarchical/structure professor_id is null Tables Used - students Data - documented below */ SELECT student_id, level, lpad('-',(level-1)*3) || first_name || ' ' || last_name AS full_name FROM students START WITH professor_id IS null CONNECT BY professor_id = PRIOR student_id; 100 1 SMITH JAMES 101 2 -JOHNSON JOHN 108 3 -RODRIGUEZ JOSEPH 109 4 -WILSON THOMAS 110 4 -MARTINEZ CHRISTOPHER 111 4 -ANDERSON DANIEL 112 4 -TAYLOR PAUL 113 4 -THOMAS MARK 102 2 -WILLIAMS ROBERT 103 3 -BROWN MICHAEL 104 4 -JONES WILLIAM 105 4 -MILLER DAVID 106 4 -DAVIS RICHARD 107 4 -GARCIA CHARLES /* Function - Identify the Institute entire hierarchical/structure Tables Used - students Data - documented below */ SELECT student_id, level, lpad('-',(level-1)*3) || first_name || ' ' || last_name AS full_name FROM students CONNECT BY student_id = PRIOR professor_id; 100 1 SMITH JAMES 101 1 JOHNSON JOHN 100 2 -SMITH JAMES 102 1 WILLIAMS ROBERT 100 2 -SMITH JAMES 103 1 BROWN MICHAEL 102 2 -WILLIAMS ROBERT 100 3 -SMITH JAMES 104 1 JONES WILLIAM 103 2 -BROWN MICHAEL 102 3 -WILLIAMS ROBERT 100 4 -SMITH JAMES 105 1 MILLER DAVID 103 2 -BROWN MICHAEL 102 3 -WILLIAMS ROBERT 100 4 -SMITH JAMES 106 1 DAVIS RICHARD 103 2 -BROWN MICHAEL 102 3 -WILLIAMS ROBERT 100 4 -SMITH JAMES 107 1 GARCIA CHARLES 103 2 -BROWN MICHAEL 102 3 -WILLIAMS ROBERT 100 4 -SMITH JAMES 108 1 RODRIGUEZ JOSEPH 101 2 -JOHNSON JOHN 100 3 -SMITH JAMES 109 1 WILSON THOMAS 108 2 -RODRIGUEZ JOSEPH 101 3 -JOHNSON JOHN 100 4 -SMITH JAMES 110 1 MARTINEZ CHRISTOPHER 108 2 -RODRIGUEZ JOSEPH 101 3 -JOHNSON JOHN 100 4 -SMITH JAMES 111 1 ANDERSON DANIEL 108 2 -RODRIGUEZ JOSEPH 101 3 -JOHNSON JOHN 100 4 -SMITH JAMES 112 1 TAYLOR PAUL 108 2 -RODRIGUEZ JOSEPH 101 3 -JOHNSON JOHN 100 4 -SMITH JAMES 113 1 THOMAS MARK 108 2 -RODRIGUEZ JOSEPH 101 3 -JOHNSON JOHN 100 4 -SMITH JAMES DROP TABLE students; COMMIT; CREATE TABLE students ( student_id NUMBER(6) , first_name VARCHAR2(20) , last_name VARCHAR2(25) , email VARCHAR2(40) , phone_number VARCHAR2(20) , join_date DATE , class_id VARCHAR2(20) , fees NUMBER(8,2) , professor_id NUMBER(6) , department_id NUMBER(4) ) ; CREATE UNIQUE INDEX stu_id_pk ON students (student_id) ; INSERT INTO students VALUES (100,'SMITH','JAMES','SMITH.JAMES@notreal.com','111.111.1245',TO_DATE('17-06-2003','DD-MM-YYYY'),'INS_CHAIRMAN',24000,NULL,NULL); INSERT INTO students VALUES (101,'JOHNSON','JOHN','JOHNSON.JOHN@notreal.com','111.111.1246',TO_DATE('21-09-2005','DD-MM-YYYY'),'INS_VP',17000,100,90); INSERT INTO students VALUES (102,'WILLIAMS','ROBERT','WILLIAMS.ROBERT@notreal.com','111.111.1247',TO_DATE('13-01-2001','DD-MM-YYYY'),'INS_VP',17000,100,90); INSERT INTO students VALUES (103,'BROWN','MICHAEL','BROWN.MICHAEL@notreal.com','111.111.1248',TO_DATE('03-01-2006','DD-MM-YYYY'),'INS_STAFF',9000,102,60); INSERT INTO students VALUES (104,'JONES','WILLIAM','JONES.WILLIAM@notreal.com','111.111.1249',TO_DATE('21-05-2007','DD-MM-YYYY'),'INS_STAFF',6000,103,60); INSERT INTO students VALUES (105,'MILLER','DAVID','MILLER.DAVID@notreal.com','111.111.1250',TO_DATE('25-06-2005','DD-MM-YYYY'),'INS_STAFF',4800,103,60); INSERT INTO students VALUES (106,'DAVIS','RICHARD','DAVIS.RICHARD@notreal.com','111.111.1251',TO_DATE('05-02-2006','DD-MM-YYYY'),'INS_STAFF',4800,103,60); INSERT INTO students VALUES (107,'GARCIA','CHARLES','GARCIA.CHARLES@notreal.com','111.111.1252',TO_DATE('07-02-2007','DD-MM-YYYY'),'INS_STAFF',4200,103,60); INSERT INTO students VALUES (108,'RODRIGUEZ','JOSEPH','RODRIGUEZ.JOSEPH@notreal.com','111.111.1253',TO_DATE('17-08-2002','DD-MM-YYYY'),'CL_PHY',12008,101,100); INSERT INTO students VALUES (109,'WILSON','THOMAS','WILSON.THOMAS@notreal.com','111.111.1254',TO_DATE('16-08-2002','DD-MM-YYYY'),'CL_MATH',9000,108,100); INSERT INTO students VALUES (110,'MARTINEZ','CHRISTOPHER','MARTINEZ.CHRISTOPHER@notreal.com','111.111.1255',TO_DATE('28-09-2005','DD-MM-YYYY'),'CL_MATH',8200,108,100); INSERT INTO students VALUES (111,'ANDERSON','DANIEL','ANDERSON.DANIEL@notreal.com','111.111.1256',TO_DATE('30-09-2005','DD-MM-YYYY'),'CL_MATH',7700,108,100); INSERT INTO students VALUES (112,'TAYLOR','PAUL','TAYLOR.PAUL@notreal.com','111.111.1257',TO_DATE('07-03-2006','DD-MM-YYYY'),'CL_MATH',7800,108,100); INSERT INTO students VALUES (113,'THOMAS','MARK','THOMAS.MARK@notreal.com','111.111.1258',TO_DATE('07-12-2007','DD-MM-YYYY'),'CL_MATH',6900,108,100); COMMIT;
[ { "code": null, "e": 1188, "s": 1062, "text": "Problem Statement: You need to traverse the hierarchy data from top to bottom marking the level of each row in the hierarchy." }, { "code": null, "e": 1198, "s": 1188, "text": "Solution:" }, { "code": null, "e": 1490, "s": 1198, "text": "Oracle provides CONNECT BY clause to specify a hierarchical query i.e. how to connect the parent nodes and child nodes and the PRIOR operator to define the join condition/s between the parent nodes, and the LEVEL pseudo-column to indicate how far from the root/parent row the current row is." }, { "code": null, "e": 1725, "s": 1490, "text": "Additionally, we can use the START WITH clause to indicate where to start the tree navigation. We must use the PRIOR operator to specify the column/s in the parent row that have the same values as the linking columns in the child row." }, { "code": null, "e": 1960, "s": 1725, "text": "In order to loop through the entire hieratchy, remove the START WITH clause. This will fetch all the students with their professor and their professor’s professor(i.e. Dean), and so on, until the top manager/director of the institute." }, { "code": null, "e": 2303, "s": 1960, "text": "/*\n Function - Identify the hierarchical/structure for the professor_id = 102\n Tables Used - students\n Data - documented below\n*/\n\nSELECT student_id,\n level,\n lpad('-',(level-1)*3) || first_name || ' ' || last_name AS full_name\n FROM students\nSTART WITH professor_id = 102\nCONNECT BY professor_id = PRIOR student_id;" }, { "code": null, "e": 2425, "s": 2303, "text": "103 1 BROWN MICHAEL\n104 2 -JONES WILLIAM\n105 2 -MILLER DAVID\n106 2 -DAVIS RICHARD\n107 2 -GARCIA CHARLES" }, { "code": null, "e": 2547, "s": 2425, "text": "103 1 BROWN MICHAEL\n104 2 -JONES WILLIAM\n105 2 -MILLER DAVID\n106 2 -DAVIS RICHARD\n107 2 -GARCIA CHARLES" }, { "code": null, "e": 2886, "s": 2547, "text": "/*\n Function - Identify the hierarchical/structure professor_id is null\n Tables Used - students\n Data - documented below\n*/\n\nSELECT student_id,\n level,\n lpad('-',(level-1)*3) || first_name || ' ' || last_name AS full_name\n FROM students\nSTART WITH professor_id IS null\nCONNECT BY professor_id = PRIOR student_id;" }, { "code": null, "e": 3300, "s": 2886, "text": "100 1 SMITH JAMES\n101 2 -JOHNSON JOHN\n108 3 -RODRIGUEZ JOSEPH\n109 4 -WILSON THOMAS\n110 4 -MARTINEZ CHRISTOPHER\n111 4 -ANDERSON DANIEL\n112 4 -TAYLOR PAUL\n113 4 -THOMAS MARK\n102 2 -WILLIAMS ROBERT\n103 3 -BROWN MICHAEL\n104 4 -JONES WILLIAM\n105 4 -MILLER DAVID\n106 4 -DAVIS RICHARD\n107 4 -GARCIA CHARLES" }, { "code": null, "e": 3603, "s": 3300, "text": "/*\n Function - Identify the Institute entire hierarchical/structure\n Tables Used - students\n Data - documented below\n*/\n\nSELECT student_id,\n level,\n lpad('-',(level-1)*3) || first_name || ' ' || last_name AS full_name\n FROM students\nCONNECT BY student_id = PRIOR professor_id;" }, { "code": null, "e": 4823, "s": 3603, "text": "100 1 SMITH JAMES\n101 1 JOHNSON JOHN\n100 2 -SMITH JAMES\n102 1 WILLIAMS ROBERT\n100 2 -SMITH JAMES\n103 1 BROWN MICHAEL\n102 2 -WILLIAMS ROBERT\n100 3 -SMITH JAMES\n104 1 JONES WILLIAM\n103 2 -BROWN MICHAEL\n102 3 -WILLIAMS ROBERT\n100 4 -SMITH JAMES\n105 1 MILLER DAVID\n103 2 -BROWN MICHAEL\n102 3 -WILLIAMS ROBERT\n100 4 -SMITH JAMES\n106 1 DAVIS RICHARD\n103 2 -BROWN MICHAEL\n102 3 -WILLIAMS ROBERT\n100 4 -SMITH JAMES\n107 1 GARCIA CHARLES\n103 2 -BROWN MICHAEL\n102 3 -WILLIAMS ROBERT\n100 4 -SMITH JAMES\n108 1 RODRIGUEZ JOSEPH\n101 2 -JOHNSON JOHN\n100 3 -SMITH JAMES\n109 1 WILSON THOMAS\n108 2 -RODRIGUEZ JOSEPH\n101 3 -JOHNSON JOHN\n100 4 -SMITH JAMES\n110 1 MARTINEZ CHRISTOPHER\n108 2 -RODRIGUEZ JOSEPH\n101 3 -JOHNSON JOHN\n100 4 -SMITH JAMES\n111 1 ANDERSON DANIEL\n108 2 -RODRIGUEZ JOSEPH\n101 3 -JOHNSON JOHN\n100 4 -SMITH JAMES\n112 1 TAYLOR PAUL\n108 2 -RODRIGUEZ JOSEPH\n101 3 -JOHNSON JOHN\n100 4 -SMITH JAMES\n113 1 THOMAS MARK\n108 2 -RODRIGUEZ JOSEPH\n101 3 -JOHNSON JOHN\n100 4 -SMITH JAMES" }, { "code": null, "e": 5211, "s": 4823, "text": "DROP TABLE students;\nCOMMIT;\n\nCREATE TABLE students\n ( student_id NUMBER(6)\n , first_name VARCHAR2(20)\n , last_name VARCHAR2(25) \n , email VARCHAR2(40) \n , phone_number VARCHAR2(20)\n , join_date DATE \n , class_id VARCHAR2(20) \n , fees NUMBER(8,2)\n , professor_id NUMBER(6)\n , department_id NUMBER(4) \n ) ;" }, { "code": null, "e": 7458, "s": 5211, "text": "CREATE UNIQUE INDEX stu_id_pk ON students (student_id) ;\nINSERT INTO students VALUES (100,'SMITH','JAMES','SMITH.JAMES@notreal.com','111.111.1245',TO_DATE('17-06-2003','DD-MM-YYYY'),'INS_CHAIRMAN',24000,NULL,NULL);\nINSERT INTO students VALUES (101,'JOHNSON','JOHN','JOHNSON.JOHN@notreal.com','111.111.1246',TO_DATE('21-09-2005','DD-MM-YYYY'),'INS_VP',17000,100,90);\nINSERT INTO students VALUES (102,'WILLIAMS','ROBERT','WILLIAMS.ROBERT@notreal.com','111.111.1247',TO_DATE('13-01-2001','DD-MM-YYYY'),'INS_VP',17000,100,90);\nINSERT INTO students VALUES (103,'BROWN','MICHAEL','BROWN.MICHAEL@notreal.com','111.111.1248',TO_DATE('03-01-2006','DD-MM-YYYY'),'INS_STAFF',9000,102,60);\nINSERT INTO students VALUES (104,'JONES','WILLIAM','JONES.WILLIAM@notreal.com','111.111.1249',TO_DATE('21-05-2007','DD-MM-YYYY'),'INS_STAFF',6000,103,60);\nINSERT INTO students VALUES (105,'MILLER','DAVID','MILLER.DAVID@notreal.com','111.111.1250',TO_DATE('25-06-2005','DD-MM-YYYY'),'INS_STAFF',4800,103,60);\nINSERT INTO students VALUES (106,'DAVIS','RICHARD','DAVIS.RICHARD@notreal.com','111.111.1251',TO_DATE('05-02-2006','DD-MM-YYYY'),'INS_STAFF',4800,103,60);\nINSERT INTO students VALUES (107,'GARCIA','CHARLES','GARCIA.CHARLES@notreal.com','111.111.1252',TO_DATE('07-02-2007','DD-MM-YYYY'),'INS_STAFF',4200,103,60);\nINSERT INTO students VALUES (108,'RODRIGUEZ','JOSEPH','RODRIGUEZ.JOSEPH@notreal.com','111.111.1253',TO_DATE('17-08-2002','DD-MM-YYYY'),'CL_PHY',12008,101,100);\nINSERT INTO students VALUES (109,'WILSON','THOMAS','WILSON.THOMAS@notreal.com','111.111.1254',TO_DATE('16-08-2002','DD-MM-YYYY'),'CL_MATH',9000,108,100);\nINSERT INTO students VALUES (110,'MARTINEZ','CHRISTOPHER','MARTINEZ.CHRISTOPHER@notreal.com','111.111.1255',TO_DATE('28-09-2005','DD-MM-YYYY'),'CL_MATH',8200,108,100);\nINSERT INTO students VALUES (111,'ANDERSON','DANIEL','ANDERSON.DANIEL@notreal.com','111.111.1256',TO_DATE('30-09-2005','DD-MM-YYYY'),'CL_MATH',7700,108,100);\nINSERT INTO students VALUES (112,'TAYLOR','PAUL','TAYLOR.PAUL@notreal.com','111.111.1257',TO_DATE('07-03-2006','DD-MM-YYYY'),'CL_MATH',7800,108,100);\nINSERT INTO students VALUES (113,'THOMAS','MARK','THOMAS.MARK@notreal.com','111.111.1258',TO_DATE('07-12-2007','DD-MM-YYYY'),'CL_MATH',6900,108,100);\n\nCOMMIT;" } ]
Top 7 FREE Artificial Intelligence Courses from the Ivy League Universities | by Roman Orac | Towards Data Science
1 2 3 4 5 6 7 8 9 10 Powered by Play.ht Create audio with Play.ht Powered by Play.ht These days it feels like every week comes with a new AI course. With such volume, we need to be really selective with our time, energy and focus. A simple but effective strategy is to attend the courses from the best minds in the field. Use your time effectively and attend the courses from the best minds in the field. With the help of my fellow Data Scientists, we curated a list of the top 7 Artificial Intelligence courses from the Ivy League Universities. The course had to be free to be included in the list. I haven’t attended all the courses on the list but I got high praise from my colleagues. Next on my course list, I wish to attend is the Reinforcement Learning course. Ivy League is a group of eight private universities: Harvard, Yale, Princeton, Brown, Dartmouth, Columbia, Cornell, and the University of Pennsylvania. While Stanford and MIT are clearly prestigious schools, they are not Ivy League schools simply because they are not members of the Ivy League. Here are a few links that might interest you: - Labeling and Data Engineering for Conversational AI and Analytics- Data Science for Business Leaders [Course]- Intro to Machine Learning with PyTorch [Course]- Become a Growth Product Manager [Course]- Deep Learning (Adaptive Computation and ML series) [Ebook]- Free skill tests for Data Scientists & Machine Learning Engineers Some of the links above are affiliate links and if you go through them to make a purchase I’ll earn a commission. Keep in mind that I link courses because of their quality and not because of the commission I receive from your purchases. In case you’ve missed my other two articles related to this topic: towardsdatascience.com towardsdatascience.com University: Georgia TechInstructor: Prof. Charles Isbell www.udacity.com Reinforcement Learning is one of the hottest topics in Machine Learning. You should take this course if you have a desire to engage with it from a theoretical perspective. In this course, you will explore automated decision-making from a Computer Science perspective through a combination of classic papers and more recent work. You will examine efficient algorithms, where they exist, for single-agent and multi-agent planning as well as approaches to learning near-optimal decisions from experience. At the end of the course, you will replicate a result from a published paper in reinforcement learning. University: MITInstructor: Prof. Berthold Horn ocw.mit.edu This MIT course provides an intensive introduction to the process of generating a symbolic description of an environment from an image. In lectures, you will learn the physics of image formation, motion vision, and recovering shapes from shading. Binary image processing and filtering are presented as preprocessing steps. Further topics include photogrammetry, object representation alignment, analog VLSI and Computational Vision. Applications to robotics and intelligent machine interaction are discussed. University: MITInstructor: Prof. Philippe Rigollet ocw.mit.edu Broadly speaking, Machine Learning refers to the automated identification of patterns in data. As such it has been a fertile ground for new statistical and algorithmic developments. The purpose of this course is to provide a mathematically rigorous introduction to these developments with emphasis on methods and their analysis. University: HarvardXInstructor: Prof. Rafael Irizarry www.edx.org In this course, you will learn valuable concepts in probability theory. The motivation for this course is the circumstances surrounding the financial crisis of 2007–2008. Part of what caused this financial crisis was that the risk of some securities sold by financial institutions was underestimated. To begin to understand this very complicated event, we need to understand the basics of probability. This course will introduce important concepts such as random variables, independence, Monte Carlo simulations, expected values, standard errors, and the Central Limit Theorem. These statistical concepts are fundamental to conducting statistical tests on data and understanding whether the data you are analyzing is likely occurring due to an experimental method or to chance. Probability theory is the mathematical foundation of statistical inference which is indispensable for analyzing data affected by chance, and thus essential for Data Scientists. University: ColumbiaXInstructor: Ansaf Salleb-Aouissi, Ph.D. www.edx.org What do self-driving cars, face recognition, web search, industrial robots, missile guidance, and tumor detection have in common? They are all complex real-world problems being solved with applications of intelligence (AI). This course will provide a broad understanding of the basic techniques for building intelligent computer systems and an understanding of how AI is applied to problems. You will learn about the history of AI, intelligent agents, state-space problem representations, uninformed and heuristic search, game playing, logical agents, and constraint satisfaction problems. You will gain hands-on experience by building a basic search agent. Adversarial search will be explored through the creation of a game and an introduction to Machine Learning includes work on linear regression. University: ColumbiaInstructor: John W. Paisley, Ph.D. www.edx.org Machine Learning is the basis for the most exciting careers in Data Analysis today. You’ll learn the models and methods and apply them to real-world situations ranging from identifying trending news topics to building recommendation engines, ranking sports teams and plotting the path of movie zombies. Major perspectives covered include: probabilistic versus non-probabilistic modeling supervised versus unsupervised learning Topics include classification and regression, clustering methods, sequential models, matrix factorization, topic modeling and model selection. Methods include linear and logistic regression, support vector machines, tree classifiers, boosting, maximum likelihood and MAP inference, EM algorithm, hidden Markov models, Kalman filters, k-means, Gaussian mixture models, among others. University: PrincetonInstructor: Kevin Wayne, Ph.D. www.coursera.org This course is for you if you would like to improve your programming skills. While it is not strictly related to Machine Learning, you’ll build strong Computer Science foundations. This course covers the essential information that every serious programmer needs to know about algorithms and data structures, with emphasis on applications and scientific performance analysis of Java implementations. Part I covers elementary data structures, sorting, and searching algorithms. Part II focuses on graph- and string-processing algorithms. University: StandfordInstructor: Prof. Andrew Ng www.coursera.org Andrew Ng’s Coursera course is my favorite Machine Learning Course. It is the first course I took in the field. You’ll build strong Machine Learning foundations by listening to this course This course provides a broad introduction to machine learning, data mining, and statistical pattern recognition. The course will also draw from numerous case studies and applications so that you’ll also learn how to apply learning algorithms to building smart robots, text understanding, computer vision and other areas. University: Johns HopkinsInstructor: Prof. Avi Rubin hopkinspokercourse.com Johns Hopkins Poker Course is not strictly related to Machine Learning, but still kinda related as it deals with statistics. This is a fun way to learn about math and combinatorics. This intersession course aims to take students from novices who may know nothing about poker to above-average players, in two weeks. The course will utilize hand examples and discussions of common poker situations to study the fundamentals of the game. Follow me on Twitter, where I regularly tweet about Data Science and Machine Learning.
[ { "code": null, "e": 174, "s": 172, "text": "1" }, { "code": null, "e": 176, "s": 174, "text": "2" }, { "code": null, "e": 178, "s": 176, "text": "3" }, { "code": null, "e": 180, "s": 178, "text": "4" }, { "code": null, "e": 182, "s": 180, "text": "5" }, { "code": null, "e": 184, "s": 182, "text": "6" }, { "code": null, "e": 186, "s": 184, "text": "7" }, { "code": null, "e": 188, "s": 186, "text": "8" }, { "code": null, "e": 190, "s": 188, "text": "9" }, { "code": null, "e": 193, "s": 190, "text": "10" }, { "code": null, "e": 212, "s": 193, "text": "Powered by Play.ht" }, { "code": null, "e": 238, "s": 212, "text": "Create audio with Play.ht" }, { "code": null, "e": 257, "s": 238, "text": "Powered by Play.ht" }, { "code": null, "e": 494, "s": 257, "text": "These days it feels like every week comes with a new AI course. With such volume, we need to be really selective with our time, energy and focus. A simple but effective strategy is to attend the courses from the best minds in the field." }, { "code": null, "e": 577, "s": 494, "text": "Use your time effectively and attend the courses from the best minds in the field." }, { "code": null, "e": 772, "s": 577, "text": "With the help of my fellow Data Scientists, we curated a list of the top 7 Artificial Intelligence courses from the Ivy League Universities. The course had to be free to be included in the list." }, { "code": null, "e": 940, "s": 772, "text": "I haven’t attended all the courses on the list but I got high praise from my colleagues. Next on my course list, I wish to attend is the Reinforcement Learning course." }, { "code": null, "e": 1092, "s": 940, "text": "Ivy League is a group of eight private universities: Harvard, Yale, Princeton, Brown, Dartmouth, Columbia, Cornell, and the University of Pennsylvania." }, { "code": null, "e": 1235, "s": 1092, "text": "While Stanford and MIT are clearly prestigious schools, they are not Ivy League schools simply because they are not members of the Ivy League." }, { "code": null, "e": 1281, "s": 1235, "text": "Here are a few links that might interest you:" }, { "code": null, "e": 1611, "s": 1281, "text": "- Labeling and Data Engineering for Conversational AI and Analytics- Data Science for Business Leaders [Course]- Intro to Machine Learning with PyTorch [Course]- Become a Growth Product Manager [Course]- Deep Learning (Adaptive Computation and ML series) [Ebook]- Free skill tests for Data Scientists & Machine Learning Engineers" }, { "code": null, "e": 1848, "s": 1611, "text": "Some of the links above are affiliate links and if you go through them to make a purchase I’ll earn a commission. Keep in mind that I link courses because of their quality and not because of the commission I receive from your purchases." }, { "code": null, "e": 1915, "s": 1848, "text": "In case you’ve missed my other two articles related to this topic:" }, { "code": null, "e": 1938, "s": 1915, "text": "towardsdatascience.com" }, { "code": null, "e": 1961, "s": 1938, "text": "towardsdatascience.com" }, { "code": null, "e": 2018, "s": 1961, "text": "University: Georgia TechInstructor: Prof. Charles Isbell" }, { "code": null, "e": 2034, "s": 2018, "text": "www.udacity.com" }, { "code": null, "e": 2206, "s": 2034, "text": "Reinforcement Learning is one of the hottest topics in Machine Learning. You should take this course if you have a desire to engage with it from a theoretical perspective." }, { "code": null, "e": 2640, "s": 2206, "text": "In this course, you will explore automated decision-making from a Computer Science perspective through a combination of classic papers and more recent work. You will examine efficient algorithms, where they exist, for single-agent and multi-agent planning as well as approaches to learning near-optimal decisions from experience. At the end of the course, you will replicate a result from a published paper in reinforcement learning." }, { "code": null, "e": 2687, "s": 2640, "text": "University: MITInstructor: Prof. Berthold Horn" }, { "code": null, "e": 2699, "s": 2687, "text": "ocw.mit.edu" }, { "code": null, "e": 2835, "s": 2699, "text": "This MIT course provides an intensive introduction to the process of generating a symbolic description of an environment from an image." }, { "code": null, "e": 3022, "s": 2835, "text": "In lectures, you will learn the physics of image formation, motion vision, and recovering shapes from shading. Binary image processing and filtering are presented as preprocessing steps." }, { "code": null, "e": 3208, "s": 3022, "text": "Further topics include photogrammetry, object representation alignment, analog VLSI and Computational Vision. Applications to robotics and intelligent machine interaction are discussed." }, { "code": null, "e": 3259, "s": 3208, "text": "University: MITInstructor: Prof. Philippe Rigollet" }, { "code": null, "e": 3271, "s": 3259, "text": "ocw.mit.edu" }, { "code": null, "e": 3453, "s": 3271, "text": "Broadly speaking, Machine Learning refers to the automated identification of patterns in data. As such it has been a fertile ground for new statistical and algorithmic developments." }, { "code": null, "e": 3600, "s": 3453, "text": "The purpose of this course is to provide a mathematically rigorous introduction to these developments with emphasis on methods and their analysis." }, { "code": null, "e": 3654, "s": 3600, "text": "University: HarvardXInstructor: Prof. Rafael Irizarry" }, { "code": null, "e": 3666, "s": 3654, "text": "www.edx.org" }, { "code": null, "e": 3837, "s": 3666, "text": "In this course, you will learn valuable concepts in probability theory. The motivation for this course is the circumstances surrounding the financial crisis of 2007–2008." }, { "code": null, "e": 4068, "s": 3837, "text": "Part of what caused this financial crisis was that the risk of some securities sold by financial institutions was underestimated. To begin to understand this very complicated event, we need to understand the basics of probability." }, { "code": null, "e": 4444, "s": 4068, "text": "This course will introduce important concepts such as random variables, independence, Monte Carlo simulations, expected values, standard errors, and the Central Limit Theorem. These statistical concepts are fundamental to conducting statistical tests on data and understanding whether the data you are analyzing is likely occurring due to an experimental method or to chance." }, { "code": null, "e": 4621, "s": 4444, "text": "Probability theory is the mathematical foundation of statistical inference which is indispensable for analyzing data affected by chance, and thus essential for Data Scientists." }, { "code": null, "e": 4682, "s": 4621, "text": "University: ColumbiaXInstructor: Ansaf Salleb-Aouissi, Ph.D." }, { "code": null, "e": 4694, "s": 4682, "text": "www.edx.org" }, { "code": null, "e": 4824, "s": 4694, "text": "What do self-driving cars, face recognition, web search, industrial robots, missile guidance, and tumor detection have in common?" }, { "code": null, "e": 4918, "s": 4824, "text": "They are all complex real-world problems being solved with applications of intelligence (AI)." }, { "code": null, "e": 5086, "s": 4918, "text": "This course will provide a broad understanding of the basic techniques for building intelligent computer systems and an understanding of how AI is applied to problems." }, { "code": null, "e": 5284, "s": 5086, "text": "You will learn about the history of AI, intelligent agents, state-space problem representations, uninformed and heuristic search, game playing, logical agents, and constraint satisfaction problems." }, { "code": null, "e": 5495, "s": 5284, "text": "You will gain hands-on experience by building a basic search agent. Adversarial search will be explored through the creation of a game and an introduction to Machine Learning includes work on linear regression." }, { "code": null, "e": 5550, "s": 5495, "text": "University: ColumbiaInstructor: John W. Paisley, Ph.D." }, { "code": null, "e": 5562, "s": 5550, "text": "www.edx.org" }, { "code": null, "e": 5865, "s": 5562, "text": "Machine Learning is the basis for the most exciting careers in Data Analysis today. You’ll learn the models and methods and apply them to real-world situations ranging from identifying trending news topics to building recommendation engines, ranking sports teams and plotting the path of movie zombies." }, { "code": null, "e": 5901, "s": 5865, "text": "Major perspectives covered include:" }, { "code": null, "e": 5949, "s": 5901, "text": "probabilistic versus non-probabilistic modeling" }, { "code": null, "e": 5989, "s": 5949, "text": "supervised versus unsupervised learning" }, { "code": null, "e": 6132, "s": 5989, "text": "Topics include classification and regression, clustering methods, sequential models, matrix factorization, topic modeling and model selection." }, { "code": null, "e": 6371, "s": 6132, "text": "Methods include linear and logistic regression, support vector machines, tree classifiers, boosting, maximum likelihood and MAP inference, EM algorithm, hidden Markov models, Kalman filters, k-means, Gaussian mixture models, among others." }, { "code": null, "e": 6423, "s": 6371, "text": "University: PrincetonInstructor: Kevin Wayne, Ph.D." }, { "code": null, "e": 6440, "s": 6423, "text": "www.coursera.org" }, { "code": null, "e": 6621, "s": 6440, "text": "This course is for you if you would like to improve your programming skills. While it is not strictly related to Machine Learning, you’ll build strong Computer Science foundations." }, { "code": null, "e": 6839, "s": 6621, "text": "This course covers the essential information that every serious programmer needs to know about algorithms and data structures, with emphasis on applications and scientific performance analysis of Java implementations." }, { "code": null, "e": 6976, "s": 6839, "text": "Part I covers elementary data structures, sorting, and searching algorithms. Part II focuses on graph- and string-processing algorithms." }, { "code": null, "e": 7025, "s": 6976, "text": "University: StandfordInstructor: Prof. Andrew Ng" }, { "code": null, "e": 7042, "s": 7025, "text": "www.coursera.org" }, { "code": null, "e": 7231, "s": 7042, "text": "Andrew Ng’s Coursera course is my favorite Machine Learning Course. It is the first course I took in the field. You’ll build strong Machine Learning foundations by listening to this course" }, { "code": null, "e": 7552, "s": 7231, "text": "This course provides a broad introduction to machine learning, data mining, and statistical pattern recognition. The course will also draw from numerous case studies and applications so that you’ll also learn how to apply learning algorithms to building smart robots, text understanding, computer vision and other areas." }, { "code": null, "e": 7605, "s": 7552, "text": "University: Johns HopkinsInstructor: Prof. Avi Rubin" }, { "code": null, "e": 7628, "s": 7605, "text": "hopkinspokercourse.com" }, { "code": null, "e": 7810, "s": 7628, "text": "Johns Hopkins Poker Course is not strictly related to Machine Learning, but still kinda related as it deals with statistics. This is a fun way to learn about math and combinatorics." }, { "code": null, "e": 8063, "s": 7810, "text": "This intersession course aims to take students from novices who may know nothing about poker to above-average players, in two weeks. The course will utilize hand examples and discussions of common poker situations to study the fundamentals of the game." } ]
Big Data Analytics - Summarizing Data
Reporting is very important in big data analytics. Every organization must have a regular provision of information to support its decision making process. This task is normally handled by data analysts with SQL and ETL (extract, transfer, and load) experience. The team in charge of this task has the responsibility of spreading the information produced in the big data analytics department to different areas of the organization. The following example demonstrates what summarization of data means. Navigate to the folder bda/part1/summarize_data and inside the folder, open the summarize_data.Rproj file by double clicking it. Then, open the summarize_data.R script and take a look at the code, and follow the explanations presented. # Install the following packages by running the following code in R. pkgs = c('data.table', 'ggplot2', 'nycflights13', 'reshape2') install.packages(pkgs) The ggplot2 package is great for data visualization. The data.table package is a great option to do fast and memory efficient summarization in R. A recent benchmark shows it is even faster than pandas, the python library used for similar tasks. Take a look at the data using the following code. This code is also available in bda/part1/summarize_data/summarize_data.Rproj file. library(nycflights13) library(ggplot2) library(data.table) library(reshape2) # Convert the flights data.frame to a data.table object and call it DT DT <- as.data.table(flights) # The data has 336776 rows and 16 columns dim(DT) # Take a look at the first rows head(DT) # year month day dep_time dep_delay arr_time arr_delay carrier # 1: 2013 1 1 517 2 830 11 UA # 2: 2013 1 1 533 4 850 20 UA # 3: 2013 1 1 542 2 923 33 AA # 4: 2013 1 1 544 -1 1004 -18 B6 # 5: 2013 1 1 554 -6 812 -25 DL # 6: 2013 1 1 554 -4 740 12 UA # tailnum flight origin dest air_time distance hour minute # 1: N14228 1545 EWR IAH 227 1400 5 17 # 2: N24211 1714 LGA IAH 227 1416 5 33 # 3: N619AA 1141 JFK MIA 160 1089 5 42 # 4: N804JB 725 JFK BQN 183 1576 5 44 # 5: N668DN 461 LGA ATL 116 762 5 54 # 6: N39463 1696 EWR ORD 150 719 5 54 The following code has an example of data summarization. ### Data Summarization # Compute the mean arrival delay DT[, list(mean_arrival_delay = mean(arr_delay, na.rm = TRUE))] # mean_arrival_delay # 1: 6.895377 # Now, we compute the same value but for each carrier mean1 = DT[, list(mean_arrival_delay = mean(arr_delay, na.rm = TRUE)), by = carrier] print(mean1) # carrier mean_arrival_delay # 1: UA 3.5580111 # 2: AA 0.3642909 # 3: B6 9.4579733 # 4: DL 1.6443409 # 5: EV 15.7964311 # 6: MQ 10.7747334 # 7: US 2.1295951 # 8: WN 9.6491199 # 9: VX 1.7644644 # 10: FL 20.1159055 # 11: AS -9.9308886 # 12: 9E 7.3796692 # 13: F9 21.9207048 # 14: HA -6.9152047 # 15: YV 15.5569853 # 16: OO 11.9310345 # Now let’s compute to means in the same line of code mean2 = DT[, list(mean_departure_delay = mean(dep_delay, na.rm = TRUE), mean_arrival_delay = mean(arr_delay, na.rm = TRUE)), by = carrier] print(mean2) # carrier mean_departure_delay mean_arrival_delay # 1: UA 12.106073 3.5580111 # 2: AA 8.586016 0.3642909 # 3: B6 13.022522 9.4579733 # 4: DL 9.264505 1.6443409 # 5: EV 19.955390 15.7964311 # 6: MQ 10.552041 10.7747334 # 7: US 3.782418 2.1295951 # 8: WN 17.711744 9.6491199 # 9: VX 12.869421 1.7644644 # 10: FL 18.726075 20.1159055 # 11: AS 5.804775 -9.9308886 # 12: 9E 16.725769 7.3796692 # 13: F9 20.215543 21.9207048 # 14: HA 4.900585 -6.9152047 # 15: YV 18.996330 15.5569853 # 16: OO 12.586207 11.9310345 ### Create a new variable called gain # this is the difference between arrival delay and departure delay DT[, gain:= arr_delay - dep_delay] # Compute the median gain per carrier median_gain = DT[, median(gain, na.rm = TRUE), by = carrier] print(median_gain) 65 Lectures 6 hours Arnab Chakraborty 18 Lectures 1.5 hours Pranjal Srivastava, Harshit Srivastava 23 Lectures 2 hours John Shea 18 Lectures 1.5 hours Pranjal Srivastava 46 Lectures 3.5 hours Pranjal Srivastava 37 Lectures 3.5 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2815, "s": 2554, "text": "Reporting is very important in big data analytics. Every organization must have a regular provision of information to support its decision making process. This task is normally handled by data analysts with SQL and ETL (extract, transfer, and load) experience." }, { "code": null, "e": 2985, "s": 2815, "text": "The team in charge of this task has the responsibility of spreading the information produced in the big data analytics department to different areas of the organization." }, { "code": null, "e": 3290, "s": 2985, "text": "The following example demonstrates what summarization of data means. Navigate to the folder bda/part1/summarize_data and inside the folder, open the summarize_data.Rproj file by double clicking it. Then, open the summarize_data.R script and take a look at the code, and follow the explanations presented." }, { "code": null, "e": 3447, "s": 3290, "text": "# Install the following packages by running the following code in R. \npkgs = c('data.table', 'ggplot2', 'nycflights13', 'reshape2') \ninstall.packages(pkgs)\n" }, { "code": null, "e": 3692, "s": 3447, "text": "The ggplot2 package is great for data visualization. The data.table package is a great option to do fast and memory efficient summarization in R. A recent benchmark shows it is even faster than pandas, the python library used for similar tasks." }, { "code": null, "e": 3825, "s": 3692, "text": "Take a look at the data using the following code. This code is also available in bda/part1/summarize_data/summarize_data.Rproj file." }, { "code": null, "e": 5154, "s": 3825, "text": "library(nycflights13) \nlibrary(ggplot2) \nlibrary(data.table) \nlibrary(reshape2) \n\n# Convert the flights data.frame to a data.table object and call it DT \nDT <- as.data.table(flights) \n\n# The data has 336776 rows and 16 columns \ndim(DT) \n\n# Take a look at the first rows \nhead(DT) \n\n# year month day dep_time dep_delay arr_time arr_delay carrier \n# 1: 2013 1 1 517 2 830 11 UA \n# 2: 2013 1 1 533 4 850 20 UA \n# 3: 2013 1 1 542 2 923 33 AA \n# 4: 2013 1 1 544 -1 1004 -18 B6 \n# 5: 2013 1 1 554 -6 812 -25 DL \n# 6: 2013 1 1 554 -4 740 12 UA \n\n# tailnum flight origin dest air_time distance hour minute \n# 1: N14228 1545 EWR IAH 227 1400 5 17 \n# 2: N24211 1714 LGA IAH 227 1416 5 33 \n# 3: N619AA 1141 JFK MIA 160 1089 5 42 \n# 4: N804JB 725 JFK BQN 183 1576 5 44 \n# 5: N668DN 461 LGA ATL 116 762 5 54 \n# 6: N39463 1696 EWR ORD 150 719 5 54\n" }, { "code": null, "e": 5211, "s": 5154, "text": "The following code has an example of data summarization." }, { "code": null, "e": 7522, "s": 5211, "text": "### Data Summarization\n# Compute the mean arrival delay \nDT[, list(mean_arrival_delay = mean(arr_delay, na.rm = TRUE))] \n# mean_arrival_delay \n# 1: 6.895377 \n# Now, we compute the same value but for each carrier \nmean1 = DT[, list(mean_arrival_delay = mean(arr_delay, na.rm = TRUE)), \n by = carrier] \nprint(mean1) \n# carrier mean_arrival_delay \n# 1: UA 3.5580111 \n# 2: AA 0.3642909 \n# 3: B6 9.4579733 \n# 4: DL 1.6443409 \n# 5: EV 15.7964311 \n# 6: MQ 10.7747334 \n# 7: US 2.1295951 \n# 8: WN 9.6491199 \n# 9: VX 1.7644644 \n# 10: FL 20.1159055 \n# 11: AS -9.9308886 \n# 12: 9E 7.3796692\n# 13: F9 21.9207048 \n# 14: HA -6.9152047 \n# 15: YV 15.5569853 \n# 16: OO 11.9310345\n\n# Now let’s compute to means in the same line of code \nmean2 = DT[, list(mean_departure_delay = mean(dep_delay, na.rm = TRUE), \n mean_arrival_delay = mean(arr_delay, na.rm = TRUE)), \n by = carrier] \nprint(mean2) \n\n# carrier mean_departure_delay mean_arrival_delay \n# 1: UA 12.106073 3.5580111 \n# 2: AA 8.586016 0.3642909 \n# 3: B6 13.022522 9.4579733 \n# 4: DL 9.264505 1.6443409 \n# 5: EV 19.955390 15.7964311 \n# 6: MQ 10.552041 10.7747334 \n# 7: US 3.782418 2.1295951 \n# 8: WN 17.711744 9.6491199 \n# 9: VX 12.869421 1.7644644 \n# 10: FL 18.726075 20.1159055 \n# 11: AS 5.804775 -9.9308886 \n# 12: 9E 16.725769 7.3796692 \n# 13: F9 20.215543 21.9207048 \n# 14: HA 4.900585 -6.9152047 \n# 15: YV 18.996330 15.5569853 \n# 16: OO 12.586207 11.9310345\n\n### Create a new variable called gain \n# this is the difference between arrival delay and departure delay \nDT[, gain:= arr_delay - dep_delay] \n\n# Compute the median gain per carrier \nmedian_gain = DT[, median(gain, na.rm = TRUE), by = carrier] \nprint(median_gain)\n" }, { "code": null, "e": 7555, "s": 7522, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 7574, "s": 7555, "text": " Arnab Chakraborty" }, { "code": null, "e": 7609, "s": 7574, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7649, "s": 7609, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 7682, "s": 7649, "text": "\n 23 Lectures \n 2 hours \n" }, { "code": null, "e": 7693, "s": 7682, "text": " John Shea" }, { "code": null, "e": 7728, "s": 7693, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7748, "s": 7728, "text": " Pranjal Srivastava" }, { "code": null, "e": 7783, "s": 7748, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7803, "s": 7783, "text": " Pranjal Srivastava" }, { "code": null, "e": 7838, "s": 7803, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7878, "s": 7838, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 7885, "s": 7878, "text": " Print" }, { "code": null, "e": 7896, "s": 7885, "text": " Add Notes" } ]
Arithmetic Operations on Images using OpenCV | Set-1 (Addition and Subtraction) - GeeksforGeeks
13 Dec, 2021 Arithmetic Operations like Addition, Subtraction, and Bitwise Operations(AND, OR, NOT, XOR) can be applied to the input images. These operations can be helpful in enhancing the properties of the input images. The Image arithmetics are important for analyzing the input image properties. The operated images can be further used as an enhanced input image, and many more operations can be applied for clarifying, thresholding, dilating etc of the image. We can add two images by using function cv2.add(). This directly adds up image pixels in the two images. Syntax: cv2.add(img1, img2) But adding the pixels is not an ideal situation. So, we use cv2.addweighted(). Remember, both images should be of equal size and depth. Syntax: cv2.addWeighted(img1, wt1, img2, wt2, gammaValue)Parameters: img1: First Input Image array(Single-channel, 8-bit or floating-point) wt1: Weight of the first input image elements to be applied to the final image img2: Second Input Image array(Single-channel, 8-bit or floating-point) wt2: Weight of the second input image elements to be applied to the final image gammaValue: Measurement of light Images used as Input:Input Image1: Input Image2: Below is the code: Python3 # Python program to illustrate# arithmetic operation of# addition of two images # organizing importsimport cv2import numpy as np # path to input images are specified and # images are loaded with imread commandimage1 = cv2.imread('input1.jpg')image2 = cv2.imread('input2.jpg') # cv2.addWeighted is applied over the# image inputs with applied parametersweightedSum = cv2.addWeighted(image1, 0.5, image2, 0.4, 0) # the window showing output image# with the weighted sumcv2.imshow('Weighted Image', weightedSum) # De-allocate any associated memory usage if cv2.waitKey(0) & 0xff == 27: cv2.destroyAllWindows() Output: Just like addition, we can subtract the pixel values in two images and merge them with the help of cv2.subtract(). The images should be of equal size and depth. Syntax: cv2.subtract(src1, src2) Images used as Input: Input Image1: Input Image2: Below is the code: Python3 # Python program to illustrate# arithmetic operation of# subtraction of pixels of two images # organizing importsimport cv2import numpy as np # path to input images are specified and # images are loaded with imread commandimage1 = cv2.imread('input1.jpg')image2 = cv2.imread('input2.jpg') # cv2.subtract is applied over the# image inputs with applied parameterssub = cv2.subtract(image1, image2) # the window showing output image# with the subtracted imagecv2.imshow('Subtracted Image', sub) # De-allocate any associated memory usage if cv2.waitKey(0) & 0xff == 27: cv2.destroyAllWindows() Output: anikakapoor Image-Processing OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace()
[ { "code": null, "e": 41552, "s": 41524, "text": "\n13 Dec, 2021" }, { "code": null, "e": 42006, "s": 41552, "text": "Arithmetic Operations like Addition, Subtraction, and Bitwise Operations(AND, OR, NOT, XOR) can be applied to the input images. These operations can be helpful in enhancing the properties of the input images. The Image arithmetics are important for analyzing the input image properties. The operated images can be further used as an enhanced input image, and many more operations can be applied for clarifying, thresholding, dilating etc of the image. " }, { "code": null, "e": 42113, "s": 42006, "text": "We can add two images by using function cv2.add(). This directly adds up image pixels in the two images. " }, { "code": null, "e": 42141, "s": 42113, "text": "Syntax: cv2.add(img1, img2)" }, { "code": null, "e": 42279, "s": 42141, "text": "But adding the pixels is not an ideal situation. So, we use cv2.addweighted(). Remember, both images should be of equal size and depth. " }, { "code": null, "e": 42684, "s": 42279, "text": "Syntax: cv2.addWeighted(img1, wt1, img2, wt2, gammaValue)Parameters: img1: First Input Image array(Single-channel, 8-bit or floating-point) wt1: Weight of the first input image elements to be applied to the final image img2: Second Input Image array(Single-channel, 8-bit or floating-point) wt2: Weight of the second input image elements to be applied to the final image gammaValue: Measurement of light " }, { "code": null, "e": 42720, "s": 42684, "text": "Images used as Input:Input Image1: " }, { "code": null, "e": 42735, "s": 42720, "text": "Input Image2: " }, { "code": null, "e": 42756, "s": 42735, "text": "Below is the code: " }, { "code": null, "e": 42764, "s": 42756, "text": "Python3" }, { "code": "# Python program to illustrate# arithmetic operation of# addition of two images # organizing importsimport cv2import numpy as np # path to input images are specified and # images are loaded with imread commandimage1 = cv2.imread('input1.jpg')image2 = cv2.imread('input2.jpg') # cv2.addWeighted is applied over the# image inputs with applied parametersweightedSum = cv2.addWeighted(image1, 0.5, image2, 0.4, 0) # the window showing output image# with the weighted sumcv2.imshow('Weighted Image', weightedSum) # De-allocate any associated memory usage if cv2.waitKey(0) & 0xff == 27: cv2.destroyAllWindows()", "e": 43377, "s": 42764, "text": null }, { "code": null, "e": 43386, "s": 43377, "text": "Output: " }, { "code": null, "e": 43551, "s": 43388, "text": "Just like addition, we can subtract the pixel values in two images and merge them with the help of cv2.subtract(). The images should be of equal size and depth. " }, { "code": null, "e": 43585, "s": 43551, "text": "Syntax: cv2.subtract(src1, src2)" }, { "code": null, "e": 43622, "s": 43585, "text": "Images used as Input: Input Image1: " }, { "code": null, "e": 43637, "s": 43622, "text": "Input Image2: " }, { "code": null, "e": 43657, "s": 43637, "text": "Below is the code: " }, { "code": null, "e": 43665, "s": 43657, "text": "Python3" }, { "code": "# Python program to illustrate# arithmetic operation of# subtraction of pixels of two images # organizing importsimport cv2import numpy as np # path to input images are specified and # images are loaded with imread commandimage1 = cv2.imread('input1.jpg')image2 = cv2.imread('input2.jpg') # cv2.subtract is applied over the# image inputs with applied parameterssub = cv2.subtract(image1, image2) # the window showing output image# with the subtracted imagecv2.imshow('Subtracted Image', sub) # De-allocate any associated memory usage if cv2.waitKey(0) & 0xff == 27: cv2.destroyAllWindows()", "e": 44260, "s": 43665, "text": null }, { "code": null, "e": 44269, "s": 44260, "text": "Output: " }, { "code": null, "e": 44281, "s": 44269, "text": "anikakapoor" }, { "code": null, "e": 44298, "s": 44281, "text": "Image-Processing" }, { "code": null, "e": 44305, "s": 44298, "text": "OpenCV" }, { "code": null, "e": 44312, "s": 44305, "text": "Python" }, { "code": null, "e": 44410, "s": 44312, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44438, "s": 44410, "text": "Read JSON file using Python" }, { "code": null, "e": 44488, "s": 44438, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 44510, "s": 44488, "text": "Python map() function" }, { "code": null, "e": 44554, "s": 44510, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 44589, "s": 44554, "text": "Read a file line by line in Python" }, { "code": null, "e": 44611, "s": 44589, "text": "Enumerate() in Python" }, { "code": null, "e": 44643, "s": 44611, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 44673, "s": 44643, "text": "Iterate over a list in Python" }, { "code": null, "e": 44715, "s": 44673, "text": "Different ways to create Pandas Dataframe" } ]
How to Convert images to NumPy array?
29 Aug, 2020 Images are an easier way to represent the working model. In Machine Learning, Python uses the image data in the format of Height, Width, Channel format. i.e. Images are converted into Numpy Array in Height, Width, Channel format. NumPy: By default in higher versions of Python like 3.x onwards, NumPy is available and if not available(in lower versions), one can install by using pip install numpy Pillow: This has to be explicitly installed in later versions too. It is a preferred image manipulation tool. In Python 3, Pillow python library which is nothing but the upgradation of PIL only. It can be installed using pip install Pillow One can easily check the version of installed Pillow by using the below code Python3 import PIL print('Installed Pillow Version:', PIL.__version__) Output: Installed Pillow Version: 7.2.0 Let us check for an image that is in the PNG or JPEG format. The image can be referred via its path. Image class is the heart of PIL. It has open() function which opens up an image and digital file format can be retrieved as well as pixel format. Image Used: Python3 from PIL import Image # sample.png is the name of the image# file and assuming that it is uploaded# in the current directory or we need# to give the pathimage = Image.open('Sample.png') # summarize some details about the imageprint(image.format)print(image.size)print(image.mode) Output : PNG (400, 200) RGB Python provides many modules and API’s for converting an image into a NumPy array. Let’s discuss a few of them in detail. Numpy module in itself provides various methods to do the same. These methods are – Method 1: Using asarray() function asarray() function is used to convert PIL images into NumPy arrays. This function converts the input to an array Python3 # Import the necessary librariesfrom PIL import Imagefrom numpy import asarray # load the image and convert into# numpy arrayimg = Image.open('Sample.png') # asarray() class is used to convert# PIL images into NumPy arraysnumpydata = asarray(img) # <class 'numpy.ndarray'>print(type(numpydata)) # shapeprint(numpydata.shape) Output : <class 'numpy.ndarray'> (200, 400, 3) Method 2: Using numpy.array() function By using numpy.array() function which takes an image as the argument and converts to NumPy array Python3 from PIL import Imageimport numpy img= Image.open("Sample.png")np_img = numpy.array(img) print(np_img.shape) Output : (200, 400, 3) In order to get the value of each pixel of the NumPy array image, we need to print the retrieved data that got either from asarray() function or array() function. Python3 # Import the necessary librariesfrom PIL import Imagefrom numpy import asarray # load the image and convert into # numpy arrayimg = Image.open('Sample.png')numpydata = asarray(img) # dataprint(numpydata) Output : [[[111 60 0] [116 65 0] [122 69 0] ... [ 97 47 0] [ 99 47 0] [100 49 0]] [[111 61 0] [118 65 0] [122 69 0] ... [ 97 47 0] [ 99 48 0] [100 49 0]] [[118 65 0] [122 69 0] [126 73 3] ... [ 98 48 0] [100 49 0] [100 49 0]] ... [[ 96 44 7] [ 95 43 6] [ 93 41 4] ... [225 80 3] [228 80 0] [229 78 0]] [[ 93 40 6] [ 90 37 5] [ 85 32 0] ... [226 81 4] [231 80 1] [232 79 1]] [[ 89 36 4] [ 84 31 0] [ 79 26 0] ... [228 81 4] [232 81 4] [233 80 2]]] Image.fromarray() function helps to get back the image from converted numpy array. We get back the pixels also same after converting back and forth. Hence, this is very much efficient Python3 # Import the necessary librariesfrom PIL import Imagefrom numpy import asarray # load the image and convert into # numpy arrayimg = Image.open('Sample.png')numpydata = asarray(img) print(type(numpydata)) # shapeprint(numpydata.shape) # Below is the way of creating Pillow # image from our numpyarraypilImage = Image.fromarray(numpydata)print(type(pilImage)) # Let us check image detailsprint(pilImage.mode)print(pilImage.size) Output : <class 'numpy.ndarray'> (200, 400, 3) <class 'PIL.Image.Image'> RGB (400, 200) Keras API provides the functions for loading, converting, and saving image data. Keras is possible to run on the top of the TensorFlow framework and hence that is mandatory to have. Deep learning computer vision images require Keras API. To install it type the below command in the terminal pip install keras As Keras requires TensorFlow 2.2 or higher. If not there, need to install it. To install it type the below command in the terminal. pip install tensorflow Python3 from keras.preprocessing.image import load_imgimport warnings # load the image via load_img # functionimg = load_img('sample.png') # details about the image printed belowprint(type(img)) print(img.format)print(img.mode)print(img.size) Output : <class 'PIL.PngImagePlugin.PngImageFile'> PNG RGB (400, 200) Using Keras API, convert images to Numpy Array and reverting the image from Numpy Array Python3 from keras.preprocessing.image import load_imgimport warningsfrom keras.preprocessing.image import img_to_arrayfrom keras.preprocessing.image import array_to_img # load the image via load_img functionimg = load_img('sample.png') # details about the image printed belowprint(type(img))print(img.format)print(img.mode)print(img.size) # convert the given image into numpy arrayimg_numpy_array = img_to_array(img)print("Image is converted and NumPy array information :") # <class 'numpy.ndarray'>print(type(img_numpy_array)) # type: float32print("type:", img_numpy_array.dtype) # shape: (200, 400, 3)print("shape:", img_numpy_array.shape) # convert back to imageimg_pil_from_numpy_array = array_to_img(img_numpy_array) # <class 'PIL.PngImagePlugin.PngImageFile'>print("converting NumPy array into image:", type(img_pil_from_numpy_array)) Output : <class 'PIL.PngImagePlugin.PngImageFile'> PNG RGB (400, 200) Image is converted and NumPy array information : <class 'numpy.ndarray'> type: float32 shape: (200, 400, 3) converting NumPy array into image: <class 'PIL.Image.Image'> From the above output, we can check that the source image PIL.Image.Image and destination image types are the same. OpenCV version from 3.x has DNN and Caffe frameworks, and they are very helpful to solve deep learning problems. It can be installed by using pip install opencv-contrib-python cv2 package has the following methods imread() function is used to load the image and It also reads the given image (PIL image) in the NumPy array format. Then we need to convert the image color from BGR to RGB. imwrite() is used to save the image in the file. Python3 import cv2 image = cv2.imread('Sample.png') # BGR -> RGBimg = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) cv2.imwrite('opncv_sample.png', img) print (type(img)) Output : <class 'numpy.ndarray'> Python is a very flexible tool and we have seen ways of converting images into Numpy Array and similarly back to images using different APIs. Manipulating the converted array and forming different image data and one can feed into deep learning neural networks. Image-Processing Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Aug, 2020" }, { "code": null, "e": 285, "s": 54, "text": "Images are an easier way to represent the working model. In Machine Learning, Python uses the image data in the format of Height, Width, Channel format. i.e. Images are converted into Numpy Array in Height, Width, Channel format. " }, { "code": null, "e": 436, "s": 285, "text": "NumPy: By default in higher versions of Python like 3.x onwards, NumPy is available and if not available(in lower versions), one can install by using" }, { "code": null, "e": 454, "s": 436, "text": "pip install numpy" }, { "code": null, "e": 675, "s": 454, "text": "Pillow: This has to be explicitly installed in later versions too. It is a preferred image manipulation tool. In Python 3, Pillow python library which is nothing but the upgradation of PIL only. It can be installed using" }, { "code": null, "e": 694, "s": 675, "text": "pip install Pillow" }, { "code": null, "e": 771, "s": 694, "text": "One can easily check the version of installed Pillow by using the below code" }, { "code": null, "e": 779, "s": 771, "text": "Python3" }, { "code": "import PIL print('Installed Pillow Version:', PIL.__version__)", "e": 843, "s": 779, "text": null }, { "code": null, "e": 851, "s": 843, "text": "Output:" }, { "code": null, "e": 884, "s": 851, "text": "Installed Pillow Version: 7.2.0\n" }, { "code": null, "e": 1131, "s": 884, "text": "Let us check for an image that is in the PNG or JPEG format. The image can be referred via its path. Image class is the heart of PIL. It has open() function which opens up an image and digital file format can be retrieved as well as pixel format." }, { "code": null, "e": 1143, "s": 1131, "text": "Image Used:" }, { "code": null, "e": 1151, "s": 1143, "text": "Python3" }, { "code": "from PIL import Image # sample.png is the name of the image# file and assuming that it is uploaded# in the current directory or we need# to give the pathimage = Image.open('Sample.png') # summarize some details about the imageprint(image.format)print(image.size)print(image.mode)", "e": 1435, "s": 1151, "text": null }, { "code": null, "e": 1444, "s": 1435, "text": "Output :" }, { "code": null, "e": 1463, "s": 1444, "text": "PNG\n(400, 200)\nRGB" }, { "code": null, "e": 1585, "s": 1463, "text": "Python provides many modules and API’s for converting an image into a NumPy array. Let’s discuss a few of them in detail." }, { "code": null, "e": 1670, "s": 1585, "text": "Numpy module in itself provides various methods to do the same. These methods are – " }, { "code": null, "e": 1705, "s": 1670, "text": "Method 1: Using asarray() function" }, { "code": null, "e": 1818, "s": 1705, "text": "asarray() function is used to convert PIL images into NumPy arrays. This function converts the input to an array" }, { "code": null, "e": 1826, "s": 1818, "text": "Python3" }, { "code": "# Import the necessary librariesfrom PIL import Imagefrom numpy import asarray # load the image and convert into# numpy arrayimg = Image.open('Sample.png') # asarray() class is used to convert# PIL images into NumPy arraysnumpydata = asarray(img) # <class 'numpy.ndarray'>print(type(numpydata)) # shapeprint(numpydata.shape)", "e": 2158, "s": 1826, "text": null }, { "code": null, "e": 2167, "s": 2158, "text": "Output :" }, { "code": null, "e": 2205, "s": 2167, "text": "<class 'numpy.ndarray'>\n(200, 400, 3)" }, { "code": null, "e": 2244, "s": 2205, "text": "Method 2: Using numpy.array() function" }, { "code": null, "e": 2341, "s": 2244, "text": "By using numpy.array() function which takes an image as the argument and converts to NumPy array" }, { "code": null, "e": 2349, "s": 2341, "text": "Python3" }, { "code": "from PIL import Imageimport numpy img= Image.open(\"Sample.png\")np_img = numpy.array(img) print(np_img.shape)", "e": 2462, "s": 2349, "text": null }, { "code": null, "e": 2471, "s": 2462, "text": "Output :" }, { "code": null, "e": 2485, "s": 2471, "text": "(200, 400, 3)" }, { "code": null, "e": 2648, "s": 2485, "text": "In order to get the value of each pixel of the NumPy array image, we need to print the retrieved data that got either from asarray() function or array() function." }, { "code": null, "e": 2656, "s": 2648, "text": "Python3" }, { "code": "# Import the necessary librariesfrom PIL import Imagefrom numpy import asarray # load the image and convert into # numpy arrayimg = Image.open('Sample.png')numpydata = asarray(img) # dataprint(numpydata)", "e": 2864, "s": 2656, "text": null }, { "code": null, "e": 2873, "s": 2864, "text": "Output :" }, { "code": null, "e": 3455, "s": 2873, "text": "[[[111 60 0]\n [116 65 0]\n [122 69 0]\n ...\n [ 97 47 0]\n [ 99 47 0]\n [100 49 0]]\n[[111 61 0]\n [118 65 0]\n [122 69 0]\n ...\n [ 97 47 0]\n [ 99 48 0]\n [100 49 0]]\n[[118 65 0]\n [122 69 0]\n [126 73 3]\n ...\n [ 98 48 0]\n [100 49 0]\n [100 49 0]]\n...\n[[ 96 44 7]\n [ 95 43 6]\n [ 93 41 4]\n ...\n [225 80 3]\n [228 80 0]\n [229 78 0]]\n[[ 93 40 6]\n [ 90 37 5]\n [ 85 32 0]\n ...\n [226 81 4]\n [231 80 1]\n [232 79 1]]\n[[ 89 36 4]\n [ 84 31 0]\n [ 79 26 0]\n ...\n [228 81 4]\n [232 81 4]\n [233 80 2]]]" }, { "code": null, "e": 3639, "s": 3455, "text": "Image.fromarray() function helps to get back the image from converted numpy array. We get back the pixels also same after converting back and forth. Hence, this is very much efficient" }, { "code": null, "e": 3647, "s": 3639, "text": "Python3" }, { "code": "# Import the necessary librariesfrom PIL import Imagefrom numpy import asarray # load the image and convert into # numpy arrayimg = Image.open('Sample.png')numpydata = asarray(img) print(type(numpydata)) # shapeprint(numpydata.shape) # Below is the way of creating Pillow # image from our numpyarraypilImage = Image.fromarray(numpydata)print(type(pilImage)) # Let us check image detailsprint(pilImage.mode)print(pilImage.size)", "e": 4083, "s": 3647, "text": null }, { "code": null, "e": 4092, "s": 4083, "text": "Output :" }, { "code": null, "e": 4171, "s": 4092, "text": "<class 'numpy.ndarray'>\n(200, 400, 3)\n<class 'PIL.Image.Image'>\nRGB\n(400, 200)" }, { "code": null, "e": 4463, "s": 4171, "text": "Keras API provides the functions for loading, converting, and saving image data. Keras is possible to run on the top of the TensorFlow framework and hence that is mandatory to have. Deep learning computer vision images require Keras API. To install it type the below command in the terminal " }, { "code": null, "e": 4481, "s": 4463, "text": "pip install keras" }, { "code": null, "e": 4613, "s": 4481, "text": "As Keras requires TensorFlow 2.2 or higher. If not there, need to install it. To install it type the below command in the terminal." }, { "code": null, "e": 4636, "s": 4613, "text": "pip install tensorflow" }, { "code": null, "e": 4644, "s": 4636, "text": "Python3" }, { "code": "from keras.preprocessing.image import load_imgimport warnings # load the image via load_img # functionimg = load_img('sample.png') # details about the image printed belowprint(type(img)) print(img.format)print(img.mode)print(img.size)", "e": 4881, "s": 4644, "text": null }, { "code": null, "e": 4890, "s": 4881, "text": "Output :" }, { "code": null, "e": 4951, "s": 4890, "text": "<class 'PIL.PngImagePlugin.PngImageFile'>\nPNG\nRGB\n(400, 200)" }, { "code": null, "e": 5039, "s": 4951, "text": "Using Keras API, convert images to Numpy Array and reverting the image from Numpy Array" }, { "code": null, "e": 5047, "s": 5039, "text": "Python3" }, { "code": "from keras.preprocessing.image import load_imgimport warningsfrom keras.preprocessing.image import img_to_arrayfrom keras.preprocessing.image import array_to_img # load the image via load_img functionimg = load_img('sample.png') # details about the image printed belowprint(type(img))print(img.format)print(img.mode)print(img.size) # convert the given image into numpy arrayimg_numpy_array = img_to_array(img)print(\"Image is converted and NumPy array information :\") # <class 'numpy.ndarray'>print(type(img_numpy_array)) # type: float32print(\"type:\", img_numpy_array.dtype) # shape: (200, 400, 3)print(\"shape:\", img_numpy_array.shape) # convert back to imageimg_pil_from_numpy_array = array_to_img(img_numpy_array) # <class 'PIL.PngImagePlugin.PngImageFile'>print(\"converting NumPy array into image:\", type(img_pil_from_numpy_array))", "e": 5897, "s": 5047, "text": null }, { "code": null, "e": 5906, "s": 5897, "text": "Output :" }, { "code": null, "e": 6136, "s": 5906, "text": "<class 'PIL.PngImagePlugin.PngImageFile'>\nPNG\nRGB\n(400, 200)\nImage is converted and NumPy array information :\n<class 'numpy.ndarray'>\ntype: float32\nshape: (200, 400, 3)\nconverting NumPy array into image: <class 'PIL.Image.Image'>" }, { "code": null, "e": 6252, "s": 6136, "text": "From the above output, we can check that the source image PIL.Image.Image and destination image types are the same." }, { "code": null, "e": 6394, "s": 6252, "text": "OpenCV version from 3.x has DNN and Caffe frameworks, and they are very helpful to solve deep learning problems. It can be installed by using" }, { "code": null, "e": 6428, "s": 6394, "text": "pip install opencv-contrib-python" }, { "code": null, "e": 6466, "s": 6428, "text": "cv2 package has the following methods" }, { "code": null, "e": 6584, "s": 6466, "text": "imread() function is used to load the image and It also reads the given image (PIL image) in the NumPy array format. " }, { "code": null, "e": 6642, "s": 6584, "text": "Then we need to convert the image color from BGR to RGB. " }, { "code": null, "e": 6691, "s": 6642, "text": "imwrite() is used to save the image in the file." }, { "code": null, "e": 6699, "s": 6691, "text": "Python3" }, { "code": "import cv2 image = cv2.imread('Sample.png') # BGR -> RGBimg = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) cv2.imwrite('opncv_sample.png', img) print (type(img))", "e": 6858, "s": 6699, "text": null }, { "code": null, "e": 6867, "s": 6858, "text": "Output :" }, { "code": null, "e": 6891, "s": 6867, "text": "<class 'numpy.ndarray'>" }, { "code": null, "e": 7152, "s": 6891, "text": "Python is a very flexible tool and we have seen ways of converting images into Numpy Array and similarly back to images using different APIs. Manipulating the converted array and forming different image data and one can feed into deep learning neural networks." }, { "code": null, "e": 7169, "s": 7152, "text": "Image-Processing" }, { "code": null, "e": 7182, "s": 7169, "text": "Python-numpy" }, { "code": null, "e": 7189, "s": 7182, "text": "Python" } ]
Puzzle 14 | (Strategy for a 2 Player Coin Game)
30 May, 2022 Puzzle: Consider a two-player coin game where each Player A and Player B gets the turn one by one. There is a row of even number of coins, and a player on his/her turn can pick a coin from any of the two corners of the row. The player that collects coins with more value wins the game. Develop a strategy for the player making the first turn i.e, Player A, such that he/she never loses the game. Note that the strategy to pick a maximum of two corners may not work. In the following example, the first player, Player A loses the game when he/she uses a strategy to pick a maximum of two corners. Example: Initial row: 18 20 15 30 10 14 Player A picks 18, now row of coins is After first pick: 20 15 30 10 14 Player B picks 20, now row of coins is After second pick: 15 30 10 14 Player A picks 15, now row of coins is After third pick: 30 10 14 Player B picks 30, now row of coins is After 4th pick: 10 14 Player A picks 14, now row of coins is Last pick: 10 Player B picks 10, game over. The total value collected by Player B is more (20 + 30 + 10) compared to first player (18 + 15 + 14). So the second picker, Player B wins. Solution: The idea is to count the sum of values of all even coins and odd coins, compare the two values. The player that makes the first move can always make sure that the other player is never able to choose an even coin if the sum of even coins is higher. Similarly, he/she can make sure that the other player is never able to choose an odd coin if the sum of odd coins is higher. So here are the steps to a proper algorithm of either winning the game or getting a tie: Step 1: Count the sum of all the coins in the even places(2nd, 4th, 6th and so on). Let the sum be “EVEN”. Step 2: Count the sum of all the coins in the odd places(1st, 3rd, 5th and so on). Let the sum be “ODD”. Step 3: Compare the value of EVEN and ODD and this is how the first player, here Player A must begin its selection.if (EVEN > ODD), start choosing from the right-hand corner and select all the even placed coins.if (EVEN < ODD), start choosing from the left-hand corner and select all the odd placed coins.if (EVEN == ODD), choosing only the odd-placed or only the even placed coins will throw a tie. if (EVEN > ODD), start choosing from the right-hand corner and select all the even placed coins.if (EVEN < ODD), start choosing from the left-hand corner and select all the odd placed coins.if (EVEN == ODD), choosing only the odd-placed or only the even placed coins will throw a tie. if (EVEN > ODD), start choosing from the right-hand corner and select all the even placed coins. if (EVEN < ODD), start choosing from the left-hand corner and select all the odd placed coins. if (EVEN == ODD), choosing only the odd-placed or only the even placed coins will throw a tie. Example: Suppose you are given the following rows of coins: 18 20 15 30 10 14 Coins at even places: 20, 30, 14 Coins at odd places: 18, 15, 10 These places are fixed independent of whether the choice of selection must begin from the left or the right-hand side. Step 1: Sum of all even placed coins = 20 + 30 + 14 = 64 Step 2: Sum of all odd placed coins = 18 + 15 + 10 = 43 Step 3: Comparing the even and the odd placed coins where EVEN > ODD Therefore, Player A must start selecting from the right-hand side and choose all the even-placed coins every time(here they are 14, 30 and 20). So first picker, Player A picks 14. Now, irrespective of whether the second Player B starts selecting from the left-hand side i.e., 18 or from the right-hand side i.e., 10, the even placed coins i.e., 14, 30 and 20 are booked for the Player A. Therefore, be it any situation that arises, the first picker Player A will always win the game. Illustration: Here are the illustrations to both the cases of pick by Player B: Case 1: When Player B starts picking from the left corner. Case 2: When Player B starts picking from the right corner after Player A. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Chinmoy Lenka prachishriddha Puzzles Puzzles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Top 20 Puzzles Commonly Asked During SDE Interviews Puzzle 21 | (3 Ants and Triangle) Puzzle 24 | (10 Coins Puzzle) Container with Most Water Puzzle | Set 35 (2 Eggs and 100 Floors) Puzzle 27 | (Hourglasses Puzzle) Puzzle | Mislabeled Jars Puzzle 31 | (Minimum cut Puzzle) Puzzle | 3 cuts to cut round cake into 8 equal pieces
[ { "code": null, "e": 54, "s": 26, "text": "\n30 May, 2022" }, { "code": null, "e": 652, "s": 54, "text": "Puzzle: Consider a two-player coin game where each Player A and Player B gets the turn one by one. There is a row of even number of coins, and a player on his/her turn can pick a coin from any of the two corners of the row. The player that collects coins with more value wins the game. Develop a strategy for the player making the first turn i.e, Player A, such that he/she never loses the game. Note that the strategy to pick a maximum of two corners may not work. In the following example, the first player, Player A loses the game when he/she uses a strategy to pick a maximum of two corners. " }, { "code": null, "e": 662, "s": 652, "text": " Example:" }, { "code": null, "e": 1199, "s": 662, "text": "Initial row: 18 20 15 30 10 14\nPlayer A picks 18, now row of coins is\n\nAfter first pick: 20 15 30 10 14\nPlayer B picks 20, now row of coins is\n\nAfter second pick: 15 30 10 14\nPlayer A picks 15, now row of coins is\n\nAfter third pick: 30 10 14\nPlayer B picks 30, now row of coins is\n\nAfter 4th pick: 10 14\nPlayer A picks 14, now row of coins is\n\nLast pick: 10 \nPlayer B picks 10, game over.\n\nThe total value collected by Player B is more (20 + \n30 + 10) compared to first player (18 + 15 + 14).\nSo the second picker, Player B wins. " }, { "code": null, "e": 1672, "s": 1199, "text": "Solution: The idea is to count the sum of values of all even coins and odd coins, compare the two values. The player that makes the first move can always make sure that the other player is never able to choose an even coin if the sum of even coins is higher. Similarly, he/she can make sure that the other player is never able to choose an odd coin if the sum of odd coins is higher. So here are the steps to a proper algorithm of either winning the game or getting a tie:" }, { "code": null, "e": 1779, "s": 1672, "text": "Step 1: Count the sum of all the coins in the even places(2nd, 4th, 6th and so on). Let the sum be “EVEN”." }, { "code": null, "e": 1884, "s": 1779, "text": "Step 2: Count the sum of all the coins in the odd places(1st, 3rd, 5th and so on). Let the sum be “ODD”." }, { "code": null, "e": 2284, "s": 1884, "text": "Step 3: Compare the value of EVEN and ODD and this is how the first player, here Player A must begin its selection.if (EVEN > ODD), start choosing from the right-hand corner and select all the even placed coins.if (EVEN < ODD), start choosing from the left-hand corner and select all the odd placed coins.if (EVEN == ODD), choosing only the odd-placed or only the even placed coins will throw a tie." }, { "code": null, "e": 2569, "s": 2284, "text": "if (EVEN > ODD), start choosing from the right-hand corner and select all the even placed coins.if (EVEN < ODD), start choosing from the left-hand corner and select all the odd placed coins.if (EVEN == ODD), choosing only the odd-placed or only the even placed coins will throw a tie." }, { "code": null, "e": 2666, "s": 2569, "text": "if (EVEN > ODD), start choosing from the right-hand corner and select all the even placed coins." }, { "code": null, "e": 2761, "s": 2666, "text": "if (EVEN < ODD), start choosing from the left-hand corner and select all the odd placed coins." }, { "code": null, "e": 2856, "s": 2761, "text": "if (EVEN == ODD), choosing only the odd-placed or only the even placed coins will throw a tie." }, { "code": null, "e": 2916, "s": 2856, "text": "Example: Suppose you are given the following rows of coins:" }, { "code": null, "e": 2934, "s": 2916, "text": "18 20 15 30 10 14" }, { "code": null, "e": 3119, "s": 2934, "text": "Coins at even places: 20, 30, 14 Coins at odd places: 18, 15, 10 These places are fixed independent of whether the choice of selection must begin from the left or the right-hand side. " }, { "code": null, "e": 3177, "s": 3119, "text": "Step 1: Sum of all even placed coins = 20 + 30 + 14 = 64 " }, { "code": null, "e": 3234, "s": 3177, "text": "Step 2: Sum of all odd placed coins = 18 + 15 + 10 = 43 " }, { "code": null, "e": 3788, "s": 3234, "text": "Step 3: Comparing the even and the odd placed coins where EVEN > ODD Therefore, Player A must start selecting from the right-hand side and choose all the even-placed coins every time(here they are 14, 30 and 20). So first picker, Player A picks 14. Now, irrespective of whether the second Player B starts selecting from the left-hand side i.e., 18 or from the right-hand side i.e., 10, the even placed coins i.e., 14, 30 and 20 are booked for the Player A. Therefore, be it any situation that arises, the first picker Player A will always win the game. " }, { "code": null, "e": 3869, "s": 3788, "text": "Illustration: Here are the illustrations to both the cases of pick by Player B: " }, { "code": null, "e": 4130, "s": 3869, "text": "Case 1: When Player B starts picking from the left corner. Case 2: When Player B starts picking from the right corner after Player A. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4144, "s": 4130, "text": "Chinmoy Lenka" }, { "code": null, "e": 4159, "s": 4144, "text": "prachishriddha" }, { "code": null, "e": 4167, "s": 4159, "text": "Puzzles" }, { "code": null, "e": 4175, "s": 4167, "text": "Puzzles" }, { "code": null, "e": 4273, "s": 4175, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4305, "s": 4273, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 4357, "s": 4305, "text": "Top 20 Puzzles Commonly Asked During SDE Interviews" }, { "code": null, "e": 4391, "s": 4357, "text": "Puzzle 21 | (3 Ants and Triangle)" }, { "code": null, "e": 4421, "s": 4391, "text": "Puzzle 24 | (10 Coins Puzzle)" }, { "code": null, "e": 4447, "s": 4421, "text": "Container with Most Water" }, { "code": null, "e": 4487, "s": 4447, "text": "Puzzle | Set 35 (2 Eggs and 100 Floors)" }, { "code": null, "e": 4520, "s": 4487, "text": "Puzzle 27 | (Hourglasses Puzzle)" }, { "code": null, "e": 4545, "s": 4520, "text": "Puzzle | Mislabeled Jars" }, { "code": null, "e": 4578, "s": 4545, "text": "Puzzle 31 | (Minimum cut Puzzle)" } ]
Management Information System (MIS)
10 Jul, 2022 Management Information System (MIS) is one of the five major Computer Based Information Systems (CBIS). Its purpose is to meet the general information needs of the managers in firm or organization. MIS is a computer based system that makes information available to users with similar needs. Management Information System (MIS) consists of following three pillars: Management, Information, and System. These are explained as following below. Management: art of getting things done through and with the people of in formally organized groups. Managerial functions: Management: art of getting things done through and with the people of in formally organized groups. Managerial functions: (i) Planning (ii) Organizing (iii) Staffing (iv) Directing (v) Controlling Information: data that have a meaning with a context ,where data is raw facts about an entity (entity is the object of interest).System: set of inter-related components with a clearly defined boundary working together to achieve a common goal. Information: data that have a meaning with a context ,where data is raw facts about an entity (entity is the object of interest). System: set of inter-related components with a clearly defined boundary working together to achieve a common goal. Why one should study MIS: It may be a student aspiring to become a manager in some organisation, an entrepreneur or a professional. Information system and information technology is a vital component of any successful business and is regarded as a major functional area like any other functional area of a business organization like marketing, finance, production, human resources (HR) etc. Information systems play following 3 vital roles for a business organisation: Supports the business processes and operations of an organisation.Support of decision making by employees and managers of an organisation.Support the strategies of an organisation for competitive advantage. Supports the business processes and operations of an organisation. Support of decision making by employees and managers of an organisation. Support the strategies of an organisation for competitive advantage. Advantages of MIS: Improves quality of an organization or an information content by providing relevant information for sound decision making. MIS change large amount of data into summarize form and thereby avoid confusion which may an answer when an information officer are flooded with detailed fact. MIS facilitates integration of specialized activities by keeping each department aware of problem and requirements of other departments. MIS serves as a link between managerial planning and control. It improves the ability of management to evaluate and improve performance. Disadvantages: Too rigid and difficult to adapt. Resistance in sharing internal information between departments can reduce the effectiveness. Hard to quantify benefit to justify implementation of MIS. Quality of output of an MIS is directly proportional to quality of input and processes. Major System in an Organizational Systems: Organizational information system are logical rather than physical way of thinking about MIS. The following are the management levels: 1. Strategic Planning Level: Plan 2. Management Control Level: Organize 3. Operational Control Level: Direct Operational control level includes: Marketing: It is the area in which considerable effort as spent in describing how the computer could be applied to the entire range of marketing operations.Finance: It does not embrace title of financial information system although computer based information system in that area are common.For ex-payroll,taxation.Human Resource: It represents area where most current attention is being focused. Terms Human Resource Information System (HRIS), and Human Resource Management System (HRMS) are common.Manufacturing: It describes how the computer could be applied to the entire range of information collection.Information Resource: It also embraced computer processing and applied the technology as both conceptual information system and physical manufacturing system. For example: quality control, cost control. Marketing: It is the area in which considerable effort as spent in describing how the computer could be applied to the entire range of marketing operations. Finance: It does not embrace title of financial information system although computer based information system in that area are common.For ex-payroll,taxation. Human Resource: It represents area where most current attention is being focused. Terms Human Resource Information System (HRIS), and Human Resource Management System (HRMS) are common. Manufacturing: It describes how the computer could be applied to the entire range of information collection. Information Resource: It also embraced computer processing and applied the technology as both conceptual information system and physical manufacturing system. For example: quality control, cost control. tampurus Information-Security Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Virtualization In Cloud Computing and Types How to write Regular Expressions? Association Rule OOPs | Object Oriented Design Java Math min() method with Examples std::unique in C++ Find maximum (or minimum) sum of a subarray of size k Software Engineering | Prototyping Model Distributed Database System
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Jul, 2022" }, { "code": null, "e": 495, "s": 54, "text": "Management Information System (MIS) is one of the five major Computer Based Information Systems (CBIS). Its purpose is to meet the general information needs of the managers in firm or organization. MIS is a computer based system that makes information available to users with similar needs. Management Information System (MIS) consists of following three pillars: Management, Information, and System. These are explained as following below." }, { "code": null, "e": 617, "s": 495, "text": "Management: art of getting things done through and with the people of in formally organized groups. Managerial functions:" }, { "code": null, "e": 739, "s": 617, "text": "Management: art of getting things done through and with the people of in formally organized groups. Managerial functions:" }, { "code": null, "e": 815, "s": 739, "text": "(i) Planning\n(ii) Organizing\n(iii) Staffing\n(iv) Directing\n(v) Controlling " }, { "code": null, "e": 1059, "s": 815, "text": "Information: data that have a meaning with a context ,where data is raw facts about an entity (entity is the object of interest).System: set of inter-related components with a clearly defined boundary working together to achieve a common goal." }, { "code": null, "e": 1189, "s": 1059, "text": "Information: data that have a meaning with a context ,where data is raw facts about an entity (entity is the object of interest)." }, { "code": null, "e": 1304, "s": 1189, "text": "System: set of inter-related components with a clearly defined boundary working together to achieve a common goal." }, { "code": null, "e": 1772, "s": 1304, "text": "Why one should study MIS: It may be a student aspiring to become a manager in some organisation, an entrepreneur or a professional. Information system and information technology is a vital component of any successful business and is regarded as a major functional area like any other functional area of a business organization like marketing, finance, production, human resources (HR) etc. Information systems play following 3 vital roles for a business organisation:" }, { "code": null, "e": 1979, "s": 1772, "text": "Supports the business processes and operations of an organisation.Support of decision making by employees and managers of an organisation.Support the strategies of an organisation for competitive advantage." }, { "code": null, "e": 2046, "s": 1979, "text": "Supports the business processes and operations of an organisation." }, { "code": null, "e": 2119, "s": 2046, "text": "Support of decision making by employees and managers of an organisation." }, { "code": null, "e": 2188, "s": 2119, "text": "Support the strategies of an organisation for competitive advantage." }, { "code": null, "e": 2207, "s": 2188, "text": "Advantages of MIS:" }, { "code": null, "e": 2330, "s": 2207, "text": "Improves quality of an organization or an information content by providing relevant information for sound decision making." }, { "code": null, "e": 2490, "s": 2330, "text": "MIS change large amount of data into summarize form and thereby avoid confusion which may an answer when an information officer are flooded with detailed fact." }, { "code": null, "e": 2627, "s": 2490, "text": "MIS facilitates integration of specialized activities by keeping each department aware of problem and requirements of other departments." }, { "code": null, "e": 2764, "s": 2627, "text": "MIS serves as a link between managerial planning and control. It improves the ability of management to evaluate and improve performance." }, { "code": null, "e": 2779, "s": 2764, "text": "Disadvantages:" }, { "code": null, "e": 2813, "s": 2779, "text": "Too rigid and difficult to adapt." }, { "code": null, "e": 2906, "s": 2813, "text": "Resistance in sharing internal information between departments can reduce the effectiveness." }, { "code": null, "e": 2965, "s": 2906, "text": "Hard to quantify benefit to justify implementation of MIS." }, { "code": null, "e": 3053, "s": 2965, "text": "Quality of output of an MIS is directly proportional to quality of input and processes." }, { "code": null, "e": 3231, "s": 3053, "text": "Major System in an Organizational Systems: Organizational information system are logical rather than physical way of thinking about MIS. The following are the management levels:" }, { "code": null, "e": 3341, "s": 3231, "text": "1. Strategic Planning Level: Plan\n2. Management Control Level: Organize\n3. Operational Control Level: Direct " }, { "code": null, "e": 3377, "s": 3341, "text": "Operational control level includes:" }, { "code": null, "e": 4187, "s": 3377, "text": "Marketing: It is the area in which considerable effort as spent in describing how the computer could be applied to the entire range of marketing operations.Finance: It does not embrace title of financial information system although computer based information system in that area are common.For ex-payroll,taxation.Human Resource: It represents area where most current attention is being focused. Terms Human Resource Information System (HRIS), and Human Resource Management System (HRMS) are common.Manufacturing: It describes how the computer could be applied to the entire range of information collection.Information Resource: It also embraced computer processing and applied the technology as both conceptual information system and physical manufacturing system. For example: quality control, cost control." }, { "code": null, "e": 4344, "s": 4187, "text": "Marketing: It is the area in which considerable effort as spent in describing how the computer could be applied to the entire range of marketing operations." }, { "code": null, "e": 4503, "s": 4344, "text": "Finance: It does not embrace title of financial information system although computer based information system in that area are common.For ex-payroll,taxation." }, { "code": null, "e": 4689, "s": 4503, "text": "Human Resource: It represents area where most current attention is being focused. Terms Human Resource Information System (HRIS), and Human Resource Management System (HRMS) are common." }, { "code": null, "e": 4798, "s": 4689, "text": "Manufacturing: It describes how the computer could be applied to the entire range of information collection." }, { "code": null, "e": 5001, "s": 4798, "text": "Information Resource: It also embraced computer processing and applied the technology as both conceptual information system and physical manufacturing system. For example: quality control, cost control." }, { "code": null, "e": 5013, "s": 5004, "text": "tampurus" }, { "code": null, "e": 5034, "s": 5013, "text": "Information-Security" }, { "code": null, "e": 5039, "s": 5034, "text": "Misc" }, { "code": null, "e": 5044, "s": 5039, "text": "Misc" }, { "code": null, "e": 5049, "s": 5044, "text": "Misc" }, { "code": null, "e": 5147, "s": 5049, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5191, "s": 5147, "text": "Virtualization In Cloud Computing and Types" }, { "code": null, "e": 5225, "s": 5191, "text": "How to write Regular Expressions?" }, { "code": null, "e": 5242, "s": 5225, "text": "Association Rule" }, { "code": null, "e": 5272, "s": 5242, "text": "OOPs | Object Oriented Design" }, { "code": null, "e": 5309, "s": 5272, "text": "Java Math min() method with Examples" }, { "code": null, "e": 5328, "s": 5309, "text": "std::unique in C++" }, { "code": null, "e": 5382, "s": 5328, "text": "Find maximum (or minimum) sum of a subarray of size k" }, { "code": null, "e": 5423, "s": 5382, "text": "Software Engineering | Prototyping Model" } ]
How to create paper corner fold effect on hover by using HTML and CSS?
30 Jun, 2021 The folding effect is quite attractive on the website, may you have seen on some websites when you hover on the paging layout it gets folded on the corner. The folding corner effect can be achieved by using HTML and CSS only. The below sections will guide you on how to create the animation. In this article, we will divide the article into two sections in the first section we will create the basic structure. In the second section, we will decorate the structure. Creating Structure: In this section, we will use only HTML to create the structure where we will use the corner folding effect. HTML Code: In this section we will create a basic div using the div tag giving it a class name. HTML <!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title> Paper corner fold effect on hover by using HTML and CSS </title></head> <body> <center> <h1> GeeksforGeeks </h1> <b> Paper corner fold effect on hover by using HTML and CSS </b> <div class="Fold"> <h3> A Computer Science Portal for Geeks</h3> </div> </center></body> </html> Design Structure: In this section, we will use only CSS to decorate the structure which is already created in the above section. CSS Code: In this section, we will first style the basic div element without the fold effect, then to create the fold effect we will use the CSS ::after pseudo-element. that will be positioned on the top right corner of the div box, the top and right border are set to colours that match the background color of parent div element.The left and bottom border are then given a darker shade of the div background color, we will also use the hover selector to create the folding effect when we hover the mouse over the box. CSS <style> h1 { color: green; } .Fold { position: absolute; left: 50%; top: 55%; transform: translate(-50%, -50%); width: 400px; height: 200px; background-color: #4EE73C; } h3 { margin: 20px; padding: 20px; } .Fold:after { position: absolute; content: ''; right: 0; top: 0; } .Fold:hover:after { transition-duration: 1s; border-bottom: 50px solid black; border-right: 50px solid white; }</style> Final Solution: It is the combination of the above two coding sections, y combining the above section we have created a folded corner effect on hover. HTML <!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title> Paper corner fold effect on hover by using HTML and CSS </title> <style> h1 { color: green; } .Fold { position: absolute; left: 50%; top: 55%; transform: translate(-50%, -50%); width: 400px; height: 200px; background-color: #4EE73C; } h3 { margin: 20px; padding: 20px; } .Fold:after { position: absolute; content: ''; right: 0; top: 0; } .Fold:hover:after { transition-duration: 1s; border-bottom: 50px solid black; border-right: 50px solid white; } </style></head> <body> <center> <h1> GeeksforGeeks </h1> <b> Paper corner fold effect on hover by using HTML and CSS </b> <div class="Fold"> <h3> A Computer Science Portal for Geeks</h3> </div> </center></body> </html> Output: simranarora5sos CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Form validation using jQuery REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2021" }, { "code": null, "e": 624, "s": 28, "text": "The folding effect is quite attractive on the website, may you have seen on some websites when you hover on the paging layout it gets folded on the corner. The folding corner effect can be achieved by using HTML and CSS only. The below sections will guide you on how to create the animation. In this article, we will divide the article into two sections in the first section we will create the basic structure. In the second section, we will decorate the structure. Creating Structure: In this section, we will use only HTML to create the structure where we will use the corner folding effect. " }, { "code": null, "e": 720, "s": 624, "text": "HTML Code: In this section we will create a basic div using the div tag giving it a class name." }, { "code": null, "e": 728, "s": 723, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\" dir=\"ltr\"> <head> <meta charset=\"utf-8\"> <title> Paper corner fold effect on hover by using HTML and CSS </title></head> <body> <center> <h1> GeeksforGeeks </h1> <b> Paper corner fold effect on hover by using HTML and CSS </b> <div class=\"Fold\"> <h3> A Computer Science Portal for Geeks</h3> </div> </center></body> </html> ", "e": 1228, "s": 728, "text": null }, { "code": null, "e": 1358, "s": 1228, "text": "Design Structure: In this section, we will use only CSS to decorate the structure which is already created in the above section. " }, { "code": null, "e": 1880, "s": 1358, "text": "CSS Code: In this section, we will first style the basic div element without the fold effect, then to create the fold effect we will use the CSS ::after pseudo-element. that will be positioned on the top right corner of the div box, the top and right border are set to colours that match the background color of parent div element.The left and bottom border are then given a darker shade of the div background color, we will also use the hover selector to create the folding effect when we hover the mouse over the box. " }, { "code": null, "e": 1884, "s": 1880, "text": "CSS" }, { "code": "<style> h1 { color: green; } .Fold { position: absolute; left: 50%; top: 55%; transform: translate(-50%, -50%); width: 400px; height: 200px; background-color: #4EE73C; } h3 { margin: 20px; padding: 20px; } .Fold:after { position: absolute; content: ''; right: 0; top: 0; } .Fold:hover:after { transition-duration: 1s; border-bottom: 50px solid black; border-right: 50px solid white; }</style>", "e": 2570, "s": 1884, "text": null }, { "code": null, "e": 2723, "s": 2570, "text": "Final Solution: It is the combination of the above two coding sections, y combining the above section we have created a folded corner effect on hover. " }, { "code": null, "e": 2728, "s": 2723, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\" dir=\"ltr\"> <head> <meta charset=\"utf-8\"> <title> Paper corner fold effect on hover by using HTML and CSS </title> <style> h1 { color: green; } .Fold { position: absolute; left: 50%; top: 55%; transform: translate(-50%, -50%); width: 400px; height: 200px; background-color: #4EE73C; } h3 { margin: 20px; padding: 20px; } .Fold:after { position: absolute; content: ''; right: 0; top: 0; } .Fold:hover:after { transition-duration: 1s; border-bottom: 50px solid black; border-right: 50px solid white; } </style></head> <body> <center> <h1> GeeksforGeeks </h1> <b> Paper corner fold effect on hover by using HTML and CSS </b> <div class=\"Fold\"> <h3> A Computer Science Portal for Geeks</h3> </div> </center></body> </html>", "e": 3902, "s": 2728, "text": null }, { "code": null, "e": 3912, "s": 3902, "text": "Output: " }, { "code": null, "e": 3930, "s": 3914, "text": "simranarora5sos" }, { "code": null, "e": 3939, "s": 3930, "text": "CSS-Misc" }, { "code": null, "e": 3949, "s": 3939, "text": "HTML-Misc" }, { "code": null, "e": 3953, "s": 3949, "text": "CSS" }, { "code": null, "e": 3958, "s": 3953, "text": "HTML" }, { "code": null, "e": 3975, "s": 3958, "text": "Web Technologies" }, { "code": null, "e": 4002, "s": 3975, "text": "Web technologies Questions" }, { "code": null, "e": 4007, "s": 4002, "text": "HTML" }, { "code": null, "e": 4105, "s": 4007, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4144, "s": 4105, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 4183, "s": 4144, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 4222, "s": 4183, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 4259, "s": 4222, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 4288, "s": 4259, "text": "Form validation using jQuery" }, { "code": null, "e": 4312, "s": 4288, "text": "REST API (Introduction)" }, { "code": null, "e": 4365, "s": 4312, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 4425, "s": 4365, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 4486, "s": 4425, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Python nonlocal Keyword
02 May, 2022 Python nonlocal keyword is used to reference a variable in the nearest scope. The nonlocal keyword won’t work on local or global variables and therefore must be used to reference variables in another scopes except the global and local one. The nonlocal keyword is used in nested functions to reference a variable in the parent function. It helps in accessing the variable in the upper scope. Since the referenced variable is reused, the memory address of the variable is also reused and therefore it saves memory. The nonlocal keyword can’t be used to reference global or local variables. The nonlocal keyword can only be used inside nested structures. Example 1: In this example, we demonstrate the working of the nonlocal keyword. Python3 def foo(): name = "geek" # Our local variable def bar(): nonlocal name # Reference name in the upper scope name = 'GeekForGeeks' # Overwrite this variable print(name) # Calling inner function bar() # Printing local variable print(name) foo() GeekForGeeks GeekForGeeks Example 2: In this example, we see what happens when we make a nonlocal variable to refer to the global variable. Python3 # Declaring a global variableglobal_name = 'geekforgeeks' def foo(): # Defining inner function def bar(): # Declaring nonlocal variable nonlocal global_name # Try to reference global variable global_name = 'GeekForGeeks'# Try to overwrite it print(global_name) # Calling inner function bar() foo() Output: SyntaxError: no binding for nonlocal 'name' found Example 3: In this example, we will see which variable nonlocal refers to when we have multiple nested functions with variables of the same name. Python3 def foo(): # Local variable of foo() name = "geek" # First inner function def bar(): name = "Geek" # Second inner function def ack(): nonlocal name # Reference to the next upper variable with this name print(name) # Print the value of the referenced variable name = 'GEEK' # Overwrite the referenced variable print(name) ack() # Calling second inner function bar() # Calling first inner function print(name) # Printing local variable of bar() foo() Geek GEEK geek Example 4: In this example we will build a reuseable counter (Just for demonstration purpose) Python3 # Our counter functiondef counter(): c = 0 # Local counter variable # This function manipulate the local c variable, when called def count(): nonlocal c c += 1 return c # Return the count() function to manipulate the local c variable on every call return count # Assign the result of counter() to a variable which we use to count upmy_counter = counter()for i in range(3): print(my_counter())print('End of my_counter') # Create a new counternew_counter = counter()for i in range(3): print(new_counter())print('End of new_counter') 1 2 3 End of my_counter 1 2 3 End of new_counter Note: Notice how the local c variable keeps alive on every call of our counter variables. clintra adnanirshad158 ghostixmusic sweetyty Blogathon-2021 Picked python-basics Blogathon Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 May, 2022" }, { "code": null, "e": 366, "s": 28, "text": "Python nonlocal keyword is used to reference a variable in the nearest scope. The nonlocal keyword won’t work on local or global variables and therefore must be used to reference variables in another scopes except the global and local one. The nonlocal keyword is used in nested functions to reference a variable in the parent function. " }, { "code": null, "e": 421, "s": 366, "text": "It helps in accessing the variable in the upper scope." }, { "code": null, "e": 543, "s": 421, "text": "Since the referenced variable is reused, the memory address of the variable is also reused and therefore it saves memory." }, { "code": null, "e": 618, "s": 543, "text": "The nonlocal keyword can’t be used to reference global or local variables." }, { "code": null, "e": 682, "s": 618, "text": "The nonlocal keyword can only be used inside nested structures." }, { "code": null, "e": 762, "s": 682, "text": "Example 1: In this example, we demonstrate the working of the nonlocal keyword." }, { "code": null, "e": 770, "s": 762, "text": "Python3" }, { "code": "def foo(): name = \"geek\" # Our local variable def bar(): nonlocal name # Reference name in the upper scope name = 'GeekForGeeks' # Overwrite this variable print(name) # Calling inner function bar() # Printing local variable print(name) foo()", "e": 1075, "s": 770, "text": null }, { "code": null, "e": 1101, "s": 1075, "text": "GeekForGeeks\nGeekForGeeks" }, { "code": null, "e": 1215, "s": 1101, "text": "Example 2: In this example, we see what happens when we make a nonlocal variable to refer to the global variable." }, { "code": null, "e": 1223, "s": 1215, "text": "Python3" }, { "code": "# Declaring a global variableglobal_name = 'geekforgeeks' def foo(): # Defining inner function def bar(): # Declaring nonlocal variable nonlocal global_name # Try to reference global variable global_name = 'GeekForGeeks'# Try to overwrite it print(global_name) # Calling inner function bar() foo()", "e": 1592, "s": 1223, "text": null }, { "code": null, "e": 1600, "s": 1592, "text": "Output:" }, { "code": null, "e": 1650, "s": 1600, "text": "SyntaxError: no binding for nonlocal 'name' found" }, { "code": null, "e": 1796, "s": 1650, "text": "Example 3: In this example, we will see which variable nonlocal refers to when we have multiple nested functions with variables of the same name." }, { "code": null, "e": 1804, "s": 1796, "text": "Python3" }, { "code": "def foo(): # Local variable of foo() name = \"geek\" # First inner function def bar(): name = \"Geek\" # Second inner function def ack(): nonlocal name # Reference to the next upper variable with this name print(name) # Print the value of the referenced variable name = 'GEEK' # Overwrite the referenced variable print(name) ack() # Calling second inner function bar() # Calling first inner function print(name) # Printing local variable of bar() foo()", "e": 2354, "s": 1804, "text": null }, { "code": null, "e": 2369, "s": 2354, "text": "Geek\nGEEK\ngeek" }, { "code": null, "e": 2463, "s": 2369, "text": "Example 4: In this example we will build a reuseable counter (Just for demonstration purpose)" }, { "code": null, "e": 2471, "s": 2463, "text": "Python3" }, { "code": "# Our counter functiondef counter(): c = 0 # Local counter variable # This function manipulate the local c variable, when called def count(): nonlocal c c += 1 return c # Return the count() function to manipulate the local c variable on every call return count # Assign the result of counter() to a variable which we use to count upmy_counter = counter()for i in range(3): print(my_counter())print('End of my_counter') # Create a new counternew_counter = counter()for i in range(3): print(new_counter())print('End of new_counter')", "e": 3026, "s": 2471, "text": null }, { "code": null, "e": 3075, "s": 3026, "text": "1\n2\n3\nEnd of my_counter\n1\n2\n3\nEnd of new_counter" }, { "code": null, "e": 3165, "s": 3075, "text": "Note: Notice how the local c variable keeps alive on every call of our counter variables." }, { "code": null, "e": 3173, "s": 3165, "text": "clintra" }, { "code": null, "e": 3188, "s": 3173, "text": "adnanirshad158" }, { "code": null, "e": 3201, "s": 3188, "text": "ghostixmusic" }, { "code": null, "e": 3210, "s": 3201, "text": "sweetyty" }, { "code": null, "e": 3225, "s": 3210, "text": "Blogathon-2021" }, { "code": null, "e": 3232, "s": 3225, "text": "Picked" }, { "code": null, "e": 3246, "s": 3232, "text": "python-basics" }, { "code": null, "e": 3256, "s": 3246, "text": "Blogathon" }, { "code": null, "e": 3263, "s": 3256, "text": "Python" } ]
NumPy - Broadcasting
The term broadcasting refers to the ability of NumPy to treat arrays of different shapes during arithmetic operations. Arithmetic operations on arrays are usually done on corresponding elements. If two arrays are of exactly the same shape, then these operations are smoothly performed. import numpy as np a = np.array([1,2,3,4]) b = np.array([10,20,30,40]) c = a * b print c Its output is as follows − [10 40 90 160] If the dimensions of two arrays are dissimilar, element-to-element operations are not possible. However, operations on arrays of non-similar shapes is still possible in NumPy, because of the broadcasting capability. The smaller array is broadcast to the size of the larger array so that they have compatible shapes. Broadcasting is possible if the following rules are satisfied − Array with smaller ndim than the other is prepended with '1' in its shape. Array with smaller ndim than the other is prepended with '1' in its shape. Size in each dimension of the output shape is maximum of the input sizes in that dimension. Size in each dimension of the output shape is maximum of the input sizes in that dimension. An input can be used in calculation, if its size in a particular dimension matches the output size or its value is exactly 1. An input can be used in calculation, if its size in a particular dimension matches the output size or its value is exactly 1. If an input has a dimension size of 1, the first data entry in that dimension is used for all calculations along that dimension. If an input has a dimension size of 1, the first data entry in that dimension is used for all calculations along that dimension. A set of arrays is said to be broadcastable if the above rules produce a valid result and one of the following is true − Arrays have exactly the same shape. Arrays have exactly the same shape. Arrays have the same number of dimensions and the length of each dimension is either a common length or 1. Arrays have the same number of dimensions and the length of each dimension is either a common length or 1. Array having too few dimensions can have its shape prepended with a dimension of length 1, so that the above stated property is true. Array having too few dimensions can have its shape prepended with a dimension of length 1, so that the above stated property is true. The following program shows an example of broadcasting. import numpy as np a = np.array([[0.0,0.0,0.0],[10.0,10.0,10.0],[20.0,20.0,20.0],[30.0,30.0,30.0]]) b = np.array([1.0,2.0,3.0]) print 'First array:' print a print '\n' print 'Second array:' print b print '\n' print 'First Array + Second Array' print a + b The output of this program would be as follows − First array: [[ 0. 0. 0.] [ 10. 10. 10.] [ 20. 20. 20.] [ 30. 30. 30.]] Second array: [ 1. 2. 3.] First Array + Second Array [[ 1. 2. 3.] [ 11. 12. 13.] [ 21. 22. 23.] [ 31. 32. 33.]] The following figure demonstrates how array b is broadcast to become compatible with a. 63 Lectures 6 hours Abhilash Nelson 19 Lectures 8 hours DATAhill Solutions Srinivas Reddy 12 Lectures 3 hours DATAhill Solutions Srinivas Reddy 10 Lectures 2.5 hours Akbar Khan 20 Lectures 2 hours Pruthviraja L 63 Lectures 6 hours Anmol Print Add Notes Bookmark this page
[ { "code": null, "e": 2529, "s": 2243, "text": "The term broadcasting refers to the ability of NumPy to treat arrays of different shapes during arithmetic operations. Arithmetic operations on arrays are usually done on corresponding elements. If two arrays are of exactly the same shape, then these operations are smoothly performed." }, { "code": null, "e": 2623, "s": 2529, "text": "import numpy as np \n\na = np.array([1,2,3,4]) \nb = np.array([10,20,30,40]) \nc = a * b \nprint c" }, { "code": null, "e": 2650, "s": 2623, "text": "Its output is as follows −" }, { "code": null, "e": 2672, "s": 2650, "text": "[10 40 90 160]\n" }, { "code": null, "e": 2988, "s": 2672, "text": "If the dimensions of two arrays are dissimilar, element-to-element operations are not possible. However, operations on arrays of non-similar shapes is still possible in NumPy, because of the broadcasting capability. The smaller array is broadcast to the size of the larger array so that they have compatible shapes." }, { "code": null, "e": 3052, "s": 2988, "text": "Broadcasting is possible if the following rules are satisfied −" }, { "code": null, "e": 3127, "s": 3052, "text": "Array with smaller ndim than the other is prepended with '1' in its shape." }, { "code": null, "e": 3202, "s": 3127, "text": "Array with smaller ndim than the other is prepended with '1' in its shape." }, { "code": null, "e": 3294, "s": 3202, "text": "Size in each dimension of the output shape is maximum of the input sizes in that dimension." }, { "code": null, "e": 3386, "s": 3294, "text": "Size in each dimension of the output shape is maximum of the input sizes in that dimension." }, { "code": null, "e": 3512, "s": 3386, "text": "An input can be used in calculation, if its size in a particular dimension matches the output size or its value is exactly 1." }, { "code": null, "e": 3638, "s": 3512, "text": "An input can be used in calculation, if its size in a particular dimension matches the output size or its value is exactly 1." }, { "code": null, "e": 3767, "s": 3638, "text": "If an input has a dimension size of 1, the first data entry in that dimension is used for all calculations along that dimension." }, { "code": null, "e": 3896, "s": 3767, "text": "If an input has a dimension size of 1, the first data entry in that dimension is used for all calculations along that dimension." }, { "code": null, "e": 4017, "s": 3896, "text": "A set of arrays is said to be broadcastable if the above rules produce a valid result and one of the following is true −" }, { "code": null, "e": 4053, "s": 4017, "text": "Arrays have exactly the same shape." }, { "code": null, "e": 4089, "s": 4053, "text": "Arrays have exactly the same shape." }, { "code": null, "e": 4196, "s": 4089, "text": "Arrays have the same number of dimensions and the length of each dimension is either a common length or 1." }, { "code": null, "e": 4303, "s": 4196, "text": "Arrays have the same number of dimensions and the length of each dimension is either a common length or 1." }, { "code": null, "e": 4437, "s": 4303, "text": "Array having too few dimensions can have its shape prepended with a dimension of length 1, so that the above stated property is true." }, { "code": null, "e": 4571, "s": 4437, "text": "Array having too few dimensions can have its shape prepended with a dimension of length 1, so that the above stated property is true." }, { "code": null, "e": 4627, "s": 4571, "text": "The following program shows an example of broadcasting." }, { "code": null, "e": 4908, "s": 4627, "text": "import numpy as np \na = np.array([[0.0,0.0,0.0],[10.0,10.0,10.0],[20.0,20.0,20.0],[30.0,30.0,30.0]]) \nb = np.array([1.0,2.0,3.0]) \n \nprint 'First array:' \nprint a \nprint '\\n' \n \nprint 'Second array:' \nprint b \nprint '\\n' \n \nprint 'First Array + Second Array' \nprint a + b" }, { "code": null, "e": 4957, "s": 4908, "text": "The output of this program would be as follows −" }, { "code": null, "e": 5150, "s": 4957, "text": "First array:\n[[ 0. 0. 0.]\n [ 10. 10. 10.]\n [ 20. 20. 20.]\n [ 30. 30. 30.]]\n\nSecond array:\n[ 1. 2. 3.]\n\nFirst Array + Second Array\n[[ 1. 2. 3.]\n [ 11. 12. 13.]\n [ 21. 22. 23.]\n [ 31. 32. 33.]]\n" }, { "code": null, "e": 5238, "s": 5150, "text": "The following figure demonstrates how array b is broadcast to become compatible with a." }, { "code": null, "e": 5271, "s": 5238, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 5288, "s": 5271, "text": " Abhilash Nelson" }, { "code": null, "e": 5321, "s": 5288, "text": "\n 19 Lectures \n 8 hours \n" }, { "code": null, "e": 5356, "s": 5321, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 5389, "s": 5356, "text": "\n 12 Lectures \n 3 hours \n" }, { "code": null, "e": 5424, "s": 5389, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 5459, "s": 5424, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5471, "s": 5459, "text": " Akbar Khan" }, { "code": null, "e": 5504, "s": 5471, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 5519, "s": 5504, "text": " Pruthviraja L" }, { "code": null, "e": 5552, "s": 5519, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 5559, "s": 5552, "text": " Anmol" }, { "code": null, "e": 5566, "s": 5559, "text": " Print" }, { "code": null, "e": 5577, "s": 5566, "text": " Add Notes" } ]
Find longest length number in a string in C++
In this problem, we are given a string str consisting of character and alphabets only. Our task is to find the longest length number in a string. Problem Description: we need to find the length of the number i.e. consecutive numerical characters in the string. Let’s take an example to understand the problem, Input: str = “code001tutorials34124point” Output: 34124 Explanation: Numbers in the string are 001 - size 3 34124 - size 5 A simple solution to the problem is by traversing the sting and finding the number’s length and its starting index. We will store the starting position and count of characters in the string for each number in the string. And at the end, return the number. Live Demo #include <iostream> using namespace std; string findLongestNumber(string str, int l) { int count = 0, max = 0, maxLenPos = -1, currPos, currLen, maxLen = 0; for (int i = 0; i < l; i++) { currPos = maxLenPos; currLen = maxLen; count = 0; maxLen = 0; if (isdigit(str[i])) maxLenPos = i; while (isdigit(str[i])) { count++; i++; maxLen++; } if (count > max) { max = count; } else { maxLenPos = currPos; maxLen = currLen; } } return (str.substr(maxLenPos, maxLen)); } int main() { string str = "code001tutorials34124point"; int l = str.length(); cout<<"The longest length number in string is "<<findLongestNumber(str, l); return 0; } The longest length number in string is 34124
[ { "code": null, "e": 1209, "s": 1062, "text": "In this problem, we are given a string str consisting of character and alphabets only. Our task is to find the longest length number in a string. " }, { "code": null, "e": 1324, "s": 1209, "text": "Problem Description: we need to find the length of the number i.e. consecutive numerical characters in the string." }, { "code": null, "e": 1374, "s": 1324, "text": "Let’s take an example to understand the problem, " }, { "code": null, "e": 1416, "s": 1374, "text": "Input: str = “code001tutorials34124point”" }, { "code": null, "e": 1430, "s": 1416, "text": "Output: 34124" }, { "code": null, "e": 1445, "s": 1430, "text": "Explanation: " }, { "code": null, "e": 1471, "s": 1445, "text": "Numbers in the string are" }, { "code": null, "e": 1484, "s": 1471, "text": "001 - size 3" }, { "code": null, "e": 1499, "s": 1484, "text": "34124 - size 5" }, { "code": null, "e": 1755, "s": 1499, "text": "A simple solution to the problem is by traversing the sting and finding the number’s length and its starting index. We will store the starting position and count of characters in the string for each number in the string. And at the end, return the number." }, { "code": null, "e": 1765, "s": 1755, "text": "Live Demo" }, { "code": null, "e": 2558, "s": 1765, "text": "#include <iostream>\nusing namespace std;\n\nstring findLongestNumber(string str, int l) {\n \n int count = 0, max = 0, maxLenPos = -1, currPos, currLen, maxLen = 0;\n\n for (int i = 0; i < l; i++) {\n currPos = maxLenPos;\n currLen = maxLen;\n count = 0;\n maxLen = 0;\n if (isdigit(str[i]))\n maxLenPos = i;\n while (isdigit(str[i])) {\n count++;\n i++;\n maxLen++;\n }\n if (count > max) {\n max = count;\n }\n else {\n maxLenPos = currPos;\n maxLen = currLen;\n }\n }\n return (str.substr(maxLenPos, maxLen));\n}\n\nint main() {\n \n string str = \"code001tutorials34124point\";\n int l = str.length();\n cout<<\"The longest length number in string is \"<<findLongestNumber(str, l);\n return 0;\n}" }, { "code": null, "e": 2603, "s": 2558, "text": "The longest length number in string is 34124" } ]
psql - Unix, Linux Command
psql [ option... ] [ dbname [ username ] ] psql is a terminal-based front-end to PostgreSQL. It enables you to type in queries interactively, issue them to PostgreSQL, and see the query results. Alternatively, input can be from a file. In addition, it provides a number of meta-commands and various shell-like features to facilitate writing scripts and automating a wide variety of tasks. command must be either a command string that is completely parsable by the server (i.e., it contains no psql specific features), or a single backslash command. Thus you cannot mix SQL and psql meta-commands. To achieve that, you could pipe the string into psql, like this: echo "\x \\ select * from foo;" | psql. If the command string contains multiple SQL commands, they are processed in a single transaction, unless there are explicit BEGIN/COMMIT commands included in the string to divide it into multiple transactions. This is different from the behavior when the same string is fed to psql’s standard input. If filename is - (hyphen), then standard input is read. Using this option is subtly different from writing psql < filename. In general, both will do what you expect, but using -f enables some nice features such as error messages with line numbers. There is also a slight chance that using this option will reduce the start-up overhead. On the other hand, the variant using the shell’s input redirection is (in theory) guaranteed to yield exactly the same output that you would have gotten had you entered everything by hand. Note: This mode is provided for those who insist on it, but you are not necessarily encouraged to use it. In particular, if you mix SQL and meta-commands on a line the order of execution might not always be clear to the inexperienced user. This option is deprecated, as it is conceptually flawed. (Prompting for a non-default user name and prompting for a password because the server requires it are really two different things.) You are encouraged to look at the -U and -W options instead. psql should automatically prompt for a password whenever the server requests password authentication. However, currently password request detection is not totally reliable, hence this option to force a prompt. If no password prompt is issued and the server requires password authentication, the connection attempt will fail. This option will remain set for the entire session, even if you change the database connection with the meta-command \connect. psql returns 0 to the shell if it finished normally, 1 if a fatal error of its own (out of memory, file not found) occurs, 2 if the connection to the server went bad and the session was not interactive, and 3 if an error occurred in a script and the variable ON_ERROR_STOP was set. psql is a regular PostgreSQL client application. In order to connect to a database you need to know the name of your target database, the host name and port number of the server and what user name you want to connect as. psql can be told about those parameters via command line options, namely -d, -h, -p, and -U respectively. If an argument is found that does not belong to any option it will be interpreted as the database name (or the user name, if the database name is already given). Not all these options are required; there are useful defaults. If you omit the host name, psql will connect via a Unix-domain socket to a server on the local host, or via TCP/IP to localhost on machines that don’t have Unix-domain sockets. The default port number is determined at compile time. Since the database server uses the same default, you will not have to specify the port in most cases. The default user name is your Unix user name, as is the default database name. Note that you can’t just connect to any database under any user name. Your database administrator should have informed you about your access rights. When the defaults aren’t quite right, you can save yourself some typing by setting the environment variables PGDATABASE, PGHOST, PGPORT and/or PGUSER to appropriate values. (For additional environment variables, see the documentation.) It is also convenient to have a ~/.pgpass file to avoid regularly having to type in passwords. See the documentation for more information. If the connection could not be made for any reason (e.g., insufficient privileges, server is not running on the targeted host, etc.), psql will return an error and terminate. In normal operation, psql provides a prompt with the name of the database to which psql is currently connected, followed by the string =>. For example, $ psql testdb Welcome to psql 8.1.22, the PostgreSQL interactive terminal. Type: \copyright for distribution terms \h for help with SQL commands \? for help with psql commands \g or terminate with semicolon to execute query \q to quit testdb=> Type: \copyright for distribution terms \h for help with SQL commands \? for help with psql commands \g or terminate with semicolon to execute query \q to quit testdb=> At the prompt, the user may type in SQL commands. Ordinarily, input lines are sent to the server when a command-terminating semicolon is reached. An end of line does not terminate a command. Thus commands can be spread over several lines for clarity. If the command was sent and executed without error, the results of the command are displayed on the screen. Whenever a command is executed, psql also polls for asynchronous notification events generated by LISTEN [listen(7)] and NOTIFY [notify(7)]. Anything you enter in psql that begins with an unquoted backslash is a psql meta-command that is processed by psql itself. These commands help make psql more useful for administration or scripting. Meta-commands are more commonly called slash or backslash commands. The format of a psql command is the backslash, followed immediately by a command verb, then any arguments. The arguments are separated from the command verb and each other by any number of whitespace characters. To include whitespace into an argument you may quote it with a single quote. To include a single quote into such an argument, precede it by a backslash. Anything contained in single quotes is furthermore subject to C-like substitutions for \n (new line), \t (tab), \digits (octal), and \xdigits (hexadecimal). If an unquoted argument begins with a colon (:), it is taken as a psql variable and the value of the variable is used as the argument instead. Arguments that are enclosed in backquotes (‘) are taken as a command line that is passed to the shell. The output of the command (with any trailing newline removed) is taken as the argument value. The above escape sequences also apply in backquotes. Some commands take an SQL identifier (such as a table name) as argument. These arguments follow the syntax rules of SQL: Unquoted letters are forced to lowercase, while double quotes (") protect letters from case conversion and allow incorporation of whitespace into the identifier. Within double quotes, paired double quotes reduce to a single double quote in the resulting name. For example, FOO"BAR"BAZ is interpreted as fooBARbaz, and "A weird"" name" becomes A weird" name. Parsing for arguments stops when another unquoted backslash occurs. This is taken as the beginning of a new meta-command. The special sequence \\ (two backslashes) marks the end of arguments and continues parsing SQL commands, if any. That way SQL and psql commands can be freely mixed on a line. But in any case, the arguments of a meta-command cannot continue beyond the end of the line. The following meta-commands are defined: Tip: To print your current working directory, use \! pwd. If username is omitted the current user name is assumed. As a special rule, \connect without any arguments will connect to the default database as the default user (as you would have gotten by starting psql without any arguments). If the connection attempt failed (wrong user name, access denied, etc.), the previous connection will be kept if and only if psql is in interactive mode. When executing a non-interactive script, processing will immediately stop with an error. This distinction was chosen as a user convenience against typos on the one hand, and a safety mechanism that scripts are not accidentally acting on the wrong database on the other hand. The syntax of the command is similar to that of the SQL COPY [copy(7)] command. Note that, because of this, special parsing rules apply to the \copy command. In particular, the variable substitution rules and backslash escapes do not apply. \copy table from stdin | stdout reads/writes based on the command input and output respectively. All rows are read from the same source that issued the command, continuing until \. is read or the stream reaches EOF. Output is sent to the same place as command output. To read/write from psql’s standard input or output, use pstdin or pstdout. This option is useful for populating tables in-line within a SQL script file. Tip: This operation is not as efficient as the SQL COPY command because all data must pass through the client/server connection. For large amounts of data the SQL command may be preferable. The command form \d+ is identical, except that more information is displayed: any comments associated with the columns of the table are shown, as is the presence of OIDs in the table. Note: If \d is used without a pattern argument, it is equivalent to \dtvs which will show a list of all tables, views, and sequences. This is purely a convenience measure. => \dd version Object descriptions Schema | Name | Object | Description ------------+---------+----------+--------------------------- pg_catalog | version | function | PostgreSQL version string (1 row) Descriptions for objects can be created with the COMMENT [comment(7)] SQL command. Note: To look up functions taking argument or returning values of a specific type, use your pager’s search capability to scroll through the \df output. To reduce clutter, \df does not show data type I/O functions. This is implemented by ignoring functions that accept or return type cstring. If pattern is specified, only objects whose names match the pattern are listed. The commands GRANT and REVOKE are used to set access privileges. See GRANT [grant(7)] for more information. The new query buffer is then re-parsed according to the normal rules of psql, where the whole buffer is treated as a single line. (Thus you cannot make scripts this way. Use \i for that.) This means also that if the query ends with (or rather contains) a semicolon, it is immediately executed. In other cases it will merely wait in the query buffer. Tip: psql searches the environment variables PSQL_EDITOR, EDITOR, and VISUAL (in that order) for an editor to use. If all of them are unset, vi is used on Unix systems, notepad.exe on Windows systems. => \echo ‘date‘ Tue Oct 26 21:40:57 CEST 1999 Tip: If you use the \o command to redirect your query output you may wish to use \qecho instead of this command. Note: To simplify typing, commands that consists of several words do not have to be quoted. Thus it is fine to type \help alter table. Note: If you want to see the lines on the screen as they are read you must set the variable ECHO to all. Tip: Use \lo_list to find out the large object’s OID. foo=> \lo_import ’/home/peter/pictures/photo.xcf’ ’a picture of me’ lo_import 152801 Note that this command is subtly different from the server-side lo_import because it acts as the local user on the local file system, rather than the server’s user and file system. Tip: Use \lo_list to find out the large object’s OID. ‘‘Query results’’ includes all tables, command responses, and notices obtained from the database server, as well as output of various backslash commands that query the database (such as \d), but not error messages. Tip: To intersperse text output in between query results, use \qecho. Adjustable printing options are: ‘‘Unaligned’’ writes all columns of a row on a line, separated by the currently active field separator. This is intended to create output that might be intended to be read in by other programs (tab-separated, comma-separated). ‘‘Aligned’’ mode is the standard, human-readable, nicely formatted text output that is default. The ‘‘HTML’’ and ‘‘LaTeX’’ modes put out tables that are intended to be included in documents using the respective mark-up language. They are not complete documents! (This might not be so dramatic in HTML, but in LaTeX you must have a complete document wrapper.) Expanded mode is supported by all four output formats. When the pager is off, the pager is not used. When the pager is on, the pager is used only when appropriate, i.e. the output is to a terminal and will not fit on the screen. (psql does not do a perfect job of estimating when to use the pager.) \pset pager turns the pager on and off. Pager can also be set to always, which causes the pager to be always used. Illustrations on how these different formats look can be seen in the Examples [psql(1)] section. Note: It is an error to call \pset without arguments. In the future this call might show the current status of all printing options. Valid variable names can contain characters, digits, and underscores. See the section Variables [psql(1)] below for details. Variable names are case-sensitive. Although you are welcome to set any variable to anything you want, psql treats several variables as special. They are documented in the section about variables. Note: This command is totally separate from the SQL command SET [set(7)]. The commands GRANT and REVOKE are used to set access privileges. See GRANT [grant(7)] for more information. This is an alias for \dp (‘‘display privileges’’). The various \d commands accept a pattern parameter to specify the object name(s) to be displayed. * means ‘‘any sequence of characters’’ and ? means ‘‘any single character’’. (This notation is comparable to Unix shell file name patterns.) Advanced users can also use regular-expression notations such as character classes, for example [0-9] to match ‘‘any digit’’. To make any of these pattern-matching characters be interpreted literally, surround it with double quotes. A pattern that contains an (unquoted) dot is interpreted as a schema name pattern followed by an object name pattern. For example, \dt foo*.bar* displays all tables in schemas whose name starts with foo and whose table name starts with bar. If no dot appears, then the pattern matches only objects that are visible in the current schema search path. Whenever the pattern parameter is omitted completely, the \d commands display all objects that are visible in the current schema search path. To see all objects in the database, use the pattern *.*. psql provides variable substitution features similar to common Unix command shells. Variables are simply name/value pairs, where the value can be any string of any length. To set variables, use the psql meta-command \set: testdb=> \set foo bar testdb=> \echo :foo bar Note: The arguments of \set are subject to the same substitution rules as with other commands. Thus you can construct interesting references such as \set :foo ’something’ and get ‘‘soft links’’ or ‘‘variable variables’’ of Perl or PHP fame, respectively. Unfortunately (or fortunately?), there is no way to do anything useful with these constructs. On the other hand, \set bar :foo is a perfectly valid way to copy a variable. If you call \set without a second argument, the variable is set, with an empty string as value. To unset (or delete) a variable, use the command \unset. psql’s internal variable names can consist of letters, numbers, and underscores in any order and any number of them. A number of these variables are treated specially by psql. They indicate certain option settings that can be changed at run time by altering the value of the variable or represent some state of the application. Although you can use these variables for any other purpose, this is not recommended, as the program behavior might grow really strange really quickly. By convention, all specially treated variables consist of all upper-case letters (and possibly numbers and underscores). To ensure maximum compatibility in the future, avoid using such variable names for your own purposes. A list of all specially treated variables follows. Note: In autocommit-off mode, you must explicitly abandon any failed transaction by entering ABORT or ROLLBACK. Also keep in mind that if you exit the session without committing, your work will be lost. Note: The autocommit-on mode is PostgreSQL’s traditional behavior, but autocommit-off is closer to the SQL spec. If you prefer autocommit-off, you may wish to set it in the system-wide psqlrc file or your ~/.psqlrc file. Note: This feature was shamelessly plagiarized from Bash. \set HISTFILE ~/.psql_history- :DBNAME Note: This feature was shamelessly plagiarized from Bash. Note: This feature was shamelessly plagiarized from Bash. Note: This feature was shamelessly plagiarized from Bash. An additional useful feature of psql variables is that you can substitute (‘‘interpolate’’) them into regular SQL statements. The syntax for this is again to prepend the variable name with a colon (:). testdb=> \set foo ’my_table’ testdb=> SELECT * FROM :foo; A popular application of this facility is to refer to the last inserted OID in subsequent statements to build a foreign key scenario. Another possible use of this mechanism is to copy the contents of a file into a table column. First load the file into a variable and then proceed as above. testdb=> \set content ’#146;’ ‘cat my_file.txt‘ ’#146;’ testdb=> INSERT INTO my_table VALUES (:content); testdb=> \set content ’#146;’ ‘sed -e "s/’/\\\\\#146;/g" < my_file.txt‘ ’#146;’ Since colons may legally appear in SQL commands, the following rule applies: the character sequence ‘‘:name’’ is not changed unless ‘‘name’’ is the name of a variable that is currently set. In any case you can escape a colon with a backslash to protect it from substitution. (The colon syntax for variables is standard SQL for embedded query languages, such as ECPG. The colon syntax for array slices and type casts are PostgreSQL extensions, hence the conflict.) The prompts psql issues can be customized to your preference. The three variables PROMPT1, PROMPT2, and PROMPT3 contain strings and special escape sequences that describe the appearance of the prompt. Prompt 1 is the normal prompt that is issued when psql requests a new command. Prompt 2 is issued when more input is expected during command input because the command was not terminated with a semicolon or a quote was not closed. Prompt 3 is issued when you run an SQL COPY command and you are expected to type in the row values on the terminal. The value of the selected prompt variable is printed literally, except where a percent sign (%) is encountered. Depending on the next character, certain other text is substituted instead. Defined substitutions are: testdb=> \set PROMPT1 ’%[%033[1;33;40m%]%n@%/%R%[%033[0m%#%] ’ psql supports the Readline library for convenient line editing and retrieval. The command history is automatically saved when psql exits and is reloaded when psql starts up. Tab-completion is also supported, although the completion logic makes no claim to be an SQL parser. If for some reason you do not like the tab completion, you can turn it off by putting this in a file named .inputrc in your home directory: $if psql set disable-completion on $endif testdb=> \foo Field separator is "oo". psql is built as a ‘‘console application’’. Since the Windows console windows use a different encoding than the rest of the system, you must take special care when using 8-bit characters within psql. If psql detects a problematic console code page, it will warn you at startup. To change the console code page, two things are necessary: The first example shows how to spread a command over several lines of input. Notice the changing prompt: testdb=> CREATE TABLE my_table ( testdb(> first integer not null default 0, testdb(> second text) testdb-> ; CREATE TABLE testdb=> \d my_table Table "my_table" Attribute | Type | Modifier -----------+---------+-------------------- first | integer | not null default 0 second | text | testdb=> \set PROMPT1 ’%n@%m %~%R%# ’ peter@localhost testdb=> peter@localhost testdb=> SELECT * FROM my_table; first | second -------+-------- 1 | one 2 | two 3 | three 4 | four (4 rows) peter@localhost testdb=> \pset border 2 Border style is 2. peter@localhost testdb=> SELECT * FROM my_table; +-------+--------+ | first | second | +-------+--------+ | 1 | one | | 2 | two | | 3 | three | | 4 | four | +-------+--------+ (4 rows) peter@localhost testdb=> \pset border 0 Border style is 0. peter@localhost testdb=> SELECT * FROM my_table; first second ----- ------ 1 one 2 two 3 three 4 four (4 rows) peter@localhost testdb=> \pset border 1 Border style is 1. peter@localhost testdb=> \pset format unaligned Output format is unaligned. peter@localhost testdb=> \pset fieldsep "," Field separator is ",". peter@localhost testdb=> \pset tuples_only Showing only tuples. peter@localhost testdb=> SELECT second, first FROM my_table; one,1 two,2 three,3 four,4 peter@localhost testdb=> \pset border 0 Border style is 0. peter@localhost testdb=> SELECT * FROM my_table; first second ----- ------ 1 one 2 two 3 three 4 four (4 rows) peter@localhost testdb=> \pset border 1 Border style is 1. peter@localhost testdb=> \pset format unaligned Output format is unaligned. peter@localhost testdb=> \pset fieldsep "," Field separator is ",". peter@localhost testdb=> \pset tuples_only Showing only tuples. peter@localhost testdb=> SELECT second, first FROM my_table; one,1 two,2 three,3 four,4 peter@localhost testdb=> \a \t \x Output format is aligned. Tuples only is off. Expanded display is on. peter@localhost testdb=> SELECT * FROM my_table; -[ RECORD 1 ]- first | 1 second | one -[ RECORD 2 ]- first | 2 second | two -[ RECORD 3 ]- first | 3 second | three -[ RECORD 4 ]- first | 4 second | four Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10628, "s": 10579, "text": "\npsql [ option... ] [ dbname\n\n [ username ] ]\n" }, { "code": null, "e": 10976, "s": 10628, "text": "\npsql is a terminal-based front-end to\nPostgreSQL. It enables you to type in\nqueries interactively, issue them to\nPostgreSQL, and see the query results.\nAlternatively, input can be from a file. In addition, it provides a\nnumber of meta-commands and various shell-like features to\nfacilitate writing scripts and automating a wide variety of tasks.\n" }, { "code": null, "e": 11291, "s": 10976, "text": "\ncommand must be either\na command string that is completely parsable by the server (i.e.,\nit contains no psql specific features),\nor a single backslash command. Thus you cannot mix\nSQL and psql\nmeta-commands. To achieve that, you could pipe the string into\npsql, like this: echo \"\\x \\\\\nselect * from foo;\" | psql.\n" }, { "code": null, "e": 11593, "s": 11291, "text": "\nIf the command string contains multiple SQL commands, they are\nprocessed in a single transaction, unless there are explicit\nBEGIN/COMMIT commands included in the string to divide it into\nmultiple transactions. This is different from the behavior when\nthe same string is fed to psql’s standard input.\n" }, { "code": null, "e": 11651, "s": 11593, "text": "\nIf filename is -\n(hyphen), then standard input is read.\n" }, { "code": null, "e": 12122, "s": 11651, "text": "\nUsing this option is subtly different from writing psql\n< filename. In general,\nboth will do what you expect, but using -f\nenables some nice features such as error messages with line\nnumbers. There is also a slight chance that using this option will\nreduce the start-up overhead. On the other hand, the variant using\nthe shell’s input redirection is (in theory) guaranteed to yield\nexactly the same output that you would have gotten had you entered\neverything by hand.\n" }, { "code": null, "e": 12364, "s": 12122, "text": "\nNote: This mode is provided for those who insist on it, but you are not\nnecessarily encouraged to use it. In particular, if you mix\nSQL and meta-commands on a line the order of\nexecution might not always be clear to the inexperienced user.\n" }, { "code": null, "e": 12619, "s": 12366, "text": "\nThis option is deprecated, as it is conceptually flawed.\n(Prompting for a non-default user name and prompting for a\npassword because the server requires it are really two different\nthings.) You are encouraged to look at the -U and\n-W options instead.\n" }, { "code": null, "e": 12946, "s": 12619, "text": "\npsql should automatically prompt for a\npassword whenever the server requests password authentication.\nHowever, currently password request detection is not totally\nreliable, hence this option to force a prompt. If no password\nprompt is issued and the server requires password authentication,\nthe connection attempt will fail.\n" }, { "code": null, "e": 13075, "s": 12946, "text": "\nThis option will remain set for the entire session, even if you\nchange the database connection with the meta-command\n\\connect.\n" }, { "code": null, "e": 13359, "s": 13075, "text": "\npsql returns 0 to the shell if it\nfinished normally, 1 if a fatal error of its own (out of memory,\nfile not found) occurs, 2 if the connection to the server went bad\nand the session was not interactive, and 3 if an error occurred in a\nscript and the variable ON_ERROR_STOP was set.\n" }, { "code": null, "e": 14475, "s": 13359, "text": "\npsql is a regular\nPostgreSQL client application. In order\nto connect to a database you need to know the name of your target\ndatabase, the host name and port number of the server and what user\nname you want to connect as. psql can be\ntold about those parameters via command line options, namely\n-d, -h, -p, and\n-U respectively. If an argument is found that does\nnot belong to any option it will be interpreted as the database name\n(or the user name, if the database name is already given). Not all\nthese options are required; there are useful defaults. If you omit the host\nname, psql will connect via a Unix-domain socket\nto a server on the local host, or via TCP/IP to localhost on\nmachines that don’t have Unix-domain sockets. The default port number is\ndetermined at compile time.\nSince the database server uses the same default, you will not have\nto specify the port in most cases. The default user name is your\nUnix user name, as is the default database name. Note that you can’t\njust connect to any database under any user name. Your database\nadministrator should have informed you about your access rights.\n" }, { "code": null, "e": 14852, "s": 14475, "text": "\nWhen the defaults aren’t quite right, you can save yourself\nsome typing by setting the environment variables\nPGDATABASE, PGHOST,\nPGPORT and/or PGUSER to appropriate\nvalues. (For additional environment variables, see the documentation.) It is also convenient to have a\n~/.pgpass file to avoid regularly having to type in\npasswords. See the documentation for more information.\n" }, { "code": null, "e": 15029, "s": 14852, "text": "\nIf the connection could not be made for any reason (e.g., insufficient\nprivileges, server is not running on the targeted host, etc.),\npsql will return an error and terminate.\n" }, { "code": null, "e": 15183, "s": 15029, "text": "\nIn normal operation, psql provides a\nprompt with the name of the database to which\npsql is currently connected, followed by\nthe string =>. For example,\n" }, { "code": null, "e": 15462, "s": 15185, "text": "$ psql testdb\nWelcome to psql 8.1.22, the PostgreSQL interactive terminal.\n\nType: \\copyright for distribution terms\n \\h for help with SQL commands\n \\? for help with psql commands\n \\g or terminate with semicolon to execute query\n \\q to quit\n\ntestdb=>\n\n" }, { "code": null, "e": 15653, "s": 15462, "text": "\nType: \\copyright for distribution terms\n \\h for help with SQL commands\n \\? for help with psql commands\n \\g or terminate with semicolon to execute query\n \\q to quit\n" }, { "code": null, "e": 15664, "s": 15653, "text": "\ntestdb=>\n" }, { "code": null, "e": 16027, "s": 15666, "text": "\nAt the prompt, the user may type in SQL commands.\nOrdinarily, input lines are sent to the server when a\ncommand-terminating semicolon is reached. An end of line does not\nterminate a command. Thus commands can be spread over several lines for\nclarity. If the command was sent and executed without error, the results\nof the command are displayed on the screen.\n" }, { "code": null, "e": 16170, "s": 16027, "text": "\nWhenever a command is executed, psql also polls\nfor asynchronous notification events generated by\nLISTEN [listen(7)] and\nNOTIFY [notify(7)].\n" }, { "code": null, "e": 16438, "s": 16170, "text": "\nAnything you enter in psql that begins\nwith an unquoted backslash is a psql\nmeta-command that is processed by psql\nitself. These commands help make\npsql more useful for administration or\nscripting. Meta-commands are more commonly called slash or backslash\ncommands.\n" }, { "code": null, "e": 16652, "s": 16438, "text": "\nThe format of a psql command is the backslash,\nfollowed immediately by a command verb, then any arguments. The arguments\nare separated from the command verb and each other by any number of\nwhitespace characters.\n" }, { "code": null, "e": 16964, "s": 16652, "text": "\nTo include whitespace into an argument you may quote it with a\nsingle quote. To include a single quote into such an argument,\nprecede it by a backslash. Anything contained in single quotes is\nfurthermore subject to C-like substitutions for\n\\n (new line), \\t (tab),\n\\digits (octal), and\n\\xdigits (hexadecimal).\n" }, { "code": null, "e": 17109, "s": 16964, "text": "\nIf an unquoted argument begins with a colon (:),\nit is taken as a psql variable and the value of the\nvariable is used as the argument instead.\n" }, { "code": null, "e": 17361, "s": 17109, "text": "\nArguments that are enclosed in backquotes (‘)\nare taken as a command line that is passed to the shell. The\noutput of the command (with any trailing newline removed) is taken\nas the argument value. The above escape sequences also apply in\nbackquotes.\n" }, { "code": null, "e": 17842, "s": 17361, "text": "\nSome commands take an SQL identifier (such as a\ntable name) as argument. These arguments follow the syntax rules\nof SQL: Unquoted letters are forced to\nlowercase, while double quotes (\") protect letters\nfrom case conversion and allow incorporation of whitespace into\nthe identifier. Within double quotes, paired double quotes reduce\nto a single double quote in the resulting name. For example,\nFOO\"BAR\"BAZ is interpreted as fooBARbaz,\nand \"A weird\"\" name\" becomes A weird\"\nname.\n" }, { "code": null, "e": 18234, "s": 17842, "text": "\nParsing for arguments stops when another unquoted backslash occurs.\nThis is taken as the beginning of a new meta-command. The special\nsequence \\\\ (two backslashes) marks the end of\narguments and continues parsing SQL commands, if\nany. That way SQL and\npsql commands can be freely mixed on a\nline. But in any case, the arguments of a meta-command cannot\ncontinue beyond the end of the line.\n" }, { "code": null, "e": 18277, "s": 18234, "text": "\nThe following meta-commands are defined:\n" }, { "code": null, "e": 18337, "s": 18277, "text": "\nTip: To print your current working directory, use \\! pwd.\n" }, { "code": null, "e": 18398, "s": 18339, "text": "\nIf username is\nomitted the current user name is assumed.\n" }, { "code": null, "e": 18574, "s": 18398, "text": "\nAs a special rule, \\connect without any\narguments will connect to the default database as the default\nuser (as you would have gotten by starting\npsql without any arguments).\n" }, { "code": null, "e": 19005, "s": 18574, "text": "\nIf the connection attempt failed (wrong user name, access\ndenied, etc.), the previous connection will be kept if and only\nif psql is in interactive mode. When\nexecuting a non-interactive script, processing will immediately\nstop with an error. This distinction was chosen as a user\nconvenience against typos on the one hand, and a safety\nmechanism that scripts are not accidentally acting on the wrong\ndatabase on the other hand.\n" }, { "code": null, "e": 19248, "s": 19005, "text": "\nThe syntax of the command is similar to that of the\nSQL COPY [copy(7)] command. Note that, because of this,\nspecial parsing rules apply to the \\copy\ncommand. In particular, the variable substitution rules and\nbackslash escapes do not apply.\n" }, { "code": null, "e": 19671, "s": 19248, "text": "\n\\copy table from stdin | stdout\nreads/writes based on the command input and output respectively.\nAll rows are read from the same source that issued the command,\ncontinuing until \\. is read or the stream\nreaches EOF. Output is sent to the same place as\ncommand output. To read/write from\npsql’s standard input or output, use\npstdin or pstdout. This option is useful\nfor populating tables in-line within a SQL script file.\n" }, { "code": null, "e": 19863, "s": 19671, "text": "\nTip: This operation is not as efficient as the SQL\nCOPY command because all data must pass\nthrough the client/server connection. For large\namounts of data the SQL command may be preferable.\n" }, { "code": null, "e": 20051, "s": 19865, "text": "\nThe command form \\d+ is identical, except that\nmore information is displayed: any comments associated with the\ncolumns of the table are shown, as is the presence of OIDs in the\ntable.\n" }, { "code": null, "e": 20225, "s": 20051, "text": "\nNote: If \\d is used without a\npattern argument, it is\nequivalent to \\dtvs which will show a list of\nall tables, views, and sequences. This is purely a convenience\nmeasure.\n" }, { "code": null, "e": 20472, "s": 20229, "text": "=> \\dd version\n Object descriptions\n Schema | Name | Object | Description\n------------+---------+----------+---------------------------\n pg_catalog | version | function | PostgreSQL version string\n(1 row)\n\n" }, { "code": null, "e": 20559, "s": 20474, "text": "\nDescriptions for objects can be created with the COMMENT [comment(7)]\nSQL command.\n" }, { "code": null, "e": 20567, "s": 20559, "text": "\nNote: " }, { "code": null, "e": 20715, "s": 20567, "text": "\nTo look up functions taking argument or returning values of a specific\ntype, use your pager’s search capability to scroll through the \\df\noutput.\n" }, { "code": null, "e": 20857, "s": 20715, "text": "\nTo reduce clutter, \\df does not show data type I/O\nfunctions. This is implemented by ignoring functions that accept\nor return type cstring.\n" }, { "code": null, "e": 20941, "s": 20859, "text": "\nIf pattern is\nspecified, only objects whose names match the pattern are listed.\n" }, { "code": null, "e": 21051, "s": 20941, "text": "\nThe commands GRANT and\nREVOKE are used to set access privileges.\nSee GRANT [grant(7)]\nfor more information.\n" }, { "code": null, "e": 21403, "s": 21051, "text": "\nThe new query buffer is then re-parsed according to the normal\nrules of psql, where the whole buffer\nis treated as a single line. (Thus you cannot make scripts this\nway. Use \\i for that.) This means also that\nif the query ends with (or rather contains) a semicolon, it is\nimmediately executed. In other cases it will merely wait in the\nquery buffer.\n" }, { "code": null, "e": 21606, "s": 21403, "text": "\nTip: psql searches the environment\nvariables PSQL_EDITOR, EDITOR, and\nVISUAL (in that order) for an editor to use. If\nall of them are unset, vi is used on Unix\nsystems, notepad.exe on Windows systems.\n" }, { "code": null, "e": 21658, "s": 21610, "text": "=> \\echo ‘date‘\nTue Oct 26 21:40:57 CEST 1999\n\n" }, { "code": null, "e": 21775, "s": 21660, "text": "\nTip: If you use the \\o command to redirect your\nquery output you may wish to use \\qecho\ninstead of this command.\n" }, { "code": null, "e": 21914, "s": 21777, "text": "\nNote: To simplify typing, commands that consists of several words do\nnot have to be quoted. Thus it is fine to type \\help\nalter table.\n" }, { "code": null, "e": 22023, "s": 21916, "text": "\nNote: If you want to see the lines on the screen as they are read you\nmust set the variable ECHO to\nall.\n" }, { "code": null, "e": 22081, "s": 22025, "text": "\nTip: Use \\lo_list to find out the large object’s\nOID.\n" }, { "code": null, "e": 22172, "s": 22085, "text": "foo=> \\lo_import ’/home/peter/pictures/photo.xcf’ ’a picture of me’\nlo_import 152801\n\n" }, { "code": null, "e": 22357, "s": 22174, "text": "\nNote that this command is subtly different from the server-side\nlo_import because it acts as the local user\non the local file system, rather than the server’s user and file\nsystem.\n" }, { "code": null, "e": 22413, "s": 22357, "text": "\nTip: Use \\lo_list to find out the large object’s\nOID.\n" }, { "code": null, "e": 22632, "s": 22415, "text": "\n‘‘Query results’’ includes all tables, command\nresponses, and notices obtained from the database server, as\nwell as output of various backslash commands that query the\ndatabase (such as \\d), but not error\nmessages.\n" }, { "code": null, "e": 22704, "s": 22632, "text": "\nTip: To intersperse text output in between query results, use\n\\qecho.\n" }, { "code": null, "e": 22741, "s": 22706, "text": "\nAdjustable printing options are:\n" }, { "code": null, "e": 23329, "s": 22741, "text": "\n‘‘Unaligned’’ writes all columns of a row on a\nline, separated by the currently active field separator. This\nis intended to create output that might be intended to be read\nin by other programs (tab-separated, comma-separated).\n‘‘Aligned’’ mode is the standard, human-readable,\nnicely formatted text output that is default. The\n‘‘HTML’’ and\n‘‘LaTeX’’ modes put out tables that are intended to\nbe included in documents using the respective mark-up\nlanguage. They are not complete documents! (This might not be\nso dramatic in HTML, but in LaTeX you must\nhave a complete document wrapper.)\n" }, { "code": null, "e": 23386, "s": 23329, "text": "\nExpanded mode is supported by all four output formats.\n" }, { "code": null, "e": 23747, "s": 23386, "text": "\nWhen the pager is off, the pager is not used. When the pager\nis on, the pager is used only when appropriate, i.e. the\noutput is to a terminal and will not fit on the screen.\n(psql does not do a perfect job of estimating\nwhen to use the pager.) \\pset pager turns the\npager on and off. Pager can also be set to always,\nwhich causes the pager to be always used.\n" }, { "code": null, "e": 23846, "s": 23747, "text": "\nIllustrations on how these different formats look can be seen in\nthe Examples [psql(1)] section.\n" }, { "code": null, "e": 23985, "s": 23850, "text": "\nNote: It is an error to call \\pset without\narguments. In the future this call might show the current status\nof all printing options.\n" }, { "code": null, "e": 24149, "s": 23987, "text": "\nValid variable names can contain characters, digits, and\nunderscores. See the section Variables [psql(1)] below for details.\nVariable names are case-sensitive.\n" }, { "code": null, "e": 24312, "s": 24149, "text": "\nAlthough you are welcome to set any variable to anything you\nwant, psql treats several variables\nas special. They are documented in the section about variables.\n" }, { "code": null, "e": 24388, "s": 24312, "text": "\nNote: This command is totally separate from the SQL\ncommand SET [set(7)].\n" }, { "code": null, "e": 24500, "s": 24390, "text": "\nThe commands GRANT and\nREVOKE are used to set access privileges.\nSee GRANT [grant(7)] for\nmore information.\n" }, { "code": null, "e": 24553, "s": 24500, "text": "\nThis is an alias for \\dp (‘‘display\nprivileges’’).\n" }, { "code": null, "e": 25027, "s": 24553, "text": "\nThe various \\d commands accept a pattern parameter to specify the\nobject name(s) to be displayed. * means ‘‘any\nsequence of characters’’ and ? means ‘‘any single\ncharacter’’. (This notation is comparable to Unix shell file name\npatterns.) Advanced users can also use regular-expression\nnotations such as character classes, for example [0-9]\nto match ‘‘any digit’’. To make any of these\npattern-matching characters be interpreted literally, surround it\nwith double quotes.\n" }, { "code": null, "e": 25379, "s": 25027, "text": "\nA pattern that contains an (unquoted) dot is interpreted as a schema\nname pattern followed by an object name pattern. For example,\n\\dt foo*.bar* displays all tables in schemas whose name\nstarts with foo and whose table name\nstarts with bar. If no dot appears, then the pattern\nmatches only objects that are visible in the current schema search path.\n" }, { "code": null, "e": 25580, "s": 25379, "text": "\nWhenever the pattern parameter\nis omitted completely, the \\d commands display all objects\nthat are visible in the current schema search path. To see all objects\nin the database, use the pattern *.*.\n" }, { "code": null, "e": 25804, "s": 25580, "text": "\npsql provides variable substitution\nfeatures similar to common Unix command shells.\nVariables are simply name/value pairs, where the value\ncan be any string of any length. To set variables, use the\npsql meta-command\n\\set:\n" }, { "code": null, "e": 25830, "s": 25806, "text": "testdb=> \\set foo bar\n\n" }, { "code": null, "e": 25860, "s": 25834, "text": "testdb=> \\echo :foo\nbar\n\n" }, { "code": null, "e": 26291, "s": 25862, "text": "\nNote: The arguments of \\set are subject to the same\nsubstitution rules as with other commands. Thus you can construct\ninteresting references such as \\set :foo\n’something’ and get ‘‘soft links’’ or\n‘‘variable variables’’ of Perl\nor PHP fame,\nrespectively. Unfortunately (or fortunately?), there is no way to do\nanything useful with these constructs. On the other hand,\n\\set bar :foo is a perfectly valid way to copy a\nvariable.\n" }, { "code": null, "e": 26448, "s": 26293, "text": "\nIf you call \\set without a second argument, the\nvariable is set, with an empty string as value. To unset (or delete) a\nvariable, use the command \\unset.\n" }, { "code": null, "e": 27203, "s": 26448, "text": "\npsql’s internal variable names can\nconsist of letters, numbers, and underscores in any order and any\nnumber of them. A number of these variables are treated specially\nby psql. They indicate certain option\nsettings that can be changed at run time by altering the value of\nthe variable or represent some state of the application. Although\nyou can use these variables for any other purpose, this is not\nrecommended, as the program behavior might grow really strange\nreally quickly. By convention, all specially treated variables\nconsist of all upper-case letters (and possibly numbers and\nunderscores). To ensure maximum compatibility in the future, avoid\nusing such variable names for your own purposes. A list of all specially\ntreated variables follows.\n" }, { "code": null, "e": 27410, "s": 27205, "text": "\nNote: In autocommit-off mode, you must explicitly abandon any failed\ntransaction by entering ABORT or ROLLBACK.\nAlso keep in mind that if you exit the session\nwithout committing, your work will be lost.\n" }, { "code": null, "e": 27635, "s": 27412, "text": "\nNote: The autocommit-on mode is PostgreSQL’s traditional\nbehavior, but autocommit-off is closer to the SQL spec. If you\nprefer autocommit-off, you may wish to set it in the system-wide\npsqlrc file or your\n~/.psqlrc file.\n" }, { "code": null, "e": 27697, "s": 27637, "text": "\nNote: This feature was shamelessly plagiarized from\nBash.\n" }, { "code": null, "e": 27742, "s": 27701, "text": "\\set HISTFILE ~/.psql_history- :DBNAME\n\n" }, { "code": null, "e": 27804, "s": 27744, "text": "\nNote: This feature was shamelessly plagiarized from\nBash.\n" }, { "code": null, "e": 27866, "s": 27806, "text": "\nNote: This feature was shamelessly plagiarized from\nBash.\n" }, { "code": null, "e": 27928, "s": 27868, "text": "\nNote: This feature was shamelessly plagiarized from\nBash.\n" }, { "code": null, "e": 28136, "s": 27932, "text": "\nAn additional useful feature of psql\nvariables is that you can substitute (‘‘interpolate’’)\nthem into regular SQL statements. The syntax for\nthis is again to prepend the variable name with a colon\n(:).\n" }, { "code": null, "e": 28198, "s": 28138, "text": "testdb=> \\set foo ’my_table’\ntestdb=> SELECT * FROM :foo;\n\n" }, { "code": null, "e": 28493, "s": 28200, "text": "\nA popular application of this facility is to refer to the last\ninserted OID in subsequent statements to build a\nforeign key scenario. Another possible use of this mechanism is to\ncopy the contents of a file into a table column. First load the file into a\nvariable and then proceed as above.\n" }, { "code": null, "e": 28602, "s": 28495, "text": "testdb=> \\set content ’#146;’ ‘cat my_file.txt‘ ’#146;’\ntestdb=> INSERT INTO my_table VALUES (:content);\n\n" }, { "code": null, "e": 28688, "s": 28606, "text": "testdb=> \\set content ’#146;’ ‘sed -e \"s/’/\\\\\\\\\\#146;/g\" < my_file.txt‘ ’#146;’\n\n" }, { "code": null, "e": 29156, "s": 28690, "text": "\nSince colons may legally appear in SQL commands, the following rule\napplies: the character sequence\n‘‘:name’’ is not changed unless ‘‘name’’ is the name\nof a variable that is currently set. In any case you can escape\na colon with a backslash to protect it from substitution. (The\ncolon syntax for variables is standard SQL for\nembedded query languages, such as ECPG.\nThe colon syntax for array slices and type casts are\nPostgreSQL extensions, hence the\nconflict.)\n" }, { "code": null, "e": 29705, "s": 29156, "text": "\nThe prompts psql issues can be customized\nto your preference. The three variables PROMPT1,\nPROMPT2, and PROMPT3 contain strings\nand special escape sequences that describe the appearance of the\nprompt. Prompt 1 is the normal prompt that is issued when\npsql requests a new command. Prompt 2 is\nissued when more input is expected during command input because the\ncommand was not terminated with a semicolon or a quote was not closed.\nPrompt 3 is issued when you run an SQL\nCOPY command and you are expected to type in the\nrow values on the terminal.\n" }, { "code": null, "e": 29922, "s": 29705, "text": "\nThe value of the selected prompt variable is printed literally,\nexcept where a percent sign (%) is encountered.\nDepending on the next character, certain other text is substituted\ninstead. Defined substitutions are:\n" }, { "code": null, "e": 29989, "s": 29924, "text": "testdb=> \\set PROMPT1 ’%[%033[1;33;40m%]%n@%/%R%[%033[0m%#%] ’\n\n" }, { "code": null, "e": 30411, "s": 29995, "text": "\npsql supports the Readline\nlibrary for convenient line editing and retrieval. The command\nhistory is automatically saved when psql\nexits and is reloaded when\npsql starts up. Tab-completion is also\nsupported, although the completion logic makes no claim to be an\nSQL parser. If for some reason you do not like the tab completion, you\ncan turn it off by putting this in a file named\n.inputrc in your home directory:\n" }, { "code": null, "e": 30457, "s": 30413, "text": "$if psql\nset disable-completion on\n$endif\n\n" }, { "code": null, "e": 30502, "s": 30461, "text": "testdb=> \\foo\nField separator is \"oo\".\n\n" }, { "code": null, "e": 30843, "s": 30504, "text": "\npsql is built as a ‘‘console\napplication’’. Since the Windows console windows use a different\nencoding than the rest of the system, you must take special care\nwhen using 8-bit characters within psql.\nIf psql detects a problematic\nconsole code page, it will warn you at startup. To change the\nconsole code page, two things are necessary:\n" }, { "code": null, "e": 30950, "s": 30843, "text": "\nThe first example shows how to spread a command over several lines of\ninput. Notice the changing prompt:\n" }, { "code": null, "e": 31078, "s": 30952, "text": "testdb=> CREATE TABLE my_table (\ntestdb(> first integer not null default 0,\ntestdb(> second text)\ntestdb-> ;\nCREATE TABLE\n\n" }, { "code": null, "e": 31280, "s": 31082, "text": "testdb=> \\d my_table\n Table \"my_table\"\n Attribute | Type | Modifier\n-----------+---------+--------------------\n first | integer | not null default 0\n second | text |\n\n" }, { "code": null, "e": 31349, "s": 31284, "text": "testdb=> \\set PROMPT1 ’%n@%m %~%R%# ’\npeter@localhost testdb=>\n\n" }, { "code": null, "e": 31501, "s": 31353, "text": "peter@localhost testdb=> SELECT * FROM my_table;\n first | second\n-------+--------\n 1 | one\n 2 | two\n 3 | three\n 4 | four\n(4 rows)\n\n" }, { "code": null, "e": 32319, "s": 31505, "text": "peter@localhost testdb=> \\pset border 2\nBorder style is 2.\npeter@localhost testdb=> SELECT * FROM my_table;\n+-------+--------+\n| first | second |\n+-------+--------+\n| 1 | one |\n| 2 | two |\n| 3 | three |\n| 4 | four |\n+-------+--------+\n(4 rows)\n\npeter@localhost testdb=> \\pset border 0\nBorder style is 0.\npeter@localhost testdb=> SELECT * FROM my_table;\nfirst second\n----- ------\n 1 one\n 2 two\n 3 three\n 4 four\n(4 rows)\n\npeter@localhost testdb=> \\pset border 1\nBorder style is 1.\npeter@localhost testdb=> \\pset format unaligned\nOutput format is unaligned.\npeter@localhost testdb=> \\pset fieldsep \",\"\nField separator is \",\".\npeter@localhost testdb=> \\pset tuples_only\nShowing only tuples.\npeter@localhost testdb=> SELECT second, first FROM my_table;\none,1\ntwo,2\nthree,3\nfour,4\n\n" }, { "code": null, "e": 32507, "s": 32319, "text": "\npeter@localhost testdb=> \\pset border 0\nBorder style is 0.\npeter@localhost testdb=> SELECT * FROM my_table;\nfirst second\n----- ------\n 1 one\n 2 two\n 3 three\n 4 four\n(4 rows)\n" }, { "code": null, "e": 32864, "s": 32507, "text": "\npeter@localhost testdb=> \\pset border 1\nBorder style is 1.\npeter@localhost testdb=> \\pset format unaligned\nOutput format is unaligned.\npeter@localhost testdb=> \\pset fieldsep \",\"\nField separator is \",\".\npeter@localhost testdb=> \\pset tuples_only\nShowing only tuples.\npeter@localhost testdb=> SELECT second, first FROM my_table;\none,1\ntwo,2\nthree,3\nfour,4\n" }, { "code": null, "e": 33182, "s": 32868, "text": "peter@localhost testdb=> \\a \\t \\x\nOutput format is aligned.\nTuples only is off.\nExpanded display is on.\npeter@localhost testdb=> SELECT * FROM my_table;\n-[ RECORD 1 ]-\nfirst | 1\nsecond | one\n-[ RECORD 2 ]-\nfirst | 2\nsecond | two\n-[ RECORD 3 ]-\nfirst | 3\nsecond | three\n-[ RECORD 4 ]-\nfirst | 4\nsecond | four\n\n" }, { "code": null, "e": 33201, "s": 33184, "text": "\nAdvertisements\n" }, { "code": null, "e": 33236, "s": 33201, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 33264, "s": 33236, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 33298, "s": 33264, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 33315, "s": 33298, "text": " Frahaan Hussain" }, { "code": null, "e": 33348, "s": 33315, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 33359, "s": 33348, "text": " Pradeep D" }, { "code": null, "e": 33394, "s": 33359, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 33410, "s": 33394, "text": " Musab Zayadneh" }, { "code": null, "e": 33443, "s": 33410, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 33455, "s": 33443, "text": " GUHARAJANM" }, { "code": null, "e": 33487, "s": 33455, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 33495, "s": 33487, "text": " Uplatz" }, { "code": null, "e": 33502, "s": 33495, "text": " Print" }, { "code": null, "e": 33513, "s": 33502, "text": " Add Notes" } ]
Max and Min Products | Practice | GeeksforGeeks
Given a set, we need to find the maximum and minimum possible product among all subsets of the set. Example 1: Input : arr[] = {1, 2, 3}; Output : Maximum product = 6 Minimum product = 1 Explanation : Maximum product is obtained by multiplying 2, 3 Minimum product is obtained by multiplying 1 Example 2: Input : arr[] = {4, -2, 5}; Output : Maximum product = 20 Minimum product = -40 Explanation : Maximum product is obtained by multiplying 4 5 Minimum product is obtained by multiplying 4, -2, 5 Example 3: Input : arr[] = {-4, -2, 3, 7, 5, 0, 1}; Output : Maximum product = 840 Minimum product = -420 Explanation : Maximum product is obtained by multiplying -4, -2, 3, 7, 5 Minimum product is obtained by multiplying -4, 3, 7 Your Task: You don't need to read input or print anything. Your task is to complete the function getMaxandMinProduct() which takes the array arr[] and its size N as inputs and returns the maximum product and minimum subset product in an vector/array/list of size 2. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 1 ≤ N ≤ 20 -9 ≤ A[i] ≤ 9 0 Debarshi Maitra1 year ago Debarshi Maitra Greedy Solution : https://ide.geeksforgeeks.o...Time Complexity : O(N)Auxiliary Space : O(1) 0 Mahima Mahendru2 years ago Mahima Mahendru hard work paid off!!https://ide.geeksforgeeks.o... 0 Sanjib Giri3 years ago Sanjib Giri Another approach to Solution https://ide.geeksforgeeks.o... 0 Sanjib Giri This comment was deleted. 0 Gyan5 years ago Gyan Can this input array contain repeating digits and zeros? 0 Siddharth Agarwal5 years ago Siddharth Agarwal Wrong !! The first test case where your code failed: Input:41 2 3 4 Its Correct output is:24 1 And Your Output is:24 24But my code is generating 24 1Here's the link of my code:http://code.geeksforgeeks.o...What should I do? 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": 338, "s": 238, "text": "Given a set, we need to find the maximum and minimum possible product among all subsets of the set." }, { "code": null, "e": 350, "s": 338, "text": "\nExample 1:" }, { "code": null, "e": 535, "s": 350, "text": "Input : \narr[] = {1, 2, 3};\nOutput : \nMaximum product = 6\nMinimum product = 1\nExplanation :\nMaximum product is obtained by multiplying\n2, 3\nMinimum product is obtained by multiplying\n1" }, { "code": null, "e": 548, "s": 537, "text": "Example 2:" }, { "code": null, "e": 742, "s": 548, "text": "Input :\narr[] = {4, -2, 5};\nOutput : \nMaximum product = 20\nMinimum product = -40\nExplanation :\nMaximum product is obtained by multiplying\n4 5\nMinimum product is obtained by multiplying\n4, -2, 5" }, { "code": null, "e": 755, "s": 744, "text": "Example 3:" }, { "code": null, "e": 976, "s": 755, "text": "Input :\narr[] = {-4, -2, 3, 7, 5, 0, 1};\nOutput : \nMaximum product = 840\nMinimum product = -420\nExplanation :\nMaximum product is obtained by multiplying\n-4, -2, 3, 7, 5\nMinimum product is obtained by multiplying\n-4, 3, 7" }, { "code": null, "e": 1246, "s": 976, "text": "\n\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function getMaxandMinProduct() which takes the array arr[] and its size N as inputs and returns the maximum product and minimum subset product in an vector/array/list of size 2." }, { "code": null, "e": 1348, "s": 1246, "text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n\nConstraints:\n1 ≤ N ≤ 20\n-9 ≤ A[i] ≤ 9" }, { "code": null, "e": 1350, "s": 1348, "text": "0" }, { "code": null, "e": 1376, "s": 1350, "text": "Debarshi Maitra1 year ago" }, { "code": null, "e": 1392, "s": 1376, "text": "Debarshi Maitra" }, { "code": null, "e": 1485, "s": 1392, "text": "Greedy Solution : https://ide.geeksforgeeks.o...Time Complexity : O(N)Auxiliary Space : O(1)" }, { "code": null, "e": 1487, "s": 1485, "text": "0" }, { "code": null, "e": 1514, "s": 1487, "text": "Mahima Mahendru2 years ago" }, { "code": null, "e": 1530, "s": 1514, "text": "Mahima Mahendru" }, { "code": null, "e": 1581, "s": 1530, "text": "hard work paid off!!https://ide.geeksforgeeks.o..." }, { "code": null, "e": 1583, "s": 1581, "text": "0" }, { "code": null, "e": 1606, "s": 1583, "text": "Sanjib Giri3 years ago" }, { "code": null, "e": 1618, "s": 1606, "text": "Sanjib Giri" }, { "code": null, "e": 1647, "s": 1618, "text": "Another approach to Solution" }, { "code": null, "e": 1678, "s": 1647, "text": "https://ide.geeksforgeeks.o..." }, { "code": null, "e": 1680, "s": 1678, "text": "0" }, { "code": null, "e": 1692, "s": 1680, "text": "Sanjib Giri" }, { "code": null, "e": 1718, "s": 1692, "text": "This comment was deleted." }, { "code": null, "e": 1720, "s": 1718, "text": "0" }, { "code": null, "e": 1736, "s": 1720, "text": "Gyan5 years ago" }, { "code": null, "e": 1741, "s": 1736, "text": "Gyan" }, { "code": null, "e": 1798, "s": 1741, "text": "Can this input array contain repeating digits and zeros?" }, { "code": null, "e": 1800, "s": 1798, "text": "0" }, { "code": null, "e": 1829, "s": 1800, "text": "Siddharth Agarwal5 years ago" }, { "code": null, "e": 1847, "s": 1829, "text": "Siddharth Agarwal" }, { "code": null, "e": 1900, "s": 1847, "text": "Wrong !! The first test case where your code failed:" }, { "code": null, "e": 1915, "s": 1900, "text": "Input:41 2 3 4" }, { "code": null, "e": 1942, "s": 1915, "text": "Its Correct output is:24 1" }, { "code": null, "e": 2071, "s": 1942, "text": "And Your Output is:24 24But my code is generating 24 1Here's the link of my code:http://code.geeksforgeeks.o...What should I do?" }, { "code": null, "e": 2217, "s": 2071, "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": 2253, "s": 2217, "text": " Login to access your submissions. " }, { "code": null, "e": 2263, "s": 2253, "text": "\nProblem\n" }, { "code": null, "e": 2273, "s": 2263, "text": "\nContest\n" }, { "code": null, "e": 2336, "s": 2273, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 2484, "s": 2336, "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": 2692, "s": 2484, "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": 2798, "s": 2692, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
\iff - Tex Command
\iff - Used to draw if and only if symbol. { \iff } \iff command draws if and only if symbol. \iff ⟺ \iff ⟺ \iff 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8029, "s": 7986, "text": "\\iff - Used to draw if and only if symbol." }, { "code": null, "e": 8038, "s": 8029, "text": "{ \\iff }" }, { "code": null, "e": 8080, "s": 8038, "text": "\\iff command draws if and only if symbol." }, { "code": null, "e": 8092, "s": 8080, "text": "\n\\iff\n\n⟺\n\n\n" }, { "code": null, "e": 8102, "s": 8092, "text": "\\iff\n\n⟺\n\n" }, { "code": null, "e": 8107, "s": 8102, "text": "\\iff" }, { "code": null, "e": 8139, "s": 8107, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8152, "s": 8139, "text": " Ashraf Said" }, { "code": null, "e": 8185, "s": 8152, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8198, "s": 8185, "text": " Ashraf Said" }, { "code": null, "e": 8230, "s": 8198, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 8266, "s": 8230, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8301, "s": 8266, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8318, "s": 8301, "text": " Mohammad Nauman" }, { "code": null, "e": 8351, "s": 8318, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8365, "s": 8351, "text": " Daniel Stern" }, { "code": null, "e": 8397, "s": 8365, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 8412, "s": 8397, "text": " Nishant Kumar" }, { "code": null, "e": 8419, "s": 8412, "text": " Print" }, { "code": null, "e": 8430, "s": 8419, "text": " Add Notes" } ]
Create Inverted Navbar in Bootstrap
To create an inverted navbar with a black background and with white text, simply add the .navbar-inverse class to the .navbar class. Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <script src="/scripts/jquery.min.js"></script> <script src="/bootstrap/js/bootstrap.min.js"></script> </head> <body> <nav class = "navbar navbar-inverse" role = "navigation"> <div class = "navbar-header"> <a class = "navbar-brand" href = "#">TutorialsPoint</a> <div> <div> <ul class = "nav navbar-nav"> <li class = "active"><a href = "#">iOS</a></li> <li><a href = "#">SVN</a></li> <li class = "dropdown"> <a href = "#" class = "dropdown-toggle" data-toggle = "dropdown"> Java <b class = "caret"></b> </a> <ul class = "dropdown-menu"> <li><a href = "#">jmeter</a></li> <li><a href = "#">EJB</a></li> <li><a href = "#">Jasper Report</a></li> </ul> </li> </ul> </div> </nav> </body> </html>
[ { "code": null, "e": 1195, "s": 1062, "text": "To create an inverted navbar with a black background and with white text, simply add the .navbar-inverse class to the .navbar class." }, { "code": null, "e": 1206, "s": 1195, "text": " Live Demo" }, { "code": null, "e": 2487, "s": 1206, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href=\"/bootstrap/css/bootstrap.min.css\" rel=\"stylesheet\">\n <script src=\"/scripts/jquery.min.js\"></script>\n <script src=\"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <nav class = \"navbar navbar-inverse\" role = \"navigation\">\n <div class = \"navbar-header\">\n <a class = \"navbar-brand\" href = \"#\">TutorialsPoint</a>\n <div>\n <div>\n <ul class = \"nav navbar-nav\">\n <li class = \"active\"><a href = \"#\">iOS</a></li>\n <li><a href = \"#\">SVN</a></li>\n <li class = \"dropdown\">\n <a href = \"#\" class = \"dropdown-toggle\" data-toggle = \"dropdown\">\n Java\n <b class = \"caret\"></b>\n </a>\n <ul class = \"dropdown-menu\">\n <li><a href = \"#\">jmeter</a></li>\n <li><a href = \"#\">EJB</a></li>\n <li><a href = \"#\">Jasper Report</a></li>\n </ul>\n </li>\n </ul>\n </div>\n </nav>\n </body>\n</html>" } ]
How to compare pointers in C/C++?
We can compare pointers if they are pointing to the same array. Relational pointers can be used to compare two pointers. Pointers can’t be multiplied or divided. Live Demo #include <stdio.h> int main() { int *p2; int *p1; p2 = (int *)300; p1 = (int *)200; if(p1 > p2) { printf("P1 is greater than p2"); } else { printf("P2 is greater than p1"); } return(0); } P2 is greater than p1 #include <iostream> using namespace std; int main() { int *p2; int *p1; p2 = (int *)300; p1 = (int *)200; if(p1>p2) { cout<<"P1 is greater than p2"; } else { cout<<"P2 is greater than p1"; } return(0); } P2 is greater than p1 Some Key points about pointer comparison − p1<=p2 and p1>=p2 both yield true and p1<p2 and p1>p2 both yield false, if two pointers p1 and p2 of the same type point to the same object or function, or both point one past the end of the same array, or are both null. p1<=p2 and p1>=p2 both yield true and p1<p2 and p1>p2 both yield false, if two pointers p1 and p2 of the same type point to the same object or function, or both point one past the end of the same array, or are both null. p1<p2, p1>p2, p1<=p2 and p1>=p2 are unspecified, if two pointers p1 and p2 of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null. p1<p2, p1>p2, p1<=p2 and p1>=p2 are unspecified, if two pointers p1 and p2 of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null. If two pointers point to non-static data members of the same object, or to subobjects or array elements of such members, with same access control then the result is specified. If two pointers point to non-static data members of the same object, or to subobjects or array elements of such members, with same access control then the result is specified. the result is unspecified, if two pointers point to non-static data members of the same object with different access control. the result is unspecified, if two pointers point to non-static data members of the same object with different access control.
[ { "code": null, "e": 1224, "s": 1062, "text": "We can compare pointers if they are pointing to the same array. Relational pointers can be used to compare two pointers. Pointers can’t be multiplied or divided." }, { "code": null, "e": 1235, "s": 1224, "text": " Live Demo" }, { "code": null, "e": 1459, "s": 1235, "text": "#include <stdio.h>\nint main() {\n int *p2;\n int *p1;\n p2 = (int *)300;\n p1 = (int *)200;\n if(p1 > p2) {\n printf(\"P1 is greater than p2\");\n } else {\n printf(\"P2 is greater than p1\");\n }\n return(0);\n}" }, { "code": null, "e": 1481, "s": 1459, "text": "P2 is greater than p1" }, { "code": null, "e": 1721, "s": 1481, "text": "#include <iostream>\nusing namespace std;\nint main() {\n int *p2;\n int *p1;\n p2 = (int *)300;\n p1 = (int *)200;\n if(p1>p2) {\n cout<<\"P1 is greater than p2\";\n } else {\n cout<<\"P2 is greater than p1\";\n }\n return(0);\n}" }, { "code": null, "e": 1743, "s": 1721, "text": "P2 is greater than p1" }, { "code": null, "e": 1786, "s": 1743, "text": "Some Key points about pointer comparison −" }, { "code": null, "e": 2007, "s": 1786, "text": "p1<=p2 and p1>=p2 both yield true and p1<p2 and p1>p2 both yield false, if two pointers p1 and p2 of the same type point to the same object or function, or both point one past the end of the same array, or are both null." }, { "code": null, "e": 2228, "s": 2007, "text": "p1<=p2 and p1>=p2 both yield true and p1<p2 and p1>p2 both yield false, if two pointers p1 and p2 of the same type point to the same object or function, or both point one past the end of the same array, or are both null." }, { "code": null, "e": 2476, "s": 2228, "text": "p1<p2, p1>p2, p1<=p2 and p1>=p2 are unspecified, if two pointers p1 and p2 of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null." }, { "code": null, "e": 2724, "s": 2476, "text": "p1<p2, p1>p2, p1<=p2 and p1>=p2 are unspecified, if two pointers p1 and p2 of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null." }, { "code": null, "e": 2900, "s": 2724, "text": "If two pointers point to non-static data members of the same object, or to subobjects or array elements of such members, with same access control then the result is specified." }, { "code": null, "e": 3076, "s": 2900, "text": "If two pointers point to non-static data members of the same object, or to subobjects or array elements of such members, with same access control then the result is specified." }, { "code": null, "e": 3202, "s": 3076, "text": "the result is unspecified, if two pointers point to non-static data members of the same object with different access control." }, { "code": null, "e": 3328, "s": 3202, "text": "the result is unspecified, if two pointers point to non-static data members of the same object with different access control." } ]
Matplotlib - Anaconda distribution
Anaconda is a free and open source distribution of the Python and R programming languages for large-scale data processing, predictive analytics, and scientific computing. The distribution makes package management and deployment simple and easy. Matplotlib and lots of other useful (data) science tools form part of the distribution. Package versions are managed by the package management system Conda. The advantage of Anaconda is that you have access to over 720 packages that can easily be installed with Anaconda's Conda, a package, dependency, and environment manager. Anaconda distribution is available for installation at https://www.anaconda.com/download/. For installation on Windows, 32 and 64 bit binaries are available − https://repo.continuum.io/archive/Anaconda3-5.1.0-Windows-x86.exe https://repo.continuum.io/archive/Anaconda3-5.1.0-Windows-x86_64.exe Installation is a fairly straightforward wizard based process. You can choose between adding Anaconda in PATH variable and registering Anaconda as your default Python. For installation on Linux, download installers for 32 bit and 64 bit installers from the downloads page − https://repo.continuum.io/archive/Anaconda3-5.1.0-Linux-x86.sh https://repo.continuum.io/archive/Anaconda3-5.1.0-Linux-x86_64.sh Now, run the following command from the Linux terminal − $ bash Anaconda3-5.0.1-Linux-x86_64.sh Canopy and ActiveState are the most sought after choices for Windows, macOS and common Linux platforms. The Windows users can find an option in WinPython. 63 Lectures 6 hours Abhilash Nelson 11 Lectures 4 hours DATAhill Solutions Srinivas Reddy 9 Lectures 2.5 hours DATAhill Solutions Srinivas Reddy 32 Lectures 4 hours Aipython 10 Lectures 2.5 hours Akbar Khan 63 Lectures 6 hours Anmol Print Add Notes Bookmark this page
[ { "code": null, "e": 3089, "s": 2516, "text": "Anaconda is a free and open source distribution of the Python and R programming languages for large-scale data processing, predictive analytics, and scientific computing. The distribution makes package management and deployment simple and easy. Matplotlib and lots of other useful (data) science tools form part of the distribution. Package versions are managed by the package management system Conda. The advantage of Anaconda is that you have access to over 720 packages that can easily be installed with Anaconda's Conda, a package, dependency, and environment manager." }, { "code": null, "e": 3248, "s": 3089, "text": "Anaconda distribution is available for installation at https://www.anaconda.com/download/. For installation on Windows, 32 and 64 bit binaries are available −" }, { "code": null, "e": 3314, "s": 3248, "text": "https://repo.continuum.io/archive/Anaconda3-5.1.0-Windows-x86.exe" }, { "code": null, "e": 3383, "s": 3314, "text": "https://repo.continuum.io/archive/Anaconda3-5.1.0-Windows-x86_64.exe" }, { "code": null, "e": 3551, "s": 3383, "text": "Installation is a fairly straightforward wizard based process. You can choose between adding Anaconda in PATH variable and registering Anaconda as your default Python." }, { "code": null, "e": 3657, "s": 3551, "text": "For installation on Linux, download installers for 32 bit and 64 bit installers from the downloads page −" }, { "code": null, "e": 3720, "s": 3657, "text": "https://repo.continuum.io/archive/Anaconda3-5.1.0-Linux-x86.sh" }, { "code": null, "e": 3786, "s": 3720, "text": "https://repo.continuum.io/archive/Anaconda3-5.1.0-Linux-x86_64.sh" }, { "code": null, "e": 3843, "s": 3786, "text": "Now, run the following command from the Linux terminal −" }, { "code": null, "e": 3883, "s": 3843, "text": "$ bash Anaconda3-5.0.1-Linux-x86_64.sh\n" }, { "code": null, "e": 4038, "s": 3883, "text": "Canopy and ActiveState are the most sought after choices for Windows, macOS and common Linux platforms. The Windows users can find an option in WinPython." }, { "code": null, "e": 4071, "s": 4038, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4088, "s": 4071, "text": " Abhilash Nelson" }, { "code": null, "e": 4121, "s": 4088, "text": "\n 11 Lectures \n 4 hours \n" }, { "code": null, "e": 4156, "s": 4121, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 4190, "s": 4156, "text": "\n 9 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4225, "s": 4190, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 4258, "s": 4225, "text": "\n 32 Lectures \n 4 hours \n" }, { "code": null, "e": 4268, "s": 4258, "text": " Aipython" }, { "code": null, "e": 4303, "s": 4268, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4315, "s": 4303, "text": " Akbar Khan" }, { "code": null, "e": 4348, "s": 4315, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4355, "s": 4348, "text": " Anmol" }, { "code": null, "e": 4362, "s": 4355, "text": " Print" }, { "code": null, "e": 4373, "s": 4362, "text": " Add Notes" } ]
How to make a text bold and italic in JavaFX?
You can set the desired font to the text node in JavaFX using the setFont() method. This method accepts an object of the class javafx.scene.text.Font. The Font class represents the fonts in JavaFX, this class provides several variants of a method named font() as shown below − font(double size) font(String family) font(String family, double size) font(String family, FontPosture posture, double size) font(String family, FontWeight weight, double size) font(String family, FontWeight weight, FontPosture posture, double size) Where, size (double) represents the size of the font. size (double) represents the size of the font. family (string) represents the family of the font that we want to apply to the text. You can get the names of installed font families using the getFamilies() method. family (string) represents the family of the font that we want to apply to the text. You can get the names of installed font families using the getFamilies() method. weight represents the weight of the font (one of the constants of the FontWeight Enum − BLACK, BOLD, EXTRA_BOLD, EXTRA_LIGHT, LIGHT, MEDIUM, NORMAL, SEMI_BOLD, THIN). weight represents the weight of the font (one of the constants of the FontWeight Enum − BLACK, BOLD, EXTRA_BOLD, EXTRA_LIGHT, LIGHT, MEDIUM, NORMAL, SEMI_BOLD, THIN). posture represents the font posture (one of the constants of the FontPosture Enum: REGULAR, ITALIC). posture represents the font posture (one of the constants of the FontPosture Enum: REGULAR, ITALIC). To make a text bold create a font bypassing FontWeight.BOLD or, FontWeight.EXTRA_BOLD as the value of the parameter weight and, to make a text italic pass FontPosture.ITALIC as the value of the parameter posture. import java.io.FileNotFoundException; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; public class Bold_Italic extends Application { public void start(Stage stage) throws FileNotFoundException { //Creating a text object String str = "Welcome to Tutorialspoint"; Text text = new Text(30.0, 80.0, str); //Setting the font bold and italic Font font = Font.font("Verdana", FontWeight.BOLD, FontPosture.ITALIC, 35); text.setFont(font); //Setting the color of the text text.setFill(Color.DARKCYAN); //Setting the stage Group root = new Group(text); Scene scene = new Scene(root, 595, 150, Color.BEIGE); stage.setTitle("Bold And Italic"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1213, "s": 1062, "text": "You can set the desired font to the text node in JavaFX using the setFont() method. This method accepts an object of the class javafx.scene.text.Font." }, { "code": null, "e": 1339, "s": 1213, "text": "The Font class represents the fonts in JavaFX, this class provides several variants of a method named font() as shown below −" }, { "code": null, "e": 1589, "s": 1339, "text": "font(double size)\nfont(String family)\nfont(String family, double size)\nfont(String family, FontPosture posture, double size)\nfont(String family, FontWeight weight, double size)\nfont(String family, FontWeight weight, FontPosture posture, double size)" }, { "code": null, "e": 1596, "s": 1589, "text": "Where," }, { "code": null, "e": 1643, "s": 1596, "text": "size (double) represents the size of the font." }, { "code": null, "e": 1690, "s": 1643, "text": "size (double) represents the size of the font." }, { "code": null, "e": 1856, "s": 1690, "text": "family (string) represents the family of the font that we want to apply to the text. You can get the names of installed font families using the getFamilies() method." }, { "code": null, "e": 2022, "s": 1856, "text": "family (string) represents the family of the font that we want to apply to the text. You can get the names of installed font families using the getFamilies() method." }, { "code": null, "e": 2189, "s": 2022, "text": "weight represents the weight of the font (one of the constants of the FontWeight Enum − BLACK, BOLD, EXTRA_BOLD, EXTRA_LIGHT, LIGHT, MEDIUM, NORMAL, SEMI_BOLD, THIN)." }, { "code": null, "e": 2356, "s": 2189, "text": "weight represents the weight of the font (one of the constants of the FontWeight Enum − BLACK, BOLD, EXTRA_BOLD, EXTRA_LIGHT, LIGHT, MEDIUM, NORMAL, SEMI_BOLD, THIN)." }, { "code": null, "e": 2457, "s": 2356, "text": "posture represents the font posture (one of the constants of the FontPosture Enum: REGULAR, ITALIC)." }, { "code": null, "e": 2558, "s": 2457, "text": "posture represents the font posture (one of the constants of the FontPosture Enum: REGULAR, ITALIC)." }, { "code": null, "e": 2771, "s": 2558, "text": "To make a text bold create a font bypassing FontWeight.BOLD or, FontWeight.EXTRA_BOLD as the value of the parameter weight and, to make a text italic pass FontPosture.ITALIC as the value of the parameter posture." }, { "code": null, "e": 3844, "s": 2771, "text": "import java.io.FileNotFoundException;\nimport javafx.application.Application;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\nimport javafx.scene.text.Font;\nimport javafx.scene.text.FontPosture;\nimport javafx.scene.text.FontWeight;\nimport javafx.scene.text.Text;\npublic class Bold_Italic extends Application {\n public void start(Stage stage) throws FileNotFoundException {\n //Creating a text object\n String str = \"Welcome to Tutorialspoint\";\n Text text = new Text(30.0, 80.0, str);\n //Setting the font bold and italic\n Font font = Font.font(\"Verdana\", FontWeight.BOLD, FontPosture.ITALIC, 35);\n text.setFont(font);\n //Setting the color of the text\n text.setFill(Color.DARKCYAN);\n //Setting the stage\n Group root = new Group(text);\n Scene scene = new Scene(root, 595, 150, Color.BEIGE);\n stage.setTitle(\"Bold And Italic\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
groupdel command in Linux with examples - GeeksforGeeks
20 May, 2019 groupdel command is used to delete a existing group. It will delete all entry that refers to the group, modifies the system account files, and it is handled by superuser or root user. Syntax: groupdel [options] GROUP Files: /etc/group : It contains the account information of the Group. /etc/gshadow : It contains the secure group account information. Exit values: This command exits with the following values. 0: Success 2: Invalid Command Syntax. 6: Specified group doesn’t exist. 8: Can’t remove users primary group. 10: Can’t update group file. Options: -f –force: It used to delete a group even if it is the primary group of a user. -h –help: It displays the help message and exit. -R –root: It apply the changes in the CHROOT_DIR directory. Also, it uses the configuration files from the CHROOT_DIR directory.My Personal Notes arrow_drop_upSave linux-command Linux-system-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. nohup Command in Linux with Examples Thread functions in C/C++ scp command in Linux with Examples mv command in Linux with examples chown command in Linux with Examples SED command in Linux | Set 2 Docker - COPY Instruction Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting nslookup command in Linux with Examples
[ { "code": null, "e": 24406, "s": 24378, "text": "\n20 May, 2019" }, { "code": null, "e": 24590, "s": 24406, "text": "groupdel command is used to delete a existing group. It will delete all entry that refers to the group, modifies the system account files, and it is handled by superuser or root user." }, { "code": null, "e": 24598, "s": 24590, "text": "Syntax:" }, { "code": null, "e": 24623, "s": 24598, "text": "groupdel [options] GROUP" }, { "code": null, "e": 24630, "s": 24623, "text": "Files:" }, { "code": null, "e": 24693, "s": 24630, "text": "/etc/group : It contains the account information of the Group." }, { "code": null, "e": 24758, "s": 24693, "text": "/etc/gshadow : It contains the secure group account information." }, { "code": null, "e": 24817, "s": 24758, "text": "Exit values: This command exits with the following values." }, { "code": null, "e": 24828, "s": 24817, "text": "0: Success" }, { "code": null, "e": 24855, "s": 24828, "text": "2: Invalid Command Syntax." }, { "code": null, "e": 24889, "s": 24855, "text": "6: Specified group doesn’t exist." }, { "code": null, "e": 24926, "s": 24889, "text": "8: Can’t remove users primary group." }, { "code": null, "e": 24955, "s": 24926, "text": "10: Can’t update group file." }, { "code": null, "e": 24964, "s": 24955, "text": "Options:" }, { "code": null, "e": 25044, "s": 24964, "text": "-f –force: It used to delete a group even if it is the primary group of a user." }, { "code": null, "e": 25093, "s": 25044, "text": "-h –help: It displays the help message and exit." }, { "code": null, "e": 25257, "s": 25093, "text": "-R –root: It apply the changes in the CHROOT_DIR directory. Also, it uses the configuration files from the CHROOT_DIR directory.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 25271, "s": 25257, "text": "linux-command" }, { "code": null, "e": 25293, "s": 25271, "text": "Linux-system-commands" }, { "code": null, "e": 25300, "s": 25293, "text": "Picked" }, { "code": null, "e": 25311, "s": 25300, "text": "Linux-Unix" }, { "code": null, "e": 25409, "s": 25311, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25446, "s": 25409, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 25472, "s": 25446, "text": "Thread functions in C/C++" }, { "code": null, "e": 25507, "s": 25472, "text": "scp command in Linux with Examples" }, { "code": null, "e": 25541, "s": 25507, "text": "mv command in Linux with examples" }, { "code": null, "e": 25578, "s": 25541, "text": "chown command in Linux with Examples" }, { "code": null, "e": 25607, "s": 25578, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 25633, "s": 25607, "text": "Docker - COPY Instruction" }, { "code": null, "e": 25673, "s": 25633, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 25708, "s": 25673, "text": "Basic Operators in Shell Scripting" } ]
How to do advanced analytics on graph data in Azure Cosmos DB | by René Bremer | Towards Data Science
Azure Cosmos DB is a fully managed multi-database service. It enables you to build highly responsive applications worldwide. As part of Cosmos DB, Gremlin is supported for graph databases. Since Cosmos DB is optimized for fast processing (OLTP), traversal limits may apply for heavy analytic workloads (OLAP). In that case, Azure Databricks and GraphFrames can be used as an alternative to do advanced analytics, see also architecture below. In the remaining of blog, the following is done: OLTP: write graph data to Cosmos DB using the Gremlin API and Python OLAP: read data from Cosmos DB, analyze data in Azure Databricks Finally, a conclusion is drawn in the last chapter. In this chapter, the Gremlin API and Python will be used to write data to Cosmos DB. Since Azure Databricks is used in the next chapter for OLAP, an Azure Databricks cluster is also used to write the data to Cosmos DB using the Gremlin API. However, any Python3 environment can be used to write the data to Cosmos DB, e.g. Visual Code, PyCharm or Azure Functions. The following steps are executed: 1.1. Install prerequisites 1.2. Install Gremlin Python Library in Azure Databricks 1.3. Get and run notebook See also architecture below. The following prerequisites need to be installed: Azure Databricks Cosmos DB with Gremlin API When creating the database and graph in Cosmos DB, /name can be used as partition key. Take PeopleDB as name of the database and friends as name of the graph, see also below. Start your Azure Databricks workspace and go to Cluster. Create a new cluster with Databricks runtime version 6.4 and only 1 worker node, see also below. Subsequently, go to your cluster and click install libraries. Then select Pypi and search for gremlinpython and click install, see also below. Go to your Azure Databricks workspace, right-click and then select import. In the radio button, select to import the following notebook using URL: https://raw.githubusercontent.com/rebremer/cosmosdb-databricks-olap/master/insert_data_CosmosDB_OLTP_Python_Gremlin.py Once the notebook is imported, you need to change the URL of your Cosmos DB endpoint and your Cosmos DB key which can be found in the portal, see also below. Now select to run the notebook and the data will be written to Cosmos DB. Verify whether the data is there, see also below. In this chapter, graph data was added using the Gremlin API, Python and Azure Databricks. In the next chapter, the data is analyzed in which the Databricks cluster is reused. In this chapter, the data is retrieved from Cosmos DB and analyzed in Azure Databricks using GraphFrames. In this, the data is directly read from Cosmos DB in Azure Databricks. Since Cosmos DB is typically used as OLTP it may be necessary to stage the data first in ADLSgen2 to minimize load on Cosmos DB, prevent time outs when massive data loads are needed and save costs. However, for simplicity, in this blog data is directly read from Cosmos DB to Azure Databricks. The following steps are executed: 2.1. Install Cosmos DB & GraphFrames libaries in Azure Databricks 2.2. Get and run notebook See also architecture below. Cosmos DB connector and GraphFrames needs to installed as a jar file to the cluster that was created in the previous chapter. Download the lastest uber Cosmos DB connector using this link to your desktop. Subsequently, go the your Azure Databricks cluster and click install libraries. Then select Jar and drop the jar file, see also below. Subsequently, download the lastest GraphFreams using this link and install this in the same was as the Cosmos DB connector. Verify that all libraries are installed correctly, see also below. Go to your Azure Databricks workspace, right-click and then select import. In the radio button, select to import the following notebook using URL: https://raw.githubusercontent.com/rebremer/cosmosdb-databricks-olap/master/get_data_cosmosDB_OLAP_Scala_GraphFrames.scala Once the notebook is imported, you need to change the URL of your cosmos DB endpoint and your Cosmos DB key which can be found in the portal, see also below. Finally you can run the notebook. In the last cell you can find the result of the Label Propagation Algorithm this is used from Community Detection, see also below. Cosmos DB is the multi-model database service in Azure and graph databases are supported. Since Cosmos DB is optimized for OLTP, the traversal limits may apply for heavy OLAP workloads. In that case, Azure Databricks and GraphFrames can be used as an alternative to do advanced analytics, see also architecture below.
[ { "code": null, "e": 613, "s": 171, "text": "Azure Cosmos DB is a fully managed multi-database service. It enables you to build highly responsive applications worldwide. As part of Cosmos DB, Gremlin is supported for graph databases. Since Cosmos DB is optimized for fast processing (OLTP), traversal limits may apply for heavy analytic workloads (OLAP). In that case, Azure Databricks and GraphFrames can be used as an alternative to do advanced analytics, see also architecture below." }, { "code": null, "e": 662, "s": 613, "text": "In the remaining of blog, the following is done:" }, { "code": null, "e": 731, "s": 662, "text": "OLTP: write graph data to Cosmos DB using the Gremlin API and Python" }, { "code": null, "e": 796, "s": 731, "text": "OLAP: read data from Cosmos DB, analyze data in Azure Databricks" }, { "code": null, "e": 848, "s": 796, "text": "Finally, a conclusion is drawn in the last chapter." }, { "code": null, "e": 1246, "s": 848, "text": "In this chapter, the Gremlin API and Python will be used to write data to Cosmos DB. Since Azure Databricks is used in the next chapter for OLAP, an Azure Databricks cluster is also used to write the data to Cosmos DB using the Gremlin API. However, any Python3 environment can be used to write the data to Cosmos DB, e.g. Visual Code, PyCharm or Azure Functions. The following steps are executed:" }, { "code": null, "e": 1273, "s": 1246, "text": "1.1. Install prerequisites" }, { "code": null, "e": 1329, "s": 1273, "text": "1.2. Install Gremlin Python Library in Azure Databricks" }, { "code": null, "e": 1355, "s": 1329, "text": "1.3. Get and run notebook" }, { "code": null, "e": 1384, "s": 1355, "text": "See also architecture below." }, { "code": null, "e": 1434, "s": 1384, "text": "The following prerequisites need to be installed:" }, { "code": null, "e": 1451, "s": 1434, "text": "Azure Databricks" }, { "code": null, "e": 1478, "s": 1451, "text": "Cosmos DB with Gremlin API" }, { "code": null, "e": 1653, "s": 1478, "text": "When creating the database and graph in Cosmos DB, /name can be used as partition key. Take PeopleDB as name of the database and friends as name of the graph, see also below." }, { "code": null, "e": 1807, "s": 1653, "text": "Start your Azure Databricks workspace and go to Cluster. Create a new cluster with Databricks runtime version 6.4 and only 1 worker node, see also below." }, { "code": null, "e": 1950, "s": 1807, "text": "Subsequently, go to your cluster and click install libraries. Then select Pypi and search for gremlinpython and click install, see also below." }, { "code": null, "e": 2097, "s": 1950, "text": "Go to your Azure Databricks workspace, right-click and then select import. In the radio button, select to import the following notebook using URL:" }, { "code": null, "e": 2216, "s": 2097, "text": "https://raw.githubusercontent.com/rebremer/cosmosdb-databricks-olap/master/insert_data_CosmosDB_OLTP_Python_Gremlin.py" }, { "code": null, "e": 2374, "s": 2216, "text": "Once the notebook is imported, you need to change the URL of your Cosmos DB endpoint and your Cosmos DB key which can be found in the portal, see also below." }, { "code": null, "e": 2498, "s": 2374, "text": "Now select to run the notebook and the data will be written to Cosmos DB. Verify whether the data is there, see also below." }, { "code": null, "e": 2673, "s": 2498, "text": "In this chapter, graph data was added using the Gremlin API, Python and Azure Databricks. In the next chapter, the data is analyzed in which the Databricks cluster is reused." }, { "code": null, "e": 3178, "s": 2673, "text": "In this chapter, the data is retrieved from Cosmos DB and analyzed in Azure Databricks using GraphFrames. In this, the data is directly read from Cosmos DB in Azure Databricks. Since Cosmos DB is typically used as OLTP it may be necessary to stage the data first in ADLSgen2 to minimize load on Cosmos DB, prevent time outs when massive data loads are needed and save costs. However, for simplicity, in this blog data is directly read from Cosmos DB to Azure Databricks. The following steps are executed:" }, { "code": null, "e": 3244, "s": 3178, "text": "2.1. Install Cosmos DB & GraphFrames libaries in Azure Databricks" }, { "code": null, "e": 3270, "s": 3244, "text": "2.2. Get and run notebook" }, { "code": null, "e": 3299, "s": 3270, "text": "See also architecture below." }, { "code": null, "e": 3639, "s": 3299, "text": "Cosmos DB connector and GraphFrames needs to installed as a jar file to the cluster that was created in the previous chapter. Download the lastest uber Cosmos DB connector using this link to your desktop. Subsequently, go the your Azure Databricks cluster and click install libraries. Then select Jar and drop the jar file, see also below." }, { "code": null, "e": 3830, "s": 3639, "text": "Subsequently, download the lastest GraphFreams using this link and install this in the same was as the Cosmos DB connector. Verify that all libraries are installed correctly, see also below." }, { "code": null, "e": 3977, "s": 3830, "text": "Go to your Azure Databricks workspace, right-click and then select import. In the radio button, select to import the following notebook using URL:" }, { "code": null, "e": 4099, "s": 3977, "text": "https://raw.githubusercontent.com/rebremer/cosmosdb-databricks-olap/master/get_data_cosmosDB_OLAP_Scala_GraphFrames.scala" }, { "code": null, "e": 4422, "s": 4099, "text": "Once the notebook is imported, you need to change the URL of your cosmos DB endpoint and your Cosmos DB key which can be found in the portal, see also below. Finally you can run the notebook. In the last cell you can find the result of the Label Propagation Algorithm this is used from Community Detection, see also below." } ]
AI with Python – Logic Programming
In this chapter, we will focus logic programming and how it helps in Artificial Intelligence. We already know that logic is the study of principles of correct reasoning or in simple words it is the study of what comes after what. For example, if two statements are true then we can infer any third statement from it. Logic Programming is the combination of two words, logic and programming. Logic Programming is a programming paradigm in which the problems are expressed as facts and rules by program statements but within a system of formal logic. Just like other programming paradigms like object oriented, functional, declarative, and procedural, etc., it is also a particular way to approach programming. Logic Programming uses facts and rules for solving the problem. That is why they are called the building blocks of Logic Programming. A goal needs to be specified for every program in logic programming. To understand how a problem can be solved in logic programming, we need to know about the building blocks − Facts and Rules − Actually, every logic program needs facts to work with so that it can achieve the given goal. Facts basically are true statements about the program and data. For example, Delhi is the capital of India. Actually, rules are the constraints which allow us to make conclusions about the problem domain. Rules basically written as logical clauses to express various facts. For example, if we are building any game then all the rules must be defined. Rules are very important to solve any problem in Logic Programming. Rules are basically logical conclusion which can express the facts. Following is the syntax of rule − A∶− B1,B2,...,Bn. Here, A is the head and B1, B2, ... Bn is the body. For example − ancestor(X,Y) :- father(X,Y). ancestor(X,Z) :- father(X,Y), ancestor(Y,Z). This can be read as, for every X and Y, if X is the father of Y and Y is an ancestor of Z, X is the ancestor of Z. For every X and Y, X is the ancestor of Z, if X is the father of Y and Y is an ancestor of Z. For starting logic programming in Python, we need to install the following two packages − It provides us a way to simplify the way we made code for business logic. It lets us express the logic in terms of rules and facts. The following command will help you install kanren − pip install kanren SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible. The following command will help you install SymPy − pip install sympy Followings are some examples which can be solved by logic programming − Actually we can find the unknown values by using logic programming in a very effective way. The following Python code will help you match a mathematical expression − Consider importing the following packages first − from kanren import run, var, fact from kanren.assoccomm import eq_assoccomm as eq from kanren.assoccomm import commutative, associative We need to define the mathematical operations which we are going to use − add = 'add' mul = 'mul' Both addition and multiplication are communicative processes. Hence, we need to specify it and this can be done as follows − fact(commutative, mul) fact(commutative, add) fact(associative, mul) fact(associative, add) It is compulsory to define variables; this can be done as follows − a, b = var('a'), var('b') We need to match the expression with the original pattern. We have the following original pattern, which is basically (5+a)*b − Original_pattern = (mul, (add, 5, a), b) We have the following two expressions to match with the original pattern − exp1 = (mul, 2, (add, 3, 1)) exp2 = (add,5,(mul,8,1)) Output can be printed with the following command − print(run(0, (a,b), eq(original_pattern, exp1))) print(run(0, (a,b), eq(original_pattern, exp2))) After running this code, we will get the following output − ((3,2)) () The first output represents the values for a and b. The first expression matched the original pattern and returned the values for a and b but the second expression did not match the original pattern hence nothing has been returned. With the help of logic programming, we can find the prime numbers from a list of numbers and can also generate prime numbers. The Python code given below will find the prime number from a list of numbers and will also generate the first 10 prime numbers. Let us first consider importing the following packages − from kanren import isvar, run, membero from kanren.core import success, fail, goaleval, condeseq, eq, var from sympy.ntheory.generate import prime, isprime import itertools as it Now, we will define a function called prime_check which will check the prime numbers based on the given numbers as data. def prime_check(x): if isvar(x): return condeseq([(eq,x,p)] for p in map(prime, it.count(1))) else: return success if isprime(x) else fail Now, we need to declare a variable which will be used − x = var() print((set(run(0,x,(membero,x,(12,14,15,19,20,21,22,23,29,30,41,44,52,62,65,85)), (prime_check,x))))) print((run(10,x,prime_check(x)))) The output of the above code will be as follows − {19, 23, 29, 41} (2, 3, 5, 7, 11, 13, 17, 19, 23, 29) Logic programming can be used to solve many problems like 8-puzzles, Zebra puzzle, Sudoku, N-queen, etc. Here we are taking an example of a variant of Zebra puzzle which is as follows − There are five houses. The English man lives in the red house. The Swede has a dog. The Dane drinks tea. The green house is immediately to the left of the white house. They drink coffee in the green house. The man who smokes Pall Mall has birds. In the yellow house they smoke Dunhill. In the middle house they drink milk. The Norwegian lives in the first house. The man who smokes Blend lives in the house next to the house with cats. In a house next to the house where they have a horse, they smoke Dunhill. The man who smokes Blue Master drinks beer. The German smokes Prince. The Norwegian lives next to the blue house. They drink water in a house next to the house where they smoke Blend. We are solving it for the question who owns zebra with the help of Python. Let us import the necessary packages − from kanren import * from kanren.core import lall import time Now, we need to define two functions − left() and next() to check whose house is left or next to who’s house − def left(q, p, list): return membero((q,p), zip(list, list[1:])) def next(q, p, list): return conde([left(q, p, list)], [left(p, q, list)]) Now, we will declare a variable house as follows − houses = var() We need to define the rules with the help of lall package as follows. There are 5 houses − rules_zebraproblem = lall( (eq, (var(), var(), var(), var(), var()), houses), (membero,('Englishman', var(), var(), var(), 'red'), houses), (membero,('Swede', var(), var(), 'dog', var()), houses), (membero,('Dane', var(), 'tea', var(), var()), houses), (left,(var(), var(), var(), var(), 'green'), (var(), var(), var(), var(), 'white'), houses), (membero,(var(), var(), 'coffee', var(), 'green'), houses), (membero,(var(), 'Pall Mall', var(), 'birds', var()), houses), (membero,(var(), 'Dunhill', var(), var(), 'yellow'), houses), (eq,(var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses), (eq,(('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses), (next,(var(), 'Blend', var(), var(), var()), (var(), var(), var(), 'cats', var()), houses), (next,(var(), 'Dunhill', var(), var(), var()), (var(), var(), var(), 'horse', var()), houses), (membero,(var(), 'Blue Master', 'beer', var(), var()), houses), (membero,('German', 'Prince', var(), var(), var()), houses), (next,('Norwegian', var(), var(), var(), var()), (var(), var(), var(), var(), 'blue'), houses), (next,(var(), 'Blend', var(), var(), var()), (var(), var(), 'water', var(), var()), houses), (membero,(var(), var(), var(), 'zebra', var()), houses) ) Now, run the solver with the preceding constraints − solutions = run(0, houses, rules_zebraproblem) With the help of the following code, we can extract the output from the solver − output_zebra = [house for house in solutions[0] if 'zebra' in house][0][0] The following code will help print the solution − print ('\n'+ output_zebra + 'owns zebra.') The output of the above code would be as follows − German owns zebra. 78 Lectures 7 hours Arnab Chakraborty 87 Lectures 9.5 hours DigiFisk (Programming Is Fun) 10 Lectures 1 hours Nikoloz Sanakoevi 15 Lectures 54 mins Mukund Kumar Mishra 11 Lectures 1 hours Gilad James, PhD 20 Lectures 2 hours Gilad James, PhD Print Add Notes Bookmark this page
[ { "code": null, "e": 2299, "s": 2205, "text": "In this chapter, we will focus logic programming and how it helps in Artificial Intelligence." }, { "code": null, "e": 2522, "s": 2299, "text": "We already know that logic is the study of principles of correct reasoning or in simple words it is the study of what comes after what. For example, if two statements are true then we can infer any third statement from it." }, { "code": null, "e": 2914, "s": 2522, "text": "Logic Programming is the combination of two words, logic and programming. Logic Programming is a programming paradigm in which the problems are expressed as facts and rules by program statements but within a system of formal logic. Just like other programming paradigms like object oriented, functional, declarative, and procedural, etc., it is also a particular way to approach programming." }, { "code": null, "e": 3243, "s": 2914, "text": "Logic Programming uses facts and rules for solving the problem. That is why they are called the building blocks of Logic Programming. A goal needs to be specified for every program in logic programming. To understand how a problem can be solved in logic programming, we need to know about the building blocks − Facts and Rules −" }, { "code": null, "e": 3445, "s": 3243, "text": "Actually, every logic program needs facts to work with so that it can achieve the given goal. Facts basically are true statements about the program and data. For example, Delhi is the capital of India." }, { "code": null, "e": 3688, "s": 3445, "text": "Actually, rules are the constraints which allow us to make conclusions about the problem domain. Rules basically written as logical clauses to express various facts. For example, if we are building any game then all the rules must be defined." }, { "code": null, "e": 3858, "s": 3688, "text": "Rules are very important to solve any problem in Logic Programming. Rules are basically logical conclusion which can express the facts. Following is the syntax of rule −" }, { "code": null, "e": 3876, "s": 3858, "text": "A∶− B1,B2,...,Bn." }, { "code": null, "e": 3928, "s": 3876, "text": "Here, A is the head and B1, B2, ... Bn is the body." }, { "code": null, "e": 3972, "s": 3928, "text": "For example − ancestor(X,Y) :- father(X,Y)." }, { "code": null, "e": 4017, "s": 3972, "text": "ancestor(X,Z) :- father(X,Y), ancestor(Y,Z)." }, { "code": null, "e": 4226, "s": 4017, "text": "This can be read as, for every X and Y, if X is the father of Y and Y is an ancestor of Z, X is the ancestor of Z. For every X and Y, X is the ancestor of Z, if X is the father of Y and Y is an ancestor of Z." }, { "code": null, "e": 4316, "s": 4226, "text": "For starting logic programming in Python, we need to install the following two packages −" }, { "code": null, "e": 4501, "s": 4316, "text": "It provides us a way to simplify the way we made code for business logic. It lets us express the logic in terms of rules and facts. The following command will help you install kanren −" }, { "code": null, "e": 4521, "s": 4501, "text": "pip install kanren\n" }, { "code": null, "e": 4787, "s": 4521, "text": "SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible. The following command will help you install SymPy −" }, { "code": null, "e": 4806, "s": 4787, "text": "pip install sympy\n" }, { "code": null, "e": 4878, "s": 4806, "text": "Followings are some examples which can be solved by logic programming −" }, { "code": null, "e": 5044, "s": 4878, "text": "Actually we can find the unknown values by using logic programming in a very effective way. The following Python code will help you match a mathematical expression −" }, { "code": null, "e": 5094, "s": 5044, "text": "Consider importing the following packages first −" }, { "code": null, "e": 5230, "s": 5094, "text": "from kanren import run, var, fact\nfrom kanren.assoccomm import eq_assoccomm as eq\nfrom kanren.assoccomm import commutative, associative" }, { "code": null, "e": 5304, "s": 5230, "text": "We need to define the mathematical operations which we are going to use −" }, { "code": null, "e": 5328, "s": 5304, "text": "add = 'add'\nmul = 'mul'" }, { "code": null, "e": 5453, "s": 5328, "text": "Both addition and multiplication are communicative processes. Hence, we need to specify it and this can be done as follows −" }, { "code": null, "e": 5545, "s": 5453, "text": "fact(commutative, mul)\nfact(commutative, add)\nfact(associative, mul)\nfact(associative, add)" }, { "code": null, "e": 5613, "s": 5545, "text": "It is compulsory to define variables; this can be done as follows −" }, { "code": null, "e": 5639, "s": 5613, "text": "a, b = var('a'), var('b')" }, { "code": null, "e": 5767, "s": 5639, "text": "We need to match the expression with the original pattern. We have the following original pattern, which is basically (5+a)*b −" }, { "code": null, "e": 5808, "s": 5767, "text": "Original_pattern = (mul, (add, 5, a), b)" }, { "code": null, "e": 5883, "s": 5808, "text": "We have the following two expressions to match with the original pattern −" }, { "code": null, "e": 5937, "s": 5883, "text": "exp1 = (mul, 2, (add, 3, 1))\nexp2 = (add,5,(mul,8,1))" }, { "code": null, "e": 5988, "s": 5937, "text": "Output can be printed with the following command −" }, { "code": null, "e": 6087, "s": 5988, "text": "print(run(0, (a,b), eq(original_pattern, exp1)))\nprint(run(0, (a,b), eq(original_pattern, exp2)))\n" }, { "code": null, "e": 6147, "s": 6087, "text": "After running this code, we will get the following output −" }, { "code": null, "e": 6159, "s": 6147, "text": "((3,2))\n()\n" }, { "code": null, "e": 6391, "s": 6159, "text": "The first output represents the values for a and b. The first expression matched the original pattern and returned the values for a and b but the second expression did not match the original pattern hence nothing has been returned." }, { "code": null, "e": 6646, "s": 6391, "text": "With the help of logic programming, we can find the prime numbers from a list of numbers and can also generate prime numbers. The Python code given below will find the prime number from a list of numbers and will also generate the first 10 prime numbers." }, { "code": null, "e": 6703, "s": 6646, "text": "Let us first consider importing the following packages −" }, { "code": null, "e": 6882, "s": 6703, "text": "from kanren import isvar, run, membero\nfrom kanren.core import success, fail, goaleval, condeseq, eq, var\nfrom sympy.ntheory.generate import prime, isprime\nimport itertools as it" }, { "code": null, "e": 7003, "s": 6882, "text": "Now, we will define a function called prime_check which will check the prime numbers based on the given numbers as data." }, { "code": null, "e": 7148, "s": 7003, "text": "def prime_check(x):\nif isvar(x):\n return condeseq([(eq,x,p)] for p in map(prime, it.count(1)))\nelse:\n return success if isprime(x) else fail" }, { "code": null, "e": 7204, "s": 7148, "text": "Now, we need to declare a variable which will be used −" }, { "code": null, "e": 7350, "s": 7204, "text": "x = var()\nprint((set(run(0,x,(membero,x,(12,14,15,19,20,21,22,23,29,30,41,44,52,62,65,85)),\n(prime_check,x)))))\nprint((run(10,x,prime_check(x))))" }, { "code": null, "e": 7400, "s": 7350, "text": "The output of the above code will be as follows −" }, { "code": null, "e": 7455, "s": 7400, "text": "{19, 23, 29, 41}\n(2, 3, 5, 7, 11, 13, 17, 19, 23, 29)\n" }, { "code": null, "e": 7641, "s": 7455, "text": "Logic programming can be used to solve many problems like 8-puzzles, Zebra puzzle, Sudoku, N-queen, etc. Here we are taking an example of a variant of Zebra puzzle which is as follows −" }, { "code": null, "e": 8335, "s": 7641, "text": "There are five houses.\nThe English man lives in the red house.\nThe Swede has a dog.\nThe Dane drinks tea.\nThe green house is immediately to the left of the white house.\nThey drink coffee in the green house.\nThe man who smokes Pall Mall has birds.\nIn the yellow house they smoke Dunhill.\nIn the middle house they drink milk.\nThe Norwegian lives in the first house.\nThe man who smokes Blend lives in the house next to the house with cats.\nIn a house next to the house where they have a horse, they smoke Dunhill.\nThe man who smokes Blue Master drinks beer.\nThe German smokes Prince.\nThe Norwegian lives next to the blue house.\nThey drink water in a house next to the house where they smoke Blend." }, { "code": null, "e": 8410, "s": 8335, "text": "We are solving it for the question who owns zebra with the help of Python." }, { "code": null, "e": 8449, "s": 8410, "text": "Let us import the necessary packages −" }, { "code": null, "e": 8511, "s": 8449, "text": "from kanren import *\nfrom kanren.core import lall\nimport time" }, { "code": null, "e": 8622, "s": 8511, "text": "Now, we need to define two functions − left() and next() to check whose house is left or next to who’s house −" }, { "code": null, "e": 8768, "s": 8622, "text": "def left(q, p, list):\n return membero((q,p), zip(list, list[1:]))\ndef next(q, p, list):\n return conde([left(q, p, list)], [left(p, q, list)])" }, { "code": null, "e": 8819, "s": 8768, "text": "Now, we will declare a variable house as follows −" }, { "code": null, "e": 8834, "s": 8819, "text": "houses = var()" }, { "code": null, "e": 8904, "s": 8834, "text": "We need to define the rules with the help of lall package as follows." }, { "code": null, "e": 8925, "s": 8904, "text": "There are 5 houses −" }, { "code": null, "e": 10249, "s": 8925, "text": "rules_zebraproblem = lall(\n (eq, (var(), var(), var(), var(), var()), houses),\n\n (membero,('Englishman', var(), var(), var(), 'red'), houses),\n (membero,('Swede', var(), var(), 'dog', var()), houses),\n (membero,('Dane', var(), 'tea', var(), var()), houses),\n (left,(var(), var(), var(), var(), 'green'),\n (var(), var(), var(), var(), 'white'), houses),\n (membero,(var(), var(), 'coffee', var(), 'green'), houses),\n (membero,(var(), 'Pall Mall', var(), 'birds', var()), houses),\n (membero,(var(), 'Dunhill', var(), var(), 'yellow'), houses),\n (eq,(var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses),\n (eq,(('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses),\n (next,(var(), 'Blend', var(), var(), var()),\n (var(), var(), var(), 'cats', var()), houses),\n (next,(var(), 'Dunhill', var(), var(), var()),\n (var(), var(), var(), 'horse', var()), houses),\n (membero,(var(), 'Blue Master', 'beer', var(), var()), houses),\n (membero,('German', 'Prince', var(), var(), var()), houses),\n (next,('Norwegian', var(), var(), var(), var()),\n (var(), var(), var(), var(), 'blue'), houses),\n (next,(var(), 'Blend', var(), var(), var()),\n (var(), var(), 'water', var(), var()), houses),\n (membero,(var(), var(), var(), 'zebra', var()), houses)\n)" }, { "code": null, "e": 10302, "s": 10249, "text": "Now, run the solver with the preceding constraints −" }, { "code": null, "e": 10349, "s": 10302, "text": "solutions = run(0, houses, rules_zebraproblem)" }, { "code": null, "e": 10430, "s": 10349, "text": "With the help of the following code, we can extract the output from the solver −" }, { "code": null, "e": 10506, "s": 10430, "text": "output_zebra = [house for house in solutions[0] if 'zebra' in house][0][0]\n" }, { "code": null, "e": 10556, "s": 10506, "text": "The following code will help print the solution −" }, { "code": null, "e": 10600, "s": 10556, "text": "print ('\\n'+ output_zebra + 'owns zebra.')\n" }, { "code": null, "e": 10651, "s": 10600, "text": "The output of the above code would be as follows −" }, { "code": null, "e": 10671, "s": 10651, "text": "German owns zebra.\n" }, { "code": null, "e": 10704, "s": 10671, "text": "\n 78 Lectures \n 7 hours \n" }, { "code": null, "e": 10723, "s": 10704, "text": " Arnab Chakraborty" }, { "code": null, "e": 10758, "s": 10723, "text": "\n 87 Lectures \n 9.5 hours \n" }, { "code": null, "e": 10789, "s": 10758, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 10822, "s": 10789, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 10841, "s": 10822, "text": " Nikoloz Sanakoevi" }, { "code": null, "e": 10873, "s": 10841, "text": "\n 15 Lectures \n 54 mins\n" }, { "code": null, "e": 10894, "s": 10873, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 10927, "s": 10894, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 10945, "s": 10927, "text": " Gilad James, PhD" }, { "code": null, "e": 10978, "s": 10945, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 10996, "s": 10978, "text": " Gilad James, PhD" }, { "code": null, "e": 11003, "s": 10996, "text": " Print" }, { "code": null, "e": 11014, "s": 11003, "text": " Add Notes" } ]
Linux Admin - MySQL Setup On CentOS 7
As touched upon briefly when configuring CentOS for use with Maria DB, there is no native MySQL package in the CentOS 7 yum repository. To account for this, we will need to add a MySQL hosted repository. One thing to note is MySQL will require a different set of base dependencies from MariaDB. Also using MySQL will break the concept and philosophy of CentOS: production packages designed for maximum reliability. So when deciding whether to use Maria or MySQL one should weigh two options: Will my current DB Schema work with Maria? What advantage does installing MySQL over Maria give me? Maria components are 100% transparent to MySQL structure, with some added efficiency with better licensing. Unless a compelling reason comes along, it is advised to configure CentOS to use MariaDB. The biggest reasons for favoring Maria on CentOS are − Most people will be using MariaDB. When experiencing issues you will get more assistance with Maria. Most people will be using MariaDB. When experiencing issues you will get more assistance with Maria. CentOS is designed to run with Maria. Hence, Maria will offer better stability. CentOS is designed to run with Maria. Hence, Maria will offer better stability. Maria is officially supported for CentOS. Maria is officially supported for CentOS. We will want to download and install the MySQL repository from − http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm Step 1 − Download the Repository. The repository comes conveniently packaged in an rpm package for easy installation. It can be downloaded with wget − [root@centos]# wget http://repo.mysql.com/mysql-community-release-el75.noarch.rpm --2017-02-26 03:18:36-- http://repo.mysql.com/mysql-community-release-el75.noarch.rpm Resolving repo.mysql.com (repo.mysql.com)... 104.86.98.130 Step 2 − Install MySQL From YUM. We can now use the yum package manager to install MySQL − [root@centos]# yum -y install mysql-server Step 3 − Start and Enable the MySQL Daemon Service. [root@centos]# systemctl start mysql [root@centos]# systemctl enable mysql Step 4 − Make sure our MySQL service is up and running. [root@centos]# netstat -antup | grep 3306 tcp6 0 0 :::3306 :::* LISTEN 6572/mysqld [root@centos]# Note − We will not allow any firewall rules through. It's common to have MySQL configured to use Unix Domain Sockets. This assures only the web-server of the LAMP stack, locally, can access the MySQL database, taking out a complete dimension in the attack vector at the database software. 57 Lectures 7.5 hours Mamta Tripathi 25 Lectures 3 hours Lets Kode It 14 Lectures 1.5 hours Abhilash Nelson 58 Lectures 2.5 hours Frahaan Hussain 129 Lectures 23 hours Eduonix Learning Solutions 23 Lectures 5 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2461, "s": 2257, "text": "As touched upon briefly when configuring CentOS for use with Maria DB, there is no native MySQL package in the CentOS 7 yum repository. To account for this, we will need to add a MySQL hosted repository." }, { "code": null, "e": 2672, "s": 2461, "text": "One thing to note is MySQL will require a different set of base dependencies from MariaDB. Also using MySQL will break the concept and philosophy of CentOS: production packages designed for maximum reliability." }, { "code": null, "e": 2849, "s": 2672, "text": "So when deciding whether to use Maria or MySQL one should weigh two options: Will my current DB Schema work with Maria? What advantage does installing MySQL over Maria give me?" }, { "code": null, "e": 3047, "s": 2849, "text": "Maria components are 100% transparent to MySQL structure, with some added efficiency with better licensing. Unless a compelling reason comes along, it is advised to configure CentOS to use MariaDB." }, { "code": null, "e": 3102, "s": 3047, "text": "The biggest reasons for favoring Maria on CentOS are −" }, { "code": null, "e": 3203, "s": 3102, "text": "Most people will be using MariaDB. When experiencing issues you will get more assistance with Maria." }, { "code": null, "e": 3304, "s": 3203, "text": "Most people will be using MariaDB. When experiencing issues you will get more assistance with Maria." }, { "code": null, "e": 3384, "s": 3304, "text": "CentOS is designed to run with Maria. Hence, Maria will offer better stability." }, { "code": null, "e": 3464, "s": 3384, "text": "CentOS is designed to run with Maria. Hence, Maria will offer better stability." }, { "code": null, "e": 3506, "s": 3464, "text": "Maria is officially supported for CentOS." }, { "code": null, "e": 3548, "s": 3506, "text": "Maria is officially supported for CentOS." }, { "code": null, "e": 3613, "s": 3548, "text": "We will want to download and install the MySQL repository from −" }, { "code": null, "e": 3676, "s": 3613, "text": "http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm" }, { "code": null, "e": 3710, "s": 3676, "text": "Step 1 − Download the Repository." }, { "code": null, "e": 3827, "s": 3710, "text": "The repository comes conveniently packaged in an rpm package for easy installation. It can be downloaded with wget −" }, { "code": null, "e": 4062, "s": 3827, "text": "[root@centos]# wget http://repo.mysql.com/mysql-community-release-el75.noarch.rpm\n --2017-02-26 03:18:36-- http://repo.mysql.com/mysql-community-release-el75.noarch.rpm\n Resolving repo.mysql.com (repo.mysql.com)... 104.86.98.130\n" }, { "code": null, "e": 4095, "s": 4062, "text": "Step 2 − Install MySQL From YUM." }, { "code": null, "e": 4153, "s": 4095, "text": "We can now use the yum package manager to install MySQL −" }, { "code": null, "e": 4197, "s": 4153, "text": "[root@centos]# yum -y install mysql-server\n" }, { "code": null, "e": 4249, "s": 4197, "text": "Step 3 − Start and Enable the MySQL Daemon Service." }, { "code": null, "e": 4327, "s": 4249, "text": "[root@centos]# systemctl start mysql \n[root@centos]# systemctl enable mysql\n" }, { "code": null, "e": 4383, "s": 4327, "text": "Step 4 − Make sure our MySQL service is up and running." }, { "code": null, "e": 4513, "s": 4383, "text": "[root@centos]# netstat -antup | grep 3306 \ntcp6 0 0 :::3306 :::* LISTEN 6572/mysqld\n[root@centos]#\n" }, { "code": null, "e": 4802, "s": 4513, "text": "Note − We will not allow any firewall rules through. It's common to have MySQL configured to use Unix Domain Sockets. This assures only the web-server of the LAMP stack, locally, can access the MySQL database, taking out a complete dimension in the attack vector at the database software." }, { "code": null, "e": 4837, "s": 4802, "text": "\n 57 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4853, "s": 4837, "text": " Mamta Tripathi" }, { "code": null, "e": 4886, "s": 4853, "text": "\n 25 Lectures \n 3 hours \n" }, { "code": null, "e": 4900, "s": 4886, "text": " Lets Kode It" }, { "code": null, "e": 4935, "s": 4900, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4952, "s": 4935, "text": " Abhilash Nelson" }, { "code": null, "e": 4987, "s": 4952, "text": "\n 58 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5004, "s": 4987, "text": " Frahaan Hussain" }, { "code": null, "e": 5039, "s": 5004, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 5067, "s": 5039, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5100, "s": 5067, "text": "\n 23 Lectures \n 5 hours \n" }, { "code": null, "e": 5140, "s": 5100, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 5147, "s": 5140, "text": " Print" }, { "code": null, "e": 5158, "s": 5147, "text": " Add Notes" } ]
Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework - GeeksforGeeks
05 Jun, 2020 Prerequisites: Download and Install Microsoft SQL Server Management Studio Download and Setting Up Visual Studio Community Version MVC stands for Model View Controller. It is a design pattern that is employed to separate the business logic, presentation logic, and data. Basically, it provides a pattern to style web application. As per MVC, you can divide the application into 3 Layers as follows: 1. Model Layer: The Model component corresponds to all or any of the data-related logic that the user works with. This will represent either the info that’s being transferred between the View and Controller components or the other business logic-related data. For instance, a Customer object will retrieve the customer information from the database, manipulate it, and update its data back to the database or use it to render data. 2. View Layer: The View component is employed for all the UI logic of the appliance. For instance, the Customer view will include all the UI components like text boxes, dropdowns, etc. that the ultimate user interacts with. 3. Controller: Controllers act as an interface between Model and consider components to process all the business logic and incoming requests, manipulate data using the Model component, and interact with the Views to render the ultimate output. For instance, the Customer controller will handle all the interactions and inputs from the Customer View and update the database using the Customer Model. An equivalent controller is going to be wont to view the Customer data. ASP.NET is a server-side web application framework created by Microsoft that runs on Windows and was started in the early 2000s. ASP.NET allows developers to make web applications, web services, and dynamic content-driven websites. The latest version of ASP.NET is 4.7.1 To learn how to set up projects in visual studio and how to create a database, refer to below-given links: Create a database in MS-SQL Server Management Studio Create a project in visual studio 1. Create a Database with the following columns: This is just a demo to make you understand the code in the article. You can create your own database according to your needs. 2. Create a Project in Visual Studio Follow the guidelines that are given in the link provided above to create a project. After creating the project add entity data model to add connection string to your web.config file, to do so follow this article Add Entity Data Model to Your ASP.NET Project. The following EDMX diagram will be shown on your solution window. 1. Create Now to create a new record in your database write the following code in the newly created controller. using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc; namespace CRUDDemo.Controllers{ public class CRUDController : Controller { // To create View of this Action result public ActionResult create() { return View(); } // Specify the type of attribute i.e. // it will add the record to the database [HttpPost] public ActionResult create(Student model) { // To open a connection to the database using(var context = new demoCRUDEntities()) { // Add data to the particular table context.Student.Add(model); // save the changes context.SaveChanges(); } string message = "Created the record successfully"; // To display the message on the screen // after the record is created successfully ViewBag.Message = message; // write @Viewbag.Message in the created // view at the place where you want to // display the message return View(); } }} After this write click on the first action result and click on AddView and then select template as Create and model class as your own created model and data context class as your own created EDMX model. Then run the project and go the URL https://localhost:port_number/Controller_name/Action_Method_name For example, https://localhost:44326/CRUD/create 2. Read: Now to See the added data on your screen follow the below-given code using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc; namespace CRUDDemo.Controllers{ public class CRUDController : Controller { [HttpGet] // Set the attribute to Read public ActionResult Read() { using(var context = new demoCRUDEntities()) { // Return the list of data from the database var data = context.Student.ToList(); return View(data); } } }} After this add the View but remember to change the template as List. Then run the project and go to the URLhttps://localhost:port_number/Controller_name/Action_Method_nameFor Example https://localhost:44326/CRUD/Read 3. Update: Now, to update the existing record follow the code given below using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc; namespace CRUDDemo.Controllers{ public class CRUDController : Controller { // To fill data in the form // to enable easy editing public ActionResult Update(int Studentid) { using(var context = new demoCRUDEntities()) { var data = context.Student.Where(x => x.StudentNo == Studentid).SingleOrDefault(); return View(data); } } // To specify that this will be // invoked when post method is called [HttpPost] [ValidateAntiForgeryToken] public ActionResult Update(int Studentid, Student model) { using(var context = new demoCRUDEntities()) { // Use of lambda expression to access // particular record from a database var data = context.Student.FirstOrDefault(x => x.StudentNo == Studentid); // Checking if any such record exist if (data != null) { data.Name = model.Name; data.Section = model.Section; data.EmailId = model.EmailId; data.Branch = model.Branch; context.SaveChanges(); // It will redirect to // the Read method return RedirectToAction("Read"); } else return View(); } } }} After this add view similarly as done previously but remember to change the template to Edit. Then run the project and go to the URL https://localhost:port_number/Controller_name/Action_Method_name?ID_U_want_to_edit For Example, https://localhost:44326/CRUD/Update?Studentid=1 4. Delete Now, to delete a record from the database follow the code given below using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc; namespace CRUDDemo.Controllers{ public class CRUDController : Controller { public ActionResult Delete() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Delete(int Studentid) { using(var context = new demoCRUDEntities()) { var data = context.Student.FirstOrDefault(x = > x.StudentNo == Studentid); if (data != null) { context.Student.Remove(data); context.SaveChanges(); return RedirectToAction("Read"); } else return View(); } } }} After this added view as done previously, but remember to change the template to Delete. Then run the project and go to the URL https://localhost:port_number/Controller_name/Action_Method_name?ID_U_want_to_DeleteFor Example, https://localhost:44326/CRUD/Delete?Studentid=1 Note: The auto-generated HTML can be modified according to your choice. If you want to have a look at the full source code and how it works you can view my GitHub repository by clicking the GitHub Link. CSharp ASP-NET C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# Dictionary with examples Difference between Ref and Out keywords in C# C# | Delegates Top 50 C# Interview Questions & Answers Extension Method in C# C# | Abstract Classes C# | String.IndexOf( ) Method | Set - 1 Different ways to sort an array in descending order in C# C# | Arrays HashSet in C# with Examples
[ { "code": null, "e": 23727, "s": 23699, "text": "\n05 Jun, 2020" }, { "code": null, "e": 23742, "s": 23727, "text": "Prerequisites:" }, { "code": null, "e": 23802, "s": 23742, "text": "Download and Install Microsoft SQL Server Management Studio" }, { "code": null, "e": 23858, "s": 23802, "text": "Download and Setting Up Visual Studio Community Version" }, { "code": null, "e": 24126, "s": 23858, "text": "MVC stands for Model View Controller. It is a design pattern that is employed to separate the business logic, presentation logic, and data. Basically, it provides a pattern to style web application. As per MVC, you can divide the application into 3 Layers as follows:" }, { "code": null, "e": 24558, "s": 24126, "text": "1. Model Layer: The Model component corresponds to all or any of the data-related logic that the user works with. This will represent either the info that’s being transferred between the View and Controller components or the other business logic-related data. For instance, a Customer object will retrieve the customer information from the database, manipulate it, and update its data back to the database or use it to render data." }, { "code": null, "e": 24782, "s": 24558, "text": "2. View Layer: The View component is employed for all the UI logic of the appliance. For instance, the Customer view will include all the UI components like text boxes, dropdowns, etc. that the ultimate user interacts with." }, { "code": null, "e": 25209, "s": 24782, "text": "3. Controller: Controllers act as an interface between Model and consider components to process all the business logic and incoming requests, manipulate data using the Model component, and interact with the Views to render the ultimate output. For instance, the Customer controller will handle all the interactions and inputs from the Customer View and update the database using the Customer Model. An equivalent controller is" }, { "code": null, "e": 25254, "s": 25209, "text": " going to be wont to view the Customer data." }, { "code": null, "e": 25525, "s": 25254, "text": "ASP.NET is a server-side web application framework created by Microsoft that runs on Windows and was started in the early 2000s. ASP.NET allows developers to make web applications, web services, and dynamic content-driven websites. The latest version of ASP.NET is 4.7.1" }, { "code": null, "e": 25632, "s": 25525, "text": "To learn how to set up projects in visual studio and how to create a database, refer to below-given links:" }, { "code": null, "e": 25685, "s": 25632, "text": "Create a database in MS-SQL Server Management Studio" }, { "code": null, "e": 25719, "s": 25685, "text": "Create a project in visual studio" }, { "code": null, "e": 25894, "s": 25719, "text": "1. Create a Database with the following columns: This is just a demo to make you understand the code in the article. You can create your own database according to your needs." }, { "code": null, "e": 26257, "s": 25894, "text": "2. Create a Project in Visual Studio Follow the guidelines that are given in the link provided above to create a project. After creating the project add entity data model to add connection string to your web.config file, to do so follow this article Add Entity Data Model to Your ASP.NET Project. The following EDMX diagram will be shown on your solution window." }, { "code": null, "e": 26369, "s": 26257, "text": "1. Create Now to create a new record in your database write the following code in the newly created controller." }, { "code": "using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc; namespace CRUDDemo.Controllers{ public class CRUDController : Controller { // To create View of this Action result public ActionResult create() { return View(); } // Specify the type of attribute i.e. // it will add the record to the database [HttpPost] public ActionResult create(Student model) { // To open a connection to the database using(var context = new demoCRUDEntities()) { // Add data to the particular table context.Student.Add(model); // save the changes context.SaveChanges(); } string message = \"Created the record successfully\"; // To display the message on the screen // after the record is created successfully ViewBag.Message = message; // write @Viewbag.Message in the created // view at the place where you want to // display the message return View(); } }}", "e": 27607, "s": 26369, "text": null }, { "code": null, "e": 27911, "s": 27607, "text": "After this write click on the first action result and click on AddView and then select template as Create and model class as your own created model and data context class as your own created EDMX model. Then run the project and go the URL https://localhost:port_number/Controller_name/Action_Method_name" }, { "code": null, "e": 27960, "s": 27911, "text": "For example, https://localhost:44326/CRUD/create" }, { "code": null, "e": 28038, "s": 27960, "text": "2. Read: Now to See the added data on your screen follow the below-given code" }, { "code": "using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc; namespace CRUDDemo.Controllers{ public class CRUDController : Controller { [HttpGet] // Set the attribute to Read public ActionResult Read() { using(var context = new demoCRUDEntities()) { // Return the list of data from the database var data = context.Student.ToList(); return View(data); } } }}", "e": 28585, "s": 28038, "text": null }, { "code": null, "e": 28802, "s": 28585, "text": "After this add the View but remember to change the template as List. Then run the project and go to the URLhttps://localhost:port_number/Controller_name/Action_Method_nameFor Example https://localhost:44326/CRUD/Read" }, { "code": null, "e": 28876, "s": 28802, "text": "3. Update: Now, to update the existing record follow the code given below" }, { "code": "using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc; namespace CRUDDemo.Controllers{ public class CRUDController : Controller { // To fill data in the form // to enable easy editing public ActionResult Update(int Studentid) { using(var context = new demoCRUDEntities()) { var data = context.Student.Where(x => x.StudentNo == Studentid).SingleOrDefault(); return View(data); } } // To specify that this will be // invoked when post method is called [HttpPost] [ValidateAntiForgeryToken] public ActionResult Update(int Studentid, Student model) { using(var context = new demoCRUDEntities()) { // Use of lambda expression to access // particular record from a database var data = context.Student.FirstOrDefault(x => x.StudentNo == Studentid); // Checking if any such record exist if (data != null) { data.Name = model.Name; data.Section = model.Section; data.EmailId = model.EmailId; data.Branch = model.Branch; context.SaveChanges(); // It will redirect to // the Read method return RedirectToAction(\"Read\"); } else return View(); } } }}", "e": 30522, "s": 28876, "text": null }, { "code": null, "e": 30738, "s": 30522, "text": "After this add view similarly as done previously but remember to change the template to Edit. Then run the project and go to the URL https://localhost:port_number/Controller_name/Action_Method_name?ID_U_want_to_edit" }, { "code": null, "e": 30799, "s": 30738, "text": "For Example, https://localhost:44326/CRUD/Update?Studentid=1" }, { "code": null, "e": 30879, "s": 30799, "text": "4. Delete Now, to delete a record from the database follow the code given below" }, { "code": "using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc; namespace CRUDDemo.Controllers{ public class CRUDController : Controller { public ActionResult Delete() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Delete(int Studentid) { using(var context = new demoCRUDEntities()) { var data = context.Student.FirstOrDefault(x = > x.StudentNo == Studentid); if (data != null) { context.Student.Remove(data); context.SaveChanges(); return RedirectToAction(\"Read\"); } else return View(); } } }}", "e": 31688, "s": 30879, "text": null }, { "code": null, "e": 31961, "s": 31688, "text": "After this added view as done previously, but remember to change the template to Delete. Then run the project and go to the URL https://localhost:port_number/Controller_name/Action_Method_name?ID_U_want_to_DeleteFor Example, https://localhost:44326/CRUD/Delete?Studentid=1" }, { "code": null, "e": 31967, "s": 31961, "text": "Note:" }, { "code": null, "e": 32033, "s": 31967, "text": "The auto-generated HTML can be modified according to your choice." }, { "code": null, "e": 32164, "s": 32033, "text": "If you want to have a look at the full source code and how it works you can view my GitHub repository by clicking the GitHub Link." }, { "code": null, "e": 32179, "s": 32164, "text": "CSharp ASP-NET" }, { "code": null, "e": 32182, "s": 32179, "text": "C#" }, { "code": null, "e": 32280, "s": 32182, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32289, "s": 32280, "text": "Comments" }, { "code": null, "e": 32302, "s": 32289, "text": "Old Comments" }, { "code": null, "e": 32330, "s": 32302, "text": "C# Dictionary with examples" }, { "code": null, "e": 32376, "s": 32330, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 32391, "s": 32376, "text": "C# | Delegates" }, { "code": null, "e": 32431, "s": 32391, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 32454, "s": 32431, "text": "Extension Method in C#" }, { "code": null, "e": 32476, "s": 32454, "text": "C# | Abstract Classes" }, { "code": null, "e": 32516, "s": 32476, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 32574, "s": 32516, "text": "Different ways to sort an array in descending order in C#" }, { "code": null, "e": 32586, "s": 32574, "text": "C# | Arrays" } ]
Autorun a Python script on windows startup - GeeksforGeeks
14 Sep, 2021 Adding a Python script to windows start-up basically means the python script will run as the windows boots up. This can be done by two step process – Step #1: Adding script to windows Startup folder After the windows boots up it runs (equivalent to double-clicking) all the application present in its startup directory. Address: C:\Users\current_user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\ By default the AppData folder under the current_user is hidden so enable hidden files to get it and paste the shortcut of the script in the given address or the script itself. Also the .PY files default must be set to python IDE else the script may end up opening as a text instead of executing. Step #2: Adding script to windows Registry This process can be risky if not done properly, it involves editing the windows registry key HKEY_CURRENT_USER from the python script itself. This registry contains the list of programs that must run once the user Login. just like few application which pops up when windows starts because the cause change in registry and add their application path to it. Registry Path: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run Below is the Python code : Python3 # Python code to add current script to the registry # module to edit the windows registryimport winreg as regimport os def AddToRegistry(): # in python __file__ is the instant of # file path where it was executed # so if it was executed from desktop, # then __file__ will be # c:\users\current_user\desktop pth = os.path.dirname(os.path.realpath(__file__)) # name of the python file with extension s_name="mYscript.py" # joins the file name to end of path address address=os.join(pth,s_name) # key we want to change is HKEY_CURRENT_USER # key value is Software\Microsoft\Windows\CurrentVersion\Run key = HKEY_CURRENT_USER key_value = "Software\Microsoft\Windows\CurrentVersion\Run" # open the key to make changes to open = reg.OpenKey(key,key_value,0,reg.KEY_ALL_ACCESS) # modify the opened key reg.SetValueEx(open,"any_name",0,reg.REG_SZ,address) # now close the opened key reg.CloseKey(open) # Driver Codeif __name__=="__main__": AddToRegistry() Note: Further codes can be added to this script for the task to be performed at every startup and the script must be run as Administrator for the first time. sagartomar9927 python-utility Python TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python How to Find the Wi-Fi Password Using CMD in Windows? Docker - COPY Instruction How to Run a Python Script using Docker? Running Python script on GPU. Top Programming Languages for Android App Development
[ { "code": null, "e": 24053, "s": 24025, "text": "\n14 Sep, 2021" }, { "code": null, "e": 24203, "s": 24053, "text": "Adding a Python script to windows start-up basically means the python script will run as the windows boots up. This can be done by two step process –" }, { "code": null, "e": 24374, "s": 24203, "text": "Step #1: Adding script to windows Startup folder After the windows boots up it runs (equivalent to double-clicking) all the application present in its startup directory. " }, { "code": null, "e": 24384, "s": 24374, "text": "Address: " }, { "code": null, "e": 24471, "s": 24384, "text": "C:\\Users\\current_user\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\ " }, { "code": null, "e": 25168, "s": 24471, "text": "By default the AppData folder under the current_user is hidden so enable hidden files to get it and paste the shortcut of the script in the given address or the script itself. Also the .PY files default must be set to python IDE else the script may end up opening as a text instead of executing. Step #2: Adding script to windows Registry This process can be risky if not done properly, it involves editing the windows registry key HKEY_CURRENT_USER from the python script itself. This registry contains the list of programs that must run once the user Login. just like few application which pops up when windows starts because the cause change in registry and add their application path to it." }, { "code": null, "e": 25183, "s": 25168, "text": "Registry Path:" }, { "code": null, "e": 25247, "s": 25183, "text": "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run" }, { "code": null, "e": 25275, "s": 25247, "text": "Below is the Python code : " }, { "code": null, "e": 25283, "s": 25275, "text": "Python3" }, { "code": "# Python code to add current script to the registry # module to edit the windows registryimport winreg as regimport os def AddToRegistry(): # in python __file__ is the instant of # file path where it was executed # so if it was executed from desktop, # then __file__ will be # c:\\users\\current_user\\desktop pth = os.path.dirname(os.path.realpath(__file__)) # name of the python file with extension s_name=\"mYscript.py\" # joins the file name to end of path address address=os.join(pth,s_name) # key we want to change is HKEY_CURRENT_USER # key value is Software\\Microsoft\\Windows\\CurrentVersion\\Run key = HKEY_CURRENT_USER key_value = \"Software\\Microsoft\\Windows\\CurrentVersion\\Run\" # open the key to make changes to open = reg.OpenKey(key,key_value,0,reg.KEY_ALL_ACCESS) # modify the opened key reg.SetValueEx(open,\"any_name\",0,reg.REG_SZ,address) # now close the opened key reg.CloseKey(open) # Driver Codeif __name__==\"__main__\": AddToRegistry()", "e": 26341, "s": 25283, "text": null }, { "code": null, "e": 26500, "s": 26341, "text": "Note: Further codes can be added to this script for the task to be performed at every startup and the script must be run as Administrator for the first time. " }, { "code": null, "e": 26515, "s": 26500, "text": "sagartomar9927" }, { "code": null, "e": 26530, "s": 26515, "text": "python-utility" }, { "code": null, "e": 26537, "s": 26530, "text": "Python" }, { "code": null, "e": 26546, "s": 26537, "text": "TechTips" }, { "code": null, "e": 26644, "s": 26546, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26653, "s": 26644, "text": "Comments" }, { "code": null, "e": 26666, "s": 26653, "text": "Old Comments" }, { "code": null, "e": 26684, "s": 26666, "text": "Python Dictionary" }, { "code": null, "e": 26719, "s": 26684, "text": "Read a file line by line in Python" }, { "code": null, "e": 26741, "s": 26719, "text": "Enumerate() in Python" }, { "code": null, "e": 26773, "s": 26741, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26803, "s": 26773, "text": "Iterate over a list in Python" }, { "code": null, "e": 26856, "s": 26803, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 26882, "s": 26856, "text": "Docker - COPY Instruction" }, { "code": null, "e": 26923, "s": 26882, "text": "How to Run a Python Script using Docker?" }, { "code": null, "e": 26953, "s": 26923, "text": "Running Python script on GPU." } ]
How to Strip Outputs and Execute Interactive Code in a Python Script | by Khuyen Tran | Towards Data Science
Have you ever seen a tutorial with an interactive Python code like this: ...and wished to get only the code that can be executed like below? It might be time-consuming to delete all >>> symbols and remove all outputs, especially when the code is long. Is there a way that you can get the clean inputs like above in one line of code? That is why I created a package called strip-interactive. In this article, I will show you how to use this package to do exactly that. To install strip-interactive, type: pip install strip-interactive Let’s use strip-interactive to extract clean inputs from interactive Python code: Output: import numpy as npprint(np.array([1,2,3]))print(np.array([4,5,6])) Cool! Now, these clean inputs are ready to be executed. To execute the inputs we have just got from get_clean_code , use theexec method: [1 2 3][4 5 6] If you prefer to execute interactive Python code in one step, use therun_interactive method: Output: [1 2 3][4 5 6] Awesome! Using therun_interactive method gives us the same outputs as using theget_clean_code and the exec methods. I believe yes, but it is better to test it out. Outputs: [1 2 3] Great, it works! Note that there will be no outputs if you use run_interactive for the code like below: So make sure to addprint to np.array([1,2,3]) to see the outputs: Output: [1 2 3] Congratulations! You have just learned how to execute interactive Python code in your Python script in one line of code using strip-interactive. This will come in handy when you want to quickly try out the interactive Python code in an article or documentation. The code of this article could be found here. If you see how this package can be improved, feel free to contribute or submit an issue here. I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter. Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
[ { "code": null, "e": 245, "s": 172, "text": "Have you ever seen a tutorial with an interactive Python code like this:" }, { "code": null, "e": 313, "s": 245, "text": "...and wished to get only the code that can be executed like below?" }, { "code": null, "e": 505, "s": 313, "text": "It might be time-consuming to delete all >>> symbols and remove all outputs, especially when the code is long. Is there a way that you can get the clean inputs like above in one line of code?" }, { "code": null, "e": 640, "s": 505, "text": "That is why I created a package called strip-interactive. In this article, I will show you how to use this package to do exactly that." }, { "code": null, "e": 676, "s": 640, "text": "To install strip-interactive, type:" }, { "code": null, "e": 706, "s": 676, "text": "pip install strip-interactive" }, { "code": null, "e": 788, "s": 706, "text": "Let’s use strip-interactive to extract clean inputs from interactive Python code:" }, { "code": null, "e": 796, "s": 788, "text": "Output:" }, { "code": null, "e": 863, "s": 796, "text": "import numpy as npprint(np.array([1,2,3]))print(np.array([4,5,6]))" }, { "code": null, "e": 919, "s": 863, "text": "Cool! Now, these clean inputs are ready to be executed." }, { "code": null, "e": 1000, "s": 919, "text": "To execute the inputs we have just got from get_clean_code , use theexec method:" }, { "code": null, "e": 1015, "s": 1000, "text": "[1 2 3][4 5 6]" }, { "code": null, "e": 1108, "s": 1015, "text": "If you prefer to execute interactive Python code in one step, use therun_interactive method:" }, { "code": null, "e": 1116, "s": 1108, "text": "Output:" }, { "code": null, "e": 1131, "s": 1116, "text": "[1 2 3][4 5 6]" }, { "code": null, "e": 1247, "s": 1131, "text": "Awesome! Using therun_interactive method gives us the same outputs as using theget_clean_code and the exec methods." }, { "code": null, "e": 1295, "s": 1247, "text": "I believe yes, but it is better to test it out." }, { "code": null, "e": 1304, "s": 1295, "text": "Outputs:" }, { "code": null, "e": 1312, "s": 1304, "text": "[1 2 3]" }, { "code": null, "e": 1329, "s": 1312, "text": "Great, it works!" }, { "code": null, "e": 1416, "s": 1329, "text": "Note that there will be no outputs if you use run_interactive for the code like below:" }, { "code": null, "e": 1482, "s": 1416, "text": "So make sure to addprint to np.array([1,2,3]) to see the outputs:" }, { "code": null, "e": 1490, "s": 1482, "text": "Output:" }, { "code": null, "e": 1498, "s": 1490, "text": "[1 2 3]" }, { "code": null, "e": 1760, "s": 1498, "text": "Congratulations! You have just learned how to execute interactive Python code in your Python script in one line of code using strip-interactive. This will come in handy when you want to quickly try out the interactive Python code in an article or documentation." }, { "code": null, "e": 1900, "s": 1760, "text": "The code of this article could be found here. If you see how this package can be improved, feel free to contribute or submit an issue here." }, { "code": null, "e": 2060, "s": 1900, "text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter." } ]
C++ Program to Check Cycle in a Graph using Topological Sort
In a Directed Acyclic Graph, we can sort vertices in linear order using topological sort. Topological sort is only work on Directed Acyclic Graph. In a Directed Acyclic Graph (DAG), there can be more than one topological sort. We shall consider a C++ program, which will perform topological sort to check cycle in a graph. Topological Sort: Begin Declare topo_sort(int *v, int T_S[][5], int i) function a = new NodeInfo. a->n = i a->S_Time = cn. Call push_node(a) function to insert data. v[i] = 1. for (int j = 0; j < 5; j++) if (T_S[i][j] == 0 || (T_S[i][j] == 1 && v[j] == 1)) then continue. else if(T_S[i][j] == 1 && v[j] == 0) then cn++. Call topo_sort(v,T_S, j) function. cn++. a = pop(). a->L_Time = cn. Store_Node(a). End. #include<iostream> #include<conio.h> using namespace std; struct NodeInfo { int n; int L_Time, S_Time; } *a = NULL; struct Node { NodeInfo *ptr; Node *nxt; } *t = NULL, *b = NULL, *npt = NULL; struct Node_Link { Node_Link *lk; NodeInfo *ptr1; } *hd = NULL, *m = NULL, *n = NULL, *npt1 = NULL; int cn = 0; bool flag = false; void push_node(NodeInfo *pt) { //insert data npt = new Node; npt->ptr = pt; npt->nxt = NULL; if (t == NULL) { t = npt; } else { npt->nxt = t; t = npt; } } NodeInfo *pop() { if (t == NULL) { cout<<"underflow\n"; } else { b = t; t = t->nxt; return(b->ptr); delete(b); } } void Store_Node(NodeInfo *pt1) { //store data npt1 = new Node_Link; npt1->ptr1 = pt1; npt1->lk = NULL; if (cn == 0) { hd = npt1; m = hd; m->lk = NULL; cn++; } else { m = hd; npt1->lk = m; hd = npt1; } } void delete_node(int x) { //delete node m = hd; if ((m->ptr1)->n == x) { hd = hd->lk; delete(m); } else { while ((m->ptr1)->n != x && m->lk != NULL) { n = m; m = m->lk; } if ((m->ptr1)->n == x) { n->lk = m->lk; delete(m); } else if (m->lk == NULL) { flag = true; cout<<"There is no circle in this graph\n"; } } } void topo_sort(int *v, int T_S[][5], int i) { //performing topological sort a = new NodeInfo; a->n = i; a->S_Time = cn; push_node(a); v[i] = 1; for (int j = 0; j < 5; j++) { if (T_S[i][j] == 0 || (T_S[i][j] == 1 && v[j] == 1)) continue; else if(T_S[i][j] == 1 && v[j] == 0) { cn++; topo_sort(v,T_S,j); } } cn++; a = pop(); a->L_Time = cn; Store_Node(a); return; } void topologic_sort(int *v, int T_S[][5], int i) { v[i] = 1; delete_node(i); for (int j = 0; j < 5; j++) { if (T_S[i][j] == 0 || (T_S[i][j] == 1 && v[j] == 1)) { continue; } else if(T_S[i][j] == 1 && v[j] == 0) { topologic_sort(v, T_S, j); } } return; } void Insert_Edge(int T_S[][5], int source, int destination) { // insert the value of edge. T_S[source][destination] = 1; return; } int main() { int v[5], T_S[5][5], T_S_N[5][5], cn = 0, a, b; for (int i = 0; i < 5; i++) { v[i] = 0; } for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { T_S[i][j] = 0; } } while (cn < 5) { cout<<"Enter the source: "; cin>>a; cout<<"Enter the destination: "; cin>>b; cout<<endl; Insert_Edge(T_S, a, b); cn++; } topo_sort(v, T_S, 0); for (int i = 0; i < 5; i++) { v[i] = 0; for (int j = 0; j < 5; j++) { T_S_N[j][i] = T_S[i][j]; } } if (hd != NULL) { topologic_sort(v, T_S_N, (hd->ptr1)->n); if (flag == false) { cout<<"There is a cycle in this graph...\n"; } } getch(); } Enter the source: 0 Enter the destination: 1 Enter the source: 1 Enter the destination: 2 Enter the source: 2 Enter the destination: 3 Enter the source: 3 Enter the destination: 4 Enter the source: 4 Enter the destination: 0 There is a cycle in this graph...
[ { "code": null, "e": 1152, "s": 1062, "text": "In a Directed Acyclic Graph, we can sort vertices in linear order using topological sort." }, { "code": null, "e": 1289, "s": 1152, "text": "Topological sort is only work on Directed Acyclic Graph. In a Directed Acyclic Graph (DAG), there can be more than one topological sort." }, { "code": null, "e": 1385, "s": 1289, "text": "We shall consider a C++ program, which will perform topological sort to check cycle in a graph." }, { "code": null, "e": 1910, "s": 1385, "text": "Topological Sort:\nBegin\n Declare topo_sort(int *v, int T_S[][5], int i) function\n a = new NodeInfo.\n a->n = i\n a->S_Time = cn.\n Call push_node(a) function to insert data.\n v[i] = 1.\n for (int j = 0; j < 5; j++)\n if (T_S[i][j] == 0 || (T_S[i][j] == 1 && v[j] == 1)) then\n continue.\n else if(T_S[i][j] == 1 && v[j] == 0) then\n cn++.\n Call topo_sort(v,T_S, j) function.\n cn++.\n a = pop().\n a->L_Time = cn.\n Store_Node(a).\nEnd." }, { "code": null, "e": 4911, "s": 1910, "text": "#include<iostream>\n#include<conio.h>\nusing namespace std;\nstruct NodeInfo {\n int n;\n int L_Time, S_Time;\n}\n*a = NULL;\nstruct Node {\n NodeInfo *ptr;\n Node *nxt;\n}\n*t = NULL, *b = NULL, *npt = NULL;\nstruct Node_Link {\n Node_Link *lk;\n NodeInfo *ptr1;\n}\n*hd = NULL, *m = NULL, *n = NULL, *npt1 = NULL;\nint cn = 0;\nbool flag = false;\nvoid push_node(NodeInfo *pt) { //insert data\n npt = new Node;\n npt->ptr = pt;\n npt->nxt = NULL;\n if (t == NULL) {\n t = npt;\n } else {\n npt->nxt = t;\n t = npt;\n }\n}\nNodeInfo *pop() {\n if (t == NULL) {\n cout<<\"underflow\\n\";\n } else {\n b = t;\n t = t->nxt;\n return(b->ptr);\n delete(b);\n }\n}\nvoid Store_Node(NodeInfo *pt1) { //store data\n npt1 = new Node_Link;\n npt1->ptr1 = pt1;\n npt1->lk = NULL;\n if (cn == 0) {\n hd = npt1;\n m = hd;\n m->lk = NULL;\n cn++;\n } else {\n m = hd;\n npt1->lk = m;\n hd = npt1;\n }\n}\nvoid delete_node(int x) { //delete node\n m = hd;\n if ((m->ptr1)->n == x) {\n hd = hd->lk;\n delete(m);\n } else {\n while ((m->ptr1)->n != x && m->lk != NULL) {\n n = m;\n m = m->lk;\n }\n if ((m->ptr1)->n == x) {\n n->lk = m->lk;\n delete(m);\n } else if (m->lk == NULL) {\n flag = true;\n cout<<\"There is no circle in this graph\\n\";\n }\n }\n}\nvoid topo_sort(int *v, int T_S[][5], int i) { //performing topological sort\n a = new NodeInfo;\n a->n = i;\n a->S_Time = cn;\n push_node(a);\n v[i] = 1;\n for (int j = 0; j < 5; j++) {\n if (T_S[i][j] == 0 || (T_S[i][j] == 1 && v[j] == 1))\n continue;\n else if(T_S[i][j] == 1 && v[j] == 0) {\n cn++;\n topo_sort(v,T_S,j);\n }\n }\n cn++;\n a = pop();\n a->L_Time = cn;\n Store_Node(a);\n return;\n}\nvoid topologic_sort(int *v, int T_S[][5], int i) {\n v[i] = 1;\n delete_node(i);\n for (int j = 0; j < 5; j++) {\n if (T_S[i][j] == 0 || (T_S[i][j] == 1 && v[j] == 1)) {\n continue;\n } else if(T_S[i][j] == 1 && v[j] == 0) {\n topologic_sort(v, T_S, j);\n }\n }\n return;\n}\nvoid Insert_Edge(int T_S[][5], int source, int destination) { // insert the value of edge.\n T_S[source][destination] = 1;\n return;\n}\nint main() {\n int v[5], T_S[5][5], T_S_N[5][5], cn = 0, a, b;\n for (int i = 0; i < 5; i++) {\n v[i] = 0;\n }\n for (int i = 0; i < 5; i++) {\n for (int j = 0; j < 5; j++) {\n T_S[i][j] = 0;\n }\n }\n while (cn < 5) {\n cout<<\"Enter the source: \";\n cin>>a;\n cout<<\"Enter the destination: \";\n cin>>b;\n cout<<endl;\n Insert_Edge(T_S, a, b);\n cn++;\n }\n topo_sort(v, T_S, 0);\n for (int i = 0; i < 5; i++) {\n v[i] = 0;\n for (int j = 0; j < 5; j++) {\n T_S_N[j][i] = T_S[i][j];\n }\n }\n if (hd != NULL) {\n topologic_sort(v, T_S_N, (hd->ptr1)->n);\n if (flag == false) {\n cout<<\"There is a cycle in this graph...\\n\";\n }\n }\n getch();\n}" }, { "code": null, "e": 5175, "s": 4911, "text": "Enter the source: 0\nEnter the destination: 1\n\nEnter the source: 1\nEnter the destination: 2\n\nEnter the source: 2\nEnter the destination: 3\n\nEnter the source: 3\nEnter the destination: 4\n\nEnter the source: 4\nEnter the destination: 0\n\nThere is a cycle in this graph..." } ]
Plotting regression and residual plot in Matplotlib
To establish a simple relationship between the observations of a given joint distribution of a variable, we can create the plot for the regression model using Seaborn. To fit the dataset using the regression model, we have to first import the necessary libraries in Python. We will create plots for each regression model, (a) Linear Regression, (b) Polynomial Regression, and (c) Logistic Regression. In this example, we will use the wine quality dataset which can be accessed from here, https://archive.ics.uci.edu/ml/datasets/wine+quality import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import pearsonr sns.set(style="dark", color_codes=True) #import the dataset wine_quality = pd.read_csv('winequality-red.csv', delimiter=';') #Plotting Linear Regression R, p = pearsonr(wine_quality['fixed acidity'], wine_quality.pH) g1 = sns.regplot(x='fixed acidity', y='pH', data=wine_quality, truncate=True, ci=99, marker='D', scatter_kws={'color': 'r'}); textstr = '$\mathrm{pearson}\hspace{0.5}\mathrm{R}^2=%.2f$\n$\mathrm{pval}=%.2e$ '% (R**2, p) props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) g1.text(0.55, 0.95, textstr, fontsize=14, va='top', bbox=props) plt.title('1. Linear Regression', size=15, color='b', weight='bold') #Let us Plot the Polynomial Regression plot for the wine dataset g2 = sns.regplot(x='fixed acidity', y='pH', data=wine_quality, order=2, ci=None, marker='s', scatter_kws={'color': 'skyblue'}, line_kws={'color': 'red'}); plt.title('2. Polynomial Regression', size=15, color='r', weight='bold') #Now plotting the Logistic Regression wine_quality['Q'] = wine_quality['quality'].map({'Low': 0, 'Med': 0, 'High':1}) g2 = sns.regplot(x='fixed acidity', y='Q', logistic=True, n_boot=750, y_jitter=.03, data=wine_quality, line_kws={'color': 'r'}) plt.show(); #Now plot the residual plot g3 = sns.residplot(x='fixed acidity', y='density', order=2, data=wine_quality, scatter_kws={'color': 'r', 'alpha': 0.5}); plt.show(); Running the above code will generate the output as,
[ { "code": null, "e": 1230, "s": 1062, "text": "To establish a simple relationship between the observations of a given joint distribution of a variable, we can create the plot for the regression model using Seaborn." }, { "code": null, "e": 1336, "s": 1230, "text": "To fit the dataset using the regression model, we have to first import the necessary libraries in Python." }, { "code": null, "e": 1463, "s": 1336, "text": "We will create plots for each regression model, (a) Linear Regression, (b) Polynomial Regression, and (c) Logistic Regression." }, { "code": null, "e": 1603, "s": 1463, "text": "In this example, we will use the wine\nquality\ndataset which can be accessed from here, https://archive.ics.uci.edu/ml/datasets/wine+quality" }, { "code": null, "e": 3057, "s": 1603, "text": "import matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy.stats import pearsonr\nsns.set(style=\"dark\", color_codes=True)\n\n#import the dataset\nwine_quality = pd.read_csv('winequality-red.csv', delimiter=';')\n\n#Plotting Linear Regression\nR, p = pearsonr(wine_quality['fixed acidity'], wine_quality.pH)\ng1 = sns.regplot(x='fixed acidity', y='pH', data=wine_quality, truncate=True, ci=99,\nmarker='D', scatter_kws={'color': 'r'});\ntextstr = '$\\mathrm{pearson}\\hspace{0.5}\\mathrm{R}^2=%.2f$\\n$\\mathrm{pval}=%.2e$ '% (R**2, p)\nprops = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\ng1.text(0.55, 0.95, textstr, fontsize=14, va='top', bbox=props)\nplt.title('1. Linear Regression', size=15, color='b', weight='bold')\n\n#Let us Plot the Polynomial Regression plot for the wine dataset\ng2 = sns.regplot(x='fixed acidity', y='pH', data=wine_quality, order=2, ci=None,\n marker='s', scatter_kws={'color': 'skyblue'},\n line_kws={'color': 'red'});\nplt.title('2. Polynomial Regression', size=15, color='r', weight='bold')\n\n#Now plotting the Logistic Regression\nwine_quality['Q'] = wine_quality['quality'].map({'Low': 0, 'Med': 0, 'High':1})\ng2 = sns.regplot(x='fixed acidity', y='Q', logistic=True,\n n_boot=750, y_jitter=.03, data=wine_quality,\n line_kws={'color': 'r'})\nplt.show();\n\n#Now plot the residual plot\ng3 = sns.residplot(x='fixed acidity', y='density', order=2,\n data=wine_quality, scatter_kws={'color': 'r',\n 'alpha': 0.5});\nplt.show();" }, { "code": null, "e": 3109, "s": 3057, "text": "Running the above code will generate the output as," } ]
Diagonal sum | Practice | GeeksforGeeks
Given a square matrix of size n×n. Your task is to calculate the sum of its diagonals. Example 1: Input: matrix = {{1, 1, 1}, {1, 1, 1}, {1, 1, 1}} Output: 6 Example 2: Input: matrix = {{1, 2}, {3, 4}} Output: 10 Your Task: You don't need to read or print anyhting. Your task is to complete the function DiagonalSum() which takes the matrix as input parameter and returns the sum of its diagonals. Expected Time Complexity: O(n) Expected Space Complexity: O(1) Constraints: 1 <= n <= 100 1 <= matrix elements <= 10000 0 cshubham4393 months ago int sum = 0; for(int i =0; i<matrix.length; i++){ for(int j = 0; j<matrix.length; j++){ if(i==j){ sum = sum+matrix[i][j]; } if(i+j==matrix.length-1){ sum = sum+matrix[i][j]; } } } return sum; -2 keshrishivam41143 months ago complexity - O(n) def DiagonalSum(self, matrix): summ=0 for i in range(len(matrix)): summ += matrix[i][i]+matrix[i][len(matrix)-1-i] return summ 0 pankajkumarravi6 months ago public int DiagonalSum(int[][] matrix){int sd1 = 0 , sd2 = 0;int j = 0 , len = matrix.length - 1 , j1 = 0;for(int i = 0; i < matrix.length; i++){j = i;sd1 = sd1 + matrix[i][j];j1 = len - j;sd2 = sd2 + matrix[i][j1];}return sd1 + sd2;} -1 pankajkumarravi6 months ago Code looks working , here in this platform, few cases failed public int DiagonalSum(int[][] matrix) { // code here int diagonalSum=0; for ( int i=0;i<matrix.length;i++){ for (int j=0;j<matrix.length;j++){ if (i==j) diagonalSum =diagonalSum+matrix[i][j]; } } return diagonalSum; } 0 mrshobhit7 months ago Python 3: Execution Time - 0.1 Sec import numpy as np class Solution: def DiagonalSum(self, matrix): # Code here matrix=np.array(matrix) return (matrix.trace())+(matrix[::-1].trace()) 0 Hardik Gupta8 months ago Hardik Gupta SOLUTION IN JAVA class Solution{ public int DiagonalSum(int[][] matrix) { int sd1 = 0 , sd2 = 0; int j = 0 , len = matrix.length - 1 , j1 = 0; for(int i = 0; i < matrix.length; i++){ j = i; sd1 = sd1 + matrix[i][j]; j1 = len - j; sd2 = sd2 + matrix[i][j1]; } return sd1 + sd2; }} 0 Shreya Nayak9 months ago Shreya Nayak int DiagonalSum(vector<vector<int> >& matrix) { // Code here int s=0,s1=0; for(int i=0;i<matrix.size();i++) {="" for(int="" j="0;j&lt;matrix.size();j++)" {="" if(i="=j)" s+="matrix[i][j];" if(i="=matrix.size()-j-1)" s1+="matrix[i][j];" }="" }="" return="" (s+s1);="" }=""> 0 Shreyansh Kumar Singh1 year ago Shreyansh Kumar Singh https://uploads.disquscdn.c... 0 Shreyansh Kumar Singh This comment was deleted. 0 Tulsi Dey2 years ago Tulsi Dey Solution in Java:Execution time: 0.15 https://uploads.disquscdn.c... 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": 327, "s": 238, "text": "Given a square matrix of size n×n. Your task is to calculate the sum of its diagonals.\n " }, { "code": null, "e": 338, "s": 327, "text": "Example 1:" }, { "code": null, "e": 400, "s": 338, "text": "Input: matrix = {{1, 1, 1}, \n{1, 1, 1}, {1, 1, 1}}\nOutput: 6\n" }, { "code": null, "e": 411, "s": 400, "text": "Example 2:" }, { "code": null, "e": 456, "s": 411, "text": "Input: matrix = {{1, 2}, {3, 4}}\nOutput: 10\n" }, { "code": null, "e": 645, "s": 458, "text": "Your Task:\nYou don't need to read or print anyhting. Your task is to complete the function DiagonalSum() which takes the matrix as input parameter and returns the sum of its diagonals.\n " }, { "code": null, "e": 766, "s": 645, "text": "Expected Time Complexity: O(n)\nExpected Space Complexity: O(1)\n\nConstraints:\n1 <= n <= 100\n1 <= matrix elements <= 10000" }, { "code": null, "e": 768, "s": 766, "text": "0" }, { "code": null, "e": 792, "s": 768, "text": "cshubham4393 months ago" }, { "code": null, "e": 1115, "s": 792, "text": " int sum = 0; for(int i =0; i<matrix.length; i++){ for(int j = 0; j<matrix.length; j++){ if(i==j){ sum = sum+matrix[i][j]; } if(i+j==matrix.length-1){ sum = sum+matrix[i][j]; } } } return sum;" }, { "code": null, "e": 1118, "s": 1115, "text": "-2" }, { "code": null, "e": 1147, "s": 1118, "text": "keshrishivam41143 months ago" }, { "code": null, "e": 1165, "s": 1147, "text": "complexity - O(n)" }, { "code": null, "e": 1299, "s": 1165, "text": "def DiagonalSum(self, matrix): summ=0 for i in range(len(matrix)): summ += matrix[i][i]+matrix[i][len(matrix)-1-i] return summ" }, { "code": null, "e": 1301, "s": 1299, "text": "0" }, { "code": null, "e": 1329, "s": 1301, "text": "pankajkumarravi6 months ago" }, { "code": null, "e": 1564, "s": 1329, "text": "public int DiagonalSum(int[][] matrix){int sd1 = 0 , sd2 = 0;int j = 0 , len = matrix.length - 1 , j1 = 0;for(int i = 0; i < matrix.length; i++){j = i;sd1 = sd1 + matrix[i][j];j1 = len - j;sd2 = sd2 + matrix[i][j1];}return sd1 + sd2;}" }, { "code": null, "e": 1567, "s": 1564, "text": "-1" }, { "code": null, "e": 1595, "s": 1567, "text": "pankajkumarravi6 months ago" }, { "code": null, "e": 1656, "s": 1595, "text": "Code looks working , here in this platform, few cases failed" }, { "code": null, "e": 1965, "s": 1658, "text": " public int DiagonalSum(int[][] matrix) { // code here int diagonalSum=0; for ( int i=0;i<matrix.length;i++){ for (int j=0;j<matrix.length;j++){ if (i==j) diagonalSum =diagonalSum+matrix[i][j]; } } return diagonalSum; }" }, { "code": null, "e": 1967, "s": 1965, "text": "0" }, { "code": null, "e": 1989, "s": 1967, "text": "mrshobhit7 months ago" }, { "code": null, "e": 1999, "s": 1989, "text": "Python 3:" }, { "code": null, "e": 2024, "s": 1999, "text": "Execution Time - 0.1 Sec" }, { "code": null, "e": 2184, "s": 2028, "text": "import numpy as np\nclass Solution:\n\tdef DiagonalSum(self, matrix):\n\t\t# Code here\n\t\tmatrix=np.array(matrix)\n\t\treturn (matrix.trace())+(matrix[::-1].trace())" }, { "code": null, "e": 2186, "s": 2184, "text": "0" }, { "code": null, "e": 2211, "s": 2186, "text": "Hardik Gupta8 months ago" }, { "code": null, "e": 2224, "s": 2211, "text": "Hardik Gupta" }, { "code": null, "e": 2241, "s": 2224, "text": "SOLUTION IN JAVA" }, { "code": null, "e": 2592, "s": 2241, "text": "class Solution{ public int DiagonalSum(int[][] matrix) { int sd1 = 0 , sd2 = 0; int j = 0 , len = matrix.length - 1 , j1 = 0; for(int i = 0; i < matrix.length; i++){ j = i; sd1 = sd1 + matrix[i][j]; j1 = len - j; sd2 = sd2 + matrix[i][j1]; } return sd1 + sd2; }}" }, { "code": null, "e": 2594, "s": 2592, "text": "0" }, { "code": null, "e": 2619, "s": 2594, "text": "Shreya Nayak9 months ago" }, { "code": null, "e": 2632, "s": 2619, "text": "Shreya Nayak" }, { "code": null, "e": 2926, "s": 2632, "text": "int DiagonalSum(vector<vector<int> >& matrix) { // Code here int s=0,s1=0; for(int i=0;i<matrix.size();i++) {=\"\" for(int=\"\" j=\"0;j&lt;matrix.size();j++)\" {=\"\" if(i=\"=j)\" s+=\"matrix[i][j];\" if(i=\"=matrix.size()-j-1)\" s1+=\"matrix[i][j];\" }=\"\" }=\"\" return=\"\" (s+s1);=\"\" }=\"\">" }, { "code": null, "e": 2928, "s": 2926, "text": "0" }, { "code": null, "e": 2960, "s": 2928, "text": "Shreyansh Kumar Singh1 year ago" }, { "code": null, "e": 2982, "s": 2960, "text": "Shreyansh Kumar Singh" }, { "code": null, "e": 3013, "s": 2982, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 3015, "s": 3013, "text": "0" }, { "code": null, "e": 3037, "s": 3015, "text": "Shreyansh Kumar Singh" }, { "code": null, "e": 3063, "s": 3037, "text": "This comment was deleted." }, { "code": null, "e": 3065, "s": 3063, "text": "0" }, { "code": null, "e": 3086, "s": 3065, "text": "Tulsi Dey2 years ago" }, { "code": null, "e": 3096, "s": 3086, "text": "Tulsi Dey" }, { "code": null, "e": 3165, "s": 3096, "text": "Solution in Java:Execution time: 0.15 https://uploads.disquscdn.c..." }, { "code": null, "e": 3311, "s": 3165, "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": 3347, "s": 3311, "text": " Login to access your submissions. " }, { "code": null, "e": 3357, "s": 3347, "text": "\nProblem\n" }, { "code": null, "e": 3367, "s": 3357, "text": "\nContest\n" }, { "code": null, "e": 3430, "s": 3367, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3578, "s": 3430, "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": 3786, "s": 3578, "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": 3892, "s": 3786, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Dial's Algorithm (Optimized Dijkstra for small range weights) - GeeksforGeeks
08 Apr, 2022 Dijkstra’s shortest path algorithm runs in O(Elog V) time when implemented with adjacency list representation (See C implementation and STL based C++ implementations for details). Input : Source = 0, Maximum Weight W = 14 Output : Vertex Distance from Source 0 0 1 4 2 12 3 19 4 21 5 11 6 9 7 8 8 14 Can we optimize Dijkstra’s shortest path algorithm to work better than O(E log V) if maximum weight is small (or range of edge weights is small)? For example, in the above diagram, maximum weight is 14. Many a times the range of weights on edges in is in small range (i.e. all edge weight can be mapped to 0, 1, 2.. w where w is a small number). In that case, Dijkstra’s algorithm can be modified by using different data structure, buckets, which is called dial implementation of dijkstra’s algorithm. time complexity is O(E + WV) where W is maximum weight on any edge of graph, so we can see that, if W is small then this implementation runs much faster than traditional algorithm. Following are important observations. Maximum distance between any two node can be at max w(V – 1) (w is maximum edge weight and we can have at max V-1 edges between two vertices). In Dijkstra algorithm, distances are finalized in non-decreasing, i.e., distance of the closer (to given source) vertices is finalized before the distant vertices. AlgorithmBelow is complete algorithm: Maintains some buckets, numbered 0, 1, 2,...,wV.Bucket k contains all temporarily labeled nodes with distance equal to k.Nodes in each bucket are represented by list of vertices.Buckets 0, 1, 2,..wV are checked sequentially until the first non-empty bucket is found. Each node contained in the first non-empty bucket has the minimum distance label by definition.One by one, these nodes with minimum distance label are permanently labeled and deleted from the bucket during the scanning process.Thus operations involving vertex include:Checking if a bucket is emptyAdding a vertex to a bucketDeleting a vertex from a bucket.The position of a temporarily labeled vertex in the buckets is updated accordingly when the distance label of a vertex changes.Process repeated until all vertices are permanently labeled (or distances of all vertices are finalized). Maintains some buckets, numbered 0, 1, 2,...,wV. Bucket k contains all temporarily labeled nodes with distance equal to k. Nodes in each bucket are represented by list of vertices. Buckets 0, 1, 2,..wV are checked sequentially until the first non-empty bucket is found. Each node contained in the first non-empty bucket has the minimum distance label by definition. One by one, these nodes with minimum distance label are permanently labeled and deleted from the bucket during the scanning process. Thus operations involving vertex include:Checking if a bucket is emptyAdding a vertex to a bucketDeleting a vertex from a bucket. Checking if a bucket is empty Adding a vertex to a bucket Deleting a vertex from a bucket. The position of a temporarily labeled vertex in the buckets is updated accordingly when the distance label of a vertex changes. Process repeated until all vertices are permanently labeled (or distances of all vertices are finalized). ImplementationSince the maximum distance can be w(V – 1), we create wV buckets (more for simplicity of code) for implementation of algorithm which can be large if w is big. C // C++ Program for Dijkstra's dial implementation#include<bits/stdc++.h>using namespace std;# define INF 0x3f3f3f3f // This class represents a directed graph using// adjacency list representationclass Graph{ int V; // No. of vertices // In a weighted graph, we need to store vertex // and weight pair for every edge list< pair<int, int> > *adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int u, int v, int w); // prints shortest path from s void shortestPath(int s, int W);}; // Allocates memory for adjacency listGraph::Graph(int V){ this->V = V; adj = new list< pair<int, int> >[V];} // adds edge between u and v of weight wvoid Graph::addEdge(int u, int v, int w){ adj[u].push_back(make_pair(v, w)); adj[v].push_back(make_pair(u, w));} // Prints shortest paths from src to all other vertices.// W is the maximum weight of an edgevoid Graph::shortestPath(int src, int W){ /* With each distance, iterator to that vertex in its bucket is stored so that vertex can be deleted in O(1) at time of updation. So dist[i].first = distance of ith vertex from src vertex dits[i].second = iterator to vertex i in bucket number */ vector<pair<int, list<int>::iterator> > dist(V); // Initialize all distances as infinite (INF) for (int i = 0; i < V; i++) dist[i].first = INF; // Create buckets B[]. // B[i] keep vertex of distance label i list<int> B[W * V + 1]; B[0].push_back(src); dist[src].first = 0; // int idx = 0; while (1) { // Go sequentially through buckets till one non-empty // bucket is found while (B[idx].size() == 0 && idx < W*V) idx++; // If all buckets are empty, we are done. if (idx == W * V) break; // Take top vertex from bucket and pop it int u = B[idx].front(); B[idx].pop_front(); // Process all adjacents of extracted vertex 'u' and // update their distanced if required. for (auto i = adj[u].begin(); i != adj[u].end(); ++i) { int v = (*i).first; int weight = (*i).second; int du = dist[u].first; int dv = dist[v].first; // If there is shorted path to v through u. if (dv > du + weight) { // If dv is not INF then it must be in B[dv] // bucket, so erase its entry using iterator // in O(1) if (dv != INF) B[dv].erase(dist[v].second); // updating the distance dist[v].first = du + weight; dv = dist[v].first; // pushing vertex v into updated distance's bucket B[dv].push_front(v); // storing updated iterator in dist[v].second dist[v].second = B[dv].begin(); } } } // Print shortest distances stored in dist[] printf("Vertex Distance from Source\n"); for (int i = 0; i < V; ++i) printf("%d %d\n", i, dist[i].first);} // Driver program to test methods of graph classint main(){ // create the graph given in above figure int V = 9; Graph g(V); // making above shown graph g.addEdge(0, 1, 4); g.addEdge(0, 7, 8); g.addEdge(1, 2, 8); g.addEdge(1, 7, 11); g.addEdge(2, 3, 7); g.addEdge(2, 8, 2); g.addEdge(2, 5, 4); g.addEdge(3, 4, 9); g.addEdge(3, 5, 14); g.addEdge(4, 5, 10); g.addEdge(5, 6, 2); g.addEdge(6, 7, 1); g.addEdge(6, 8, 6); g.addEdge(7, 8, 7); // maximum weighted edge - 14 g.shortestPath(0, 14); return 0;} Output: Vertex Distance from Source 0 0 1 4 2 12 3 19 4 21 5 11 6 9 7 8 8 14 IllustrationBelow is step by step illustration taken from here. YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=PwJwc5oj8cw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. surinderdawra388 Dijkstra Shortest Path Graph Greedy Greedy Graph Shortest Path Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Best First Search (Informed Search) Eulerian path and circuit for undirected graph Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm) Find if there is a path between two vertices in a directed graph Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS) Program for array rotation Huffman Coding | Greedy Algo-3 Write a program to print all permutations of a given string Fractional Knapsack Problem Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
[ { "code": null, "e": 25092, "s": 25064, "text": "\n08 Apr, 2022" }, { "code": null, "e": 25272, "s": 25092, "text": "Dijkstra’s shortest path algorithm runs in O(Elog V) time when implemented with adjacency list representation (See C implementation and STL based C++ implementations for details)." }, { "code": null, "e": 25608, "s": 25272, "text": "\nInput : Source = 0, Maximum Weight W = 14\nOutput : \n Vertex Distance from Source\n 0 0\n 1 4\n 2 12\n 3 19\n 4 21\n 5 11\n 6 9\n 7 8\n 8 14" }, { "code": null, "e": 26329, "s": 25608, "text": "Can we optimize Dijkstra’s shortest path algorithm to work better than O(E log V) if maximum weight is small (or range of edge weights is small)? For example, in the above diagram, maximum weight is 14. Many a times the range of weights on edges in is in small range (i.e. all edge weight can be mapped to 0, 1, 2.. w where w is a small number). In that case, Dijkstra’s algorithm can be modified by using different data structure, buckets, which is called dial implementation of dijkstra’s algorithm. time complexity is O(E + WV) where W is maximum weight on any edge of graph, so we can see that, if W is small then this implementation runs much faster than traditional algorithm. Following are important observations." }, { "code": null, "e": 26472, "s": 26329, "text": "Maximum distance between any two node can be at max w(V – 1) (w is maximum edge weight and we can have at max V-1 edges between two vertices)." }, { "code": null, "e": 26636, "s": 26472, "text": "In Dijkstra algorithm, distances are finalized in non-decreasing, i.e., distance of the closer (to given source) vertices is finalized before the distant vertices." }, { "code": null, "e": 26674, "s": 26636, "text": "AlgorithmBelow is complete algorithm:" }, { "code": null, "e": 27530, "s": 26674, "text": "Maintains some buckets, numbered 0, 1, 2,...,wV.Bucket k contains all temporarily labeled nodes with distance equal to k.Nodes in each bucket are represented by list of vertices.Buckets 0, 1, 2,..wV are checked sequentially until the first non-empty bucket is found. Each node contained in the first non-empty bucket has the minimum distance label by definition.One by one, these nodes with minimum distance label are permanently labeled and deleted from the bucket during the scanning process.Thus operations involving vertex include:Checking if a bucket is emptyAdding a vertex to a bucketDeleting a vertex from a bucket.The position of a temporarily labeled vertex in the buckets is updated accordingly when the distance label of a vertex changes.Process repeated until all vertices are permanently labeled (or distances of all vertices are finalized)." }, { "code": null, "e": 27579, "s": 27530, "text": "Maintains some buckets, numbered 0, 1, 2,...,wV." }, { "code": null, "e": 27653, "s": 27579, "text": "Bucket k contains all temporarily labeled nodes with distance equal to k." }, { "code": null, "e": 27711, "s": 27653, "text": "Nodes in each bucket are represented by list of vertices." }, { "code": null, "e": 27896, "s": 27711, "text": "Buckets 0, 1, 2,..wV are checked sequentially until the first non-empty bucket is found. Each node contained in the first non-empty bucket has the minimum distance label by definition." }, { "code": null, "e": 28029, "s": 27896, "text": "One by one, these nodes with minimum distance label are permanently labeled and deleted from the bucket during the scanning process." }, { "code": null, "e": 28159, "s": 28029, "text": "Thus operations involving vertex include:Checking if a bucket is emptyAdding a vertex to a bucketDeleting a vertex from a bucket." }, { "code": null, "e": 28189, "s": 28159, "text": "Checking if a bucket is empty" }, { "code": null, "e": 28217, "s": 28189, "text": "Adding a vertex to a bucket" }, { "code": null, "e": 28250, "s": 28217, "text": "Deleting a vertex from a bucket." }, { "code": null, "e": 28378, "s": 28250, "text": "The position of a temporarily labeled vertex in the buckets is updated accordingly when the distance label of a vertex changes." }, { "code": null, "e": 28484, "s": 28378, "text": "Process repeated until all vertices are permanently labeled (or distances of all vertices are finalized)." }, { "code": null, "e": 28659, "s": 28484, "text": " ImplementationSince the maximum distance can be w(V – 1), we create wV buckets (more for simplicity of code) for implementation of algorithm which can be large if w is big. " }, { "code": null, "e": 28661, "s": 28659, "text": "C" }, { "code": "// C++ Program for Dijkstra's dial implementation#include<bits/stdc++.h>using namespace std;# define INF 0x3f3f3f3f // This class represents a directed graph using// adjacency list representationclass Graph{ int V; // No. of vertices // In a weighted graph, we need to store vertex // and weight pair for every edge list< pair<int, int> > *adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int u, int v, int w); // prints shortest path from s void shortestPath(int s, int W);}; // Allocates memory for adjacency listGraph::Graph(int V){ this->V = V; adj = new list< pair<int, int> >[V];} // adds edge between u and v of weight wvoid Graph::addEdge(int u, int v, int w){ adj[u].push_back(make_pair(v, w)); adj[v].push_back(make_pair(u, w));} // Prints shortest paths from src to all other vertices.// W is the maximum weight of an edgevoid Graph::shortestPath(int src, int W){ /* With each distance, iterator to that vertex in its bucket is stored so that vertex can be deleted in O(1) at time of updation. So dist[i].first = distance of ith vertex from src vertex dits[i].second = iterator to vertex i in bucket number */ vector<pair<int, list<int>::iterator> > dist(V); // Initialize all distances as infinite (INF) for (int i = 0; i < V; i++) dist[i].first = INF; // Create buckets B[]. // B[i] keep vertex of distance label i list<int> B[W * V + 1]; B[0].push_back(src); dist[src].first = 0; // int idx = 0; while (1) { // Go sequentially through buckets till one non-empty // bucket is found while (B[idx].size() == 0 && idx < W*V) idx++; // If all buckets are empty, we are done. if (idx == W * V) break; // Take top vertex from bucket and pop it int u = B[idx].front(); B[idx].pop_front(); // Process all adjacents of extracted vertex 'u' and // update their distanced if required. for (auto i = adj[u].begin(); i != adj[u].end(); ++i) { int v = (*i).first; int weight = (*i).second; int du = dist[u].first; int dv = dist[v].first; // If there is shorted path to v through u. if (dv > du + weight) { // If dv is not INF then it must be in B[dv] // bucket, so erase its entry using iterator // in O(1) if (dv != INF) B[dv].erase(dist[v].second); // updating the distance dist[v].first = du + weight; dv = dist[v].first; // pushing vertex v into updated distance's bucket B[dv].push_front(v); // storing updated iterator in dist[v].second dist[v].second = B[dv].begin(); } } } // Print shortest distances stored in dist[] printf(\"Vertex Distance from Source\\n\"); for (int i = 0; i < V; ++i) printf(\"%d %d\\n\", i, dist[i].first);} // Driver program to test methods of graph classint main(){ // create the graph given in above figure int V = 9; Graph g(V); // making above shown graph g.addEdge(0, 1, 4); g.addEdge(0, 7, 8); g.addEdge(1, 2, 8); g.addEdge(1, 7, 11); g.addEdge(2, 3, 7); g.addEdge(2, 8, 2); g.addEdge(2, 5, 4); g.addEdge(3, 4, 9); g.addEdge(3, 5, 14); g.addEdge(4, 5, 10); g.addEdge(5, 6, 2); g.addEdge(6, 7, 1); g.addEdge(6, 8, 6); g.addEdge(7, 8, 7); // maximum weighted edge - 14 g.shortestPath(0, 14); return 0;}", "e": 32336, "s": 28661, "text": null }, { "code": null, "e": 32344, "s": 32336, "text": "Output:" }, { "code": null, "e": 32449, "s": 32344, "text": "Vertex Distance from Source\n0 0\n1 4\n2 12\n3 19\n4 21\n5 11\n6 9\n7 8\n8 14" }, { "code": null, "e": 32528, "s": 32449, "text": " IllustrationBelow is step by step illustration taken from here. " }, { "code": null, "e": 32820, "s": 32528, "text": "YouTube<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=PwJwc5oj8cw\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 32993, "s": 32820, "text": "This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 33010, "s": 32993, "text": "surinderdawra388" }, { "code": null, "e": 33019, "s": 33010, "text": "Dijkstra" }, { "code": null, "e": 33033, "s": 33019, "text": "Shortest Path" }, { "code": null, "e": 33039, "s": 33033, "text": "Graph" }, { "code": null, "e": 33046, "s": 33039, "text": "Greedy" }, { "code": null, "e": 33053, "s": 33046, "text": "Greedy" }, { "code": null, "e": 33059, "s": 33053, "text": "Graph" }, { "code": null, "e": 33073, "s": 33059, "text": "Shortest Path" }, { "code": null, "e": 33171, "s": 33073, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33180, "s": 33171, "text": "Comments" }, { "code": null, "e": 33193, "s": 33180, "text": "Old Comments" }, { "code": null, "e": 33229, "s": 33193, "text": "Best First Search (Informed Search)" }, { "code": null, "e": 33276, "s": 33229, "text": "Eulerian path and circuit for undirected graph" }, { "code": null, "e": 33346, "s": 33276, "text": "Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)" }, { "code": null, "e": 33411, "s": 33346, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 33492, "s": 33411, "text": "Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)" }, { "code": null, "e": 33519, "s": 33492, "text": "Program for array rotation" }, { "code": null, "e": 33550, "s": 33519, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 33610, "s": 33550, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 33638, "s": 33610, "text": "Fractional Knapsack Problem" } ]
Count the NaN values in one or more columns in Pandas DataFrame - GeeksforGeeks
17 Aug, 2020 Let us see how to count the total number of NaN values in one or more columns in a Pandas DataFrame. In order to count the NaN values in the DataFrame, we are required to assign a dictionary to the DataFrame and that dictionary should contain numpy.nan values which is a NaN(null) value. Consider the following DataFrame. # importing the modulesimport numpy as npimport pandas as pd # creating the DataFramedictionary = {'Names': ['Simon', 'Josh', 'Amen', 'Habby', 'Jonathan', 'Nick', 'Jake'], 'Capitals': ['VIENNA', np.nan, 'BRASILIA', np.nan, 'PARIS', 'DELHI', 'BERLIN'], 'Countries': ['AUSTRIA', 'BELGIUM', 'BRAZIL', np.nan, np.nan, 'INDIA', np.nan]}table = pd.DataFrame(dictionary, columns = ['Names', 'Capitals', 'Countries']) # displaying the DataFramedisplay(table) Output : Example 1 : Counting the NaN values in a single column. print("Number of null values in column 1 : " + str(table.iloc[:, 1].isnull().sum()))print("Number of null values in column 2 : " + str(table.iloc[:, 2].isnull().sum())) Output : Number of null values in column 1 : 2 Number of null values in column 2 : 3 Example 2 : Counting the NaN values in a single row. print("Number of null values in row 0 : " + str(table.iloc[0, ].isnull().sum()))print("Number of null values in row 1 : " + str(table.iloc[1, ].isnull().sum()))print("Number of null values in row 3 : " + str(table.iloc[3, ].isnull().sum())) Output : Number of null values in row 0 : 0 Number of null values in row 1 : 1 Number of null values in row 3 : 2 Example 3 : Counting the total NaN values in the DataFrame. print("Total Number of null values in the DataFrame : " + str(table.isnull().sum().sum())) Output : Total Number of null values in the DataFrame : 5 Example 4 : Counting the NaN values in all the columns. display(table.isnull().sum()) Output : Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? 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 Defaultdict in Python Python | os.path.join() method Python | Get unique values from a list Selecting rows in pandas DataFrame based on conditions Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n17 Aug, 2020" }, { "code": null, "e": 24580, "s": 24292, "text": "Let us see how to count the total number of NaN values in one or more columns in a Pandas DataFrame. In order to count the NaN values in the DataFrame, we are required to assign a dictionary to the DataFrame and that dictionary should contain numpy.nan values which is a NaN(null) value." }, { "code": null, "e": 24614, "s": 24580, "text": "Consider the following DataFrame." }, { "code": "# importing the modulesimport numpy as npimport pandas as pd # creating the DataFramedictionary = {'Names': ['Simon', 'Josh', 'Amen', 'Habby', 'Jonathan', 'Nick', 'Jake'], 'Capitals': ['VIENNA', np.nan, 'BRASILIA', np.nan, 'PARIS', 'DELHI', 'BERLIN'], 'Countries': ['AUSTRIA', 'BELGIUM', 'BRAZIL', np.nan, np.nan, 'INDIA', np.nan]}table = pd.DataFrame(dictionary, columns = ['Names', 'Capitals', 'Countries']) # displaying the DataFramedisplay(table)", "e": 25259, "s": 24614, "text": null }, { "code": null, "e": 25268, "s": 25259, "text": "Output :" }, { "code": null, "e": 25324, "s": 25268, "text": "Example 1 : Counting the NaN values in a single column." }, { "code": "print(\"Number of null values in column 1 : \" + str(table.iloc[:, 1].isnull().sum()))print(\"Number of null values in column 2 : \" + str(table.iloc[:, 2].isnull().sum()))", "e": 25507, "s": 25324, "text": null }, { "code": null, "e": 25516, "s": 25507, "text": "Output :" }, { "code": null, "e": 25593, "s": 25516, "text": "Number of null values in column 1 : 2\nNumber of null values in column 2 : 3\n" }, { "code": null, "e": 25646, "s": 25593, "text": "Example 2 : Counting the NaN values in a single row." }, { "code": "print(\"Number of null values in row 0 : \" + str(table.iloc[0, ].isnull().sum()))print(\"Number of null values in row 1 : \" + str(table.iloc[1, ].isnull().sum()))print(\"Number of null values in row 3 : \" + str(table.iloc[3, ].isnull().sum()))", "e": 25908, "s": 25646, "text": null }, { "code": null, "e": 25917, "s": 25908, "text": "Output :" }, { "code": null, "e": 26023, "s": 25917, "text": "Number of null values in row 0 : 0\nNumber of null values in row 1 : 1\nNumber of null values in row 3 : 2\n" }, { "code": null, "e": 26083, "s": 26023, "text": "Example 3 : Counting the total NaN values in the DataFrame." }, { "code": "print(\"Total Number of null values in the DataFrame : \" + str(table.isnull().sum().sum()))", "e": 26181, "s": 26083, "text": null }, { "code": null, "e": 26190, "s": 26181, "text": "Output :" }, { "code": null, "e": 26240, "s": 26190, "text": "Total Number of null values in the DataFrame : 5\n" }, { "code": null, "e": 26296, "s": 26240, "text": "Example 4 : Counting the NaN values in all the columns." }, { "code": "display(table.isnull().sum())", "e": 26326, "s": 26296, "text": null }, { "code": null, "e": 26335, "s": 26326, "text": "Output :" }, { "code": null, "e": 26359, "s": 26335, "text": "Python pandas-dataFrame" }, { "code": null, "e": 26373, "s": 26359, "text": "Python-pandas" }, { "code": null, "e": 26380, "s": 26373, "text": "Python" }, { "code": null, "e": 26478, "s": 26380, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26510, "s": 26478, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26566, "s": 26510, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26608, "s": 26566, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26650, "s": 26608, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26672, "s": 26650, "text": "Defaultdict in Python" }, { "code": null, "e": 26703, "s": 26672, "text": "Python | os.path.join() method" }, { "code": null, "e": 26742, "s": 26703, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26797, "s": 26742, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26826, "s": 26797, "text": "Create a directory in Python" } ]
Nth natural number after removing all numbers consisting of the digit 9 - GeeksforGeeks
13 Apr, 2022 Given a positive integer N, the task is to find the Nth natural number after removing all the natural numbers containing digit 9. Examples: Input: N = 8Output: 8Explanation:Since 9 is the first natural number that contains the digit 9 and is the 9th natural number, therefore, no removal required to find the 8th natural number, which is 8. Input: N = 9Output: 10Explanation:Removing number 9, the first 9 natural numbers are {1, 2, 3, 4, 5, 6, 7, 8, 10}.Therefore, the 9th natural number is 10. Naive Approach: The simplest approach to solve the above problem is to iterate up to N and keep excluding all numbers less than N containing the digit 9. Finally, print the Nth natural number obtained. Follow below steps below to solve the problems : Initialize one variable count = 0 and use for loop and pass the element of loop to isDigitNine(i) function to check whether that number contains 9 or not and increment that if not present And once count hit N assign the last i to to count and break the loop. Return answer as count Java public class nthnaturalNum { public static void main(String[] args) { long N = 18976; long ans = findNth(N); System.out.println(ans); } static long findNth(long N) { //code here long count = 0; for(int i = 1; i > 0; i++ ){ // call function digitnine() with i if(isDigitNine(i) == false) { count ++; if(count == N ) { count = i; // once count is equal to N then break; //assign last i to count and break the loop } } } return count ; } // isDigitNine function return true if number contain digit 9 // else will return false static boolean isDigitNine(int i){ while(i > 0){ int rem = i % 10; if(rem == 9){ return true; } i = i / 10; } return false; } }/* This code is contributed by devendra solunke */ 28024 Time Complexity: O(N)Auxiliary Space: O(1) Efficient Approach: The above approach can be optimized based on the following observations: It is known that, digits of base 2 numbers varies from 0 to 1. Similarly, digits of base 10 numbers varies from 0 to 9. Therefore, the digits of base 9 numbers will vary from 0 to 8. It can be observed that Nth number in base 9 is equal to Nth number after skipping numbers containing digit 9. So the task is reduced to find the base 9 equivalent of the number N. Follow the steps below to solve the problem: Initialize two variables, say res = 0 and p = 1, to store the number in base 9 and to store the position of a digit. Iterate while N is greater than 0 and perform the following operations:Update res as res = res + p*(N%9).Divide N by 9 and multiply p by 10. Update res as res = res + p*(N%9). Divide N by 9 and multiply p by 10. After completing the above steps, print the value of res. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of above approach #include <bits/stdc++.h>using namespace std; // Function to find Nth number in base 9long long findNthNumber(long long N){ // Stores the Nth number long long result = 0; long long p = 1; // Iterate while N is // greater than 0 while (N > 0) { // Update result result += (p * (N % 9)); // Divide N by 9 N = N / 9; // Multiply p by 10 p = p * 10; } // Return result return result;} // Driver Codeint main(){ int N = 9; cout << findNthNumber(N); return 0;} // Java program for the above approachimport java.util.*;class GFG{ // Function to find Nth number in base 9 static long findNthNumber(long N) { // Stores the Nth number long result = 0; long p = 1; // Iterate while N is // greater than 0 while (N > 0) { // Update result result += (p * (N % 9)); // Divide N by 9 N = N / 9; // Multiply p by 10 p = p * 10; } // Return result return result; } // Driver Code public static void main(String[] args) { int N = 9; System.out.print(findNthNumber(N)); }} // This code is contributed by splevel62. # Python 3 implementation of above approach # Function to find Nth number in base 9def findNthNumber(N): # Stores the Nth number result = 0 p = 1 # Iterate while N is # greater than 0 while (N > 0): # Update result result += (p * (N % 9)) # Divide N by 9 N = N // 9 # Multiply p by 10 p = p * 10 # Return result return result # Driver Codeif __name__ == '__main__': N = 9 print(findNthNumber(N)) # This code is contributed by bgangwar59. // C# implementation of above approachusing System;class GFG{ // Function to find Nth number in base 9 static long findNthNumber(long N) { // Stores the Nth number long result = 0; long p = 1; // Iterate while N is // greater than 0 while (N > 0) { // Update result result += (p * (N % 9)); // Divide N by 9 N = N / 9; // Multiply p by 10 p = p * 10; } // Return result return result; } // Driver code static void Main () { int N = 9; Console.Write(findNthNumber(N)); }} // This code is contributed by divyesh072019. <script> // Javascript implementation of above approach // Function to find Nth number in base 9 function findNthNumber(N) { // Stores the Nth number let result = 0; let p = 1; // Iterate while N is // greater than 0 while (N > 0) { // Update result result += (p * (N % 9)); // Divide N by 9 N = parseInt(N / 9, 10); // Multiply p by 10 p = p * 10; } // Return result return result; } let N = 9; document.write(findNthNumber(N)); </script> 10 Time Complexity: O(log9 N)Auxiliary Space: O(1) bgangwar59 divyesh072019 splevel62 rameshtravel07 arorakashish0911 devendrasalunke base-conversion Natural Numbers Technical Scripter 2020 Mathematical Technical Scripter Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Find all factors of a natural number | Set 1 Check if a number is Palindrome Program to print prime numbers from 1 to N. Program to add two binary strings Program to multiply two matrices Fizz Buzz Implementation Find pair with maximum GCD in an array Find Union and Intersection of two unsorted arrays Count all possible paths from top left to bottom right of a mXn matrix Count ways to reach the n'th stair
[ { "code": null, "e": 24325, "s": 24297, "text": "\n13 Apr, 2022" }, { "code": null, "e": 24455, "s": 24325, "text": "Given a positive integer N, the task is to find the Nth natural number after removing all the natural numbers containing digit 9." }, { "code": null, "e": 24465, "s": 24455, "text": "Examples:" }, { "code": null, "e": 24666, "s": 24465, "text": "Input: N = 8Output: 8Explanation:Since 9 is the first natural number that contains the digit 9 and is the 9th natural number, therefore, no removal required to find the 8th natural number, which is 8." }, { "code": null, "e": 24821, "s": 24666, "text": "Input: N = 9Output: 10Explanation:Removing number 9, the first 9 natural numbers are {1, 2, 3, 4, 5, 6, 7, 8, 10}.Therefore, the 9th natural number is 10." }, { "code": null, "e": 25023, "s": 24821, "text": "Naive Approach: The simplest approach to solve the above problem is to iterate up to N and keep excluding all numbers less than N containing the digit 9. Finally, print the Nth natural number obtained." }, { "code": null, "e": 25073, "s": 25023, "text": "Follow below steps below to solve the problems : " }, { "code": null, "e": 25108, "s": 25073, "text": "Initialize one variable count = 0" }, { "code": null, "e": 25263, "s": 25108, "text": "and use for loop and pass the element of loop to isDigitNine(i) function to check whether that number contains 9 or not and increment that if not present " }, { "code": null, "e": 25335, "s": 25263, "text": "And once count hit N assign the last i to to count and break the loop." }, { "code": null, "e": 25359, "s": 25335, "text": "Return answer as count " }, { "code": null, "e": 25364, "s": 25359, "text": "Java" }, { "code": "public class nthnaturalNum { public static void main(String[] args) { long N = 18976; long ans = findNth(N); System.out.println(ans); } static long findNth(long N) { //code here long count = 0; for(int i = 1; i > 0; i++ ){ // call function digitnine() with i if(isDigitNine(i) == false) { count ++; if(count == N ) { count = i; // once count is equal to N then break; //assign last i to count and break the loop } } } return count ; } // isDigitNine function return true if number contain digit 9 // else will return false static boolean isDigitNine(int i){ while(i > 0){ int rem = i % 10; if(rem == 9){ return true; } i = i / 10; } return false; } }/* This code is contributed by devendra solunke */", "e": 26398, "s": 25364, "text": null }, { "code": null, "e": 26405, "s": 26398, "text": "28024\n" }, { "code": null, "e": 26448, "s": 26405, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 26542, "s": 26448, "text": "Efficient Approach: The above approach can be optimized based on the following observations: " }, { "code": null, "e": 26662, "s": 26542, "text": "It is known that, digits of base 2 numbers varies from 0 to 1. Similarly, digits of base 10 numbers varies from 0 to 9." }, { "code": null, "e": 26725, "s": 26662, "text": "Therefore, the digits of base 9 numbers will vary from 0 to 8." }, { "code": null, "e": 26836, "s": 26725, "text": "It can be observed that Nth number in base 9 is equal to Nth number after skipping numbers containing digit 9." }, { "code": null, "e": 26906, "s": 26836, "text": "So the task is reduced to find the base 9 equivalent of the number N." }, { "code": null, "e": 26951, "s": 26906, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 27068, "s": 26951, "text": "Initialize two variables, say res = 0 and p = 1, to store the number in base 9 and to store the position of a digit." }, { "code": null, "e": 27209, "s": 27068, "text": "Iterate while N is greater than 0 and perform the following operations:Update res as res = res + p*(N%9).Divide N by 9 and multiply p by 10." }, { "code": null, "e": 27244, "s": 27209, "text": "Update res as res = res + p*(N%9)." }, { "code": null, "e": 27280, "s": 27244, "text": "Divide N by 9 and multiply p by 10." }, { "code": null, "e": 27338, "s": 27280, "text": "After completing the above steps, print the value of res." }, { "code": null, "e": 27389, "s": 27338, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27393, "s": 27389, "text": "C++" }, { "code": null, "e": 27398, "s": 27393, "text": "Java" }, { "code": null, "e": 27406, "s": 27398, "text": "Python3" }, { "code": null, "e": 27409, "s": 27406, "text": "C#" }, { "code": null, "e": 27420, "s": 27409, "text": "Javascript" }, { "code": "// C++ implementation of above approach #include <bits/stdc++.h>using namespace std; // Function to find Nth number in base 9long long findNthNumber(long long N){ // Stores the Nth number long long result = 0; long long p = 1; // Iterate while N is // greater than 0 while (N > 0) { // Update result result += (p * (N % 9)); // Divide N by 9 N = N / 9; // Multiply p by 10 p = p * 10; } // Return result return result;} // Driver Codeint main(){ int N = 9; cout << findNthNumber(N); return 0;}", "e": 27997, "s": 27420, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to find Nth number in base 9 static long findNthNumber(long N) { // Stores the Nth number long result = 0; long p = 1; // Iterate while N is // greater than 0 while (N > 0) { // Update result result += (p * (N % 9)); // Divide N by 9 N = N / 9; // Multiply p by 10 p = p * 10; } // Return result return result; } // Driver Code public static void main(String[] args) { int N = 9; System.out.print(findNthNumber(N)); }} // This code is contributed by splevel62.", "e": 28618, "s": 27997, "text": null }, { "code": "# Python 3 implementation of above approach # Function to find Nth number in base 9def findNthNumber(N): # Stores the Nth number result = 0 p = 1 # Iterate while N is # greater than 0 while (N > 0): # Update result result += (p * (N % 9)) # Divide N by 9 N = N // 9 # Multiply p by 10 p = p * 10 # Return result return result # Driver Codeif __name__ == '__main__': N = 9 print(findNthNumber(N)) # This code is contributed by bgangwar59.", "e": 29149, "s": 28618, "text": null }, { "code": "// C# implementation of above approachusing System;class GFG{ // Function to find Nth number in base 9 static long findNthNumber(long N) { // Stores the Nth number long result = 0; long p = 1; // Iterate while N is // greater than 0 while (N > 0) { // Update result result += (p * (N % 9)); // Divide N by 9 N = N / 9; // Multiply p by 10 p = p * 10; } // Return result return result; } // Driver code static void Main () { int N = 9; Console.Write(findNthNumber(N)); }} // This code is contributed by divyesh072019.", "e": 29749, "s": 29149, "text": null }, { "code": "<script> // Javascript implementation of above approach // Function to find Nth number in base 9 function findNthNumber(N) { // Stores the Nth number let result = 0; let p = 1; // Iterate while N is // greater than 0 while (N > 0) { // Update result result += (p * (N % 9)); // Divide N by 9 N = parseInt(N / 9, 10); // Multiply p by 10 p = p * 10; } // Return result return result; } let N = 9; document.write(findNthNumber(N)); </script>", "e": 30316, "s": 29749, "text": null }, { "code": null, "e": 30319, "s": 30316, "text": "10" }, { "code": null, "e": 30367, "s": 30319, "text": "Time Complexity: O(log9 N)Auxiliary Space: O(1)" }, { "code": null, "e": 30378, "s": 30367, "text": "bgangwar59" }, { "code": null, "e": 30392, "s": 30378, "text": "divyesh072019" }, { "code": null, "e": 30402, "s": 30392, "text": "splevel62" }, { "code": null, "e": 30417, "s": 30402, "text": "rameshtravel07" }, { "code": null, "e": 30434, "s": 30417, "text": "arorakashish0911" }, { "code": null, "e": 30450, "s": 30434, "text": "devendrasalunke" }, { "code": null, "e": 30466, "s": 30450, "text": "base-conversion" }, { "code": null, "e": 30482, "s": 30466, "text": "Natural Numbers" }, { "code": null, "e": 30506, "s": 30482, "text": "Technical Scripter 2020" }, { "code": null, "e": 30519, "s": 30506, "text": "Mathematical" }, { "code": null, "e": 30538, "s": 30519, "text": "Technical Scripter" }, { "code": null, "e": 30551, "s": 30538, "text": "Mathematical" }, { "code": null, "e": 30649, "s": 30551, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30658, "s": 30649, "text": "Comments" }, { "code": null, "e": 30671, "s": 30658, "text": "Old Comments" }, { "code": null, "e": 30716, "s": 30671, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 30748, "s": 30716, "text": "Check if a number is Palindrome" }, { "code": null, "e": 30792, "s": 30748, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 30826, "s": 30792, "text": "Program to add two binary strings" }, { "code": null, "e": 30859, "s": 30826, "text": "Program to multiply two matrices" }, { "code": null, "e": 30884, "s": 30859, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 30923, "s": 30884, "text": "Find pair with maximum GCD in an array" }, { "code": null, "e": 30974, "s": 30923, "text": "Find Union and Intersection of two unsorted arrays" }, { "code": null, "e": 31045, "s": 30974, "text": "Count all possible paths from top left to bottom right of a mXn matrix" } ]
Get Absolute path of a file in Java
The method java.io.File.getAbsolutePath() is used to obtain the absolute path of a file in the form of a string. This method requires no parameters. A program that demonstrates this is given as follows − Live Demo import java.io.File; public class Demo { public static void main(String[] args) { File file = new File("C:" + File.separator + "jdk11.0.2" + File.separator, "demo1.java"); System.out.println("The absolute path name is: " + file.getAbsolutePath()); } } The output of the above program is as follows − The absolute path name is:/C:/jdk11.0.2/demo1.java Now let us understand the above program. The absolute pathname of the file is obtained using the method java.io.File.getAbsolutePath() in the form of a string and is printed. A code snippet that demonstrates this is given as follows − File file = new File("C:" + File.separator + "jdk11.0.2" + File.separator, "demo1.java"); System.out.println("The absolute path name is: " + file.getAbsolutePath());
[ { "code": null, "e": 1211, "s": 1062, "text": "The method java.io.File.getAbsolutePath() is used to obtain the absolute path of a file in the form of a string. This method requires no parameters." }, { "code": null, "e": 1266, "s": 1211, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1277, "s": 1266, "text": " Live Demo" }, { "code": null, "e": 1547, "s": 1277, "text": "import java.io.File;\npublic class Demo {\n public static void main(String[] args) {\n File file = new File(\"C:\" + File.separator + \"jdk11.0.2\" + File.separator, \"demo1.java\");\n System.out.println(\"The absolute path name is: \" + file.getAbsolutePath());\n }\n}" }, { "code": null, "e": 1595, "s": 1547, "text": "The output of the above program is as follows −" }, { "code": null, "e": 1646, "s": 1595, "text": "The absolute path name is:/C:/jdk11.0.2/demo1.java" }, { "code": null, "e": 1687, "s": 1646, "text": "Now let us understand the above program." }, { "code": null, "e": 1881, "s": 1687, "text": "The absolute pathname of the file is obtained using the method java.io.File.getAbsolutePath() in the form of a string and is printed. A code snippet that demonstrates this is given as follows −" }, { "code": null, "e": 2047, "s": 1881, "text": "File file = new File(\"C:\" + File.separator + \"jdk11.0.2\" + File.separator, \"demo1.java\");\nSystem.out.println(\"The absolute path name is: \" + file.getAbsolutePath());" } ]
Can we declare interface members as private or protected in java8?
Interface in Java is similar to a class but, it contains only abstract methods and fields which are final and static. Since all the methods are abstract you cannot instantiate it. To use it, you need to implement this interface using a class and provide body to all the abstract methods in it. If the members of the interface are private you cannot provide implementation to the methods or, cannot access the fields of it in the implementing class. Therefore, the members of an interface cannot be private. If you try to declare the members of an interface private, a compile-time error is generated saying “modifier private not allowed here”. In the following Java example, we are trying to declare the field and method of an interface private. public interface MyInterface { private static final int num = 10; private abstract void demo(); } On compiling, the above program generates the following error. MyInterface.java:2: error: modifier private not allowed here private static final int num = 10; ^ MyInterface.java:3: error: modifier private not allowed here private abstract void demo(); ^ 2 errors In general, the protected members can be accessed in the same class or, the class inheriting it. But, we do not inherit an interface we will implement it. Therefore, the members of an interface cannot be protected. If you try to declare the members of an interface protected, a compile-time error is generated saying “modifier protected not allowed here”. In the following Java example, we are trying to declare the field and method of an interface protected. public interface MyInterface{ protected static final int num = 10; protected abstract void demo(); } On compiling, the above program generates the following error. MyInterface.java:2: error: modifier protected not allowed here protected static final int num = 10; ^ MyInterface.java:3: error: modifier protected not allowed here protected abstract void demo(); ^ 2 errors
[ { "code": null, "e": 1180, "s": 1062, "text": "Interface in Java is similar to a class but, it contains only abstract methods and fields which are final and static." }, { "code": null, "e": 1356, "s": 1180, "text": "Since all the methods are abstract you cannot instantiate it. To use it, you need to implement this interface using a class and provide body to all the abstract methods in it." }, { "code": null, "e": 1511, "s": 1356, "text": "If the members of the interface are private you cannot provide implementation to the methods or, cannot access the fields of it in the implementing class." }, { "code": null, "e": 1706, "s": 1511, "text": "Therefore, the members of an interface cannot be private. If you try to declare the members of an interface private, a compile-time error is generated saying “modifier private not allowed here”." }, { "code": null, "e": 1808, "s": 1706, "text": "In the following Java example, we are trying to declare the field and method of an interface private." }, { "code": null, "e": 1912, "s": 1808, "text": "public interface MyInterface {\n private static final int num = 10;\n private abstract void demo();\n}" }, { "code": null, "e": 1975, "s": 1912, "text": "On compiling, the above program generates the following error." }, { "code": null, "e": 2234, "s": 1975, "text": "MyInterface.java:2: error: modifier private not allowed here\n private static final int num = 10;\n ^\nMyInterface.java:3: error: modifier private not allowed here\n private abstract void demo();\n ^\n2 errors" }, { "code": null, "e": 2389, "s": 2234, "text": "In general, the protected members can be accessed in the same class or, the class inheriting it. But, we do not inherit an interface we will implement it." }, { "code": null, "e": 2590, "s": 2389, "text": "Therefore, the members of an interface cannot be protected. If you try to declare the members of an interface protected, a compile-time error is generated saying “modifier protected not allowed here”." }, { "code": null, "e": 2694, "s": 2590, "text": "In the following Java example, we are trying to declare the field and method of an interface protected." }, { "code": null, "e": 2801, "s": 2694, "text": "public interface MyInterface{\n protected static final int num = 10;\n protected abstract void demo();\n}" }, { "code": null, "e": 2864, "s": 2801, "text": "On compiling, the above program generates the following error." }, { "code": null, "e": 3072, "s": 2864, "text": "MyInterface.java:2: error: modifier protected not allowed here\nprotected static final int num = 10;\n^\nMyInterface.java:3: error: modifier protected not allowed here\nprotected abstract void demo();\n^\n2 errors" } ]
if – Django Template Tags
02 Dec, 2021 A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of a programming such as variables, for loops, comments, extends, if else etc. This article revolves about how to use if tag in Templates. The {% if %} tag evaluates a variable, and if that variable is “true” (i.e. exists, is not empty, and is not a false boolean value) the contents of the block are output. Syntax: {% if variable %} // statements {% else %} // statements {% endif %} Example: html {% if athlete_list %} Number of athletes: {{ athlete_list|length }}{% elif athlete_in_locker_room_list %} Athletes should be out of the locker room soon!{% else %} No athletes.{% endif %} In the above, if athlete_list is not empty, the number of athletes will be displayed by the {{ athlete_list|length }} variable.As one can see, the if tag may take one or several {% elif %} clauses, as well as an {% else %} clause that will be displayed if all previous conditions fail. These clauses are optional. Illustration of How to use if tag in Django templates using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Now create a view through which we will pass the context dictionary, In geeks/views.py, Python3 # import Http Response from djangofrom django.shortcuts import render # create a functiondef geeks_view(request): # create a dictionary context = { "data" : 99, } # return response return render(request, "geeks.html", context) Create a url path to map to this view. In geeks/urls.py, Python3 from django.urls import path # importing views from views.pyfrom .views import geeks_view urlpatterns = [ path('', geeks_view),] Create a template in templates/geeks.html, html {% if data %}Value in data is : - {{ data }}{% else %}Data is empty{% endif%} Let’s check what is displayed on “/” are displayed in the template. Let’s check if {% else %} statement is working or not. Now let’s pass an empty array and use empty tag along with for tag. In geeks/views.py, Python3 ## import Http Response from djangofrom django.shortcuts import render # create a functiondef geeks_view(request): # create a dictionary context = { "data" : False, } # return response return render(request, "geeks.html", context) Now, check http://127.0.0.1:8000/, if tags may use and, or or not to test a number of variables or to negate a given variable: {% if athlete_list and coach_list %} Both athletes and coaches are available. {% endif %} {% if not athlete_list %} There are no athletes. {% endif %} {% if athlete_list or coach_list %} There are some athletes or some coaches. {% endif %} {% if not athlete_list or coach_list %} There are no athletes or there are some coaches. {% endif %} {% if athlete_list and not coach_list %} There are some athletes and absolutely no coaches. {% endif %} surindertarika1234 Django-templates Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate over a list in Python How to iterate through Excel rows in Python? Enumerate() in Python Python Dictionary Python OOPs Concepts Different ways to create Pandas Dataframe *args and **kwargs in Python Python Classes and Objects Introduction To PYTHON Stack in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Dec, 2021" }, { "code": null, "e": 679, "s": 52, "text": "A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of a programming such as variables, for loops, comments, extends, if else etc. This article revolves about how to use if tag in Templates. The {% if %} tag evaluates a variable, and if that variable is “true” (i.e. exists, is not empty, and is not a false boolean value) the contents of the block are output. " }, { "code": null, "e": 687, "s": 679, "text": "Syntax:" }, { "code": null, "e": 756, "s": 687, "text": "{% if variable %}\n// statements\n{% else %}\n// statements\n{% endif %}" }, { "code": null, "e": 766, "s": 756, "text": "Example: " }, { "code": null, "e": 771, "s": 766, "text": "html" }, { "code": "{% if athlete_list %} Number of athletes: {{ athlete_list|length }}{% elif athlete_in_locker_room_list %} Athletes should be out of the locker room soon!{% else %} No athletes.{% endif %}", "e": 968, "s": 771, "text": null }, { "code": null, "e": 1283, "s": 968, "text": "In the above, if athlete_list is not empty, the number of athletes will be displayed by the {{ athlete_list|length }} variable.As one can see, the if tag may take one or several {% elif %} clauses, as well as an {% else %} clause that will be displayed if all previous conditions fail. These clauses are optional. " }, { "code": null, "e": 1422, "s": 1283, "text": "Illustration of How to use if tag in Django templates using an Example. Consider a project named geeksforgeeks having an app named geeks. " }, { "code": null, "e": 1511, "s": 1422, "text": "Refer to the following articles to check how to create a project and an app in Django. " }, { "code": null, "e": 1562, "s": 1511, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 1595, "s": 1562, "text": "How to Create an App in Django ?" }, { "code": null, "e": 1683, "s": 1595, "text": "Now create a view through which we will pass the context dictionary, In geeks/views.py," }, { "code": null, "e": 1691, "s": 1683, "text": "Python3" }, { "code": "# import Http Response from djangofrom django.shortcuts import render # create a functiondef geeks_view(request): # create a dictionary context = { \"data\" : 99, } # return response return render(request, \"geeks.html\", context)", "e": 1941, "s": 1691, "text": null }, { "code": null, "e": 1998, "s": 1941, "text": "Create a url path to map to this view. In geeks/urls.py," }, { "code": null, "e": 2006, "s": 1998, "text": "Python3" }, { "code": "from django.urls import path # importing views from views.pyfrom .views import geeks_view urlpatterns = [ path('', geeks_view),]", "e": 2138, "s": 2006, "text": null }, { "code": null, "e": 2181, "s": 2138, "text": "Create a template in templates/geeks.html," }, { "code": null, "e": 2186, "s": 2181, "text": "html" }, { "code": "{% if data %}Value in data is : - {{ data }}{% else %}Data is empty{% endif%}", "e": 2264, "s": 2186, "text": null }, { "code": null, "e": 2333, "s": 2264, "text": "Let’s check what is displayed on “/” are displayed in the template. " }, { "code": null, "e": 2476, "s": 2333, "text": "Let’s check if {% else %} statement is working or not. Now let’s pass an empty array and use empty tag along with for tag. In geeks/views.py, " }, { "code": null, "e": 2484, "s": 2476, "text": "Python3" }, { "code": "## import Http Response from djangofrom django.shortcuts import render # create a functiondef geeks_view(request): # create a dictionary context = { \"data\" : False, } # return response return render(request, \"geeks.html\", context)", "e": 2738, "s": 2484, "text": null }, { "code": null, "e": 2774, "s": 2738, "text": "Now, check http://127.0.0.1:8000/, " }, { "code": null, "e": 2867, "s": 2774, "text": "if tags may use and, or or not to test a number of variables or to negate a given variable: " }, { "code": null, "e": 3336, "s": 2867, "text": "{% if athlete_list and coach_list %}\n Both athletes and coaches are available.\n{% endif %}\n\n{% if not athlete_list %}\n There are no athletes.\n{% endif %}\n\n{% if athlete_list or coach_list %}\n There are some athletes or some coaches.\n{% endif %}\n\n{% if not athlete_list or coach_list %}\n There are no athletes or there are some coaches.\n{% endif %}\n\n{% if athlete_list and not coach_list %}\n There are some athletes and absolutely no coaches.\n{% endif %}" }, { "code": null, "e": 3355, "s": 3336, "text": "surindertarika1234" }, { "code": null, "e": 3372, "s": 3355, "text": "Django-templates" }, { "code": null, "e": 3386, "s": 3372, "text": "Python Django" }, { "code": null, "e": 3393, "s": 3386, "text": "Python" }, { "code": null, "e": 3491, "s": 3393, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3521, "s": 3491, "text": "Iterate over a list in Python" }, { "code": null, "e": 3566, "s": 3521, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 3588, "s": 3566, "text": "Enumerate() in Python" }, { "code": null, "e": 3606, "s": 3588, "text": "Python Dictionary" }, { "code": null, "e": 3627, "s": 3606, "text": "Python OOPs Concepts" }, { "code": null, "e": 3669, "s": 3627, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3698, "s": 3669, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3725, "s": 3698, "text": "Python Classes and Objects" }, { "code": null, "e": 3748, "s": 3725, "text": "Introduction To PYTHON" } ]
GATE | GATE CS 1997 | Question 14
19 Nov, 2018 The correct matching for the following pairs is (A) DMA I/O (1) High speed RAM (B) Cache (2) Disk (C) Interrupt I/O (3) Printer (D) Condition Code Register (4) ALU Codes: A B C D a 4 3 1 2 b 2 1 3 4 c 4 3 2 1 d 2 3 4 1 (A) a(B) b(C) c(D) dAnswer: (B)Explanation:Quiz of this Question GATE CS 1997 GATE-GATE CS 1997 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Nov, 2018" }, { "code": null, "e": 76, "s": 28, "text": "The correct matching for the following pairs is" }, { "code": null, "e": 249, "s": 76, "text": "(A) DMA I/O (1) High speed RAM\n(B) Cache (2) Disk\n(C) Interrupt I/O (3) Printer\n(D) Condition Code Register (4) ALU\n" }, { "code": null, "e": 348, "s": 249, "text": "Codes:\n A B C D \na 4 3 1 2\nb 2 1 3 4\nc 4 3 2 1\nd 2 3 4 1\n" }, { "code": null, "e": 413, "s": 348, "text": "(A) a(B) b(C) c(D) dAnswer: (B)Explanation:Quiz of this Question" }, { "code": null, "e": 426, "s": 413, "text": "GATE CS 1997" }, { "code": null, "e": 444, "s": 426, "text": "GATE-GATE CS 1997" }, { "code": null, "e": 449, "s": 444, "text": "GATE" } ]
UML - Quick Guide
UML is a standard language for specifying, visualizing, constructing, and documenting the artifacts of software systems. UML was created by the Object Management Group (OMG) and UML 1.0 specification draft was proposed to the OMG in January 1997. OMG is continuously making efforts to create a truly industry standard. UML stands for Unified Modeling Language. UML stands for Unified Modeling Language. UML is different from the other common programming languages such as C++, Java, COBOL, etc. UML is different from the other common programming languages such as C++, Java, COBOL, etc. UML is a pictorial language used to make software blueprints. UML is a pictorial language used to make software blueprints. UML can be described as a general purpose visual modeling language to visualize, specify, construct, and document software system. UML can be described as a general purpose visual modeling language to visualize, specify, construct, and document software system. Although UML is generally used to model software systems, it is not limited within this boundary. It is also used to model non-software systems as well. For example, the process flow in a manufacturing unit, etc. Although UML is generally used to model software systems, it is not limited within this boundary. It is also used to model non-software systems as well. For example, the process flow in a manufacturing unit, etc. UML is not a programming language but tools can be used to generate code in various languages using UML diagrams. UML has a direct relation with object oriented analysis and design. After some standardization, UML has become an OMG standard. A picture is worth a thousand words, this idiom absolutely fits describing UML. Object-oriented concepts were introduced much earlier than UML. At that point of time, there were no standard methodologies to organize and consolidate the object-oriented development. It was then that UML came into picture. There are a number of goals for developing UML but the most important is to define some general purpose modeling language, which all modelers can use and it also needs to be made simple to understand and use. UML diagrams are not only made for developers but also for business users, common people, and anybody interested to understand the system. The system can be a software or non-software system. Thus it must be clear that UML is not a development method rather it accompanies with processes to make it a successful system. In conclusion, the goal of UML can be defined as a simple modeling mechanism to model all possible practical systems in today’s complex environment. To understand the conceptual model of UML, first we need to clarify what is a conceptual model? and why a conceptual model is required? A conceptual model can be defined as a model which is made of concepts and their relationships. A conceptual model can be defined as a model which is made of concepts and their relationships. A conceptual model is the first step before drawing a UML diagram. It helps to understand the entities in the real world and how they interact with each other. A conceptual model is the first step before drawing a UML diagram. It helps to understand the entities in the real world and how they interact with each other. As UML describes the real-time systems, it is very important to make a conceptual model and then proceed gradually. The conceptual model of UML can be mastered by learning the following three major elements − UML building blocks Rules to connect the building blocks Common mechanisms of UML UML can be described as the successor of object-oriented (OO) analysis and design. An object contains both data and methods that control the data. The data represents the state of the object. A class describes an object and they also form a hierarchy to model the real-world system. The hierarchy is represented as inheritance and the classes can also be associated in different ways as per the requirement. Objects are the real-world entities that exist around us and the basic concepts such as abstraction, encapsulation, inheritance, and polymorphism all can be represented using UML. UML is powerful enough to represent all the concepts that exist in object-oriented analysis and design. UML diagrams are representation of object-oriented concepts only. Thus, before learning UML, it becomes important to understand OO concept in detail. Following are some fundamental concepts of the object-oriented world − Objects − Objects represent an entity and the basic building block. Objects − Objects represent an entity and the basic building block. Class − Class is the blue print of an object. Class − Class is the blue print of an object. Abstraction − Abstraction represents the behavior of an real world entity. Abstraction − Abstraction represents the behavior of an real world entity. Encapsulation − Encapsulation is the mechanism of binding the data together and hiding them from the outside world. Encapsulation − Encapsulation is the mechanism of binding the data together and hiding them from the outside world. Inheritance − Inheritance is the mechanism of making new classes from existing ones. Inheritance − Inheritance is the mechanism of making new classes from existing ones. Polymorphism − It defines the mechanism to exists in different forms. Polymorphism − It defines the mechanism to exists in different forms. OO can be defined as an investigation and to be more specific, it is the investigation of objects. Design means collaboration of identified objects. Thus, it is important to understand the OO analysis and design concepts. The most important purpose of OO analysis is to identify objects of a system to be designed. This analysis is also done for an existing system. Now an efficient analysis is only possible when we are able to start thinking in a way where objects can be identified. After identifying the objects, their relationships are identified and finally the design is produced. The purpose of OO analysis and design can described as − Identifying the objects of a system. Identifying the objects of a system. Identifying their relationships. Identifying their relationships. Making a design, which can be converted to executables using OO languages. Making a design, which can be converted to executables using OO languages. There are three basic steps where the OO concepts are applied and implemented. The steps can be defined as OO Analysis → OO Design → OO implementation using OO languages The above three points can be described in detail as − During OO analysis, the most important purpose is to identify objects and describe them in a proper way. If these objects are identified efficiently, then the next job of design is easy. The objects should be identified with responsibilities. Responsibilities are the functions performed by the object. Each and every object has some type of responsibilities to be performed. When these responsibilities are collaborated, the purpose of the system is fulfilled. During OO analysis, the most important purpose is to identify objects and describe them in a proper way. If these objects are identified efficiently, then the next job of design is easy. The objects should be identified with responsibilities. Responsibilities are the functions performed by the object. Each and every object has some type of responsibilities to be performed. When these responsibilities are collaborated, the purpose of the system is fulfilled. The second phase is OO design. During this phase, emphasis is placed on the requirements and their fulfilment. In this stage, the objects are collaborated according to their intended association. After the association is complete, the design is also complete. The second phase is OO design. During this phase, emphasis is placed on the requirements and their fulfilment. In this stage, the objects are collaborated according to their intended association. After the association is complete, the design is also complete. The third phase is OO implementation. In this phase, the design is implemented using OO languages such as Java, C++, etc. The third phase is OO implementation. In this phase, the design is implemented using OO languages such as Java, C++, etc. UML is a modeling language used to model software and non-software systems. Although UML is used for non-software systems, the emphasis is on modeling OO software applications. Most of the UML diagrams discussed so far are used to model different aspects such as static, dynamic, etc. Now whatever be the aspect, the artifacts are nothing but objects. If we look into class diagram, object diagram, collaboration diagram, interaction diagrams all would basically be designed based on the objects. Hence, the relation between OO design and UML is very important to understand. The OO design is transformed into UML diagrams according to the requirement. Before understanding the UML in detail, the OO concept should be learned properly. Once the OO analysis and design is done, the next step is very easy. The input from OO analysis and design is the input to UML diagrams. As UML describes the real-time systems, it is very important to make a conceptual model and then proceed gradually. The conceptual model of UML can be mastered by learning the following three major elements − UML building blocks Rules to connect the building blocks Common mechanisms of UML This chapter describes all the UML building blocks. The building blocks of UML can be defined as − Things Relationships Diagrams Things are the most important building blocks of UML. Things can be − Structural Behavioral Grouping Annotational Structural things define the static part of the model. They represent the physical and conceptual elements. Following are the brief descriptions of the structural things. Class − Class represents a set of objects having similar responsibilities. Interface − Interface defines a set of operations, which specify the responsibility of a class. Collaboration −Collaboration defines an interaction between elements. Use case −Use case represents a set of actions performed by a system for a specific goal. Component −Component describes the physical part of a system. Node − A node can be defined as a physical element that exists at run time. A behavioral thing consists of the dynamic parts of UML models. Following are the behavioral things − Interaction − Interaction is defined as a behavior that consists of a group of messages exchanged among elements to accomplish a specific task. State machine − State machine is useful when the state of an object in its life cycle is important. It defines the sequence of states an object goes through in response to events. Events are external factors responsible for state change Grouping things can be defined as a mechanism to group elements of a UML model together. There is only one grouping thing available − Package − Package is the only one grouping thing available for gathering structural and behavioral things. Annotational things can be defined as a mechanism to capture remarks, descriptions, and comments of UML model elements. Note - It is the only one Annotational thing available. A note is used to render comments, constraints, etc. of an UML element. Relationship is another most important building block of UML. It shows how the elements are associated with each other and this association describes the functionality of an application. There are four kinds of relationships available. Dependency is a relationship between two things in which change in one element also affects the other. Association is basically a set of links that connects the elements of a UML model. It also describes how many objects are taking part in that relationship. Generalization can be defined as a relationship which connects a specialized element with a generalized element. It basically describes the inheritance relationship in the world of objects. Realization can be defined as a relationship in which two elements are connected. One element describes some responsibility, which is not implemented and the other one implements them. This relationship exists in case of interfaces. UML diagrams are the ultimate output of the entire discussion. All the elements, relationships are used to make a complete UML diagram and the diagram represents a system. The visual effect of the UML diagram is the most important part of the entire process. All the other elements are used to make it complete. UML includes the following nine diagrams, the details of which are described in the subsequent chapters. Class diagram Object diagram Use case diagram Sequence diagram Collaboration diagram Activity diagram Statechart diagram Deployment diagram Component diagram Any real-world system is used by different users. The users can be developers, testers, business people, analysts, and many more. Hence, before designing a system, the architecture is made with different perspectives in mind. The most important part is to visualize the system from the perspective of different viewers. The better we understand the better we can build the system. UML plays an important role in defining different perspectives of a system. These perspectives are − Design Implementation Process Deployment The center is the Use Case view which connects all these four. A Use Case represents the functionality of the system. Hence, other perspectives are connected with use case. Design of a system consists of classes, interfaces, and collaboration. UML provides class diagram, object diagram to support this. Implementation defines the components assembled together to make a complete physical system. UML component diagram is used to support the implementation perspective. Process defines the flow of the system. Hence, the same elements as used in Design are also used to support this perspective. Deployment represents the physical nodes of the system that forms the hardware. UML deployment diagram is used to support this perspective. It is very important to distinguish between the UML model. Different diagrams are used for different types of UML modeling. There are three important types of UML modeling. Structural modeling captures the static features of a system. They consist of the following − Classes diagrams Objects diagrams Deployment diagrams Package diagrams Composite structure diagram Component diagram Structural model represents the framework for the system and this framework is the place where all other components exist. Hence, the class diagram, component diagram and deployment diagrams are part of structural modeling. They all represent the elements and the mechanism to assemble them. The structural model never describes the dynamic behavior of the system. Class diagram is the most widely used structural diagram. Behavioral model describes the interaction in the system. It represents the interaction among the structural diagrams. Behavioral modeling shows the dynamic nature of the system. They consist of the following − Activity diagrams Interaction diagrams Use case diagrams All the above show the dynamic sequence of flow in a system. Architectural model represents the overall framework of the system. It contains both structural and behavioral elements of the system. Architectural model can be defined as the blueprint of the entire system. Package diagram comes under architectural modeling. UML is popular for its diagrammatic notations. We all know that UML is for visualizing, specifying, constructing and documenting the components of software and non-software systems. Hence, visualization is the most important part which needs to be understood and remembered. UML notations are the most important elements in modeling. Efficient and appropriate use of notations is very important for making a complete and meaningful model. The model is useless, unless its purpose is depicted properly. Hence, learning notations should be emphasized from the very beginning. Different notations are available for things and relationships. UML diagrams are made using the notations of things and relationships. Extensibility is another important feature which makes UML more powerful and flexible. The chapter describes basic UML notations in detail. This is just an extension to the UML building block section discussed in Chapter Two. Graphical notations used in structural things are most widely used in UML. These are considered as the nouns of UML models. Following are the list of structural things. Classes Object Interface Collaboration Use case Active classes Components Nodes UML class is represented by the following figure. The diagram is divided into four parts. The top section is used to name the class. The second one is used to show the attributes of the class. The third section is used to describe the operations performed by the class. The fourth section is optional to show any additional components. Classes are used to represent objects. Objects can be anything having properties and responsibility. The object is represented in the same way as the class. The only difference is the name which is underlined as shown in the following figure. As the object is an actual implementation of a class, which is known as the instance of a class. Hence, it has the same usage as the class. Interface is represented by a circle as shown in the following figure. It has a name which is generally written below the circle. Interface is used to describe the functionality without implementation. Interface is just like a template where you define different functions, not the implementation. When a class implements the interface, it also implements the functionality as per requirement. Collaboration is represented by a dotted eclipse as shown in the following figure. It has a name written inside the eclipse. Collaboration represents responsibilities. Generally, responsibilities are in a group. Use case is represented as an eclipse with a name inside it. It may contain additional responsibilities. Use case is used to capture high level functionalities of a system. An actor can be defined as some internal or external entity that interacts with the system. An actor is used in a use case diagram to describe the internal or external entities. Initial state is defined to show the start of a process. This notation is used in almost all diagrams. The usage of Initial State Notation is to show the starting point of a process. Final state is used to show the end of a process. This notation is also used in almost all diagrams to describe the end. The usage of Final State Notation is to show the termination point of a process. Active class looks similar to a class with a solid border. Active class is generally used to describe the concurrent behavior of a system. Active class is used to represent the concurrency in a system. A component in UML is shown in the following figure with a name inside. Additional elements can be added wherever required. Component is used to represent any part of a system for which UML diagrams are made. A node in UML is represented by a square box as shown in the following figure with a name. A node represents the physical component of the system. Node is used to represent the physical part of a system such as the server, network, etc. Dynamic parts are one of the most important elements in UML. UML has a set of powerful features to represent the dynamic part of software and non-software systems. These features include interactions and state machines. Interactions can be of two types − Sequential (Represented by sequence diagram) Collaborative (Represented by collaboration diagram) Interaction is basically a message exchange between two UML components. The following diagram represents different notations used in an interaction. Interaction is used to represent the communication among the components of a system. State machine describes the different states of a component in its life cycle. The notations are described in the following diagram. State machine is used to describe different states of a system component. The state can be active, idle, or any other depending upon the situation. Organizing the UML models is one of the most important aspects of the design. In UML, there is only one element available for grouping and that is package. Package notation is shown in the following figure and is used to wrap the components of a system. In any diagram, explanation of different elements and their functionalities are very important. Hence, UML has notes notation to support this requirement. This notation is shown in the following figure. These notations are used to provide necessary information of a system. A model is not complete unless the relationships between elements are described properly. The Relationship gives a proper meaning to a UML model. Following are the different types of relationships available in UML. Dependency Association Generalization Extensibility Dependency is an important aspect in UML elements. It describes the dependent elements and the direction of dependency. Dependency is represented by a dotted arrow as shown in the following figure. The arrow head represents the independent element and the other end represents the dependent element. Dependency is used to represent the dependency between two elements of a system Association describes how the elements in a UML diagram are associated. In simple words, it describes how many elements are taking part in an interaction. Association is represented by a dotted line with (without) arrows on both sides. The two ends represent two associated elements as shown in the following figure. The multiplicity is also mentioned at the ends (1, *, etc.) to show how many objects are associated. Association is used to represent the relationship between two elements of a system. Generalization describes the inheritance relationship of the object-oriented world. It is a parent and child relationship. Generalization is represented by an arrow with a hollow arrow head as shown in the following figure. One end represents the parent element and the other end represents the child element. Generalization is used to describe parent-child relationship of two elements of a system. All the languages (programming or modeling) have some mechanism to extend its capabilities such as syntax, semantics, etc. UML also has the following mechanisms to provide extensibility features. Stereotypes (Represents new elements) Tagged values (Represents new attributes) Constraints (Represents the boundaries) Extensibility notations are used to enhance the power of the language. It is basically additional elements used to represent some extra behavior of the system. These extra behaviors are not covered by the standard available notations. In the previous chapters, we have discussed about the building blocks and other necessary elements of UML. Now we need to understand where to use those elements. The elements are like components which can be associated in different ways to make a complete UML picture, which is known as diagram. Thus, it is very important to understand the different diagrams to implement the knowledge in real-life systems. Any complex system is best understood by making some kind of diagrams or pictures. These diagrams have a better impact on our understanding. If we look around, we will realize that the diagrams are not a new concept but it is used widely in different forms in different industries. We prepare UML diagrams to understand the system in a better and simple way. A single diagram is not enough to cover all the aspects of the system. UML defines various kinds of diagrams to cover most of the aspects of a system. You can also create your own set of diagrams to meet your requirements. Diagrams are generally made in an incremental and iterative way. There are two broad categories of diagrams and they are again divided into subcategories − Structural Diagrams Structural Diagrams Behavioral Diagrams Behavioral Diagrams The structural diagrams represent the static aspect of the system. These static aspects represent those parts of a diagram, which forms the main structure and are therefore stable. These static parts are represented by classes, interfaces, objects, components, and nodes. The four structural diagrams are − Class diagram Object diagram Component diagram Deployment diagram Class diagrams are the most common diagrams used in UML. Class diagram consists of classes, interfaces, associations, and collaboration. Class diagrams basically represent the object-oriented view of a system, which is static in nature. Active class is used in a class diagram to represent the concurrency of the system. Class diagram represents the object orientation of a system. Hence, it is generally used for development purpose. This is the most widely used diagram at the time of system construction. Object diagrams can be described as an instance of class diagram. Thus, these diagrams are more close to real-life scenarios where we implement a system. Object diagrams are a set of objects and their relationship is just like class diagrams. They also represent the static view of the system. The usage of object diagrams is similar to class diagrams but they are used to build prototype of a system from a practical perspective. Component diagrams represent a set of components and their relationships. These components consist of classes, interfaces, or collaborations. Component diagrams represent the implementation view of a system. During the design phase, software artifacts (classes, interfaces, etc.) of a system are arranged in different groups depending upon their relationship. Now, these groups are known as components. Finally, it can be said component diagrams are used to visualize the implementation. Deployment diagrams are a set of nodes and their relationships. These nodes are physical entities where the components are deployed. Deployment diagrams are used for visualizing the deployment view of a system. This is generally used by the deployment team. Note − If the above descriptions and usages are observed carefully then it is very clear that all the diagrams have some relationship with one another. Component diagrams are dependent upon the classes, interfaces, etc. which are part of class/object diagram. Again, the deployment diagram is dependent upon the components, which are used to make component diagrams. Any system can have two aspects, static and dynamic. So, a model is considered as complete when both the aspects are fully covered. Behavioral diagrams basically capture the dynamic aspect of a system. Dynamic aspect can be further described as the changing/moving parts of a system. UML has the following five types of behavioral diagrams − Use case diagram Sequence diagram Collaboration diagram Statechart diagram Activity diagram Use case diagrams are a set of use cases, actors, and their relationships. They represent the use case view of a system. A use case represents a particular functionality of a system. Hence, use case diagram is used to describe the relationships among the functionalities and their internal/external controllers. These controllers are known as actors. A sequence diagram is an interaction diagram. From the name, it is clear that the diagram deals with some sequences, which are the sequence of messages flowing from one object to another. Interaction among the components of a system is very important from implementation and execution perspective. Sequence diagram is used to visualize the sequence of calls in a system to perform a specific functionality. Collaboration diagram is another form of interaction diagram. It represents the structural organization of a system and the messages sent/received. Structural organization consists of objects and links. The purpose of collaboration diagram is similar to sequence diagram. However, the specific purpose of collaboration diagram is to visualize the organization of objects and their interaction. Any real-time system is expected to be reacted by some kind of internal/external events. These events are responsible for state change of the system. Statechart diagram is used to represent the event driven state change of a system. It basically describes the state change of a class, interface, etc. State chart diagram is used to visualize the reaction of a system by internal/external factors. Activity diagram describes the flow of control in a system. It consists of activities and links. The flow can be sequential, concurrent, or branched. Activities are nothing but the functions of a system. Numbers of activity diagrams are prepared to capture the entire flow in a system. Activity diagrams are used to visualize the flow of controls in a system. This is prepared to have an idea of how the system will work when executed. Note − Dynamic nature of a system is very difficult to capture. UML has provided features to capture the dynamics of a system from different angles. Sequence diagrams and collaboration diagrams are isomorphic, hence they can be converted from one another without losing any information. This is also true for Statechart and activity diagram. Class diagram is a static diagram. It represents the static view of an application. Class diagram is not only used for visualizing, describing, and documenting different aspects of a system but also for constructing executable code of the software application. Class diagram describes the attributes and operations of a class and also the constraints imposed on the system. The class diagrams are widely used in the modeling of objectoriented systems because they are the only UML diagrams, which can be mapped directly with object-oriented languages. Class diagram shows a collection of classes, interfaces, associations, collaborations, and constraints. It is also known as a structural diagram. The purpose of class diagram is to model the static view of an application. Class diagrams are the only diagrams which can be directly mapped with object-oriented languages and thus widely used at the time of construction. UML diagrams like activity diagram, sequence diagram can only give the sequence flow of the application, however class diagram is a bit different. It is the most popular UML diagram in the coder community. The purpose of the class diagram can be summarized as − Analysis and design of the static view of an application. Analysis and design of the static view of an application. Describe responsibilities of a system. Describe responsibilities of a system. Base for component and deployment diagrams. Base for component and deployment diagrams. Forward and reverse engineering. Forward and reverse engineering. Class diagrams are the most popular UML diagrams used for construction of software applications. It is very important to learn the drawing procedure of class diagram. Class diagrams have a lot of properties to consider while drawing but here the diagram will be considered from a top level view. Class diagram is basically a graphical representation of the static view of the system and represents different aspects of the application. A collection of class diagrams represent the whole system. The following points should be remembered while drawing a class diagram − The name of the class diagram should be meaningful to describe the aspect of the system. The name of the class diagram should be meaningful to describe the aspect of the system. Each element and their relationships should be identified in advance. Each element and their relationships should be identified in advance. Responsibility (attributes and methods) of each class should be clearly identified Responsibility (attributes and methods) of each class should be clearly identified For each class, minimum number of properties should be specified, as unnecessary properties will make the diagram complicated. For each class, minimum number of properties should be specified, as unnecessary properties will make the diagram complicated. Use notes whenever required to describe some aspect of the diagram. At the end of the drawing it should be understandable to the developer/coder. Use notes whenever required to describe some aspect of the diagram. At the end of the drawing it should be understandable to the developer/coder. Finally, before making the final version, the diagram should be drawn on plain paper and reworked as many times as possible to make it correct. Finally, before making the final version, the diagram should be drawn on plain paper and reworked as many times as possible to make it correct. The following diagram is an example of an Order System of an application. It describes a particular aspect of the entire application. First of all, Order and Customer are identified as the two elements of the system. They have a one-to-many relationship because a customer can have multiple orders. First of all, Order and Customer are identified as the two elements of the system. They have a one-to-many relationship because a customer can have multiple orders. Order class is an abstract class and it has two concrete classes (inheritance relationship) SpecialOrder and NormalOrder. Order class is an abstract class and it has two concrete classes (inheritance relationship) SpecialOrder and NormalOrder. The two inherited classes have all the properties as the Order class. In addition, they have additional functions like dispatch () and receive (). The two inherited classes have all the properties as the Order class. In addition, they have additional functions like dispatch () and receive (). The following class diagram has been drawn considering all the points mentioned above. Class diagram is a static diagram and it is used to model the static view of a system. The static view describes the vocabulary of the system. Class diagram is also considered as the foundation for component and deployment diagrams. Class diagrams are not only used to visualize the static view of the system but they are also used to construct the executable code for forward and reverse engineering of any system. Generally, UML diagrams are not directly mapped with any object-oriented programming languages but the class diagram is an exception. Class diagram clearly shows the mapping with object-oriented languages such as Java, C++, etc. From practical experience, class diagram is generally used for construction purpose. In a nutshell it can be said, class diagrams are used for − Describing the static view of the system. Describing the static view of the system. Showing the collaboration among the elements of the static view. Showing the collaboration among the elements of the static view. Describing the functionalities performed by the system. Describing the functionalities performed by the system. Construction of software applications using object oriented languages. Construction of software applications using object oriented languages. Object diagrams are derived from class diagrams so object diagrams are dependent upon class diagrams. Object diagrams represent an instance of a class diagram. The basic concepts are similar for class diagrams and object diagrams. Object diagrams also represent the static view of a system but this static view is a snapshot of the system at a particular moment. Object diagrams are used to render a set of objects and their relationships as an instance. The purpose of a diagram should be understood clearly to implement it practically. The purposes of object diagrams are similar to class diagrams. The difference is that a class diagram represents an abstract model consisting of classes and their relationships. However, an object diagram represents an instance at a particular moment, which is concrete in nature. It means the object diagram is closer to the actual system behavior. The purpose is to capture the static view of a system at a particular moment. The purpose of the object diagram can be summarized as − Forward and reverse engineering. Forward and reverse engineering. Object relationships of a system Object relationships of a system Static view of an interaction. Static view of an interaction. Understand object behaviour and their relationship from practical perspective Understand object behaviour and their relationship from practical perspective We have already discussed that an object diagram is an instance of a class diagram. It implies that an object diagram consists of instances of things used in a class diagram. So both diagrams are made of same basic elements but in different form. In class diagram elements are in abstract form to represent the blue print and in object diagram the elements are in concrete form to represent the real world object. To capture a particular system, numbers of class diagrams are limited. However, if we consider object diagrams then we can have unlimited number of instances, which are unique in nature. Only those instances are considered, which have an impact on the system. From the above discussion, it is clear that a single object diagram cannot capture all the necessary instances or rather cannot specify all the objects of a system. Hence, the solution is − First, analyze the system and decide which instances have important data and association. First, analyze the system and decide which instances have important data and association. Second, consider only those instances, which will cover the functionality. Second, consider only those instances, which will cover the functionality. Third, make some optimization as the number of instances are unlimited. Third, make some optimization as the number of instances are unlimited. Before drawing an object diagram, the following things should be remembered and understood clearly − Object diagrams consist of objects. Object diagrams consist of objects. The link in object diagram is used to connect objects. The link in object diagram is used to connect objects. Objects and links are the two elements used to construct an object diagram. Objects and links are the two elements used to construct an object diagram. After this, the following things are to be decided before starting the construction of the diagram − The object diagram should have a meaningful name to indicate its purpose. The object diagram should have a meaningful name to indicate its purpose. The most important elements are to be identified. The most important elements are to be identified. The association among objects should be clarified. The association among objects should be clarified. Values of different elements need to be captured to include in the object diagram. Values of different elements need to be captured to include in the object diagram. Add proper notes at points where more clarity is required. Add proper notes at points where more clarity is required. The following diagram is an example of an object diagram. It represents the Order management system which we have discussed in the chapter Class Diagram. The following diagram is an instance of the system at a particular time of purchase. It has the following objects. Customer Customer Order Order SpecialOrder SpecialOrder NormalOrder NormalOrder Now the customer object (C) is associated with three order objects (O1, O2, and O3). These order objects are associated with special order and normal order objects (S1, S2, and N1). The customer has the following three orders with different numbers (12, 32 and 40) for the particular time considered. The customer can increase the number of orders in future and in that scenario the object diagram will reflect that. If order, special order, and normal order objects are observed then you will find that they have some values. For orders, the values are 12, 32, and 40 which implies that the objects have these values for a particular moment (here the particular time when the purchase is made is considered as the moment) when the instance is captured The same is true for special order and normal order objects which have number of orders as 20, 30, and 60. If a different time of purchase is considered, then these values will change accordingly. The following object diagram has been drawn considering all the points mentioned above Object diagrams can be imagined as the snapshot of a running system at a particular moment. Let us consider an example of a running train Now, if you take a snap of the running train then you will find a static picture of it having the following − A particular state which is running. A particular state which is running. A particular number of passengers. which will change if the snap is taken in a different time A particular number of passengers. which will change if the snap is taken in a different time Here, we can imagine the snap of the running train is an object having the above values. And this is true for any real-life simple or complex system. In a nutshell, it can be said that object diagrams are used for − Making the prototype of a system. Making the prototype of a system. Reverse engineering. Reverse engineering. Modeling complex data structures. Modeling complex data structures. Understanding the system from practical perspective. Understanding the system from practical perspective. Component diagrams are different in terms of nature and behavior. Component diagrams are used to model the physical aspects of a system. Now the question is, what are these physical aspects? Physical aspects are the elements such as executables, libraries, files, documents, etc. which reside in a node. Component diagrams are used to visualize the organization and relationships among components in a system. These diagrams are also used to make executable systems. Component diagram is a special kind of diagram in UML. The purpose is also different from all other diagrams discussed so far. It does not describe the functionality of the system but it describes the components used to make those functionalities. Thus from that point of view, component diagrams are used to visualize the physical components in a system. These components are libraries, packages, files, etc. Component diagrams can also be described as a static implementation view of a system. Static implementation represents the organization of the components at a particular moment. A single component diagram cannot represent the entire system but a collection of diagrams is used to represent the whole. The purpose of the component diagram can be summarized as − Visualize the components of a system. Visualize the components of a system. Construct executables by using forward and reverse engineering. Construct executables by using forward and reverse engineering. Describe the organization and relationships of the components. Describe the organization and relationships of the components. Component diagrams are used to describe the physical artifacts of a system. This artifact includes files, executables, libraries, etc The purpose of this diagram is different. Component diagrams are used during the implementation phase of an application. However, it is prepared well in advance to visualize the implementation details. Initially, the system is designed using different UML diagrams and then when the artifacts are ready, component diagrams are used to get an idea of the implementation. This diagram is very important as without it the application cannot be implemented efficiently. A well-prepared component diagram is also important for other aspects such as application performance, maintenance, etc. Before drawing a component diagram, the following artifacts are to be identified clearly − Files used in the system. Files used in the system. Libraries and other artifacts relevant to the application. Libraries and other artifacts relevant to the application. Relationships among the artifacts. Relationships among the artifacts. After identifying the artifacts, the following points need to be kept in mind. Use a meaningful name to identify the component for which the diagram is to be drawn. Use a meaningful name to identify the component for which the diagram is to be drawn. Prepare a mental layout before producing the using tools. Prepare a mental layout before producing the using tools. Use notes for clarifying important points. Use notes for clarifying important points. Following is a component diagram for order management system. Here, the artifacts are files. The diagram shows the files in the application and their relationships. In actual, the component diagram also contains dlls, libraries, folders, etc. In the following diagram, four files are identified and their relationships are produced. Component diagram cannot be matched directly with other UML diagrams discussed so far as it is drawn for completely different purpose. The following component diagram has been drawn considering all the points mentioned above. We have already described that component diagrams are used to visualize the static implementation view of a system. Component diagrams are special type of UML diagrams used for different purposes. These diagrams show the physical components of a system. To clarify it, we can say that component diagrams describe the organization of the components in a system. Organization can be further described as the location of the components in a system. These components are organized in a special way to meet the system requirements. As we have already discussed, those components are libraries, files, executables, etc. Before implementing the application, these components are to be organized. This component organization is also designed separately as a part of project execution. Component diagrams are very important from implementation perspective. Thus, the implementation team of an application should have a proper knowledge of the component details Component diagrams can be used to − Model the components of a system. Model the components of a system. Model the database schema. Model the database schema. Model the executables of an application. Model the executables of an application. Model the system's source code. Model the system's source code. Deployment diagrams are used to visualize the topology of the physical components of a system, where the software components are deployed. Deployment diagrams are used to describe the static deployment view of a system. Deployment diagrams consist of nodes and their relationships. The term Deployment itself describes the purpose of the diagram. Deployment diagrams are used for describing the hardware components, where software components are deployed. Component diagrams and deployment diagrams are closely related. Component diagrams are used to describe the components and deployment diagrams shows how they are deployed in hardware. UML is mainly designed to focus on the software artifacts of a system. However, these two diagrams are special diagrams used to focus on software and hardware components. Most of the UML diagrams are used to handle logical components but deployment diagrams are made to focus on the hardware topology of a system. Deployment diagrams are used by the system engineers. The purpose of deployment diagrams can be described as − Visualize the hardware topology of a system. Visualize the hardware topology of a system. Describe the hardware components used to deploy software components. Describe the hardware components used to deploy software components. Describe the runtime processing nodes. Describe the runtime processing nodes. Deployment diagram represents the deployment view of a system. It is related to the component diagram because the components are deployed using the deployment diagrams. A deployment diagram consists of nodes. Nodes are nothing but physical hardware used to deploy the application. Deployment diagrams are useful for system engineers. An efficient deployment diagram is very important as it controls the following parameters − Performance Performance Scalability Scalability Maintainability Maintainability Portability Portability Before drawing a deployment diagram, the following artifacts should be identified − Nodes Nodes Relationships among nodes Relationships among nodes Following is a sample deployment diagram to provide an idea of the deployment view of order management system. Here, we have shown nodes as − Monitor Monitor Modem Modem Caching server Caching server Server Server The application is assumed to be a web-based application, which is deployed in a clustered environment using server 1, server 2, and server 3. The user connects to the application using the Internet. The control flows from the caching server to the clustered environment. The following deployment diagram has been drawn considering all the points mentioned above. Deployment diagrams are mainly used by system engineers. These diagrams are used to describe the physical components (hardware), their distribution, and association. Deployment diagrams can be visualized as the hardware components/nodes on which the software components reside. Software applications are developed to model complex business processes. Efficient software applications are not sufficient to meet the business requirements. Business requirements can be described as the need to support the increasing number of users, quick response time, etc. To meet these types of requirements, hardware components should be designed efficiently and in a cost-effective way. Now-a-days software applications are very complex in nature. Software applications can be standalone, web-based, distributed, mainframe-based and many more. Hence, it is very important to design the hardware components efficiently. Deployment diagrams can be used − To model the hardware topology of a system. To model the hardware topology of a system. To model the embedded system. To model the embedded system. To model the hardware details for a client/server system. To model the hardware details for a client/server system. To model the hardware details of a distributed application. To model the hardware details of a distributed application. For Forward and Reverse engineering. For Forward and Reverse engineering. To model a system, the most important aspect is to capture the dynamic behavior. Dynamic behavior means the behavior of the system when it is running/operating. Only static behavior is not sufficient to model a system rather dynamic behavior is more important than static behavior. In UML, there are five diagrams available to model the dynamic nature and use case diagram is one of them. Now as we have to discuss that the use case diagram is dynamic in nature, there should be some internal or external factors for making the interaction. These internal and external agents are known as actors. Use case diagrams consists of actors, use cases and their relationships. The diagram is used to model the system/subsystem of an application. A single use case diagram captures a particular functionality of a system. Hence to model the entire system, a number of use case diagrams are used. The purpose of use case diagram is to capture the dynamic aspect of a system. However, this definition is too generic to describe the purpose, as other four diagrams (activity, sequence, collaboration, and Statechart) also have the same purpose. We will look into some specific purpose, which will distinguish it from other four diagrams. Use case diagrams are used to gather the requirements of a system including internal and external influences. These requirements are mostly design requirements. Hence, when a system is analyzed to gather its functionalities, use cases are prepared and actors are identified. When the initial task is complete, use case diagrams are modelled to present the outside view. In brief, the purposes of use case diagrams can be said to be as follows − Used to gather the requirements of a system. Used to gather the requirements of a system. Used to get an outside view of a system. Used to get an outside view of a system. Identify the external and internal factors influencing the system. Identify the external and internal factors influencing the system. Show the interaction among the requirements are actors. Show the interaction among the requirements are actors. Use case diagrams are considered for high level requirement analysis of a system. When the requirements of a system are analyzed, the functionalities are captured in use cases. We can say that use cases are nothing but the system functionalities written in an organized manner. The second thing which is relevant to use cases are the actors. Actors can be defined as something that interacts with the system. Actors can be a human user, some internal applications, or may be some external applications. When we are planning to draw a use case diagram, we should have the following items identified. Functionalities to be represented as use case Functionalities to be represented as use case Actors Actors Relationships among the use cases and actors. Relationships among the use cases and actors. Use case diagrams are drawn to capture the functional requirements of a system. After identifying the above items, we have to use the following guidelines to draw an efficient use case diagram The name of a use case is very important. The name should be chosen in such a way so that it can identify the functionalities performed. The name of a use case is very important. The name should be chosen in such a way so that it can identify the functionalities performed. Give a suitable name for actors. Give a suitable name for actors. Show relationships and dependencies clearly in the diagram. Show relationships and dependencies clearly in the diagram. Do not try to include all types of relationships, as the main purpose of the diagram is to identify the requirements. Do not try to include all types of relationships, as the main purpose of the diagram is to identify the requirements. Use notes whenever required to clarify some important points. Use notes whenever required to clarify some important points. Following is a sample use case diagram representing the order management system. Hence, if we look into the diagram then we will find three use cases (Order, SpecialOrder, and NormalOrder) and one actor which is the customer. The SpecialOrder and NormalOrder use cases are extended from Order use case. Hence, they have extended relationship. Another important point is to identify the system boundary, which is shown in the picture. The actor Customer lies outside the system as it is an external user of the system. As we have already discussed there are five diagrams in UML to model the dynamic view of a system. Now each and every model has some specific purpose to use. Actually these specific purposes are different angles of a running system. To understand the dynamics of a system, we need to use different types of diagrams. Use case diagram is one of them and its specific purpose is to gather system requirements and actors. Use case diagrams specify the events of a system and their flows. But use case diagram never describes how they are implemented. Use case diagram can be imagined as a black box where only the input, output, and the function of the black box is known. These diagrams are used at a very high level of design. This high level design is refined again and again to get a complete and practical picture of the system. A well-structured use case also describes the pre-condition, post condition, and exceptions. These extra elements are used to make test cases when performing the testing. Although use case is not a good candidate for forward and reverse engineering, still they are used in a slightly different way to make forward and reverse engineering. The same is true for reverse engineering. Use case diagram is used differently to make it suitable for reverse engineering. In forward engineering, use case diagrams are used to make test cases and in reverse engineering use cases are used to prepare the requirement details from the existing application. Use case diagrams can be used for − Requirement analysis and high level design. Requirement analysis and high level design. Model the context of a system. Model the context of a system. Reverse engineering. Reverse engineering. Forward engineering. Forward engineering. From the term Interaction, it is clear that the diagram is used to describe some type of interactions among the different elements in the model. This interaction is a part of dynamic behavior of the system. This interactive behavior is represented in UML by two diagrams known as Sequence diagram and Collaboration diagram. The basic purpose of both the diagrams are similar. Sequence diagram emphasizes on time sequence of messages and collaboration diagram emphasizes on the structural organization of the objects that send and receive messages. The purpose of interaction diagrams is to visualize the interactive behavior of the system. Visualizing the interaction is a difficult task. Hence, the solution is to use different types of models to capture the different aspects of the interaction. Sequence and collaboration diagrams are used to capture the dynamic nature but from a different angle. The purpose of interaction diagram is − To capture the dynamic behaviour of a system. To capture the dynamic behaviour of a system. To describe the message flow in the system. To describe the message flow in the system. To describe the structural organization of the objects. To describe the structural organization of the objects. To describe the interaction among objects. To describe the interaction among objects. As we have already discussed, the purpose of interaction diagrams is to capture the dynamic aspect of a system. So to capture the dynamic aspect, we need to understand what a dynamic aspect is and how it is visualized. Dynamic aspect can be defined as the snapshot of the running system at a particular moment We have two types of interaction diagrams in UML. One is the sequence diagram and the other is the collaboration diagram. The sequence diagram captures the time sequence of the message flow from one object to another and the collaboration diagram describes the organization of objects in a system taking part in the message flow. Following things are to be identified clearly before drawing the interaction diagram Objects taking part in the interaction. Objects taking part in the interaction. Message flows among the objects. Message flows among the objects. The sequence in which the messages are flowing. The sequence in which the messages are flowing. Object organization. Object organization. Following are two interaction diagrams modeling the order management system. The first diagram is a sequence diagram and the second is a collaboration diagram The sequence diagram has four objects (Customer, Order, SpecialOrder and NormalOrder). The following diagram shows the message sequence for SpecialOrder object and the same can be used in case of NormalOrder object. It is important to understand the time sequence of message flows. The message flow is nothing but a method call of an object. The first call is sendOrder () which is a method of Order object. The next call is confirm () which is a method of SpecialOrder object and the last call is Dispatch () which is a method of SpecialOrder object. The following diagram mainly describes the method calls from one object to another, and this is also the actual scenario when the system is running. The second interaction diagram is the collaboration diagram. It shows the object organization as seen in the following diagram. In the collaboration diagram, the method call sequence is indicated by some numbering technique. The number indicates how the methods are called one after another. We have taken the same order management system to describe the collaboration diagram. Method calls are similar to that of a sequence diagram. However, difference being the sequence diagram does not describe the object organization, whereas the collaboration diagram shows the object organization. To choose between these two diagrams, emphasis is placed on the type of requirement. If the time sequence is important, then the sequence diagram is used. If organization is required, then collaboration diagram is used. We have already discussed that interaction diagrams are used to describe the dynamic nature of a system. Now, we will look into the practical scenarios where these diagrams are used. To understand the practical application, we need to understand the basic nature of sequence and collaboration diagram. The main purpose of both the diagrams are similar as they are used to capture the dynamic behavior of a system. However, the specific purpose is more important to clarify and understand. Sequence diagrams are used to capture the order of messages flowing from one object to another. Collaboration diagrams are used to describe the structural organization of the objects taking part in the interaction. A single diagram is not sufficient to describe the dynamic aspect of an entire system, so a set of diagrams are used to capture it as a whole. Interaction diagrams are used when we want to understand the message flow and the structural organization. Message flow means the sequence of control flow from one object to another. Structural organization means the visual organization of the elements in a system. Interaction diagrams can be used − To model the flow of control by time sequence. To model the flow of control by time sequence. To model the flow of control by structural organizations. To model the flow of control by structural organizations. For forward engineering. For forward engineering. For reverse engineering. For reverse engineering. The name of the diagram itself clarifies the purpose of the diagram and other details. It describes different states of a component in a system. The states are specific to a component/object of a system. A Statechart diagram describes a state machine. State machine can be defined as a machine which defines different states of an object and these states are controlled by external or internal events. Activity diagram explained in the next chapter, is a special kind of a Statechart diagram. As Statechart diagram defines the states, it is used to model the lifetime of an object. Statechart diagram is one of the five UML diagrams used to model the dynamic nature of a system. They define different states of an object during its lifetime and these states are changed by events. Statechart diagrams are useful to model the reactive systems. Reactive systems can be defined as a system that responds to external or internal events. Statechart diagram describes the flow of control from one state to another state. States are defined as a condition in which an object exists and it changes when some event is triggered. The most important purpose of Statechart diagram is to model lifetime of an object from creation to termination. Statechart diagrams are also used for forward and reverse engineering of a system. However, the main purpose is to model the reactive system. Following are the main purposes of using Statechart diagrams − To model the dynamic aspect of a system. To model the dynamic aspect of a system. To model the life time of a reactive system. To model the life time of a reactive system. To describe different states of an object during its life time. To describe different states of an object during its life time. Define a state machine to model the states of an object. Define a state machine to model the states of an object. Statechart diagram is used to describe the states of different objects in its life cycle. Emphasis is placed on the state changes upon some internal or external events. These states of objects are important to analyze and implement them accurately. Statechart diagrams are very important for describing the states. States can be identified as the condition of objects when a particular event occurs. Before drawing a Statechart diagram we should clarify the following points − Identify the important objects to be analyzed. Identify the important objects to be analyzed. Identify the states. Identify the states. Identify the events. Identify the events. Following is an example of a Statechart diagram where the state of Order object is analyzed The first state is an idle state from where the process starts. The next states are arrived for events like send request, confirm request, and dispatch order. These events are responsible for the state changes of order object. During the life cycle of an object (here order object) it goes through the following states and there may be some abnormal exits. This abnormal exit may occur due to some problem in the system. When the entire life cycle is complete, it is considered as a complete transaction as shown in the following figure. The initial and final state of an object is also shown in the following figure. From the above discussion, we can define the practical applications of a Statechart diagram. Statechart diagrams are used to model the dynamic aspect of a system like other four diagrams discussed in this tutorial. However, it has some distinguishing characteristics for modeling the dynamic nature. Statechart diagram defines the states of a component and these state changes are dynamic in nature. Its specific purpose is to define the state changes triggered by events. Events are internal or external factors influencing the system. Statechart diagrams are used to model the states and also the events operating on the system. When implementing a system, it is very important to clarify different states of an object during its life time and Statechart diagrams are used for this purpose. When these states and events are identified, they are used to model it and these models are used during the implementation of the system. If we look into the practical implementation of Statechart diagram, then it is mainly used to analyze the object states influenced by events. This analysis is helpful to understand the system behavior during its execution. The main usage can be described as − To model the object states of a system. To model the object states of a system. To model the reactive system. Reactive system consists of reactive objects. To model the reactive system. Reactive system consists of reactive objects. To identify the events responsible for state changes. To identify the events responsible for state changes. Forward and reverse engineering. Forward and reverse engineering. Activity diagram is another important diagram in UML to describe the dynamic aspects of the system. Activity diagram is basically a flowchart to represent the flow from one activity to another activity. The activity can be described as an operation of the system. The control flow is drawn from one operation to another. This flow can be sequential, branched, or concurrent. Activity diagrams deal with all type of flow control by using different elements such as fork, join, etc The basic purposes of activity diagrams is similar to other four diagrams. It captures the dynamic behavior of the system. Other four diagrams are used to show the message flow from one object to another but activity diagram is used to show message flow from one activity to another. Activity is a particular operation of the system. Activity diagrams are not only used for visualizing the dynamic nature of a system, but they are also used to construct the executable system by using forward and reverse engineering techniques. The only missing thing in the activity diagram is the message part. It does not show any message flow from one activity to another. Activity diagram is sometimes considered as the flowchart. Although the diagrams look like a flowchart, they are not. It shows different flows such as parallel, branched, concurrent, and single. The purpose of an activity diagram can be described as − Draw the activity flow of a system. Draw the activity flow of a system. Describe the sequence from one activity to another. Describe the sequence from one activity to another. Describe the parallel, branched and concurrent flow of the system. Describe the parallel, branched and concurrent flow of the system. Activity diagrams are mainly used as a flowchart that consists of activities performed by the system. Activity diagrams are not exactly flowcharts as they have some additional capabilities. These additional capabilities include branching, parallel flow, swimlane, etc. Before drawing an activity diagram, we must have a clear understanding about the elements used in activity diagram. The main element of an activity diagram is the activity itself. An activity is a function performed by the system. After identifying the activities, we need to understand how they are associated with constraints and conditions. Before drawing an activity diagram, we should identify the following elements − Activities Activities Association Association Conditions Conditions Constraints Constraints Once the above-mentioned parameters are identified, we need to make a mental layout of the entire flow. This mental layout is then transformed into an activity diagram. Following is an example of an activity diagram for order management system. In the diagram, four activities are identified which are associated with conditions. One important point should be clearly understood that an activity diagram cannot be exactly matched with the code. The activity diagram is made to understand the flow of activities and is mainly used by the business users Following diagram is drawn with the four main activities − Send order by the customer Send order by the customer Receipt of the order Receipt of the order Confirm the order Confirm the order Dispatch the order Dispatch the order After receiving the order request, condition checks are performed to check if it is normal or special order. After the type of order is identified, dispatch activity is performed and that is marked as the termination of the process. The basic usage of activity diagram is similar to other four UML diagrams. The specific usage is to model the control flow from one activity to another. This control flow does not include messages. Activity diagram is suitable for modeling the activity flow of the system. An application can have multiple systems. Activity diagram also captures these systems and describes the flow from one system to another. This specific usage is not available in other diagrams. These systems can be database, external queues, or any other system. We will now look into the practical applications of the activity diagram. From the above discussion, it is clear that an activity diagram is drawn from a very high level. So it gives high level view of a system. This high level view is mainly for business users or any other person who is not a technical person. This diagram is used to model the activities which are nothing but business requirements. The diagram has more impact on business understanding rather than on implementation details. Activity diagram can be used for − Modeling work flow by using activities. Modeling work flow by using activities. Modeling business requirements. Modeling business requirements. High level understanding of the system's functionalities. High level understanding of the system's functionalities. Investigating business requirements at a later stage. Investigating business requirements at a later stage.
[ { "code": null, "e": 2209, "s": 2088, "text": "UML is a standard language for specifying, visualizing, constructing, and documenting the\nartifacts of software systems." }, { "code": null, "e": 2335, "s": 2209, "text": "UML was created by the Object Management Group (OMG) and UML 1.0 specification draft was proposed to the OMG in January 1997." }, { "code": null, "e": 2407, "s": 2335, "text": "OMG is continuously making efforts to create a truly industry standard." }, { "code": null, "e": 2449, "s": 2407, "text": "UML stands for Unified Modeling Language." }, { "code": null, "e": 2491, "s": 2449, "text": "UML stands for Unified Modeling Language." }, { "code": null, "e": 2583, "s": 2491, "text": "UML is different from the other common programming languages such as C++, Java, COBOL, etc." }, { "code": null, "e": 2675, "s": 2583, "text": "UML is different from the other common programming languages such as C++, Java, COBOL, etc." }, { "code": null, "e": 2737, "s": 2675, "text": "UML is a pictorial language used to make software blueprints." }, { "code": null, "e": 2799, "s": 2737, "text": "UML is a pictorial language used to make software blueprints." }, { "code": null, "e": 2930, "s": 2799, "text": "UML can be described as a general purpose visual modeling language to visualize, specify, construct, and document software system." }, { "code": null, "e": 3061, "s": 2930, "text": "UML can be described as a general purpose visual modeling language to visualize, specify, construct, and document software system." }, { "code": null, "e": 3274, "s": 3061, "text": "Although UML is generally used to model software systems, it is not limited within this boundary. It is also used to model non-software systems as well. For example, the process flow in a manufacturing unit, etc." }, { "code": null, "e": 3487, "s": 3274, "text": "Although UML is generally used to model software systems, it is not limited within this boundary. It is also used to model non-software systems as well. For example, the process flow in a manufacturing unit, etc." }, { "code": null, "e": 3729, "s": 3487, "text": "UML is not a programming language but tools can be used to generate code in various languages using UML diagrams. UML has a direct relation with object oriented analysis and design. After some standardization, UML has become an OMG standard." }, { "code": null, "e": 4034, "s": 3729, "text": "A picture is worth a thousand words, this idiom absolutely fits describing UML. Object-oriented\nconcepts were introduced much earlier than UML. At that point of time, there were no standard methodologies to organize and consolidate the object-oriented development. It was then that UML came into picture." }, { "code": null, "e": 4243, "s": 4034, "text": "There are a number of goals for developing UML but the most important is to define some general purpose modeling language, which all modelers can use and it also needs to be made simple to understand and use." }, { "code": null, "e": 4563, "s": 4243, "text": "UML diagrams are not only made for developers but also for business users, common people, and anybody interested to understand the system. The system can be a software or non-software system. Thus it must be clear that UML is not a development method rather it accompanies with processes to make it a successful system." }, { "code": null, "e": 4712, "s": 4563, "text": "In conclusion, the goal of UML can be defined as a simple modeling mechanism to model all possible practical systems in today’s complex environment." }, { "code": null, "e": 4848, "s": 4712, "text": "To understand the conceptual model of UML, first we need to clarify what is a conceptual model? and why a conceptual model is required?" }, { "code": null, "e": 4944, "s": 4848, "text": "A conceptual model can be defined as a model which is made of concepts and their relationships." }, { "code": null, "e": 5040, "s": 4944, "text": "A conceptual model can be defined as a model which is made of concepts and their relationships." }, { "code": null, "e": 5200, "s": 5040, "text": "A conceptual model is the first step before drawing a UML diagram. It helps to understand the entities in the real world and how they interact with each other." }, { "code": null, "e": 5360, "s": 5200, "text": "A conceptual model is the first step before drawing a UML diagram. It helps to understand the entities in the real world and how they interact with each other." }, { "code": null, "e": 5569, "s": 5360, "text": "As UML describes the real-time systems, it is very important to make a conceptual model and then proceed gradually. The conceptual model of UML can be mastered by learning the following three major elements −" }, { "code": null, "e": 5589, "s": 5569, "text": "UML building blocks" }, { "code": null, "e": 5626, "s": 5589, "text": "Rules to connect the building blocks" }, { "code": null, "e": 5651, "s": 5626, "text": "Common mechanisms of UML" }, { "code": null, "e": 5734, "s": 5651, "text": "UML can be described as the successor of object-oriented (OO) analysis and design." }, { "code": null, "e": 6059, "s": 5734, "text": "An object contains both data and methods that control the data. The data represents the state of the object. A class describes an object and they also form a hierarchy to model the real-world system. The hierarchy is represented as inheritance and the classes can also be associated in different ways as per the requirement." }, { "code": null, "e": 6239, "s": 6059, "text": "Objects are the real-world entities that exist around us and the basic concepts such as abstraction, encapsulation, inheritance, and polymorphism all can be represented using UML." }, { "code": null, "e": 6493, "s": 6239, "text": "UML is powerful enough to represent all the concepts that exist in object-oriented analysis and design. UML diagrams are representation of object-oriented concepts only. Thus, before learning UML, it becomes important to understand OO concept in detail." }, { "code": null, "e": 6564, "s": 6493, "text": "Following are some fundamental concepts of the object-oriented world −" }, { "code": null, "e": 6632, "s": 6564, "text": "Objects − Objects represent an entity and the basic building block." }, { "code": null, "e": 6700, "s": 6632, "text": "Objects − Objects represent an entity and the basic building block." }, { "code": null, "e": 6746, "s": 6700, "text": "Class − Class is the blue print of an object." }, { "code": null, "e": 6792, "s": 6746, "text": "Class − Class is the blue print of an object." }, { "code": null, "e": 6867, "s": 6792, "text": "Abstraction − Abstraction represents the behavior of an real world entity." }, { "code": null, "e": 6942, "s": 6867, "text": "Abstraction − Abstraction represents the behavior of an real world entity." }, { "code": null, "e": 7058, "s": 6942, "text": "Encapsulation − Encapsulation is the mechanism of binding the data together and\nhiding them from the outside world." }, { "code": null, "e": 7174, "s": 7058, "text": "Encapsulation − Encapsulation is the mechanism of binding the data together and\nhiding them from the outside world." }, { "code": null, "e": 7259, "s": 7174, "text": "Inheritance − Inheritance is the mechanism of making new classes from existing ones." }, { "code": null, "e": 7344, "s": 7259, "text": "Inheritance − Inheritance is the mechanism of making new classes from existing ones." }, { "code": null, "e": 7414, "s": 7344, "text": "Polymorphism − It defines the mechanism to exists in different forms." }, { "code": null, "e": 7484, "s": 7414, "text": "Polymorphism − It defines the mechanism to exists in different forms." }, { "code": null, "e": 7633, "s": 7484, "text": "OO can be defined as an investigation and to be more specific, it is the investigation of objects. Design means collaboration of identified objects." }, { "code": null, "e": 8072, "s": 7633, "text": "Thus, it is important to understand the OO analysis and design concepts. The most important purpose of OO analysis is to identify objects of a system to be designed. This analysis is also done for an existing system. Now an efficient analysis is only possible when we are able to start thinking in a way where objects can be identified. After identifying the objects, their relationships are identified and finally the design is produced." }, { "code": null, "e": 8129, "s": 8072, "text": "The purpose of OO analysis and design can described as −" }, { "code": null, "e": 8166, "s": 8129, "text": "Identifying the objects of a system." }, { "code": null, "e": 8203, "s": 8166, "text": "Identifying the objects of a system." }, { "code": null, "e": 8236, "s": 8203, "text": "Identifying their relationships." }, { "code": null, "e": 8269, "s": 8236, "text": "Identifying their relationships." }, { "code": null, "e": 8344, "s": 8269, "text": "Making a design, which can be converted to executables using OO languages." }, { "code": null, "e": 8419, "s": 8344, "text": "Making a design, which can be converted to executables using OO languages." }, { "code": null, "e": 8526, "s": 8419, "text": "There are three basic steps where the OO concepts are applied and implemented. The steps can be defined as" }, { "code": null, "e": 8589, "s": 8526, "text": "OO Analysis → OO Design → OO implementation using OO languages" }, { "code": null, "e": 8644, "s": 8589, "text": "The above three points can be described in detail as −" }, { "code": null, "e": 9106, "s": 8644, "text": "During OO analysis, the most important purpose is to identify objects and describe them in a proper way. If these objects are identified efficiently, then the next job of design is easy. The objects should be identified with responsibilities. Responsibilities are the functions performed by the object. Each and every object has some type of responsibilities to be performed. When these responsibilities are\ncollaborated, the purpose of the system is fulfilled." }, { "code": null, "e": 9568, "s": 9106, "text": "During OO analysis, the most important purpose is to identify objects and describe them in a proper way. If these objects are identified efficiently, then the next job of design is easy. The objects should be identified with responsibilities. Responsibilities are the functions performed by the object. Each and every object has some type of responsibilities to be performed. When these responsibilities are\ncollaborated, the purpose of the system is fulfilled." }, { "code": null, "e": 9828, "s": 9568, "text": "The second phase is OO design. During this phase, emphasis is placed on the requirements and their fulfilment. In this stage, the objects are collaborated according to their intended association. After the association is complete, the\ndesign is also complete." }, { "code": null, "e": 10088, "s": 9828, "text": "The second phase is OO design. During this phase, emphasis is placed on the requirements and their fulfilment. In this stage, the objects are collaborated according to their intended association. After the association is complete, the\ndesign is also complete." }, { "code": null, "e": 10210, "s": 10088, "text": "The third phase is OO implementation. In this phase, the design is implemented using OO languages such as Java, C++, etc." }, { "code": null, "e": 10332, "s": 10210, "text": "The third phase is OO implementation. In this phase, the design is implemented using OO languages such as Java, C++, etc." }, { "code": null, "e": 10684, "s": 10332, "text": "UML is a modeling language used to model software and non-software systems. Although UML is used for non-software systems, the emphasis is on modeling OO software applications. Most of the UML diagrams discussed so far are used to model different\naspects such as static, dynamic, etc. Now whatever be the aspect, the artifacts are nothing but objects." }, { "code": null, "e": 10829, "s": 10684, "text": "If we look into class diagram, object diagram, collaboration diagram, interaction diagrams all would basically be designed based on the objects." }, { "code": null, "e": 11205, "s": 10829, "text": "Hence, the relation between OO design and UML is very important to understand. The OO design is transformed into UML diagrams according to the requirement. Before understanding the UML in detail, the OO concept should be learned properly. Once the OO analysis and design is done, the next step is very easy. The input from OO analysis and\ndesign is the input to UML diagrams." }, { "code": null, "e": 11414, "s": 11205, "text": "As UML describes the real-time systems, it is very important to make a conceptual model and then proceed gradually. The conceptual model of UML can be mastered by learning the following three major elements −" }, { "code": null, "e": 11434, "s": 11414, "text": "UML building blocks" }, { "code": null, "e": 11471, "s": 11434, "text": "Rules to connect the building blocks" }, { "code": null, "e": 11496, "s": 11471, "text": "Common mechanisms of UML" }, { "code": null, "e": 11595, "s": 11496, "text": "This chapter describes all the UML building blocks. The building blocks of UML can be defined as −" }, { "code": null, "e": 11602, "s": 11595, "text": "Things" }, { "code": null, "e": 11616, "s": 11602, "text": "Relationships" }, { "code": null, "e": 11625, "s": 11616, "text": "Diagrams" }, { "code": null, "e": 11695, "s": 11625, "text": "Things are the most important building blocks of UML. Things can be −" }, { "code": null, "e": 11706, "s": 11695, "text": "Structural" }, { "code": null, "e": 11717, "s": 11706, "text": "Behavioral" }, { "code": null, "e": 11726, "s": 11717, "text": "Grouping" }, { "code": null, "e": 11739, "s": 11726, "text": "Annotational" }, { "code": null, "e": 11910, "s": 11739, "text": "Structural things define the static part of the model. They represent the physical and\nconceptual elements. Following are the brief descriptions of the structural things." }, { "code": null, "e": 11985, "s": 11910, "text": "Class − Class represents a set of objects having similar responsibilities." }, { "code": null, "e": 12081, "s": 11985, "text": "Interface − Interface defines a set of operations, which specify the responsibility of a class." }, { "code": null, "e": 12151, "s": 12081, "text": "Collaboration −Collaboration defines an interaction between elements." }, { "code": null, "e": 12241, "s": 12151, "text": "Use case −Use case represents a set of actions performed by a system for a specific goal." }, { "code": null, "e": 12303, "s": 12241, "text": "Component −Component describes the physical part of a system." }, { "code": null, "e": 12379, "s": 12303, "text": "Node − A node can be defined as a physical element that exists at run time." }, { "code": null, "e": 12481, "s": 12379, "text": "A behavioral thing consists of the dynamic parts of UML models. Following are the\nbehavioral things −" }, { "code": null, "e": 12625, "s": 12481, "text": "Interaction − Interaction is defined as a behavior that consists of a group of messages exchanged among elements to accomplish a specific task." }, { "code": null, "e": 12862, "s": 12625, "text": "State machine − State machine is useful when the state of an object in its life cycle is\nimportant. It defines the sequence of states an object goes through in response to events. Events are external factors responsible for state change" }, { "code": null, "e": 12996, "s": 12862, "text": "Grouping things can be defined as a mechanism to group elements of a UML model together. There is only one grouping thing available −" }, { "code": null, "e": 13103, "s": 12996, "text": "Package − Package is the only one grouping thing available for gathering structural and behavioral things." }, { "code": null, "e": 13351, "s": 13103, "text": "Annotational things can be defined as a mechanism to capture remarks, descriptions, and comments of UML model elements. Note - It is the only one Annotational thing available. A note is used to render comments, constraints, etc. of an UML element." }, { "code": null, "e": 13538, "s": 13351, "text": "Relationship is another most important building block of UML. It shows how the elements\nare associated with each other and this association describes the functionality of an application." }, { "code": null, "e": 13587, "s": 13538, "text": "There are four kinds of relationships available." }, { "code": null, "e": 13690, "s": 13587, "text": "Dependency is a relationship between two things in which change in one element also affects the other." }, { "code": null, "e": 13846, "s": 13690, "text": "Association is basically a set of links that connects the elements of a UML model. It also describes how many objects are taking part in that relationship." }, { "code": null, "e": 14036, "s": 13846, "text": "Generalization can be defined as a relationship which connects a specialized element with a generalized element. It basically describes the inheritance relationship in the world of objects." }, { "code": null, "e": 14269, "s": 14036, "text": "Realization can be defined as a relationship in which two elements are connected. One element describes some responsibility, which is not implemented and the other one implements them. This relationship exists in case of interfaces." }, { "code": null, "e": 14441, "s": 14269, "text": "UML diagrams are the ultimate output of the entire discussion. All the elements, relationships are used to make a complete UML diagram and the diagram represents a system." }, { "code": null, "e": 14581, "s": 14441, "text": "The visual effect of the UML diagram is the most important part of the entire process. All the other elements are used to make it complete." }, { "code": null, "e": 14686, "s": 14581, "text": "UML includes the following nine diagrams, the details of which are described in the subsequent chapters." }, { "code": null, "e": 14700, "s": 14686, "text": "Class diagram" }, { "code": null, "e": 14715, "s": 14700, "text": "Object diagram" }, { "code": null, "e": 14732, "s": 14715, "text": "Use case diagram" }, { "code": null, "e": 14749, "s": 14732, "text": "Sequence diagram" }, { "code": null, "e": 14771, "s": 14749, "text": "Collaboration diagram" }, { "code": null, "e": 14788, "s": 14771, "text": "Activity diagram" }, { "code": null, "e": 14807, "s": 14788, "text": "Statechart diagram" }, { "code": null, "e": 14826, "s": 14807, "text": "Deployment diagram" }, { "code": null, "e": 14844, "s": 14826, "text": "Component diagram" }, { "code": null, "e": 15225, "s": 14844, "text": "Any real-world system is used by different users. The users can be developers, testers, business people, analysts, and many more. Hence, before designing a system, the architecture is made with different perspectives in mind. The most important part is to\nvisualize the system from the perspective of different viewers. The better we understand the better we can build the system." }, { "code": null, "e": 15326, "s": 15225, "text": "UML plays an important role in defining different perspectives of a system. These perspectives are −" }, { "code": null, "e": 15333, "s": 15326, "text": "Design" }, { "code": null, "e": 15348, "s": 15333, "text": "Implementation" }, { "code": null, "e": 15356, "s": 15348, "text": "Process" }, { "code": null, "e": 15367, "s": 15356, "text": "Deployment" }, { "code": null, "e": 15540, "s": 15367, "text": "The center is the Use Case view which connects all these four. A Use Case represents\nthe functionality of the system. Hence, other perspectives are connected with use case." }, { "code": null, "e": 15671, "s": 15540, "text": "Design of a system consists of classes, interfaces, and collaboration. UML provides class\ndiagram, object diagram to support this." }, { "code": null, "e": 15837, "s": 15671, "text": "Implementation defines the components assembled together to make a complete physical system. UML component diagram is used to support the implementation perspective." }, { "code": null, "e": 15963, "s": 15837, "text": "Process defines the flow of the system. Hence, the same elements as used in Design are\nalso used to support this perspective." }, { "code": null, "e": 16103, "s": 15963, "text": "Deployment represents the physical nodes of the system that forms the hardware. UML\ndeployment diagram is used to support this perspective." }, { "code": null, "e": 16276, "s": 16103, "text": "It is very important to distinguish between the UML model. Different diagrams are used for different types of UML modeling. There are three important types of UML modeling." }, { "code": null, "e": 16370, "s": 16276, "text": "Structural modeling captures the static features of a system. They consist of the following −" }, { "code": null, "e": 16387, "s": 16370, "text": "Classes diagrams" }, { "code": null, "e": 16404, "s": 16387, "text": "Objects diagrams" }, { "code": null, "e": 16424, "s": 16404, "text": "Deployment diagrams" }, { "code": null, "e": 16441, "s": 16424, "text": "Package diagrams" }, { "code": null, "e": 16469, "s": 16441, "text": "Composite structure diagram" }, { "code": null, "e": 16487, "s": 16469, "text": "Component diagram" }, { "code": null, "e": 16779, "s": 16487, "text": "Structural model represents the framework for the system and this framework is the place where all other components exist. Hence, the class diagram, component diagram and deployment diagrams are part of structural modeling. They all represent the elements and the mechanism to assemble them." }, { "code": null, "e": 16910, "s": 16779, "text": "The structural model never describes the dynamic behavior of the system. Class diagram is the most widely used structural diagram." }, { "code": null, "e": 17121, "s": 16910, "text": "Behavioral model describes the interaction in the system. It represents the interaction among the structural diagrams. Behavioral modeling shows the dynamic nature of the system. They consist of the following −" }, { "code": null, "e": 17139, "s": 17121, "text": "Activity diagrams" }, { "code": null, "e": 17160, "s": 17139, "text": "Interaction diagrams" }, { "code": null, "e": 17179, "s": 17160, "text": "Use case diagrams" }, { "code": null, "e": 17240, "s": 17179, "text": "All the above show the dynamic sequence of flow in a system." }, { "code": null, "e": 17501, "s": 17240, "text": "Architectural model represents the overall framework of the system. It contains both structural and behavioral elements of the system. Architectural model can be defined as the blueprint of the entire system. Package diagram comes under architectural modeling." }, { "code": null, "e": 17776, "s": 17501, "text": "UML is popular for its diagrammatic notations. We all know that UML is for visualizing, specifying, constructing and documenting the components of software and non-software systems. Hence, visualization is the most important part which needs to be understood and remembered." }, { "code": null, "e": 18003, "s": 17776, "text": "UML notations are the most important elements in modeling. Efficient and appropriate use of notations is very important for making a complete and meaningful model. The model is useless, unless its purpose is depicted properly." }, { "code": null, "e": 18297, "s": 18003, "text": "Hence, learning notations should be emphasized from the very beginning. Different notations are available for things and relationships. UML diagrams are made using the notations of things and relationships. Extensibility is another important feature which\nmakes UML more powerful and flexible." }, { "code": null, "e": 18436, "s": 18297, "text": "The chapter describes basic UML notations in detail. This is just an extension to the UML building block section discussed in Chapter Two." }, { "code": null, "e": 18605, "s": 18436, "text": "Graphical notations used in structural things are most widely used in UML. These are considered as the nouns of UML models. Following are the list of structural things." }, { "code": null, "e": 18613, "s": 18605, "text": "Classes" }, { "code": null, "e": 18620, "s": 18613, "text": "Object" }, { "code": null, "e": 18630, "s": 18620, "text": "Interface" }, { "code": null, "e": 18644, "s": 18630, "text": "Collaboration" }, { "code": null, "e": 18653, "s": 18644, "text": "Use case" }, { "code": null, "e": 18668, "s": 18653, "text": "Active classes" }, { "code": null, "e": 18679, "s": 18668, "text": "Components" }, { "code": null, "e": 18685, "s": 18679, "text": "Nodes" }, { "code": null, "e": 18775, "s": 18685, "text": "UML class is represented by the following figure. The diagram is divided into four parts." }, { "code": null, "e": 18818, "s": 18775, "text": "The top section is used to name the class." }, { "code": null, "e": 18878, "s": 18818, "text": "The second one is used to show the attributes of the class." }, { "code": null, "e": 18955, "s": 18878, "text": "The third section is used to describe the operations performed by the class." }, { "code": null, "e": 19021, "s": 18955, "text": "The fourth section is optional to show any additional components." }, { "code": null, "e": 19122, "s": 19021, "text": "Classes are used to represent objects. Objects can be anything having properties and responsibility." }, { "code": null, "e": 19264, "s": 19122, "text": "The object is represented in the same way as the class. The only difference is the name which is underlined as shown in the following figure." }, { "code": null, "e": 19404, "s": 19264, "text": "As the object is an actual implementation of a class, which is known as the instance of a class. Hence, it has the same usage as the class." }, { "code": null, "e": 19534, "s": 19404, "text": "Interface is represented by a circle as shown in the following figure. It has a name which is generally written below the circle." }, { "code": null, "e": 19798, "s": 19534, "text": "Interface is used to describe the functionality without implementation. Interface is just like\na template where you define different functions, not the implementation. When a class implements the interface, it also implements the functionality as per requirement." }, { "code": null, "e": 19923, "s": 19798, "text": "Collaboration is represented by a dotted eclipse as shown in the following figure. It has a name written inside the eclipse." }, { "code": null, "e": 20010, "s": 19923, "text": "Collaboration represents responsibilities. Generally, responsibilities are in a group." }, { "code": null, "e": 20115, "s": 20010, "text": "Use case is represented as an eclipse with a name inside it. It may contain additional responsibilities." }, { "code": null, "e": 20183, "s": 20115, "text": "Use case is used to capture high level functionalities of a system." }, { "code": null, "e": 20275, "s": 20183, "text": "An actor can be defined as some internal or external entity that interacts with the system." }, { "code": null, "e": 20361, "s": 20275, "text": "An actor is used in a use case diagram to describe the internal or external entities." }, { "code": null, "e": 20464, "s": 20361, "text": "Initial state is defined to show the start of a process. This notation is used in almost all diagrams." }, { "code": null, "e": 20544, "s": 20464, "text": "The usage of Initial State Notation is to show the starting point of a process." }, { "code": null, "e": 20665, "s": 20544, "text": "Final state is used to show the end of a process. This notation is also used in almost all diagrams to describe the end." }, { "code": null, "e": 20747, "s": 20665, "text": "The usage of Final State Notation is to show the termination point of a process." }, { "code": null, "e": 20886, "s": 20747, "text": "Active class looks similar to a class with a solid border. Active class is generally used to describe the concurrent behavior of a system." }, { "code": null, "e": 20949, "s": 20886, "text": "Active class is used to represent the concurrency in a system." }, { "code": null, "e": 21073, "s": 20949, "text": "A component in UML is shown in the following figure with a name inside. Additional elements can be added wherever required." }, { "code": null, "e": 21158, "s": 21073, "text": "Component is used to represent any part of a system for which UML diagrams are made." }, { "code": null, "e": 21305, "s": 21158, "text": "A node in UML is represented by a square box as shown in the following figure with a name. A node represents the physical component of the system." }, { "code": null, "e": 21395, "s": 21305, "text": "Node is used to represent the physical part of a system such as the server, network, etc." }, { "code": null, "e": 21615, "s": 21395, "text": "Dynamic parts are one of the most important elements in UML. UML has a set of powerful\nfeatures to represent the dynamic part of software and non-software systems. These features include interactions and state machines." }, { "code": null, "e": 21650, "s": 21615, "text": "Interactions can be of two types −" }, { "code": null, "e": 21695, "s": 21650, "text": "Sequential (Represented by sequence diagram)" }, { "code": null, "e": 21748, "s": 21695, "text": "Collaborative (Represented by collaboration diagram)" }, { "code": null, "e": 21897, "s": 21748, "text": "Interaction is basically a message exchange between two UML components. The following diagram represents different notations used in an interaction." }, { "code": null, "e": 21982, "s": 21897, "text": "Interaction is used to represent the communication among the components of a system." }, { "code": null, "e": 22115, "s": 21982, "text": "State machine describes the different states of a component in its life cycle. The notations are described in the following diagram." }, { "code": null, "e": 22263, "s": 22115, "text": "State machine is used to describe different states of a system component. The state can be active, idle, or any other depending upon the situation." }, { "code": null, "e": 22419, "s": 22263, "text": "Organizing the UML models is one of the most important aspects of the design. In UML, there is only one element available for grouping and that is package." }, { "code": null, "e": 22517, "s": 22419, "text": "Package notation is shown in the following figure and is used to wrap the components of a system." }, { "code": null, "e": 22672, "s": 22517, "text": "In any diagram, explanation of different elements and their functionalities are very important. Hence, UML has notes notation to support this requirement." }, { "code": null, "e": 22791, "s": 22672, "text": "This notation is shown in the following figure. These notations are used to provide necessary information of a system." }, { "code": null, "e": 23006, "s": 22791, "text": "A model is not complete unless the relationships between elements are described properly.\nThe Relationship gives a proper meaning to a UML model. Following are the different types\nof relationships available in UML." }, { "code": null, "e": 23017, "s": 23006, "text": "Dependency" }, { "code": null, "e": 23029, "s": 23017, "text": "Association" }, { "code": null, "e": 23044, "s": 23029, "text": "Generalization" }, { "code": null, "e": 23058, "s": 23044, "text": "Extensibility" }, { "code": null, "e": 23178, "s": 23058, "text": "Dependency is an important aspect in UML elements. It describes the dependent elements and the direction of dependency." }, { "code": null, "e": 23358, "s": 23178, "text": "Dependency is represented by a dotted arrow as shown in the following figure. The arrow head represents the independent element and the other end represents the dependent element." }, { "code": null, "e": 23438, "s": 23358, "text": "Dependency is used to represent the dependency between two elements of a system" }, { "code": null, "e": 23593, "s": 23438, "text": "Association describes how the elements in a UML diagram are associated. In simple words, it describes how many elements are taking part in an interaction." }, { "code": null, "e": 23856, "s": 23593, "text": "Association is represented by a dotted line with (without) arrows on both sides. The two ends represent two associated elements as shown in the following figure. The multiplicity is also mentioned at the ends (1, *, etc.) to show how many objects are associated." }, { "code": null, "e": 23940, "s": 23856, "text": "Association is used to represent the relationship between two elements of a system." }, { "code": null, "e": 24063, "s": 23940, "text": "Generalization describes the inheritance relationship of the object-oriented world. It is a\nparent and child relationship." }, { "code": null, "e": 24250, "s": 24063, "text": "Generalization is represented by an arrow with a hollow arrow head as shown in the following figure. One end represents the parent element and the other end represents the child element." }, { "code": null, "e": 24340, "s": 24250, "text": "Generalization is used to describe parent-child relationship of two elements of a system." }, { "code": null, "e": 24536, "s": 24340, "text": "All the languages (programming or modeling) have some mechanism to extend its capabilities such as syntax, semantics, etc. UML also has the following mechanisms to provide extensibility features." }, { "code": null, "e": 24574, "s": 24536, "text": "Stereotypes (Represents new elements)" }, { "code": null, "e": 24616, "s": 24574, "text": "Tagged values (Represents new attributes)" }, { "code": null, "e": 24656, "s": 24616, "text": "Constraints (Represents the boundaries)" }, { "code": null, "e": 24891, "s": 24656, "text": "Extensibility notations are used to enhance the power of the language. It is basically additional elements used to represent some extra behavior of the system. These extra behaviors are not covered by the standard available notations." }, { "code": null, "e": 25053, "s": 24891, "text": "In the previous chapters, we have discussed about the building blocks and other necessary elements of UML. Now we need to understand where to use those elements." }, { "code": null, "e": 25300, "s": 25053, "text": "The elements are like components which can be associated in different ways to make a complete UML picture, which is known as diagram. Thus, it is very important to understand the different diagrams to implement the knowledge in real-life systems." }, { "code": null, "e": 25582, "s": 25300, "text": "Any complex system is best understood by making some kind of diagrams or pictures. These diagrams have a better impact on our understanding. If we look around, we will realize that the diagrams are not a new concept but it is used widely in different forms in different industries." }, { "code": null, "e": 25810, "s": 25582, "text": "We prepare UML diagrams to understand the system in a better and simple way. A single diagram is not enough to cover all the aspects of the system. UML defines various kinds of diagrams to cover most of the aspects of a system." }, { "code": null, "e": 25947, "s": 25810, "text": "You can also create your own set of diagrams to meet your requirements. Diagrams are generally made in an incremental and iterative way." }, { "code": null, "e": 26038, "s": 25947, "text": "There are two broad categories of diagrams and they are again divided into subcategories −" }, { "code": null, "e": 26058, "s": 26038, "text": "Structural Diagrams" }, { "code": null, "e": 26078, "s": 26058, "text": "Structural Diagrams" }, { "code": null, "e": 26098, "s": 26078, "text": "Behavioral Diagrams" }, { "code": null, "e": 26118, "s": 26098, "text": "Behavioral Diagrams" }, { "code": null, "e": 26299, "s": 26118, "text": "The structural diagrams represent the static aspect of the system. These static aspects represent those parts of a diagram, which forms the main structure and are therefore stable." }, { "code": null, "e": 26425, "s": 26299, "text": "These static parts are represented by classes, interfaces, objects, components, and nodes. The four structural diagrams are −" }, { "code": null, "e": 26439, "s": 26425, "text": "Class diagram" }, { "code": null, "e": 26454, "s": 26439, "text": "Object diagram" }, { "code": null, "e": 26472, "s": 26454, "text": "Component diagram" }, { "code": null, "e": 26491, "s": 26472, "text": "Deployment diagram" }, { "code": null, "e": 26728, "s": 26491, "text": "Class diagrams are the most common diagrams used in UML. Class diagram consists of classes, interfaces, associations, and collaboration. Class diagrams basically represent the object-oriented view of a system, which is static in nature." }, { "code": null, "e": 26812, "s": 26728, "text": "Active class is used in a class diagram to represent the concurrency of the system." }, { "code": null, "e": 26999, "s": 26812, "text": "Class diagram represents the object orientation of a system. Hence, it is generally used for development purpose. This is the most widely used diagram at the time of system construction." }, { "code": null, "e": 27153, "s": 26999, "text": "Object diagrams can be described as an instance of class diagram. Thus, these diagrams are more close to real-life scenarios where we implement a system." }, { "code": null, "e": 27293, "s": 27153, "text": "Object diagrams are a set of objects and their relationship is just like class diagrams. They\nalso represent the static view of the system." }, { "code": null, "e": 27430, "s": 27293, "text": "The usage of object diagrams is similar to class diagrams but they are used to build prototype of a system from a practical perspective." }, { "code": null, "e": 27638, "s": 27430, "text": "Component diagrams represent a set of components and their relationships. These components consist of classes, interfaces, or collaborations. Component diagrams represent the implementation view of a system." }, { "code": null, "e": 27833, "s": 27638, "text": "During the design phase, software artifacts (classes, interfaces, etc.) of a system are arranged in different groups depending upon their relationship. Now, these groups are known as components." }, { "code": null, "e": 27918, "s": 27833, "text": "Finally, it can be said component diagrams are used to visualize the implementation." }, { "code": null, "e": 28051, "s": 27918, "text": "Deployment diagrams are a set of nodes and their relationships. These nodes are physical entities where the components are deployed." }, { "code": null, "e": 28176, "s": 28051, "text": "Deployment diagrams are used for visualizing the deployment view of a system. This is generally used by the deployment team." }, { "code": null, "e": 28543, "s": 28176, "text": "Note − If the above descriptions and usages are observed carefully then it is very clear that\nall the diagrams have some relationship with one another. Component diagrams are dependent upon the classes, interfaces, etc. which are part of class/object diagram. Again, the deployment diagram is dependent upon the components, which are used to make\ncomponent diagrams." }, { "code": null, "e": 28675, "s": 28543, "text": "Any system can have two aspects, static and dynamic. So, a model is considered as\ncomplete when both the aspects are fully covered." }, { "code": null, "e": 28827, "s": 28675, "text": "Behavioral diagrams basically capture the dynamic aspect of a system. Dynamic aspect can be further described as the changing/moving parts of a system." }, { "code": null, "e": 28886, "s": 28827, "text": "UML has the following five types of behavioral diagrams −" }, { "code": null, "e": 28903, "s": 28886, "text": "Use case diagram" }, { "code": null, "e": 28920, "s": 28903, "text": "Sequence diagram" }, { "code": null, "e": 28942, "s": 28920, "text": "Collaboration diagram" }, { "code": null, "e": 28961, "s": 28942, "text": "Statechart diagram" }, { "code": null, "e": 28978, "s": 28961, "text": "Activity diagram" }, { "code": null, "e": 29099, "s": 28978, "text": "Use case diagrams are a set of use cases, actors, and their relationships. They represent the use case view of a system." }, { "code": null, "e": 29329, "s": 29099, "text": "A use case represents a particular functionality of a system. Hence, use case diagram is used to describe the relationships among the functionalities and their internal/external controllers. These controllers are known as actors." }, { "code": null, "e": 29517, "s": 29329, "text": "A sequence diagram is an interaction diagram. From the name, it is clear that the diagram deals with some sequences, which are the sequence of messages flowing from one object to another." }, { "code": null, "e": 29736, "s": 29517, "text": "Interaction among the components of a system is very important from implementation and execution perspective. Sequence diagram is used to visualize the sequence of calls in a system to perform a specific functionality." }, { "code": null, "e": 29939, "s": 29736, "text": "Collaboration diagram is another form of interaction diagram. It represents the structural\norganization of a system and the messages sent/received. Structural organization consists of objects and links." }, { "code": null, "e": 30130, "s": 29939, "text": "The purpose of collaboration diagram is similar to sequence diagram. However, the specific purpose of collaboration diagram is to visualize the organization of objects and their interaction." }, { "code": null, "e": 30280, "s": 30130, "text": "Any real-time system is expected to be reacted by some kind of internal/external events. These events are responsible for state change of the system." }, { "code": null, "e": 30431, "s": 30280, "text": "Statechart diagram is used to represent the event driven state change of a system. It basically describes the state change of a class, interface, etc." }, { "code": null, "e": 30527, "s": 30431, "text": "State chart diagram is used to visualize the reaction of a system by internal/external factors." }, { "code": null, "e": 30677, "s": 30527, "text": "Activity diagram describes the flow of control in a system. It consists of activities and links. The flow can be sequential, concurrent, or branched." }, { "code": null, "e": 30813, "s": 30677, "text": "Activities are nothing but the functions of a system. Numbers of activity diagrams are prepared to capture the entire flow in a system." }, { "code": null, "e": 30963, "s": 30813, "text": "Activity diagrams are used to visualize the flow of controls in a system. This is prepared to have an idea of how the system will work when executed." }, { "code": null, "e": 31305, "s": 30963, "text": "Note − Dynamic nature of a system is very difficult to capture. UML has provided features\nto capture the dynamics of a system from different angles. Sequence diagrams and collaboration diagrams are isomorphic, hence they can be converted from one another without losing any information. This is also true for Statechart and activity diagram." }, { "code": null, "e": 31566, "s": 31305, "text": "Class diagram is a static diagram. It represents the static view of an application. Class diagram is not only used for visualizing, describing, and documenting different aspects of a system but also for constructing executable code of the software application." }, { "code": null, "e": 31857, "s": 31566, "text": "Class diagram describes the attributes and operations of a class and also the constraints\nimposed on the system. The class diagrams are widely used in the modeling of objectoriented systems because they are the only UML diagrams, which can be mapped directly with object-oriented languages." }, { "code": null, "e": 32003, "s": 31857, "text": "Class diagram shows a collection of classes, interfaces, associations, collaborations, and\nconstraints. It is also known as a structural diagram." }, { "code": null, "e": 32226, "s": 32003, "text": "The purpose of class diagram is to model the static view of an application. Class diagrams are the only diagrams which can be directly mapped with object-oriented languages and thus widely used at the time of construction." }, { "code": null, "e": 32432, "s": 32226, "text": "UML diagrams like activity diagram, sequence diagram can only give the sequence flow of the application, however class diagram is a bit different. It is the most popular UML diagram in the coder community." }, { "code": null, "e": 32488, "s": 32432, "text": "The purpose of the class diagram can be summarized as −" }, { "code": null, "e": 32546, "s": 32488, "text": "Analysis and design of the static view of an application." }, { "code": null, "e": 32604, "s": 32546, "text": "Analysis and design of the static view of an application." }, { "code": null, "e": 32643, "s": 32604, "text": "Describe responsibilities of a system." }, { "code": null, "e": 32682, "s": 32643, "text": "Describe responsibilities of a system." }, { "code": null, "e": 32726, "s": 32682, "text": "Base for component and deployment diagrams." }, { "code": null, "e": 32770, "s": 32726, "text": "Base for component and deployment diagrams." }, { "code": null, "e": 32803, "s": 32770, "text": "Forward and reverse engineering." }, { "code": null, "e": 32836, "s": 32803, "text": "Forward and reverse engineering." }, { "code": null, "e": 33003, "s": 32836, "text": "Class diagrams are the most popular UML diagrams used for construction of software\napplications. It is very important to learn the drawing procedure of class diagram." }, { "code": null, "e": 33132, "s": 33003, "text": "Class diagrams have a lot of properties to consider while drawing but here the diagram will be considered from a top level view." }, { "code": null, "e": 33331, "s": 33132, "text": "Class diagram is basically a graphical representation of the static view of the system and represents different aspects of the application. A collection of class diagrams represent the whole system." }, { "code": null, "e": 33405, "s": 33331, "text": "The following points should be remembered while drawing a class diagram −" }, { "code": null, "e": 33494, "s": 33405, "text": "The name of the class diagram should be meaningful to describe the aspect of the system." }, { "code": null, "e": 33583, "s": 33494, "text": "The name of the class diagram should be meaningful to describe the aspect of the system." }, { "code": null, "e": 33653, "s": 33583, "text": "Each element and their relationships should be identified in advance." }, { "code": null, "e": 33723, "s": 33653, "text": "Each element and their relationships should be identified in advance." }, { "code": null, "e": 33806, "s": 33723, "text": "Responsibility (attributes and methods) of each class should be clearly identified" }, { "code": null, "e": 33889, "s": 33806, "text": "Responsibility (attributes and methods) of each class should be clearly identified" }, { "code": null, "e": 34016, "s": 33889, "text": "For each class, minimum number of properties should be specified, as unnecessary properties will make the diagram complicated." }, { "code": null, "e": 34143, "s": 34016, "text": "For each class, minimum number of properties should be specified, as unnecessary properties will make the diagram complicated." }, { "code": null, "e": 34289, "s": 34143, "text": "Use notes whenever required to describe some aspect of the diagram. At the end of the drawing it should be understandable to the developer/coder." }, { "code": null, "e": 34435, "s": 34289, "text": "Use notes whenever required to describe some aspect of the diagram. At the end of the drawing it should be understandable to the developer/coder." }, { "code": null, "e": 34579, "s": 34435, "text": "Finally, before making the final version, the diagram should be drawn on plain paper and reworked as many times as possible to make it correct." }, { "code": null, "e": 34723, "s": 34579, "text": "Finally, before making the final version, the diagram should be drawn on plain paper and reworked as many times as possible to make it correct." }, { "code": null, "e": 34857, "s": 34723, "text": "The following diagram is an example of an Order System of an application. It describes a particular aspect of the entire application." }, { "code": null, "e": 35022, "s": 34857, "text": "First of all, Order and Customer are identified as the two elements of the system. They have a one-to-many relationship because a customer can have multiple orders." }, { "code": null, "e": 35187, "s": 35022, "text": "First of all, Order and Customer are identified as the two elements of the system. They have a one-to-many relationship because a customer can have multiple orders." }, { "code": null, "e": 35309, "s": 35187, "text": "Order class is an abstract class and it has two concrete classes (inheritance relationship) SpecialOrder and NormalOrder." }, { "code": null, "e": 35431, "s": 35309, "text": "Order class is an abstract class and it has two concrete classes (inheritance relationship) SpecialOrder and NormalOrder." }, { "code": null, "e": 35578, "s": 35431, "text": "The two inherited classes have all the properties as the Order class. In addition,\nthey have additional functions like dispatch () and receive ()." }, { "code": null, "e": 35725, "s": 35578, "text": "The two inherited classes have all the properties as the Order class. In addition,\nthey have additional functions like dispatch () and receive ()." }, { "code": null, "e": 35812, "s": 35725, "text": "The following class diagram has been drawn considering all the points mentioned above." }, { "code": null, "e": 35955, "s": 35812, "text": "Class diagram is a static diagram and it is used to model the static view of a system. The static view describes the vocabulary of the system." }, { "code": null, "e": 36228, "s": 35955, "text": "Class diagram is also considered as the foundation for component and deployment diagrams. Class diagrams are not only used to visualize the static view of the system but they are also used to construct the executable code for forward and reverse engineering\nof any system." }, { "code": null, "e": 36362, "s": 36228, "text": "Generally, UML diagrams are not directly mapped with any object-oriented programming languages but the class diagram is an exception." }, { "code": null, "e": 36542, "s": 36362, "text": "Class diagram clearly shows the mapping with object-oriented languages such as Java, C++, etc. From practical experience, class diagram is generally used for construction purpose." }, { "code": null, "e": 36602, "s": 36542, "text": "In a nutshell it can be said, class diagrams are used for −" }, { "code": null, "e": 36644, "s": 36602, "text": "Describing the static view of the system." }, { "code": null, "e": 36686, "s": 36644, "text": "Describing the static view of the system." }, { "code": null, "e": 36751, "s": 36686, "text": "Showing the collaboration among the elements of the static view." }, { "code": null, "e": 36816, "s": 36751, "text": "Showing the collaboration among the elements of the static view." }, { "code": null, "e": 36872, "s": 36816, "text": "Describing the functionalities performed by the system." }, { "code": null, "e": 36928, "s": 36872, "text": "Describing the functionalities performed by the system." }, { "code": null, "e": 36999, "s": 36928, "text": "Construction of software applications using object oriented languages." }, { "code": null, "e": 37070, "s": 36999, "text": "Construction of software applications using object oriented languages." }, { "code": null, "e": 37172, "s": 37070, "text": "Object diagrams are derived from class diagrams so object diagrams are dependent upon class diagrams." }, { "code": null, "e": 37433, "s": 37172, "text": "Object diagrams represent an instance of a class diagram. The basic concepts are similar for class diagrams and object diagrams. Object diagrams also represent the static view of a system but this static view is a snapshot of the system at a particular moment." }, { "code": null, "e": 37525, "s": 37433, "text": "Object diagrams are used to render a set of objects and their relationships as an instance." }, { "code": null, "e": 37671, "s": 37525, "text": "The purpose of a diagram should be understood clearly to implement it practically. The purposes of object diagrams are similar to class diagrams." }, { "code": null, "e": 37889, "s": 37671, "text": "The difference is that a class diagram represents an abstract model consisting of classes and their relationships. However, an object diagram represents an instance at a particular moment, which is concrete in nature." }, { "code": null, "e": 38036, "s": 37889, "text": "It means the object diagram is closer to the actual system behavior. The purpose is to capture the static view of a system at a particular moment." }, { "code": null, "e": 38093, "s": 38036, "text": "The purpose of the object diagram can be summarized as −" }, { "code": null, "e": 38126, "s": 38093, "text": "Forward and reverse engineering." }, { "code": null, "e": 38159, "s": 38126, "text": "Forward and reverse engineering." }, { "code": null, "e": 38192, "s": 38159, "text": "Object relationships of a system" }, { "code": null, "e": 38225, "s": 38192, "text": "Object relationships of a system" }, { "code": null, "e": 38256, "s": 38225, "text": "Static view of an interaction." }, { "code": null, "e": 38287, "s": 38256, "text": "Static view of an interaction." }, { "code": null, "e": 38365, "s": 38287, "text": "Understand object behaviour and their relationship from practical perspective" }, { "code": null, "e": 38443, "s": 38365, "text": "Understand object behaviour and their relationship from practical perspective" }, { "code": null, "e": 38618, "s": 38443, "text": "We have already discussed that an object diagram is an instance of a class diagram. It implies that an object diagram consists of instances of things used in a class diagram." }, { "code": null, "e": 38857, "s": 38618, "text": "So both diagrams are made of same basic elements but in different form. In class diagram elements are in abstract form to represent the blue print and in object diagram the elements are in concrete form to represent the real world object." }, { "code": null, "e": 39117, "s": 38857, "text": "To capture a particular system, numbers of class diagrams are limited. However, if we consider object diagrams then we can have unlimited number of instances, which are unique in nature. Only those instances are considered, which have an impact on the\nsystem." }, { "code": null, "e": 39307, "s": 39117, "text": "From the above discussion, it is clear that a single object diagram cannot capture all the\nnecessary instances or rather cannot specify all the objects of a system. Hence, the solution is −" }, { "code": null, "e": 39397, "s": 39307, "text": "First, analyze the system and decide which instances have important data and association." }, { "code": null, "e": 39487, "s": 39397, "text": "First, analyze the system and decide which instances have important data and association." }, { "code": null, "e": 39562, "s": 39487, "text": "Second, consider only those instances, which will cover the functionality." }, { "code": null, "e": 39637, "s": 39562, "text": "Second, consider only those instances, which will cover the functionality." }, { "code": null, "e": 39709, "s": 39637, "text": "Third, make some optimization as the number of instances are unlimited." }, { "code": null, "e": 39781, "s": 39709, "text": "Third, make some optimization as the number of instances are unlimited." }, { "code": null, "e": 39882, "s": 39781, "text": "Before drawing an object diagram, the following things should be remembered and understood clearly −" }, { "code": null, "e": 39918, "s": 39882, "text": "Object diagrams consist of objects." }, { "code": null, "e": 39954, "s": 39918, "text": "Object diagrams consist of objects." }, { "code": null, "e": 40009, "s": 39954, "text": "The link in object diagram is used to connect objects." }, { "code": null, "e": 40064, "s": 40009, "text": "The link in object diagram is used to connect objects." }, { "code": null, "e": 40140, "s": 40064, "text": "Objects and links are the two elements used to construct an object diagram." }, { "code": null, "e": 40216, "s": 40140, "text": "Objects and links are the two elements used to construct an object diagram." }, { "code": null, "e": 40317, "s": 40216, "text": "After this, the following things are to be decided before starting the construction of the diagram −" }, { "code": null, "e": 40391, "s": 40317, "text": "The object diagram should have a meaningful name to indicate its purpose." }, { "code": null, "e": 40465, "s": 40391, "text": "The object diagram should have a meaningful name to indicate its purpose." }, { "code": null, "e": 40515, "s": 40465, "text": "The most important elements are to be identified." }, { "code": null, "e": 40565, "s": 40515, "text": "The most important elements are to be identified." }, { "code": null, "e": 40616, "s": 40565, "text": "The association among objects should be clarified." }, { "code": null, "e": 40667, "s": 40616, "text": "The association among objects should be clarified." }, { "code": null, "e": 40750, "s": 40667, "text": "Values of different elements need to be captured to include in the object diagram." }, { "code": null, "e": 40833, "s": 40750, "text": "Values of different elements need to be captured to include in the object diagram." }, { "code": null, "e": 40892, "s": 40833, "text": "Add proper notes at points where more clarity is required." }, { "code": null, "e": 40951, "s": 40892, "text": "Add proper notes at points where more clarity is required." }, { "code": null, "e": 41220, "s": 40951, "text": "The following diagram is an example of an object diagram. It represents the Order management system which we have discussed in the chapter Class Diagram. The following diagram is an instance of the system at a particular time of purchase. It has the following\nobjects." }, { "code": null, "e": 41229, "s": 41220, "text": "Customer" }, { "code": null, "e": 41238, "s": 41229, "text": "Customer" }, { "code": null, "e": 41244, "s": 41238, "text": "Order" }, { "code": null, "e": 41250, "s": 41244, "text": "Order" }, { "code": null, "e": 41263, "s": 41250, "text": "SpecialOrder" }, { "code": null, "e": 41276, "s": 41263, "text": "SpecialOrder" }, { "code": null, "e": 41288, "s": 41276, "text": "NormalOrder" }, { "code": null, "e": 41300, "s": 41288, "text": "NormalOrder" }, { "code": null, "e": 41601, "s": 41300, "text": "Now the customer object (C) is associated with three order objects (O1, O2, and O3). These order objects are associated with special order and normal order objects (S1, S2, and N1). The customer has the following three orders with different numbers (12, 32 and 40) for the particular time considered." }, { "code": null, "e": 41827, "s": 41601, "text": "The customer can increase the number of orders in future and in that scenario the object diagram will reflect that. If order, special order, and normal order objects are observed then you will find that they have some values." }, { "code": null, "e": 42053, "s": 41827, "text": "For orders, the values are 12, 32, and 40 which implies that the objects have these values for a particular moment (here the particular time when the purchase is made is considered as the moment) when the instance is captured" }, { "code": null, "e": 42250, "s": 42053, "text": "The same is true for special order and normal order objects which have number of orders as 20, 30, and 60. If a different time of purchase is considered, then these values will change accordingly." }, { "code": null, "e": 42337, "s": 42250, "text": "The following object diagram has been drawn considering all the points mentioned above" }, { "code": null, "e": 42475, "s": 42337, "text": "Object diagrams can be imagined as the snapshot of a running system at a particular moment. Let us consider an example of a running train" }, { "code": null, "e": 42585, "s": 42475, "text": "Now, if you take a snap of the running train then you will find a static picture of it having the following −" }, { "code": null, "e": 42622, "s": 42585, "text": "A particular state which is running." }, { "code": null, "e": 42659, "s": 42622, "text": "A particular state which is running." }, { "code": null, "e": 42753, "s": 42659, "text": "A particular number of passengers. which will change if the snap is taken in a different time" }, { "code": null, "e": 42847, "s": 42753, "text": "A particular number of passengers. which will change if the snap is taken in a different time" }, { "code": null, "e": 42997, "s": 42847, "text": "Here, we can imagine the snap of the running train is an object having the above values. And this is true for any real-life simple or complex system." }, { "code": null, "e": 43063, "s": 42997, "text": "In a nutshell, it can be said that object diagrams are used for −" }, { "code": null, "e": 43097, "s": 43063, "text": "Making the prototype of a system." }, { "code": null, "e": 43131, "s": 43097, "text": "Making the prototype of a system." }, { "code": null, "e": 43152, "s": 43131, "text": "Reverse engineering." }, { "code": null, "e": 43173, "s": 43152, "text": "Reverse engineering." }, { "code": null, "e": 43207, "s": 43173, "text": "Modeling complex data structures." }, { "code": null, "e": 43241, "s": 43207, "text": "Modeling complex data structures." }, { "code": null, "e": 43294, "s": 43241, "text": "Understanding the system from practical perspective." }, { "code": null, "e": 43347, "s": 43294, "text": "Understanding the system from practical perspective." }, { "code": null, "e": 43651, "s": 43347, "text": "Component diagrams are different in terms of nature and behavior. Component diagrams are used to model the physical aspects of a system. Now the question is, what are these physical aspects? Physical aspects are the elements such as executables, libraries, files,\ndocuments, etc. which reside in a node." }, { "code": null, "e": 43814, "s": 43651, "text": "Component diagrams are used to visualize the organization and relationships among components in a system. These diagrams are also used to make executable systems." }, { "code": null, "e": 44062, "s": 43814, "text": "Component diagram is a special kind of diagram in UML. The purpose is also different from all other diagrams discussed so far. It does not describe the functionality of the system but it describes the components used to make those functionalities." }, { "code": null, "e": 44224, "s": 44062, "text": "Thus from that point of view, component diagrams are used to visualize the physical components in a system. These components are libraries, packages, files, etc." }, { "code": null, "e": 44402, "s": 44224, "text": "Component diagrams can also be described as a static implementation view of a system. Static implementation represents the organization of the components at a particular moment." }, { "code": null, "e": 44525, "s": 44402, "text": "A single component diagram cannot represent the entire system but a collection of\ndiagrams is used to represent the whole." }, { "code": null, "e": 44585, "s": 44525, "text": "The purpose of the component diagram can be summarized as −" }, { "code": null, "e": 44623, "s": 44585, "text": "Visualize the components of a system." }, { "code": null, "e": 44661, "s": 44623, "text": "Visualize the components of a system." }, { "code": null, "e": 44725, "s": 44661, "text": "Construct executables by using forward and reverse engineering." }, { "code": null, "e": 44789, "s": 44725, "text": "Construct executables by using forward and reverse engineering." }, { "code": null, "e": 44852, "s": 44789, "text": "Describe the organization and relationships of the components." }, { "code": null, "e": 44915, "s": 44852, "text": "Describe the organization and relationships of the components." }, { "code": null, "e": 45049, "s": 44915, "text": "Component diagrams are used to describe the physical artifacts of a system. This artifact\nincludes files, executables, libraries, etc" }, { "code": null, "e": 45251, "s": 45049, "text": "The purpose of this diagram is different. Component diagrams are used during the implementation phase of an application. However, it is prepared well in advance to visualize the implementation details." }, { "code": null, "e": 45419, "s": 45251, "text": "Initially, the system is designed using different UML diagrams and then when the artifacts are ready, component diagrams are used to get an idea of the implementation." }, { "code": null, "e": 45636, "s": 45419, "text": "This diagram is very important as without it the application cannot be implemented efficiently. A well-prepared component diagram is also important for other aspects such as application performance, maintenance, etc." }, { "code": null, "e": 45727, "s": 45636, "text": "Before drawing a component diagram, the following artifacts are to be identified clearly −" }, { "code": null, "e": 45753, "s": 45727, "text": "Files used in the system." }, { "code": null, "e": 45779, "s": 45753, "text": "Files used in the system." }, { "code": null, "e": 45838, "s": 45779, "text": "Libraries and other artifacts relevant to the application." }, { "code": null, "e": 45897, "s": 45838, "text": "Libraries and other artifacts relevant to the application." }, { "code": null, "e": 45932, "s": 45897, "text": "Relationships among the artifacts." }, { "code": null, "e": 45967, "s": 45932, "text": "Relationships among the artifacts." }, { "code": null, "e": 46046, "s": 45967, "text": "After identifying the artifacts, the following points need to be kept in mind." }, { "code": null, "e": 46132, "s": 46046, "text": "Use a meaningful name to identify the component for which the diagram is to be drawn." }, { "code": null, "e": 46218, "s": 46132, "text": "Use a meaningful name to identify the component for which the diagram is to be drawn." }, { "code": null, "e": 46276, "s": 46218, "text": "Prepare a mental layout before producing the using tools." }, { "code": null, "e": 46334, "s": 46276, "text": "Prepare a mental layout before producing the using tools." }, { "code": null, "e": 46377, "s": 46334, "text": "Use notes for clarifying important points." }, { "code": null, "e": 46420, "s": 46377, "text": "Use notes for clarifying important points." }, { "code": null, "e": 46663, "s": 46420, "text": "Following is a component diagram for order management system. Here, the artifacts are files. The diagram shows the files in the application and their relationships. In actual, the component diagram also contains dlls, libraries, folders, etc." }, { "code": null, "e": 46888, "s": 46663, "text": "In the following diagram, four files are identified and their relationships are produced. Component diagram cannot be matched directly with other UML diagrams discussed so far as it is drawn for completely different purpose." }, { "code": null, "e": 46979, "s": 46888, "text": "The following component diagram has been drawn considering all the points mentioned above." }, { "code": null, "e": 47176, "s": 46979, "text": "We have already described that component diagrams are used to visualize the static implementation view of a system. Component diagrams are special type of UML diagrams used for different purposes." }, { "code": null, "e": 47340, "s": 47176, "text": "These diagrams show the physical components of a system. To clarify it, we can say that component diagrams describe the organization of the components in a system." }, { "code": null, "e": 47506, "s": 47340, "text": "Organization can be further described as the location of the components in a system. These components are organized in a special way to meet the system requirements." }, { "code": null, "e": 47756, "s": 47506, "text": "As we have already discussed, those components are libraries, files, executables, etc. Before implementing the application, these components are to be organized. This component organization is also designed separately as a part of project execution." }, { "code": null, "e": 47931, "s": 47756, "text": "Component diagrams are very important from implementation perspective. Thus, the implementation team of an application should have a proper knowledge of the component details" }, { "code": null, "e": 47967, "s": 47931, "text": "Component diagrams can be used to −" }, { "code": null, "e": 48001, "s": 47967, "text": "Model the components of a system." }, { "code": null, "e": 48035, "s": 48001, "text": "Model the components of a system." }, { "code": null, "e": 48062, "s": 48035, "text": "Model the database schema." }, { "code": null, "e": 48089, "s": 48062, "text": "Model the database schema." }, { "code": null, "e": 48130, "s": 48089, "text": "Model the executables of an application." }, { "code": null, "e": 48171, "s": 48130, "text": "Model the executables of an application." }, { "code": null, "e": 48203, "s": 48171, "text": "Model the system's source code." }, { "code": null, "e": 48235, "s": 48203, "text": "Model the system's source code." }, { "code": null, "e": 48374, "s": 48235, "text": "Deployment diagrams are used to visualize the topology of the physical components of a system, where the software components are deployed." }, { "code": null, "e": 48517, "s": 48374, "text": "Deployment diagrams are used to describe the static deployment view of a system. Deployment diagrams consist of nodes and their relationships." }, { "code": null, "e": 48755, "s": 48517, "text": "The term Deployment itself describes the purpose of the diagram. Deployment diagrams are used for describing the hardware components, where software components are deployed. Component diagrams and deployment diagrams are closely related." }, { "code": null, "e": 48875, "s": 48755, "text": "Component diagrams are used to describe the components and deployment diagrams shows how they are deployed in hardware." }, { "code": null, "e": 49046, "s": 48875, "text": "UML is mainly designed to focus on the software artifacts of a system. However, these two diagrams are special diagrams used to focus on software and hardware components." }, { "code": null, "e": 49243, "s": 49046, "text": "Most of the UML diagrams are used to handle logical components but deployment diagrams are made to focus on the hardware topology of a system. Deployment diagrams are used by the system engineers." }, { "code": null, "e": 49300, "s": 49243, "text": "The purpose of deployment diagrams can be described as −" }, { "code": null, "e": 49345, "s": 49300, "text": "Visualize the hardware topology of a system." }, { "code": null, "e": 49390, "s": 49345, "text": "Visualize the hardware topology of a system." }, { "code": null, "e": 49459, "s": 49390, "text": "Describe the hardware components used to deploy software components." }, { "code": null, "e": 49528, "s": 49459, "text": "Describe the hardware components used to deploy software components." }, { "code": null, "e": 49567, "s": 49528, "text": "Describe the runtime processing nodes." }, { "code": null, "e": 49606, "s": 49567, "text": "Describe the runtime processing nodes." }, { "code": null, "e": 49887, "s": 49606, "text": "Deployment diagram represents the deployment view of a system. It is related to the component diagram because the components are deployed using the deployment diagrams. A deployment diagram consists of nodes. Nodes are nothing but physical\nhardware used to deploy the application." }, { "code": null, "e": 50033, "s": 49887, "text": "Deployment diagrams are useful for system engineers. An efficient deployment diagram is very important as it controls the following parameters − " }, { "code": null, "e": 50045, "s": 50033, "text": "Performance" }, { "code": null, "e": 50057, "s": 50045, "text": "Performance" }, { "code": null, "e": 50069, "s": 50057, "text": "Scalability" }, { "code": null, "e": 50081, "s": 50069, "text": "Scalability" }, { "code": null, "e": 50097, "s": 50081, "text": "Maintainability" }, { "code": null, "e": 50113, "s": 50097, "text": "Maintainability" }, { "code": null, "e": 50125, "s": 50113, "text": "Portability" }, { "code": null, "e": 50137, "s": 50125, "text": "Portability" }, { "code": null, "e": 50221, "s": 50137, "text": "Before drawing a deployment diagram, the following artifacts should be identified −" }, { "code": null, "e": 50227, "s": 50221, "text": "Nodes" }, { "code": null, "e": 50233, "s": 50227, "text": "Nodes" }, { "code": null, "e": 50259, "s": 50233, "text": "Relationships among nodes" }, { "code": null, "e": 50285, "s": 50259, "text": "Relationships among nodes" }, { "code": null, "e": 50428, "s": 50285, "text": "Following is a sample deployment diagram to provide an idea of the deployment view of order management system. Here, we have shown nodes as − " }, { "code": null, "e": 50436, "s": 50428, "text": "Monitor" }, { "code": null, "e": 50444, "s": 50436, "text": "Monitor" }, { "code": null, "e": 50450, "s": 50444, "text": "Modem" }, { "code": null, "e": 50456, "s": 50450, "text": "Modem" }, { "code": null, "e": 50471, "s": 50456, "text": "Caching server" }, { "code": null, "e": 50486, "s": 50471, "text": "Caching server" }, { "code": null, "e": 50493, "s": 50486, "text": "Server" }, { "code": null, "e": 50500, "s": 50493, "text": "Server" }, { "code": null, "e": 50772, "s": 50500, "text": "The application is assumed to be a web-based application, which is deployed in a clustered\nenvironment using server 1, server 2, and server 3. The user connects to the application using the Internet. The control flows from the caching server to the clustered environment." }, { "code": null, "e": 50864, "s": 50772, "text": "The following deployment diagram has been drawn considering all the points mentioned above." }, { "code": null, "e": 51030, "s": 50864, "text": "Deployment diagrams are mainly used by system engineers. These diagrams are used to describe the physical components (hardware), their distribution, and association." }, { "code": null, "e": 51142, "s": 51030, "text": "Deployment diagrams can be visualized as the hardware components/nodes on which the software components reside." }, { "code": null, "e": 51421, "s": 51142, "text": "Software applications are developed to model complex business processes. Efficient software applications are not sufficient to meet the business requirements. Business requirements can be described as the need to support the increasing number of users,\nquick response time, etc." }, { "code": null, "e": 51538, "s": 51421, "text": "To meet these types of requirements, hardware components should be designed efficiently and in a cost-effective way." }, { "code": null, "e": 51770, "s": 51538, "text": "Now-a-days software applications are very complex in nature. Software applications can be standalone, web-based, distributed, mainframe-based and many more. Hence, it is very important to design the hardware components efficiently." }, { "code": null, "e": 51804, "s": 51770, "text": "Deployment diagrams can be used −" }, { "code": null, "e": 51848, "s": 51804, "text": "To model the hardware topology of a system." }, { "code": null, "e": 51892, "s": 51848, "text": "To model the hardware topology of a system." }, { "code": null, "e": 51922, "s": 51892, "text": "To model the embedded system." }, { "code": null, "e": 51952, "s": 51922, "text": "To model the embedded system." }, { "code": null, "e": 52010, "s": 51952, "text": "To model the hardware details for a client/server system." }, { "code": null, "e": 52068, "s": 52010, "text": "To model the hardware details for a client/server system." }, { "code": null, "e": 52128, "s": 52068, "text": "To model the hardware details of a distributed application." }, { "code": null, "e": 52188, "s": 52128, "text": "To model the hardware details of a distributed application." }, { "code": null, "e": 52225, "s": 52188, "text": "For Forward and Reverse engineering." }, { "code": null, "e": 52262, "s": 52225, "text": "For Forward and Reverse engineering." }, { "code": null, "e": 52423, "s": 52262, "text": "To model a system, the most important aspect is to capture the dynamic behavior. Dynamic behavior means the behavior of the system when it is running/operating." }, { "code": null, "e": 52803, "s": 52423, "text": "Only static behavior is not sufficient to model a system rather dynamic behavior is more important than static behavior. In UML, there are five diagrams available to model the dynamic nature and use case diagram is one of them. Now as we have to discuss that the use case diagram is dynamic in nature, there should be some internal or external factors for making the interaction." }, { "code": null, "e": 53076, "s": 52803, "text": "These internal and external agents are known as actors. Use case diagrams consists of actors, use cases and their relationships. The diagram is used to model the system/subsystem of an application. A single use case diagram captures a particular functionality of a system." }, { "code": null, "e": 53150, "s": 53076, "text": "Hence to model the entire system, a number of use case diagrams are used." }, { "code": null, "e": 53489, "s": 53150, "text": "The purpose of use case diagram is to capture the dynamic aspect of a system. However, this definition is too generic to describe the purpose, as other four diagrams (activity, sequence, collaboration, and Statechart) also have the same purpose. We will look into some specific purpose, which will distinguish it from other four diagrams." }, { "code": null, "e": 53764, "s": 53489, "text": "Use case diagrams are used to gather the requirements of a system including internal and\nexternal influences. These requirements are mostly design requirements. Hence, when a system is analyzed to gather its functionalities, use cases are prepared and actors are identified." }, { "code": null, "e": 53859, "s": 53764, "text": "When the initial task is complete, use case diagrams are modelled to present the outside view." }, { "code": null, "e": 53934, "s": 53859, "text": "In brief, the purposes of use case diagrams can be said to be as follows −" }, { "code": null, "e": 53979, "s": 53934, "text": "Used to gather the requirements of a system." }, { "code": null, "e": 54024, "s": 53979, "text": "Used to gather the requirements of a system." }, { "code": null, "e": 54065, "s": 54024, "text": "Used to get an outside view of a system." }, { "code": null, "e": 54106, "s": 54065, "text": "Used to get an outside view of a system." }, { "code": null, "e": 54173, "s": 54106, "text": "Identify the external and internal factors influencing the system." }, { "code": null, "e": 54240, "s": 54173, "text": "Identify the external and internal factors influencing the system." }, { "code": null, "e": 54296, "s": 54240, "text": "Show the interaction among the requirements are actors." }, { "code": null, "e": 54352, "s": 54296, "text": "Show the interaction among the requirements are actors." }, { "code": null, "e": 54529, "s": 54352, "text": "Use case diagrams are considered for high level requirement analysis of a system. When the requirements of a system are analyzed, the functionalities are captured in use cases." }, { "code": null, "e": 54761, "s": 54529, "text": "We can say that use cases are nothing but the system functionalities written in an organized manner. The second thing which is relevant to use cases are the actors. Actors can be defined as something that interacts with the system." }, { "code": null, "e": 54951, "s": 54761, "text": "Actors can be a human user, some internal applications, or may be some external applications. When we are planning to draw a use case diagram, we should have the following items identified." }, { "code": null, "e": 54997, "s": 54951, "text": "Functionalities to be represented as use case" }, { "code": null, "e": 55043, "s": 54997, "text": "Functionalities to be represented as use case" }, { "code": null, "e": 55050, "s": 55043, "text": "Actors" }, { "code": null, "e": 55057, "s": 55050, "text": "Actors" }, { "code": null, "e": 55103, "s": 55057, "text": "Relationships among the use cases and actors." }, { "code": null, "e": 55149, "s": 55103, "text": "Relationships among the use cases and actors." }, { "code": null, "e": 55342, "s": 55149, "text": "Use case diagrams are drawn to capture the functional requirements of a system. After\nidentifying the above items, we have to use the following guidelines to draw an efficient use case diagram" }, { "code": null, "e": 55479, "s": 55342, "text": "The name of a use case is very important. The name should be chosen in such a way so that it can identify the functionalities performed." }, { "code": null, "e": 55616, "s": 55479, "text": "The name of a use case is very important. The name should be chosen in such a way so that it can identify the functionalities performed." }, { "code": null, "e": 55649, "s": 55616, "text": "Give a suitable name for actors." }, { "code": null, "e": 55682, "s": 55649, "text": "Give a suitable name for actors." }, { "code": null, "e": 55742, "s": 55682, "text": "Show relationships and dependencies clearly in the diagram." }, { "code": null, "e": 55802, "s": 55742, "text": "Show relationships and dependencies clearly in the diagram." }, { "code": null, "e": 55920, "s": 55802, "text": "Do not try to include all types of relationships, as the main purpose of the diagram\nis to identify the requirements." }, { "code": null, "e": 56038, "s": 55920, "text": "Do not try to include all types of relationships, as the main purpose of the diagram\nis to identify the requirements." }, { "code": null, "e": 56100, "s": 56038, "text": "Use notes whenever required to clarify some important points." }, { "code": null, "e": 56162, "s": 56100, "text": "Use notes whenever required to clarify some important points." }, { "code": null, "e": 56388, "s": 56162, "text": "Following is a sample use case diagram representing the order management system. Hence, if we look into the diagram then we will find three use cases (Order,\nSpecialOrder, and NormalOrder) and one actor which is the customer." }, { "code": null, "e": 56680, "s": 56388, "text": "The SpecialOrder and NormalOrder use cases are extended from Order use case. Hence, they have extended relationship. Another important point is to identify the system boundary, which is shown in the picture. The actor Customer lies outside the system as it is an external user of the system." }, { "code": null, "e": 56913, "s": 56680, "text": "As we have already discussed there are five diagrams in UML to model the dynamic view of a system. Now each and every model has some specific purpose to use. Actually these specific purposes are different angles of a running system." }, { "code": null, "e": 57099, "s": 56913, "text": "To understand the dynamics of a system, we need to use different types of diagrams. Use case diagram is one of them and its specific purpose is to gather system requirements and actors." }, { "code": null, "e": 57350, "s": 57099, "text": "Use case diagrams specify the events of a system and their flows. But use case diagram never describes how they are implemented. Use case diagram can be imagined as a black box where only the input, output, and the function of the black box is known." }, { "code": null, "e": 57682, "s": 57350, "text": "These diagrams are used at a very high level of design. This high level design is refined again and again to get a complete and practical picture of the system. A well-structured use case also describes the pre-condition, post condition, and exceptions. These extra elements are used to make test cases when performing the testing." }, { "code": null, "e": 57974, "s": 57682, "text": "Although use case is not a good candidate for forward and reverse engineering, still they are used in a slightly different way to make forward and reverse engineering. The same is true for reverse engineering. Use case diagram is used differently to make it suitable for reverse engineering." }, { "code": null, "e": 58156, "s": 57974, "text": "In forward engineering, use case diagrams are used to make test cases and in reverse engineering use cases are used to prepare the requirement details from the existing application." }, { "code": null, "e": 58192, "s": 58156, "text": "Use case diagrams can be used for −" }, { "code": null, "e": 58236, "s": 58192, "text": "Requirement analysis and high level design." }, { "code": null, "e": 58280, "s": 58236, "text": "Requirement analysis and high level design." }, { "code": null, "e": 58311, "s": 58280, "text": "Model the context of a system." }, { "code": null, "e": 58342, "s": 58311, "text": "Model the context of a system." }, { "code": null, "e": 58363, "s": 58342, "text": "Reverse engineering." }, { "code": null, "e": 58384, "s": 58363, "text": "Reverse engineering." }, { "code": null, "e": 58405, "s": 58384, "text": "Forward engineering." }, { "code": null, "e": 58426, "s": 58405, "text": "Forward engineering." }, { "code": null, "e": 58633, "s": 58426, "text": "From the term Interaction, it is clear that the diagram is used to describe some type of interactions among the different elements in the model. This interaction is a part of dynamic behavior of the system." }, { "code": null, "e": 58802, "s": 58633, "text": "This interactive behavior is represented in UML by two diagrams known as Sequence diagram and Collaboration diagram. The basic purpose of both the diagrams are similar." }, { "code": null, "e": 58974, "s": 58802, "text": "Sequence diagram emphasizes on time sequence of messages and collaboration diagram emphasizes on the structural organization of the objects that send and receive messages." }, { "code": null, "e": 59224, "s": 58974, "text": "The purpose of interaction diagrams is to visualize the interactive behavior of the system. Visualizing the interaction is a difficult task. Hence, the solution is to use different types of models to capture the different aspects of the interaction." }, { "code": null, "e": 59328, "s": 59224, "text": "Sequence and collaboration diagrams are used to capture the dynamic nature but from a different angle." }, { "code": null, "e": 59368, "s": 59328, "text": "The purpose of interaction diagram is −" }, { "code": null, "e": 59414, "s": 59368, "text": "To capture the dynamic behaviour of a system." }, { "code": null, "e": 59460, "s": 59414, "text": "To capture the dynamic behaviour of a system." }, { "code": null, "e": 59504, "s": 59460, "text": "To describe the message flow in the system." }, { "code": null, "e": 59548, "s": 59504, "text": "To describe the message flow in the system." }, { "code": null, "e": 59604, "s": 59548, "text": "To describe the structural organization of the objects." }, { "code": null, "e": 59660, "s": 59604, "text": "To describe the structural organization of the objects." }, { "code": null, "e": 59703, "s": 59660, "text": "To describe the interaction among objects." }, { "code": null, "e": 59746, "s": 59703, "text": "To describe the interaction among objects." }, { "code": null, "e": 60056, "s": 59746, "text": "As we have already discussed, the purpose of interaction diagrams is to capture the dynamic aspect of a system. So to capture the dynamic aspect, we need to understand what a dynamic aspect is and how it is visualized. Dynamic aspect can be defined as the\nsnapshot of the running system at a particular moment" }, { "code": null, "e": 60386, "s": 60056, "text": "We have two types of interaction diagrams in UML. One is the sequence diagram and the\nother is the collaboration diagram. The sequence diagram captures the time sequence of\nthe message flow from one object to another and the collaboration diagram describes the\norganization of objects in a system taking part in the message flow." }, { "code": null, "e": 60471, "s": 60386, "text": "Following things are to be identified clearly before drawing the interaction diagram" }, { "code": null, "e": 60511, "s": 60471, "text": "Objects taking part in the interaction." }, { "code": null, "e": 60551, "s": 60511, "text": "Objects taking part in the interaction." }, { "code": null, "e": 60584, "s": 60551, "text": "Message flows among the objects." }, { "code": null, "e": 60617, "s": 60584, "text": "Message flows among the objects." }, { "code": null, "e": 60665, "s": 60617, "text": "The sequence in which the messages are flowing." }, { "code": null, "e": 60713, "s": 60665, "text": "The sequence in which the messages are flowing." }, { "code": null, "e": 60734, "s": 60713, "text": "Object organization." }, { "code": null, "e": 60755, "s": 60734, "text": "Object organization." }, { "code": null, "e": 60914, "s": 60755, "text": "Following are two interaction diagrams modeling the order management system. The first diagram is a sequence diagram and the second is a collaboration diagram" }, { "code": null, "e": 61001, "s": 60914, "text": "The sequence diagram has four objects (Customer, Order, SpecialOrder and NormalOrder)." }, { "code": null, "e": 61256, "s": 61001, "text": "The following diagram shows the message sequence for SpecialOrder object and the same can be used in case of NormalOrder object. It is important to understand the time sequence of message flows. The message flow is nothing but a method call of an object." }, { "code": null, "e": 61615, "s": 61256, "text": "The first call is sendOrder () which is a method of Order object. The next call is confirm () which is a method of SpecialOrder object and the last call is Dispatch () which is a method of SpecialOrder object. The following diagram mainly describes the method calls\nfrom one object to another, and this is also the actual scenario when the system is running." }, { "code": null, "e": 61993, "s": 61615, "text": "The second interaction diagram is the collaboration diagram. It shows the object organization as seen in the following diagram. In the collaboration diagram, the method call sequence is indicated by some numbering technique. The number indicates how the\nmethods are called one after another. We have taken the same order management system to describe the collaboration diagram." }, { "code": null, "e": 62204, "s": 61993, "text": "Method calls are similar to that of a sequence diagram. However, difference being the sequence diagram does not describe the object organization, whereas the collaboration diagram shows the object organization." }, { "code": null, "e": 62424, "s": 62204, "text": "To choose between these two diagrams, emphasis is placed on the type of requirement. If the time sequence is important, then the sequence diagram is used. If organization is required, then collaboration diagram is used." }, { "code": null, "e": 62726, "s": 62424, "text": "We have already discussed that interaction diagrams are used to describe the dynamic nature of a system. Now, we will look into the practical scenarios where these diagrams are used. To understand the practical application, we need to understand the basic nature\nof sequence and collaboration diagram." }, { "code": null, "e": 62913, "s": 62726, "text": "The main purpose of both the diagrams are similar as they are used to capture the dynamic behavior of a system. However, the specific purpose is more important to clarify and understand." }, { "code": null, "e": 63271, "s": 62913, "text": "Sequence diagrams are used to capture the order of messages flowing from one object to another. Collaboration diagrams are used to describe the structural organization of the objects taking part in the interaction. A single diagram is not sufficient to describe the dynamic aspect of an entire system, so a set of diagrams are used to capture it as a whole." }, { "code": null, "e": 63538, "s": 63271, "text": "Interaction diagrams are used when we want to understand the message flow and the structural organization. Message flow means the sequence of control flow from one object to another. Structural organization means the visual organization of the elements in a system." }, { "code": null, "e": 63573, "s": 63538, "text": "Interaction diagrams can be used −" }, { "code": null, "e": 63620, "s": 63573, "text": "To model the flow of control by time sequence." }, { "code": null, "e": 63667, "s": 63620, "text": "To model the flow of control by time sequence." }, { "code": null, "e": 63725, "s": 63667, "text": "To model the flow of control by structural organizations." }, { "code": null, "e": 63783, "s": 63725, "text": "To model the flow of control by structural organizations." }, { "code": null, "e": 63808, "s": 63783, "text": "For forward engineering." }, { "code": null, "e": 63833, "s": 63808, "text": "For forward engineering." }, { "code": null, "e": 63858, "s": 63833, "text": "For reverse engineering." }, { "code": null, "e": 63883, "s": 63858, "text": "For reverse engineering." }, { "code": null, "e": 64087, "s": 63883, "text": "The name of the diagram itself clarifies the purpose of the diagram and other details. It\ndescribes different states of a component in a system. The states are specific to a component/object of a system." }, { "code": null, "e": 64285, "s": 64087, "text": "A Statechart diagram describes a state machine. State machine can be defined as a machine which defines different states of an object and these states are controlled by external or internal events." }, { "code": null, "e": 64465, "s": 64285, "text": "Activity diagram explained in the next chapter, is a special kind of a Statechart diagram. As Statechart diagram defines the states, it is used to model the lifetime of an object." }, { "code": null, "e": 64816, "s": 64465, "text": "Statechart diagram is one of the five UML diagrams used to model the dynamic nature of a system. They define different states of an object during its lifetime and these states are changed by events. Statechart diagrams are useful to model the reactive systems. Reactive systems can be defined as a system that responds to external or internal events." }, { "code": null, "e": 65116, "s": 64816, "text": "Statechart diagram describes the flow of control from one state to another state. States are defined as a condition in which an object exists and it changes when some event is triggered. The most important purpose of Statechart diagram is to model lifetime of an object from creation to termination." }, { "code": null, "e": 65258, "s": 65116, "text": "Statechart diagrams are also used for forward and reverse engineering of a system. However, the main purpose is to model the reactive system." }, { "code": null, "e": 65321, "s": 65258, "text": "Following are the main purposes of using Statechart diagrams −" }, { "code": null, "e": 65362, "s": 65321, "text": "To model the dynamic aspect of a system." }, { "code": null, "e": 65403, "s": 65362, "text": "To model the dynamic aspect of a system." }, { "code": null, "e": 65448, "s": 65403, "text": "To model the life time of a reactive system." }, { "code": null, "e": 65493, "s": 65448, "text": "To model the life time of a reactive system." }, { "code": null, "e": 65557, "s": 65493, "text": "To describe different states of an object during its life time." }, { "code": null, "e": 65621, "s": 65557, "text": "To describe different states of an object during its life time." }, { "code": null, "e": 65678, "s": 65621, "text": "Define a state machine to model the states of an object." }, { "code": null, "e": 65735, "s": 65678, "text": "Define a state machine to model the states of an object." }, { "code": null, "e": 65984, "s": 65735, "text": "Statechart diagram is used to describe the states of different objects in its life cycle. Emphasis is placed on the state changes upon some internal or external events. These states of objects are important to analyze and implement them accurately." }, { "code": null, "e": 66135, "s": 65984, "text": "Statechart diagrams are very important for describing the states. States can be identified as the condition of objects when a particular event occurs." }, { "code": null, "e": 66212, "s": 66135, "text": "Before drawing a Statechart diagram we should clarify the following points −" }, { "code": null, "e": 66259, "s": 66212, "text": "Identify the important objects to be analyzed." }, { "code": null, "e": 66306, "s": 66259, "text": "Identify the important objects to be analyzed." }, { "code": null, "e": 66327, "s": 66306, "text": "Identify the states." }, { "code": null, "e": 66348, "s": 66327, "text": "Identify the states." }, { "code": null, "e": 66369, "s": 66348, "text": "Identify the events." }, { "code": null, "e": 66390, "s": 66369, "text": "Identify the events." }, { "code": null, "e": 66482, "s": 66390, "text": "Following is an example of a Statechart diagram where the state of Order object is analyzed" }, { "code": null, "e": 66709, "s": 66482, "text": "The first state is an idle state from where the process starts. The next states are arrived for events like send request, confirm request, and dispatch order. These events are responsible for the state changes of order object." }, { "code": null, "e": 67100, "s": 66709, "text": "During the life cycle of an object (here order object) it goes through the following states and there may be some abnormal exits. This abnormal exit may occur due to some problem in the system. When the entire life cycle is complete, it is considered as a complete transaction as shown in the following figure. The initial and final state of an object is also shown in the following figure." }, { "code": null, "e": 67400, "s": 67100, "text": "From the above discussion, we can define the practical applications of a Statechart diagram. Statechart diagrams are used to model the dynamic aspect of a system like other four diagrams discussed in this tutorial. However, it has some distinguishing characteristics for modeling the dynamic nature." }, { "code": null, "e": 67637, "s": 67400, "text": "Statechart diagram defines the states of a component and these state changes are dynamic in nature. Its specific purpose is to define the state changes triggered by events. Events are internal or external factors influencing the system." }, { "code": null, "e": 68031, "s": 67637, "text": "Statechart diagrams are used to model the states and also the events operating on the system. When implementing a system, it is very important to clarify different states of an object during its life time and Statechart diagrams are used for this purpose. When these states and events are identified, they are used to model it and these models are used during the implementation of the system." }, { "code": null, "e": 68255, "s": 68031, "text": "If we look into the practical implementation of Statechart diagram, then it is mainly used to analyze the object states influenced by events. This analysis is helpful to understand the system behavior during its execution. " }, { "code": null, "e": 68292, "s": 68255, "text": "The main usage can be described as −" }, { "code": null, "e": 68332, "s": 68292, "text": "To model the object states of a system." }, { "code": null, "e": 68372, "s": 68332, "text": "To model the object states of a system." }, { "code": null, "e": 68448, "s": 68372, "text": "To model the reactive system. Reactive system consists of reactive objects." }, { "code": null, "e": 68524, "s": 68448, "text": "To model the reactive system. Reactive system consists of reactive objects." }, { "code": null, "e": 68578, "s": 68524, "text": "To identify the events responsible for state changes." }, { "code": null, "e": 68632, "s": 68578, "text": "To identify the events responsible for state changes." }, { "code": null, "e": 68665, "s": 68632, "text": "Forward and reverse engineering." }, { "code": null, "e": 68698, "s": 68665, "text": "Forward and reverse engineering." }, { "code": null, "e": 68798, "s": 68698, "text": "Activity diagram is another important diagram in UML to describe the dynamic aspects of the system." }, { "code": null, "e": 68962, "s": 68798, "text": "Activity diagram is basically a flowchart to represent the flow from one activity to another\nactivity. The activity can be described as an operation of the system." }, { "code": null, "e": 69178, "s": 68962, "text": "The control flow is drawn from one operation to another. This flow can be sequential, branched, or concurrent. Activity diagrams deal with all type of flow control by using different elements such as fork, join, etc" }, { "code": null, "e": 69462, "s": 69178, "text": "The basic purposes of activity diagrams is similar to other four diagrams. It captures the dynamic behavior of the system. Other four diagrams are used to show the message flow from one object to another but activity diagram is used to show message flow from one activity to another." }, { "code": null, "e": 69775, "s": 69462, "text": "Activity is a particular operation of the system. Activity diagrams are not only used for visualizing the dynamic nature of a system, but they are also used to construct the executable system by using forward and reverse engineering techniques. The only missing\nthing in the activity diagram is the message part." }, { "code": null, "e": 70034, "s": 69775, "text": "It does not show any message flow from one activity to another. Activity diagram is sometimes considered as the flowchart. Although the diagrams look like a flowchart, they are not. It shows different flows such as parallel, branched, concurrent, and single." }, { "code": null, "e": 70091, "s": 70034, "text": "The purpose of an activity diagram can be described as −" }, { "code": null, "e": 70127, "s": 70091, "text": "Draw the activity flow of a system." }, { "code": null, "e": 70163, "s": 70127, "text": "Draw the activity flow of a system." }, { "code": null, "e": 70215, "s": 70163, "text": "Describe the sequence from one activity to another." }, { "code": null, "e": 70267, "s": 70215, "text": "Describe the sequence from one activity to another." }, { "code": null, "e": 70334, "s": 70267, "text": "Describe the parallel, branched and concurrent flow of the system." }, { "code": null, "e": 70401, "s": 70334, "text": "Describe the parallel, branched and concurrent flow of the system." }, { "code": null, "e": 70670, "s": 70401, "text": "Activity diagrams are mainly used as a flowchart that consists of activities performed by the system. Activity diagrams are not exactly flowcharts as they have some additional capabilities. These additional capabilities include branching, parallel flow, swimlane, etc." }, { "code": null, "e": 71014, "s": 70670, "text": "Before drawing an activity diagram, we must have a clear understanding about the elements used in activity diagram. The main element of an activity diagram is the activity itself. An activity is a function performed by the system. After identifying the activities, we need to understand how they are associated with constraints and conditions." }, { "code": null, "e": 71094, "s": 71014, "text": "Before drawing an activity diagram, we should identify the following elements −" }, { "code": null, "e": 71105, "s": 71094, "text": "Activities" }, { "code": null, "e": 71116, "s": 71105, "text": "Activities" }, { "code": null, "e": 71128, "s": 71116, "text": "Association" }, { "code": null, "e": 71140, "s": 71128, "text": "Association" }, { "code": null, "e": 71151, "s": 71140, "text": "Conditions" }, { "code": null, "e": 71162, "s": 71151, "text": "Conditions" }, { "code": null, "e": 71174, "s": 71162, "text": "Constraints" }, { "code": null, "e": 71186, "s": 71174, "text": "Constraints" }, { "code": null, "e": 71355, "s": 71186, "text": "Once the above-mentioned parameters are identified, we need to make a mental layout of the entire flow. This mental layout is then transformed into an activity diagram." }, { "code": null, "e": 71738, "s": 71355, "text": "Following is an example of an activity diagram for order management system. In the diagram, four activities are identified which are associated with conditions. One important point should be clearly understood that an activity diagram cannot be exactly matched with the code. The activity diagram is made to understand the flow of activities and is mainly used by the business users" }, { "code": null, "e": 71797, "s": 71738, "text": "Following diagram is drawn with the four main activities −" }, { "code": null, "e": 71824, "s": 71797, "text": "Send order by the customer" }, { "code": null, "e": 71851, "s": 71824, "text": "Send order by the customer" }, { "code": null, "e": 71872, "s": 71851, "text": "Receipt of the order" }, { "code": null, "e": 71893, "s": 71872, "text": "Receipt of the order" }, { "code": null, "e": 71911, "s": 71893, "text": "Confirm the order" }, { "code": null, "e": 71929, "s": 71911, "text": "Confirm the order" }, { "code": null, "e": 71948, "s": 71929, "text": "Dispatch the order" }, { "code": null, "e": 71967, "s": 71948, "text": "Dispatch the order" }, { "code": null, "e": 72200, "s": 71967, "text": "After receiving the order request, condition checks are performed to check if it is normal or special order. After the type of order is identified, dispatch activity is performed and that is marked as the termination of the process." }, { "code": null, "e": 72398, "s": 72200, "text": "The basic usage of activity diagram is similar to other four UML diagrams. The specific usage is to model the control flow from one activity to another. This control flow does not include messages." }, { "code": null, "e": 72736, "s": 72398, "text": "Activity diagram is suitable for modeling the activity flow of the system. An application can\nhave multiple systems. Activity diagram also captures these systems and describes the flow from one system to another. This specific usage is not available in other diagrams. These systems can be database, external queues, or any other system." }, { "code": null, "e": 73049, "s": 72736, "text": "We will now look into the practical applications of the activity diagram. From the above discussion, it is clear that an activity diagram is drawn from a very high level. So it gives high level view of a system. This high level view is mainly for business users or any other person who is not a technical person." }, { "code": null, "e": 73232, "s": 73049, "text": "This diagram is used to model the activities which are nothing but business requirements. The diagram has more impact on business understanding rather than on implementation details." }, { "code": null, "e": 73267, "s": 73232, "text": "Activity diagram can be used for −" }, { "code": null, "e": 73307, "s": 73267, "text": "Modeling work flow by using activities." }, { "code": null, "e": 73347, "s": 73307, "text": "Modeling work flow by using activities." }, { "code": null, "e": 73379, "s": 73347, "text": "Modeling business requirements." }, { "code": null, "e": 73411, "s": 73379, "text": "Modeling business requirements." }, { "code": null, "e": 73469, "s": 73411, "text": "High level understanding of the system's functionalities." }, { "code": null, "e": 73527, "s": 73469, "text": "High level understanding of the system's functionalities." }, { "code": null, "e": 73581, "s": 73527, "text": "Investigating business requirements at a later stage." } ]
Java Program to Print a given matrix in reverse spiral form
10 Jan, 2022 Given a 2D array, print it in reverse spiral form. We have already discussed Print a given matrix in spiral form. This article discusses how to do the reverse printing. See the following examples. Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1 Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Output: 11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1 Java // JAVA Code for Print a given matrix in // reverse spiral formclass GFG { public static int R = 3, C = 6; // Function that print matrix in reverse spiral form. public static void ReversespiralPrint(int m, int n, int a[][]) { // Large array to initialize it // with elements of matrix long b[] = new long[100]; /* k - starting row index l - starting column index*/ int i, k = 0, l = 0; // Counter for single dimension array //in which elements will be stored int z = 0; // Total elements in matrix int size = m * n; while (k < m && l < n) { // Variable to store value of matrix. int val; /* Print the first row from the remaining rows */ for (i = l; i < n; ++i) { val = a[k][i]; b[z] = val; ++z; } k++; /* Print the last column from the remaining columns */ for (i = k; i < m; ++i) { val = a[i][n-1]; b[z] = val; ++z; } n--; /* Print the last row from the remaining rows */ if ( k < m) { for (i = n-1; i >= l; --i) { val = a[m-1][i]; b[z] = val; ++z; } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m-1; i >= k; --i) { val = a[i][l]; b[z] = val; ++z; } l++; } } for (int x = size-1 ; x>=0 ; --x) { System.out.print(b[x]+" "); } } /* Driver program to test above function */ public static void main(String[] args) { int a[][] = { {1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18}}; ReversespiralPrint(R, C, a); } }// This code is contributed by Arnav Kr. Mandal. Output: 11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1 Please refer complete article on Print a given matrix in reverse spiral form for more details! pattern-printing spiral Java Java Programs Matrix School Programming pattern-printing Matrix Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jan, 2022" }, { "code": null, "e": 227, "s": 28, "text": "Given a 2D array, print it in reverse spiral form. We have already discussed Print a given matrix in spiral form. This article discusses how to do the reverse printing. See the following examples. " }, { "code": null, "e": 524, "s": 227, "text": "Input:\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n 13 14 15 16\nOutput: \n10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1\nInput:\n 1 2 3 4 5 6\n 7 8 9 10 11 12\n 13 14 15 16 17 18\nOutput: \n11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1" }, { "code": null, "e": 533, "s": 528, "text": "Java" }, { "code": "// JAVA Code for Print a given matrix in // reverse spiral formclass GFG { public static int R = 3, C = 6; // Function that print matrix in reverse spiral form. public static void ReversespiralPrint(int m, int n, int a[][]) { // Large array to initialize it // with elements of matrix long b[] = new long[100]; /* k - starting row index l - starting column index*/ int i, k = 0, l = 0; // Counter for single dimension array //in which elements will be stored int z = 0; // Total elements in matrix int size = m * n; while (k < m && l < n) { // Variable to store value of matrix. int val; /* Print the first row from the remaining rows */ for (i = l; i < n; ++i) { val = a[k][i]; b[z] = val; ++z; } k++; /* Print the last column from the remaining columns */ for (i = k; i < m; ++i) { val = a[i][n-1]; b[z] = val; ++z; } n--; /* Print the last row from the remaining rows */ if ( k < m) { for (i = n-1; i >= l; --i) { val = a[m-1][i]; b[z] = val; ++z; } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m-1; i >= k; --i) { val = a[i][l]; b[z] = val; ++z; } l++; } } for (int x = size-1 ; x>=0 ; --x) { System.out.print(b[x]+\" \"); } } /* Driver program to test above function */ public static void main(String[] args) { int a[][] = { {1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18}}; ReversespiralPrint(R, C, a); } }// This code is contributed by Arnav Kr. Mandal.", "e": 3001, "s": 533, "text": null }, { "code": null, "e": 3010, "s": 3001, "text": "Output: " }, { "code": null, "e": 3055, "s": 3010, "text": "11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1" }, { "code": null, "e": 3150, "s": 3055, "text": "Please refer complete article on Print a given matrix in reverse spiral form for more details!" }, { "code": null, "e": 3167, "s": 3150, "text": "pattern-printing" }, { "code": null, "e": 3174, "s": 3167, "text": "spiral" }, { "code": null, "e": 3179, "s": 3174, "text": "Java" }, { "code": null, "e": 3193, "s": 3179, "text": "Java Programs" }, { "code": null, "e": 3200, "s": 3193, "text": "Matrix" }, { "code": null, "e": 3219, "s": 3200, "text": "School Programming" }, { "code": null, "e": 3236, "s": 3219, "text": "pattern-printing" }, { "code": null, "e": 3243, "s": 3236, "text": "Matrix" }, { "code": null, "e": 3248, "s": 3243, "text": "Java" }, { "code": null, "e": 3346, "s": 3248, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3361, "s": 3346, "text": "Stream In Java" }, { "code": null, "e": 3382, "s": 3361, "text": "Introduction to Java" }, { "code": null, "e": 3403, "s": 3382, "text": "Constructors in Java" }, { "code": null, "e": 3422, "s": 3403, "text": "Exceptions in Java" }, { "code": null, "e": 3439, "s": 3422, "text": "Generics in Java" }, { "code": null, "e": 3465, "s": 3439, "text": "Java Programming Examples" }, { "code": null, "e": 3499, "s": 3465, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 3546, "s": 3499, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 3584, "s": 3546, "text": "Factory method design pattern in Java" } ]
Negative weight cycle | Practice | GeeksforGeeks
Given a weighted directed graph with n nodes and m edges. Nodes are labeled from 0 to n-1, the task is to check if it contains a negative weight cycle or not. Note: edges[i] is defined as u, v and weight. Example 1: Input: n = 3, edges = {{0,1,-1},{1,2,-2}, {2,0,-3}} Output: 1 Explanation: The graph contains negative weight cycle as 0->1->2->0 with weight -1,-2,-3. Example 2: Input: n = 3, edges = {{0,1,-1},{1,2,-2}, {2,0,3}} Output: 0 Explanation: The graph does not contain any negative weight cycle. Your Task: You don't need to read or print anyhting. Your task is to complete the function isNegativeWeightCycle() which takes n and edges as input paramater and returns 1 if graph contains negative weight cycle otherwise returns 0. Expected Time Complexity: O(n*m) Expected Space Compelxity: O(n) Constraints: 1 <= n <= 100 1 <= m <= n*(n-1), where m is the total number of Edges in the directed graph. 0 roboto7o32oo33 days ago Clean Python Solution ✨ ✨ (Using Bellman Ford's Algorithm) class Solution: def isNegativeWeightCycle(self, n, edges): # initialize all the distance to be infinite distance = [float('inf') for _ in range(n)] # make distance to vertex 0 to be 0 distance[0] = 0 # iterate over all the edges n-1 times for _ in range(n-1): for (u,v,w) in edges: distance[v] = min(distance[v], distance[u]+w) # check if distance has converged after n-1 iterations, if not then there is a negative cycle for (u,v,w) in edges: if distance[v] > distance[u]+w: return 1 return 0 0 donkn69123 days ago int isNegativeWeightCycle(int n, vector<vector<int>>edges){ int m = edges.size(); int inf = 10000000; vector<int> dist(n, inf); dist[0] = 0; for(int j = 0; j<n-1; j++){ for(int i = 0;i<m;i++) { if(dist[edges[i][0]] + edges[i][2] < dist[edges[i][1]]) { dist[edges[i][1]] = dist[edges[i][0]] + edges[i][2]; } } } //relaxing n-1 times according to Bellman Ford // int fl = 0; for(int i = 0;i<m;i++) { if(dist[edges[i][0]] + edges[i][2] < dist[edges[i][1]]) { return 1; } } //if relaxing nth time gives less distance then there is a negative cycle. return 0; } 0 yashwant19je09383 days ago Don't Know what the heck happened but, I just make one change in cycle detection code i.e., (in checks include) if weight is negative, return true :)) ... and all test cases passed. +1 akshaydayma93512 weeks ago It can be solved just by using dfs. →Call dfs n(number of vertices) times. →In dfs, while traversing if you encounter cycle and it's summation of weight comes out to be negative. Then just return graph contains negative cycle. struct Node{ int data; int weight; }; void edge(vector<vector<Node> > &adj, int a, int b, int w){ Node temp2; temp2.data = b; temp2.weight = w; adj[a].push_back(temp2); //directed graph given } int dfs(int node, vector<vector<Node> > &adj, vector<bool> &visited, int sum){ visited[node] = true; for(int i=0;i<adj[node].size();i++){ if(!visited[adj[node][i].data]){ if(dfs(adj[node][i].data,adj, visited,sum+adj[node][i].weight) == 1) return 1; } else{ if( sum+adj[node][i].weight < 0 ) return 1; } } visited[node] = false; return 0; } int isNegativeWeightCycle(int n, vector<vector<int>>edges){ // Code here vector<vector<Node> > adj(n); for(int i=0;i<edges.size();i++){ edge(adj, edges[i][0], edges[i][1], edges[i][2]); } vector<bool> visited(n, false); for(int i=0;i<n;i++){ if(!visited[i]){ if(dfs(i, adj, visited, 0) == 1) return 1; } } return 0;} +3 learningdsa2 weeks ago Concise Bellman Ford's Algorithm (C++): [0.85/2.8] int isNegativeWeightCycle(int n, vector<vector<int>>edges){ vector<int> distance(n, INT_MAX); distance[0] = 0; for(int x = 0; x < n - 1; x++){ for(auto z: edges){ if(distance[z[0]] != INT_MAX and distance[z[1]] > distance[z[0]] + z[2]){ distance[z[1]] = distance[z[0]] + z[2]; } } } for(auto z: edges){ if(distance[z[0]] != INT_MAX and distance[z[1]] > distance[z[0]] + z[2]){ return 1; } } return 0; } +7 ashishkyjp113 weeks ago Don't use INT_MAX as an initializer in the distance array, as it will throw some error. Use some other value like 1e+6. 0 ashishkyjp113 weeks ago int isNegativeWeightCycle(int n, vector<vector<int>>edges){ // Code here vector<int> dist(n,1000000); dist[0]=0; for(int i=1; i<=n-1; i++) { for(auto &edge:edges) { if(dist[edge[0]]+edge[2]<dist[edge[1]]) { dist[edge[1]]=dist[edge[0]]+edge[2]; } } } for(auto &edge:edges) { if(dist[edge[0]]+edge[2]<dist[edge[1]]) { return 1; } } return 0; } 0 monilmodi2002 This comment was deleted. 0 vishaltalawar034 weeks ago class Solution{ public int isNegativeWeightCycle(int n, int[][] edges) { //code here int dist[] = new int[n]; Arrays.fill(dist, Integer.MAX_VALUE); dist[0] = 0; for(int count = 1;count<n; count++){ for(int j=0;j<edges.length;j++){ int src = edges[j][0]; int dest = edges[j][1]; int wt = edges[j][2]; if(dist[src]!=Integer.MAX_VALUE && dist[src] + wt < dist[dest]){ dist[dest] = dist[src] +wt; } } } for(int j=0;j<edges.length;j++){ int src = edges[j][0]; int dest = edges[j][1]; int wt = edges[j][2]; if(dist[src]!=Integer.MAX_VALUE && dist[src] + wt < dist[dest]){ return 1; } } return 0; }} 0 kurmiamreet444 weeks ago class Solution{ public int isNegativeWeightCycle(int n, int[][] edges) { int [] visited = new int[n];// stores the minimum cost value for each vertex from the source Arrays.fill(visited, Integer.MAX_VALUE); visited[0]=0; for(int i=0;i<n-1;i++)// iteration for n vertices to check negative weight // if in the final i.e more than n-1 runs and the visited array value changes then it is negative weight cycle // it takes n-1 runs to completely work on the graph in Bellman Ford algorithm { for(int j=0;j<edges.length;j++)//cycle through the 2d graph { if(visited[edges[j][0]]!= Integer.MAX_VALUE &&visited[edges[j][0]]+edges[j][2]<visited[edges[j][1]]) { visited[edges[j][1]]=visited[edges[j][0]] +edges[j][2]; } } } for(int j=0;j<edges.length;j++) { if(visited[edges[j][0]]+edges[j][2]<visited[edges[j][1]]) { return 1; } } return 0; }} 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. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems 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": 445, "s": 238, "text": "Given a weighted directed graph with n nodes and m edges. Nodes are labeled from 0 to n-1, the task is to check if it contains a negative weight cycle or not.\nNote: edges[i] is defined as u, v and weight.\n " }, { "code": null, "e": 456, "s": 445, "text": "Example 1:" }, { "code": null, "e": 609, "s": 456, "text": "Input: n = 3, edges = {{0,1,-1},{1,2,-2},\n{2,0,-3}}\nOutput: 1\nExplanation: The graph contains negative weight\ncycle as 0->1->2->0 with weight -1,-2,-3.\n" }, { "code": null, "e": 620, "s": 609, "text": "Example 2:" }, { "code": null, "e": 749, "s": 620, "text": "Input: n = 3, edges = {{0,1,-1},{1,2,-2},\n{2,0,3}}\nOutput: 0\nExplanation: The graph does not contain any\nnegative weight cycle.\n" }, { "code": null, "e": 986, "s": 751, "text": "Your Task:\nYou don't need to read or print anyhting. Your task is to complete the function isNegativeWeightCycle() which takes n and edges as input paramater and returns 1 if graph contains negative weight cycle otherwise returns 0.\n " }, { "code": null, "e": 1053, "s": 986, "text": "Expected Time Complexity: O(n*m)\nExpected Space Compelxity: O(n)\n " }, { "code": null, "e": 1159, "s": 1053, "text": "Constraints:\n1 <= n <= 100\n1 <= m <= n*(n-1), where m is the total number of Edges in the directed graph." }, { "code": null, "e": 1161, "s": 1159, "text": "0" }, { "code": null, "e": 1185, "s": 1161, "text": "roboto7o32oo33 days ago" }, { "code": null, "e": 1244, "s": 1185, "text": "Clean Python Solution ✨ ✨ (Using Bellman Ford's Algorithm)" }, { "code": null, "e": 1859, "s": 1246, "text": "class Solution:\n\tdef isNegativeWeightCycle(self, n, edges):\n\t \n\t # initialize all the distance to be infinite\n\t distance = [float('inf') for _ in range(n)]\n\t \n\t # make distance to vertex 0 to be 0\n\t distance[0] = 0\n\t \n\t # iterate over all the edges n-1 times\n\t for _ in range(n-1):\n\t for (u,v,w) in edges:\n\t distance[v] = min(distance[v], distance[u]+w)\n\t \n\t # check if distance has converged after n-1 iterations, if not then there is a negative cycle\n\t for (u,v,w) in edges:\n\t if distance[v] > distance[u]+w:\n\t return 1\n\t \n\t return 0" }, { "code": null, "e": 1861, "s": 1859, "text": "0" }, { "code": null, "e": 1881, "s": 1861, "text": "donkn69123 days ago" }, { "code": null, "e": 2615, "s": 1881, "text": "\tint isNegativeWeightCycle(int n, vector<vector<int>>edges){\n\t int m = edges.size();\n int inf = 10000000; \n vector<int> dist(n, inf); \n dist[0] = 0; \n for(int j = 0; j<n-1; j++){\n for(int i = 0;i<m;i++) {\n if(dist[edges[i][0]] + edges[i][2] < dist[edges[i][1]]) {\n dist[edges[i][1]] = dist[edges[i][0]] + edges[i][2]; \n }\n }\n } \n //relaxing n-1 times according to Bellman Ford\n\n // int fl = 0; \n for(int i = 0;i<m;i++) {\n if(dist[edges[i][0]] + edges[i][2] < dist[edges[i][1]]) {\n return 1;\n }\n }\n //if relaxing nth time gives less distance then there is a negative cycle.\n \n \n \n \n return 0;\n\t}" }, { "code": null, "e": 2617, "s": 2615, "text": "0" }, { "code": null, "e": 2644, "s": 2617, "text": "yashwant19je09383 days ago" }, { "code": null, "e": 2827, "s": 2644, "text": "Don't Know what the heck happened but, I just make one change in cycle detection code i.e., (in checks include) if weight is negative, return true :)) ... and all test cases passed." }, { "code": null, "e": 2830, "s": 2827, "text": "+1" }, { "code": null, "e": 2857, "s": 2830, "text": "akshaydayma93512 weeks ago" }, { "code": null, "e": 2896, "s": 2859, "text": "It can be solved just by using dfs. " }, { "code": null, "e": 2935, "s": 2896, "text": "→Call dfs n(number of vertices) times." }, { "code": null, "e": 3088, "s": 2935, "text": "→In dfs, while traversing if you encounter cycle and it's summation of weight comes out to be negative. Then just return graph contains negative cycle. " }, { "code": null, "e": 3457, "s": 3092, "text": "struct Node{ int data; int weight; }; void edge(vector<vector<Node> > &adj, int a, int b, int w){ Node temp2; temp2.data = b; temp2.weight = w; adj[a].push_back(temp2); //directed graph given } int dfs(int node, vector<vector<Node> > &adj, vector<bool> &visited, int sum){ visited[node] = true;" }, { "code": null, "e": 3810, "s": 3457, "text": " for(int i=0;i<adj[node].size();i++){ if(!visited[adj[node][i].data]){ if(dfs(adj[node][i].data,adj, visited,sum+adj[node][i].weight) == 1) return 1; } else{ if( sum+adj[node][i].weight < 0 ) return 1; } } visited[node] = false; return 0; }" }, { "code": null, "e": 4196, "s": 3810, "text": "int isNegativeWeightCycle(int n, vector<vector<int>>edges){ // Code here vector<vector<Node> > adj(n); for(int i=0;i<edges.size();i++){ edge(adj, edges[i][0], edges[i][1], edges[i][2]); } vector<bool> visited(n, false); for(int i=0;i<n;i++){ if(!visited[i]){ if(dfs(i, adj, visited, 0) == 1) return 1; } } return 0;}" }, { "code": null, "e": 4199, "s": 4196, "text": "+3" }, { "code": null, "e": 4222, "s": 4199, "text": "learningdsa2 weeks ago" }, { "code": null, "e": 4273, "s": 4222, "text": "Concise Bellman Ford's Algorithm (C++): [0.85/2.8]" }, { "code": null, "e": 4753, "s": 4273, "text": "int isNegativeWeightCycle(int n, vector<vector<int>>edges){\n\tvector<int> distance(n, INT_MAX);\n\tdistance[0] = 0;\n\tfor(int x = 0; x < n - 1; x++){\n\t for(auto z: edges){\n\t if(distance[z[0]] != INT_MAX and distance[z[1]] > distance[z[0]] + z[2]){\n\t distance[z[1]] = distance[z[0]] + z[2];\n\t }\n\t }\n\t}\n for(auto z: edges){\n if(distance[z[0]] != INT_MAX and distance[z[1]] > distance[z[0]] + z[2]){\n return 1;\n }\n }\n\treturn 0;\n}" }, { "code": null, "e": 4756, "s": 4753, "text": "+7" }, { "code": null, "e": 4780, "s": 4756, "text": "ashishkyjp113 weeks ago" }, { "code": null, "e": 4900, "s": 4780, "text": "Don't use INT_MAX as an initializer in the distance array, as it will throw some error. Use some other value like 1e+6." }, { "code": null, "e": 4902, "s": 4900, "text": "0" }, { "code": null, "e": 4926, "s": 4902, "text": "ashishkyjp113 weeks ago" }, { "code": null, "e": 5483, "s": 4926, "text": "int isNegativeWeightCycle(int n, vector<vector<int>>edges){\n\t // Code here\n\t vector<int> dist(n,1000000);\n\t dist[0]=0;\n\t \n\t for(int i=1; i<=n-1; i++)\n\t {\n for(auto &edge:edges)\n\t {\n\t if(dist[edge[0]]+edge[2]<dist[edge[1]])\n\t {\n\t dist[edge[1]]=dist[edge[0]]+edge[2];\n\t }\n\t }\n\t }\n\t \n for(auto &edge:edges)\n {\n if(dist[edge[0]]+edge[2]<dist[edge[1]])\n {\n return 1;\n }\n }\n\t \n\t return 0;\n\t}" }, { "code": null, "e": 5485, "s": 5483, "text": "0" }, { "code": null, "e": 5499, "s": 5485, "text": "monilmodi2002" }, { "code": null, "e": 5525, "s": 5499, "text": "This comment was deleted." }, { "code": null, "e": 5527, "s": 5525, "text": "0" }, { "code": null, "e": 5554, "s": 5527, "text": "vishaltalawar034 weeks ago" }, { "code": null, "e": 6459, "s": 5554, "text": "class Solution{ public int isNegativeWeightCycle(int n, int[][] edges) { //code here int dist[] = new int[n]; Arrays.fill(dist, Integer.MAX_VALUE); dist[0] = 0; for(int count = 1;count<n; count++){ for(int j=0;j<edges.length;j++){ int src = edges[j][0]; int dest = edges[j][1]; int wt = edges[j][2]; if(dist[src]!=Integer.MAX_VALUE && dist[src] + wt < dist[dest]){ dist[dest] = dist[src] +wt; } } } for(int j=0;j<edges.length;j++){ int src = edges[j][0]; int dest = edges[j][1]; int wt = edges[j][2]; if(dist[src]!=Integer.MAX_VALUE && dist[src] + wt < dist[dest]){ return 1; } } return 0; }}" }, { "code": null, "e": 6461, "s": 6459, "text": "0" }, { "code": null, "e": 6486, "s": 6461, "text": "kurmiamreet444 weeks ago" }, { "code": null, "e": 7581, "s": 6486, "text": "class Solution{ public int isNegativeWeightCycle(int n, int[][] edges) { int [] visited = new int[n];// stores the minimum cost value for each vertex from the source Arrays.fill(visited, Integer.MAX_VALUE); visited[0]=0; for(int i=0;i<n-1;i++)// iteration for n vertices to check negative weight // if in the final i.e more than n-1 runs and the visited array value changes then it is negative weight cycle // it takes n-1 runs to completely work on the graph in Bellman Ford algorithm { for(int j=0;j<edges.length;j++)//cycle through the 2d graph { if(visited[edges[j][0]]!= Integer.MAX_VALUE &&visited[edges[j][0]]+edges[j][2]<visited[edges[j][1]]) { visited[edges[j][1]]=visited[edges[j][0]] +edges[j][2]; } } } for(int j=0;j<edges.length;j++) { if(visited[edges[j][0]]+edges[j][2]<visited[edges[j][1]]) { return 1; } } return 0; }}" }, { "code": null, "e": 7727, "s": 7581, "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": 7763, "s": 7727, "text": " Login to access your submissions. " }, { "code": null, "e": 7773, "s": 7763, "text": "\nProblem\n" }, { "code": null, "e": 7783, "s": 7773, "text": "\nContest\n" }, { "code": null, "e": 7846, "s": 7783, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8031, "s": 7846, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 8315, "s": 8031, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 8461, "s": 8315, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 8538, "s": 8461, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 8579, "s": 8538, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 8607, "s": 8579, "text": "Disable browser extensions." }, { "code": null, "e": 8678, "s": 8607, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 8865, "s": 8678, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
JavaScript Math pow( ) Method
09 Feb, 2022 Below is the example of the Math pow() Method. Example:<script type="text/javascript"> document.write(Math.pow(3, 4));</script> <script type="text/javascript"> document.write(Math.pow(3, 4));</script> Output:81 81 The Math.pow() method is used to power of a number i.e., the value of number raised to some exponent. Since the Math.pow() is a static method of Math and therefore it is always used as Math.pow() and not as a method of an object created of Math class. Syntax: Math.pow(base, exponent) Parameters: This method accepts two parameters as mentioned above and described below: base:It is the base number which is to be raised. exponent:It is the value used to raise the base. Return Value: The Math.pow() method returns a number representing the given base raised to the power of the given exponent. More codes for the above method are as follows: Program 1: When both base and exponent are passed as positive numbers in parameters: <script type="text/javascript"> document.write(Math.pow(9, 3));</script> Output: 729 Program 2: When the base value is negative and the exponent is positive: <script type="text/javascript"> document.write(Math.pow(-9, 3));</script> Output: -729 Program 3: When the base value is positive and the exponent is negative: <script type="text/javascript"> document.write(Math.pow(9, -3));</script> Output: 0.0013717421124828531 Program 4: When the base value is negative and the exponent has decimal point: <script type="text/javascript"> document.write(Math.pow(-9, 0.5));</script> Output: NaN Supported Browsers: Google Chrome 1 and above Internet Explorer 3 and above Firefox 1 and above Opera 3 and above Safari 1 and above shubham_singh ysachin2314 javascript-math JavaScript-Methods JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Feb, 2022" }, { "code": null, "e": 75, "s": 28, "text": "Below is the example of the Math pow() Method." }, { "code": null, "e": 159, "s": 75, "text": "Example:<script type=\"text/javascript\"> document.write(Math.pow(3, 4));</script>" }, { "code": "<script type=\"text/javascript\"> document.write(Math.pow(3, 4));</script>", "e": 235, "s": 159, "text": null }, { "code": null, "e": 245, "s": 235, "text": "Output:81" }, { "code": null, "e": 248, "s": 245, "text": "81" }, { "code": null, "e": 500, "s": 248, "text": "The Math.pow() method is used to power of a number i.e., the value of number raised to some exponent. Since the Math.pow() is a static method of Math and therefore it is always used as Math.pow() and not as a method of an object created of Math class." }, { "code": null, "e": 508, "s": 500, "text": "Syntax:" }, { "code": null, "e": 533, "s": 508, "text": "Math.pow(base, exponent)" }, { "code": null, "e": 620, "s": 533, "text": "Parameters: This method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 670, "s": 620, "text": "base:It is the base number which is to be raised." }, { "code": null, "e": 719, "s": 670, "text": "exponent:It is the value used to raise the base." }, { "code": null, "e": 843, "s": 719, "text": "Return Value: The Math.pow() method returns a number representing the given base raised to the power of the given exponent." }, { "code": null, "e": 891, "s": 843, "text": "More codes for the above method are as follows:" }, { "code": null, "e": 976, "s": 891, "text": "Program 1: When both base and exponent are passed as positive numbers in parameters:" }, { "code": "<script type=\"text/javascript\"> document.write(Math.pow(9, 3));</script>", "e": 1052, "s": 976, "text": null }, { "code": null, "e": 1060, "s": 1052, "text": "Output:" }, { "code": null, "e": 1064, "s": 1060, "text": "729" }, { "code": null, "e": 1137, "s": 1064, "text": "Program 2: When the base value is negative and the exponent is positive:" }, { "code": "<script type=\"text/javascript\"> document.write(Math.pow(-9, 3));</script>", "e": 1214, "s": 1137, "text": null }, { "code": null, "e": 1222, "s": 1214, "text": "Output:" }, { "code": null, "e": 1227, "s": 1222, "text": "-729" }, { "code": null, "e": 1300, "s": 1227, "text": "Program 3: When the base value is positive and the exponent is negative:" }, { "code": "<script type=\"text/javascript\"> document.write(Math.pow(9, -3));</script>", "e": 1377, "s": 1300, "text": null }, { "code": null, "e": 1385, "s": 1377, "text": "Output:" }, { "code": null, "e": 1407, "s": 1385, "text": "0.0013717421124828531" }, { "code": null, "e": 1486, "s": 1407, "text": "Program 4: When the base value is negative and the exponent has decimal point:" }, { "code": "<script type=\"text/javascript\"> document.write(Math.pow(-9, 0.5));</script>", "e": 1565, "s": 1486, "text": null }, { "code": null, "e": 1573, "s": 1565, "text": "Output:" }, { "code": null, "e": 1577, "s": 1573, "text": "NaN" }, { "code": null, "e": 1597, "s": 1577, "text": "Supported Browsers:" }, { "code": null, "e": 1623, "s": 1597, "text": "Google Chrome 1 and above" }, { "code": null, "e": 1653, "s": 1623, "text": "Internet Explorer 3 and above" }, { "code": null, "e": 1673, "s": 1653, "text": "Firefox 1 and above" }, { "code": null, "e": 1691, "s": 1673, "text": "Opera 3 and above" }, { "code": null, "e": 1710, "s": 1691, "text": "Safari 1 and above" }, { "code": null, "e": 1724, "s": 1710, "text": "shubham_singh" }, { "code": null, "e": 1736, "s": 1724, "text": "ysachin2314" }, { "code": null, "e": 1752, "s": 1736, "text": "javascript-math" }, { "code": null, "e": 1771, "s": 1752, "text": "JavaScript-Methods" }, { "code": null, "e": 1782, "s": 1771, "text": "JavaScript" }, { "code": null, "e": 1799, "s": 1782, "text": "Web Technologies" }, { "code": null, "e": 1897, "s": 1799, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1958, "s": 1897, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2030, "s": 1958, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2070, "s": 2030, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2123, "s": 2070, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2164, "s": 2123, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2197, "s": 2164, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2259, "s": 2197, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2320, "s": 2259, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2370, "s": 2320, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
seaborn.lineplot() method in Python
17 Jul, 2020 Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. The colors stand out, the layers blend nicely together, the contours flow throughout, and the overall package not only has a nice aesthetic quality, but it provides meaningful insights to us as well. Draw a line plot with the possibility of several semantic groupings. The relationship between x and y can be shown for different subsets of the data using the hue, size, and style parameters. These parameters control what visual semantics are used to identify the different subsets. It is possible to show up to three dimensions independently by using all three semantic types, but this style of plot can be hard to interpret and is often ineffective. Using redundant semantics (i.e. both hue and style for the same variable) can be helpful for making graphics more accessible. Syntax : sns.lineplot(x=None, y=None, hue=None, size=None, style=None, data=None, palette=None, hue_order=None, hue_norm=None, sizes=None, size_order=None, size_norm=None, dashes=True, markers=None, style_order=None, units=None, estimator=’mean’, ci=95, n_boot=1000, sort=True, err_style=’band’, err_kws=None, legend=’brief’, ax=None, **kwargs,) Parameters: x, y: Input data variables; must be numeric. Can pass data directly or reference columns in data. hue: Grouping variable that will produce lines with different colors. Can be either categorical or numeric, although color mapping will behave differently in latter case. style: Grouping variable that will produce lines with different dashes and/or markers. Can have a numeric dtype but will always be treated as categorical. data: Tidy (“long-form”) dataframe where each column is a variable and each row is an observation. markers: Object determining how to draw the markers for different levels of the style variable. legend: How to draw the legend. If “brief”, numeric “hue“ and “size“ variables will be represented with a sample of evenly spaced values. Below is the implementation of above method with some examples : Example 1: Python3 # importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("iris") # draw lineplotsns.lineplot(x="sepal_length", y="sepal_width", data=data)plt.show() Output : Example 2 : Python3 # importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("tips") # draw lineplot# hue by sex# style to huesns.lineplot(x="total_bill", y="size", hue="sex", style="sex", data=data) plt.show() Output : Python-Seaborn Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Jul, 2020" }, { "code": null, "e": 416, "s": 52, "text": "Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. The colors stand out, the layers blend nicely together, the contours flow throughout, and the overall package not only has a nice aesthetic quality, but it provides meaningful insights to us as well." }, { "code": null, "e": 994, "s": 416, "text": "Draw a line plot with the possibility of several semantic groupings. The relationship between x and y can be shown for different subsets of the data using the hue, size, and style parameters. These parameters control what visual semantics are used to identify the different subsets. It is possible to show up to three dimensions independently by using all three semantic types, but this style of plot can be hard to interpret and is often ineffective. Using redundant semantics (i.e. both hue and style for the same variable) can be helpful for making graphics more accessible." }, { "code": null, "e": 1340, "s": 994, "text": "Syntax : sns.lineplot(x=None, y=None, hue=None, size=None, style=None, data=None, palette=None, hue_order=None, hue_norm=None, sizes=None, size_order=None, size_norm=None, dashes=True, markers=None, style_order=None, units=None, estimator=’mean’, ci=95, n_boot=1000, sort=True, err_style=’band’, err_kws=None, legend=’brief’, ax=None, **kwargs,)" }, { "code": null, "e": 1352, "s": 1340, "text": "Parameters:" }, { "code": null, "e": 1450, "s": 1352, "text": "x, y: Input data variables; must be numeric. Can pass data directly or reference columns in data." }, { "code": null, "e": 1621, "s": 1450, "text": "hue: Grouping variable that will produce lines with different colors. Can be either categorical or numeric, although color mapping will behave differently in latter case." }, { "code": null, "e": 1776, "s": 1621, "text": "style: Grouping variable that will produce lines with different dashes and/or markers. Can have a numeric dtype but will always be treated as categorical." }, { "code": null, "e": 1876, "s": 1776, "text": "data: Tidy (“long-form”) dataframe where each column is a variable and each row is an observation. " }, { "code": null, "e": 1972, "s": 1876, "text": "markers: Object determining how to draw the markers for different levels of the style variable." }, { "code": null, "e": 2110, "s": 1972, "text": "legend: How to draw the legend. If “brief”, numeric “hue“ and “size“ variables will be represented with a sample of evenly spaced values." }, { "code": null, "e": 2175, "s": 2110, "text": "Below is the implementation of above method with some examples :" }, { "code": null, "e": 2186, "s": 2175, "text": "Example 1:" }, { "code": null, "e": 2194, "s": 2186, "text": "Python3" }, { "code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"iris\") # draw lineplotsns.lineplot(x=\"sepal_length\", y=\"sepal_width\", data=data)plt.show()", "e": 2402, "s": 2194, "text": null }, { "code": null, "e": 2411, "s": 2402, "text": "Output :" }, { "code": null, "e": 2423, "s": 2411, "text": "Example 2 :" }, { "code": null, "e": 2431, "s": 2423, "text": "Python3" }, { "code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"tips\") # draw lineplot# hue by sex# style to huesns.lineplot(x=\"total_bill\", y=\"size\", hue=\"sex\", style=\"sex\", data=data) plt.show()", "e": 2706, "s": 2431, "text": null }, { "code": null, "e": 2715, "s": 2706, "text": "Output :" }, { "code": null, "e": 2730, "s": 2715, "text": "Python-Seaborn" }, { "code": null, "e": 2737, "s": 2730, "text": "Python" }, { "code": null, "e": 2835, "s": 2737, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2853, "s": 2835, "text": "Python Dictionary" }, { "code": null, "e": 2895, "s": 2853, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2917, "s": 2895, "text": "Enumerate() in Python" }, { "code": null, "e": 2952, "s": 2917, "text": "Read a file line by line in Python" }, { "code": null, "e": 2984, "s": 2952, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3013, "s": 2984, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3043, "s": 3013, "text": "Iterate over a list in Python" }, { "code": null, "e": 3070, "s": 3043, "text": "Python Classes and Objects" }, { "code": null, "e": 3106, "s": 3070, "text": "Convert integer to string in Python" } ]
What is the AddSingleton vs AddScoped vs Add Transient C# Asp.net Core?
There are three ways by which dependencies can be registered in Startup.cs. i.e. AddSingleton, AddScoped and AddTransient. When we register a type as singleton, only one instance is available throughout the application and for every request. It is similar to having a static object. The instance is created for the first request and the same is available throughout the application and for each subsequent requests. public void ConfigureServices(IServiceCollection services){ services.AddSingleton<ILog,Logger>() } When we register a type as Scoped, one instance is available throughout the application per request. When a new request comes in, the new instance is created. Add scoped specifies that a single object is available per request. public void ConfigureServices(IServiceCollection services){ services.AddScoped<ILog,Logger>() } When we register a type as Transient, every time a new instance is created. Transient creates new instance for every service/ controller as well as for every request and every user. public void ConfigureServices(IServiceCollection services){ services.AddTransient<ILog,Logger>() }
[ { "code": null, "e": 1310, "s": 1187, "text": "There are three ways by which dependencies can be registered in Startup.cs. i.e.\nAddSingleton, AddScoped and AddTransient." }, { "code": null, "e": 1429, "s": 1310, "text": "When we register a type as singleton, only one instance is available throughout the\napplication and for every request." }, { "code": null, "e": 1470, "s": 1429, "text": "It is similar to having a static object." }, { "code": null, "e": 1603, "s": 1470, "text": "The instance is created for the first request and the same is available throughout the\napplication and for each subsequent requests." }, { "code": null, "e": 1705, "s": 1603, "text": "public void ConfigureServices(IServiceCollection services){\n services.AddSingleton<ILog,Logger>()\n}" }, { "code": null, "e": 1932, "s": 1705, "text": "When we register a type as Scoped, one instance is available throughout the\napplication per request. When a new request comes in,\nthe new instance is created. Add scoped specifies that a single object is available per\nrequest." }, { "code": null, "e": 2031, "s": 1932, "text": "public void ConfigureServices(IServiceCollection services){\n services.AddScoped<ILog,Logger>()\n}" }, { "code": null, "e": 2213, "s": 2031, "text": "When we register a type as Transient, every time a new instance is created. Transient\ncreates new instance for every service/ controller as well as for every request and\nevery user." }, { "code": null, "e": 2315, "s": 2213, "text": "public void ConfigureServices(IServiceCollection services){\n services.AddTransient<ILog,Logger>()\n}" } ]
Python – Consecutive Row summation in Matrix
29 Dec, 2019 This particular article focuses on a problem that has utility in competitive as well as day-day programming. Sometimes, we need to get the sum between the like indices when compared with the next list. The sum between the like elements in that index is returned. Let’s discuss certain ways in which this task can be performed. Method #1 : Using sum() + abs() + zip() + list comprehensionThis particular problem can also be solved using the combination of the above 4 operations. Here zip function does the dual task of pairing the list and also pairing the like indices for sum, to be computed by abs function and then sum is found using sum function, all bounded by list comprehension. # Python3 code to demonstrate# Consecutive Row summation in Matrix# using sum() + abs() + zip() + list comprehension # initializing list test_list = [[3, 4, 5], [4, 6, 8], [1, 9, 2], [3, 7, 10]] # printing original list print("The original list : " + str(test_list)) # using sum() + abs() + zip() + list comprehension# Consecutive Row summation in Matrixres = [sum(abs(i + j) for i, j in zip(*ele)) for ele in zip(test_list, test_list[1:])] # print resultprint("The row summation sublist : " + str(res)) The original list : [[3, 4, 5], [4, 6, 8], [1, 9, 2], [3, 7, 10]] The row summation sublist : [30, 30, 32] Method #2 : Using sum() + map() + abs + zip()This task can also be achieved using the combination of above functions, the addition is map function that performs the task of binding of abs operation to the whole list. # Python3 code to demonstrate# Consecutive Row summation in Matrix# using sum() + map() + abs + zip() # initializing list test_list = [[3, 4, 5], [4, 6, 8], [1, 9, 2], [3, 7, 10]] # printing original list print("The original list : " + str(test_list)) # using sum() + map() + abs + zip()# Consecutive Row summation in Matrixres = [sum(map(abs, (i + j for i, j in zip(x, y)))) for x, y in zip(test_list, test_list[1:])] # print resultprint("The row summation sublist : " + str(res)) The original list : [[3, 4, 5], [4, 6, 8], [1, 9, 2], [3, 7, 10]] The row summation sublist : [30, 30, 32] Python list-programs 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 ? 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 | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Dec, 2019" }, { "code": null, "e": 355, "s": 28, "text": "This particular article focuses on a problem that has utility in competitive as well as day-day programming. Sometimes, we need to get the sum between the like indices when compared with the next list. The sum between the like elements in that index is returned. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 715, "s": 355, "text": "Method #1 : Using sum() + abs() + zip() + list comprehensionThis particular problem can also be solved using the combination of the above 4 operations. Here zip function does the dual task of pairing the list and also pairing the like indices for sum, to be computed by abs function and then sum is found using sum function, all bounded by list comprehension." }, { "code": "# Python3 code to demonstrate# Consecutive Row summation in Matrix# using sum() + abs() + zip() + list comprehension # initializing list test_list = [[3, 4, 5], [4, 6, 8], [1, 9, 2], [3, 7, 10]] # printing original list print(\"The original list : \" + str(test_list)) # using sum() + abs() + zip() + list comprehension# Consecutive Row summation in Matrixres = [sum(abs(i + j) for i, j in zip(*ele)) for ele in zip(test_list, test_list[1:])] # print resultprint(\"The row summation sublist : \" + str(res))", "e": 1223, "s": 715, "text": null }, { "code": null, "e": 1331, "s": 1223, "text": "The original list : [[3, 4, 5], [4, 6, 8], [1, 9, 2], [3, 7, 10]]\nThe row summation sublist : [30, 30, 32]\n" }, { "code": null, "e": 1550, "s": 1333, "text": "Method #2 : Using sum() + map() + abs + zip()This task can also be achieved using the combination of above functions, the addition is map function that performs the task of binding of abs operation to the whole list." }, { "code": "# Python3 code to demonstrate# Consecutive Row summation in Matrix# using sum() + map() + abs + zip() # initializing list test_list = [[3, 4, 5], [4, 6, 8], [1, 9, 2], [3, 7, 10]] # printing original list print(\"The original list : \" + str(test_list)) # using sum() + map() + abs + zip()# Consecutive Row summation in Matrixres = [sum(map(abs, (i + j for i, j in zip(x, y)))) for x, y in zip(test_list, test_list[1:])] # print resultprint(\"The row summation sublist : \" + str(res))", "e": 2036, "s": 1550, "text": null }, { "code": null, "e": 2144, "s": 2036, "text": "The original list : [[3, 4, 5], [4, 6, 8], [1, 9, 2], [3, 7, 10]]\nThe row summation sublist : [30, 30, 32]\n" }, { "code": null, "e": 2165, "s": 2144, "text": "Python list-programs" }, { "code": null, "e": 2187, "s": 2165, "text": "Python matrix-program" }, { "code": null, "e": 2194, "s": 2187, "text": "Python" }, { "code": null, "e": 2210, "s": 2194, "text": "Python Programs" }, { "code": null, "e": 2308, "s": 2210, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2340, "s": 2308, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2367, "s": 2340, "text": "Python Classes and Objects" }, { "code": null, "e": 2388, "s": 2367, "text": "Python OOPs Concepts" }, { "code": null, "e": 2411, "s": 2388, "text": "Introduction To PYTHON" }, { "code": null, "e": 2467, "s": 2411, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2489, "s": 2467, "text": "Defaultdict in Python" }, { "code": null, "e": 2528, "s": 2489, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2566, "s": 2528, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2603, "s": 2566, "text": "Python Program for Fibonacci numbers" } ]
Number of children of given node in n-ary Tree
23 Jun, 2021 Given a node x, find the number of children of x(if it exists) in the given n-ary tree. Example : Input : x = 50 Output : 3 Explanation : 50 has 3 children having values 40, 100 and 20. Approach : Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Initialize the number of children as 0. For every node in the n-ary tree, check if its value is equal to x or not. If yes, then return the number of children. If the value of x is not equal to the current node then, push all the children of current node in the queue. Keep Repeating the above step until the queue becomes empty. Below is the implementation of the above idea : C++ Java Python3 C# Javascript // C++ program to find number// of children of given node#include <bits/stdc++.h>using namespace std; // Represents a node of an n-ary treeclass Node { public: int key; vector<Node*> child; Node(int data) { key = data; }}; // Function to calculate number// of children of given nodeint numberOfChildren(Node* root, int x){ // initialize the numChildren as 0 int numChildren = 0; if (root == NULL) return 0; // Creating a queue and pushing the root queue<Node*> q; q.push(root); while (!q.empty()) { int n = q.size(); // If this node has children while (n > 0) { // Dequeue an item from queue and // check if it is equal to x // If YES, then return number of children Node* p = q.front(); q.pop(); if (p->key == x) { numChildren = numChildren + p->child.size(); return numChildren; } // Enqueue all children of the dequeued item for (int i = 0; i < p->child.size(); i++) q.push(p->child[i]); n--; } } return numChildren;} // Driver programint main(){ // Creating a generic tree Node* root = new Node(20); (root->child).push_back(new Node(2)); (root->child).push_back(new Node(34)); (root->child).push_back(new Node(50)); (root->child).push_back(new Node(60)); (root->child).push_back(new Node(70)); (root->child[0]->child).push_back(new Node(15)); (root->child[0]->child).push_back(new Node(20)); (root->child[1]->child).push_back(new Node(30)); (root->child[2]->child).push_back(new Node(40)); (root->child[2]->child).push_back(new Node(100)); (root->child[2]->child).push_back(new Node(20)); (root->child[0]->child[1]->child).push_back(new Node(25)); (root->child[0]->child[1]->child).push_back(new Node(50)); // Node whose number of // children is to be calculated int x = 50; // Function calling cout << numberOfChildren(root, x) << endl; return 0;} // Java program to find number// of children of given nodeimport java.util.*; class GFG{ // Represents a node of an n-ary treestatic class Node{ int key; Vector<Node> child = new Vector<>(); Node(int data) { key = data; }}; // Function to calculate number// of children of given nodestatic int numberOfChildren(Node root, int x){ // initialize the numChildren as 0 int numChildren = 0; if (root == null) return 0; // Creating a queue and pushing the root Queue<Node> q = new LinkedList<Node>(); q.add(root); while (!q.isEmpty()) { int n = q.size(); // If this node has children while (n > 0) { // Dequeue an item from queue and // check if it is equal to x // If YES, then return number of children Node p = q.peek(); q.remove(); if (p.key == x) { numChildren = numChildren + p.child.size(); return numChildren; } // Enqueue all children of the dequeued item for (int i = 0; i < p.child.size(); i++) q.add(p.child.get(i)); n--; } } return numChildren;} // Driver Codepublic static void main(String[] args){ // Creating a generic tree Node root = new Node(20); (root.child).add(new Node(2)); (root.child).add(new Node(34)); (root.child).add(new Node(50)); (root.child).add(new Node(60)); (root.child).add(new Node(70)); (root.child.get(0).child).add(new Node(15)); (root.child.get(0).child).add(new Node(20)); (root.child.get(1).child).add(new Node(30)); (root.child.get(2).child).add(new Node(40)); (root.child.get(2).child).add(new Node(100)); (root.child.get(2).child).add(new Node(20)); (root.child.get(0).child.get(1).child).add(new Node(25)); (root.child.get(0).child.get(1).child).add(new Node(50)); // Node whose number of // children is to be calculated int x = 50; // Function calling System.out.println(numberOfChildren(root, x));}} // This code is contributed by 29AjayKumar # Python3 program to find number# of children of given node # Node of a linked listclass Node: def __init__(self, data = None): self.key = data self.child = [] # Function to calculate number# of children of given nodedef numberOfChildren( root, x): # initialize the numChildren as 0 numChildren = 0 if (root == None): return 0 # Creating a queue and appending the root q = [] q.append(root) while (len(q) > 0) : n = len(q) # If this node has children while (n > 0): # Dequeue an item from queue and # check if it is equal to x # If YES, then return number of children p = q[0] q.pop(0) if (p.key == x) : numChildren = numChildren + len(p.child) return numChildren i = 0 # Enqueue all children of the dequeued item while ( i < len(p.child)): q.append(p.child[i]) i = i + 1 n = n - 1 return numChildren # Driver program # Creating a generic treeroot = Node(20)(root.child).append(Node(2))(root.child).append(Node(34))(root.child).append(Node(50))(root.child).append(Node(60))(root.child).append(Node(70))(root.child[0].child).append(Node(15))(root.child[0].child).append(Node(20))(root.child[1].child).append(Node(30))(root.child[2].child).append(Node(40))(root.child[2].child).append(Node(100))(root.child[2].child).append(Node(20))(root.child[0].child[1].child).append(Node(25))(root.child[0].child[1].child).append(Node(50)) # Node whose number of# children is to be calculatedx = 50 # Function callingprint( numberOfChildren(root, x) ) # This code is contributed by Arnab Kundu // C# program to find number// of children of given nodeusing System;using System.Collections.Generic; class GFG{ // Represents a node of an n-ary treepublic class Node{ public int key; public List<Node> child = new List<Node>(); public Node(int data) { key = data; }}; // Function to calculate number// of children of given nodestatic int numberOfChildren(Node root, int x){ // initialize the numChildren as 0 int numChildren = 0; if (root == null) return 0; // Creating a queue and pushing the root Queue<Node> q = new Queue<Node>(); q.Enqueue(root); while (q.Count != 0) { int n = q.Count; // If this node has children while (n > 0) { // Dequeue an item from queue and // check if it is equal to x // If YES, then return number of children Node p = q.Peek(); q.Dequeue(); if (p.key == x) { numChildren = numChildren + p.child.Count; return numChildren; } // Enqueue all children of the dequeued item for (int i = 0; i < p.child.Count; i++) q.Enqueue(p.child[i]); n--; } } return numChildren;} // Driver Codepublic static void Main(String[] args){ // Creating a generic tree Node root = new Node(20); (root.child).Add(new Node(2)); (root.child).Add(new Node(34)); (root.child).Add(new Node(50)); (root.child).Add(new Node(60)); (root.child).Add(new Node(70)); (root.child[0].child).Add(new Node(15)); (root.child[0].child).Add(new Node(20)); (root.child[1].child).Add(new Node(30)); (root.child[2].child).Add(new Node(40)); (root.child[2].child).Add(new Node(100)); (root.child[2].child).Add(new Node(20)); (root.child[0].child[1].child).Add(new Node(25)); (root.child[0].child[1].child).Add(new Node(50)); // Node whose number of // children is to be calculated int x = 50; // Function calling Console.WriteLine(numberOfChildren(root, x));}} // This code is contributed by 29AjayKumar <script> // javascript program to find number// of children of given node // Represents a node of an n-ary treeclass Node{ constructor(data) { this.key = data; this.child = [] }}; // Function to calculate number// of children of given nodefunction numberOfChildren(root, x){ // initialize the numChildren as 0 var numChildren = 0; if (root == null) return 0; // Creating a queue and pushing the root var q = []; q.push(root); while (q.length != 0) { var n = q.length; // If this node has children while (n > 0) { // Dequeue an item from queue and // check if it is equal to x // If YES, then return number of children var p = q[0]; q.shift(); if (p.key == x) { numChildren = numChildren + p.child.length; return numChildren; } // push all children of the dequeued item for (var i = 0; i < p.child.length; i++) q.push(p.child[i]); n--; } } return numChildren;} // Driver Code// Creating a generic treevar root = new Node(20);(root.child).push(new Node(2));(root.child).push(new Node(34));(root.child).push(new Node(50));(root.child).push(new Node(60));(root.child).push(new Node(70));(root.child[0].child).push(new Node(15));(root.child[0].child).push(new Node(20));(root.child[1].child).push(new Node(30));(root.child[2].child).push(new Node(40));(root.child[2].child).push(new Node(100));(root.child[2].child).push(new Node(20));(root.child[0].child[1].child).push(new Node(25));(root.child[0].child[1].child).push(new Node(50)); // Node whose number of// children is to be calculatedvar x = 50; // Function callingdocument.write(numberOfChildren(root, x)); // This code is contributed by itsok.</script> 3 Time Complexity : O(N), where N is the number of nodes in tree. Auxiliary Space : O(N), where N is the number of nodes in tree. Number of children of given node in n-ary Tree | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersNumber of children of given node in n-ary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:35•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=TPTa3cm5YYc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> ?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk 29AjayKumar andrew1234 itsok n-ary-tree Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Print Right View of a Binary Tree BFS vs DFS for Binary Tree Introduction to Data Structures Introduction to Tree Data Structure A program to check if a binary tree is BST or not Binary Tree | Set 3 (Types of Binary Tree) Decision Tree Binary Tree | Set 2 (Properties) Iterative Preorder Traversal What is Data Structure: Types, Classifications and Applications
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2021" }, { "code": null, "e": 144, "s": 54, "text": "Given a node x, find the number of children of x(if it exists) in the given n-ary tree. " }, { "code": null, "e": 156, "s": 144, "text": "Example : " }, { "code": null, "e": 244, "s": 156, "text": "Input : x = 50\nOutput : 3\nExplanation : 50 has 3 children having values 40, 100 and 20." }, { "code": null, "e": 259, "s": 246, "text": "Approach : " }, { "code": null, "e": 268, "s": 259, "text": "Chapters" }, { "code": null, "e": 295, "s": 268, "text": "descriptions off, selected" }, { "code": null, "e": 345, "s": 295, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 368, "s": 345, "text": "captions off, selected" }, { "code": null, "e": 376, "s": 368, "text": "English" }, { "code": null, "e": 400, "s": 376, "text": "This is a modal window." }, { "code": null, "e": 469, "s": 400, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 491, "s": 469, "text": "End of dialog window." }, { "code": null, "e": 531, "s": 491, "text": "Initialize the number of children as 0." }, { "code": null, "e": 650, "s": 531, "text": "For every node in the n-ary tree, check if its value is equal to x or not. If yes, then return the number of children." }, { "code": null, "e": 759, "s": 650, "text": "If the value of x is not equal to the current node then, push all the children of current node in the queue." }, { "code": null, "e": 820, "s": 759, "text": "Keep Repeating the above step until the queue becomes empty." }, { "code": null, "e": 870, "s": 820, "text": "Below is the implementation of the above idea : " }, { "code": null, "e": 874, "s": 870, "text": "C++" }, { "code": null, "e": 879, "s": 874, "text": "Java" }, { "code": null, "e": 887, "s": 879, "text": "Python3" }, { "code": null, "e": 890, "s": 887, "text": "C#" }, { "code": null, "e": 901, "s": 890, "text": "Javascript" }, { "code": "// C++ program to find number// of children of given node#include <bits/stdc++.h>using namespace std; // Represents a node of an n-ary treeclass Node { public: int key; vector<Node*> child; Node(int data) { key = data; }}; // Function to calculate number// of children of given nodeint numberOfChildren(Node* root, int x){ // initialize the numChildren as 0 int numChildren = 0; if (root == NULL) return 0; // Creating a queue and pushing the root queue<Node*> q; q.push(root); while (!q.empty()) { int n = q.size(); // If this node has children while (n > 0) { // Dequeue an item from queue and // check if it is equal to x // If YES, then return number of children Node* p = q.front(); q.pop(); if (p->key == x) { numChildren = numChildren + p->child.size(); return numChildren; } // Enqueue all children of the dequeued item for (int i = 0; i < p->child.size(); i++) q.push(p->child[i]); n--; } } return numChildren;} // Driver programint main(){ // Creating a generic tree Node* root = new Node(20); (root->child).push_back(new Node(2)); (root->child).push_back(new Node(34)); (root->child).push_back(new Node(50)); (root->child).push_back(new Node(60)); (root->child).push_back(new Node(70)); (root->child[0]->child).push_back(new Node(15)); (root->child[0]->child).push_back(new Node(20)); (root->child[1]->child).push_back(new Node(30)); (root->child[2]->child).push_back(new Node(40)); (root->child[2]->child).push_back(new Node(100)); (root->child[2]->child).push_back(new Node(20)); (root->child[0]->child[1]->child).push_back(new Node(25)); (root->child[0]->child[1]->child).push_back(new Node(50)); // Node whose number of // children is to be calculated int x = 50; // Function calling cout << numberOfChildren(root, x) << endl; return 0;}", "e": 2966, "s": 901, "text": null }, { "code": "// Java program to find number// of children of given nodeimport java.util.*; class GFG{ // Represents a node of an n-ary treestatic class Node{ int key; Vector<Node> child = new Vector<>(); Node(int data) { key = data; }}; // Function to calculate number// of children of given nodestatic int numberOfChildren(Node root, int x){ // initialize the numChildren as 0 int numChildren = 0; if (root == null) return 0; // Creating a queue and pushing the root Queue<Node> q = new LinkedList<Node>(); q.add(root); while (!q.isEmpty()) { int n = q.size(); // If this node has children while (n > 0) { // Dequeue an item from queue and // check if it is equal to x // If YES, then return number of children Node p = q.peek(); q.remove(); if (p.key == x) { numChildren = numChildren + p.child.size(); return numChildren; } // Enqueue all children of the dequeued item for (int i = 0; i < p.child.size(); i++) q.add(p.child.get(i)); n--; } } return numChildren;} // Driver Codepublic static void main(String[] args){ // Creating a generic tree Node root = new Node(20); (root.child).add(new Node(2)); (root.child).add(new Node(34)); (root.child).add(new Node(50)); (root.child).add(new Node(60)); (root.child).add(new Node(70)); (root.child.get(0).child).add(new Node(15)); (root.child.get(0).child).add(new Node(20)); (root.child.get(1).child).add(new Node(30)); (root.child.get(2).child).add(new Node(40)); (root.child.get(2).child).add(new Node(100)); (root.child.get(2).child).add(new Node(20)); (root.child.get(0).child.get(1).child).add(new Node(25)); (root.child.get(0).child.get(1).child).add(new Node(50)); // Node whose number of // children is to be calculated int x = 50; // Function calling System.out.println(numberOfChildren(root, x));}} // This code is contributed by 29AjayKumar", "e": 5115, "s": 2966, "text": null }, { "code": "# Python3 program to find number# of children of given node # Node of a linked listclass Node: def __init__(self, data = None): self.key = data self.child = [] # Function to calculate number# of children of given nodedef numberOfChildren( root, x): # initialize the numChildren as 0 numChildren = 0 if (root == None): return 0 # Creating a queue and appending the root q = [] q.append(root) while (len(q) > 0) : n = len(q) # If this node has children while (n > 0): # Dequeue an item from queue and # check if it is equal to x # If YES, then return number of children p = q[0] q.pop(0) if (p.key == x) : numChildren = numChildren + len(p.child) return numChildren i = 0 # Enqueue all children of the dequeued item while ( i < len(p.child)): q.append(p.child[i]) i = i + 1 n = n - 1 return numChildren # Driver program # Creating a generic treeroot = Node(20)(root.child).append(Node(2))(root.child).append(Node(34))(root.child).append(Node(50))(root.child).append(Node(60))(root.child).append(Node(70))(root.child[0].child).append(Node(15))(root.child[0].child).append(Node(20))(root.child[1].child).append(Node(30))(root.child[2].child).append(Node(40))(root.child[2].child).append(Node(100))(root.child[2].child).append(Node(20))(root.child[0].child[1].child).append(Node(25))(root.child[0].child[1].child).append(Node(50)) # Node whose number of# children is to be calculatedx = 50 # Function callingprint( numberOfChildren(root, x) ) # This code is contributed by Arnab Kundu", "e": 6867, "s": 5115, "text": null }, { "code": "// C# program to find number// of children of given nodeusing System;using System.Collections.Generic; class GFG{ // Represents a node of an n-ary treepublic class Node{ public int key; public List<Node> child = new List<Node>(); public Node(int data) { key = data; }}; // Function to calculate number// of children of given nodestatic int numberOfChildren(Node root, int x){ // initialize the numChildren as 0 int numChildren = 0; if (root == null) return 0; // Creating a queue and pushing the root Queue<Node> q = new Queue<Node>(); q.Enqueue(root); while (q.Count != 0) { int n = q.Count; // If this node has children while (n > 0) { // Dequeue an item from queue and // check if it is equal to x // If YES, then return number of children Node p = q.Peek(); q.Dequeue(); if (p.key == x) { numChildren = numChildren + p.child.Count; return numChildren; } // Enqueue all children of the dequeued item for (int i = 0; i < p.child.Count; i++) q.Enqueue(p.child[i]); n--; } } return numChildren;} // Driver Codepublic static void Main(String[] args){ // Creating a generic tree Node root = new Node(20); (root.child).Add(new Node(2)); (root.child).Add(new Node(34)); (root.child).Add(new Node(50)); (root.child).Add(new Node(60)); (root.child).Add(new Node(70)); (root.child[0].child).Add(new Node(15)); (root.child[0].child).Add(new Node(20)); (root.child[1].child).Add(new Node(30)); (root.child[2].child).Add(new Node(40)); (root.child[2].child).Add(new Node(100)); (root.child[2].child).Add(new Node(20)); (root.child[0].child[1].child).Add(new Node(25)); (root.child[0].child[1].child).Add(new Node(50)); // Node whose number of // children is to be calculated int x = 50; // Function calling Console.WriteLine(numberOfChildren(root, x));}} // This code is contributed by 29AjayKumar", "e": 9022, "s": 6867, "text": null }, { "code": "<script> // javascript program to find number// of children of given node // Represents a node of an n-ary treeclass Node{ constructor(data) { this.key = data; this.child = [] }}; // Function to calculate number// of children of given nodefunction numberOfChildren(root, x){ // initialize the numChildren as 0 var numChildren = 0; if (root == null) return 0; // Creating a queue and pushing the root var q = []; q.push(root); while (q.length != 0) { var n = q.length; // If this node has children while (n > 0) { // Dequeue an item from queue and // check if it is equal to x // If YES, then return number of children var p = q[0]; q.shift(); if (p.key == x) { numChildren = numChildren + p.child.length; return numChildren; } // push all children of the dequeued item for (var i = 0; i < p.child.length; i++) q.push(p.child[i]); n--; } } return numChildren;} // Driver Code// Creating a generic treevar root = new Node(20);(root.child).push(new Node(2));(root.child).push(new Node(34));(root.child).push(new Node(50));(root.child).push(new Node(60));(root.child).push(new Node(70));(root.child[0].child).push(new Node(15));(root.child[0].child).push(new Node(20));(root.child[1].child).push(new Node(30));(root.child[2].child).push(new Node(40));(root.child[2].child).push(new Node(100));(root.child[2].child).push(new Node(20));(root.child[0].child[1].child).push(new Node(25));(root.child[0].child[1].child).push(new Node(50)); // Node whose number of// children is to be calculatedvar x = 50; // Function callingdocument.write(numberOfChildren(root, x)); // This code is contributed by itsok.</script>", "e": 10924, "s": 9022, "text": null }, { "code": null, "e": 10926, "s": 10924, "text": "3" }, { "code": null, "e": 11058, "s": 10928, "text": "Time Complexity : O(N), where N is the number of nodes in tree. Auxiliary Space : O(N), where N is the number of nodes in tree. " }, { "code": null, "e": 11968, "s": 11058, "text": "Number of children of given node in n-ary Tree | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersNumber of children of given node in n-ary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:35•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=TPTa3cm5YYc\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 12010, "s": 11968, "text": "?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk " }, { "code": null, "e": 12022, "s": 12010, "text": "29AjayKumar" }, { "code": null, "e": 12033, "s": 12022, "text": "andrew1234" }, { "code": null, "e": 12039, "s": 12033, "text": "itsok" }, { "code": null, "e": 12050, "s": 12039, "text": "n-ary-tree" }, { "code": null, "e": 12055, "s": 12050, "text": "Tree" }, { "code": null, "e": 12060, "s": 12055, "text": "Tree" }, { "code": null, "e": 12158, "s": 12060, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12192, "s": 12158, "text": "Print Right View of a Binary Tree" }, { "code": null, "e": 12219, "s": 12192, "text": "BFS vs DFS for Binary Tree" }, { "code": null, "e": 12251, "s": 12219, "text": "Introduction to Data Structures" }, { "code": null, "e": 12287, "s": 12251, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 12337, "s": 12287, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 12380, "s": 12337, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 12394, "s": 12380, "text": "Decision Tree" }, { "code": null, "e": 12427, "s": 12394, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 12456, "s": 12427, "text": "Iterative Preorder Traversal" } ]
How to convert a number into array in JavaScript ?
26 Jul, 2021 We have given a number and the task is to convert the given number into an array using JavaScript. Examples: Input: 235283 Output: [2, 3, 5, 2, 8, 3] Input: 8998123 Output: [8, 9, 9, 8, 1, 2, 3] Input: 1234567 Output: [1, 2, 3, 4, 5, 6, 7] In this article, we will use two different methods to convert the given number into an array. Method 1: Using Array.from() Method: The JavaScript Array from() method returns an Array object from any object with a length property or an iterable object. Syntax : Array.from(object, mapFunction, thisValue) Approach: Store a number in a variable.Use Array.from() method and in its first parameter enter the string type cast value.In the second parameter, we use a function i.e. myFunc, at every iteration the function will be called.The myFunc function will take a parameter that was returned by the iteration of Array.from() method. We typecast the number into a string so the type of parameter is a string, but we will typecast it into integer and return it.The value returned by the Array.from() is our result. Store a number in a variable. Use Array.from() method and in its first parameter enter the string type cast value. In the second parameter, we use a function i.e. myFunc, at every iteration the function will be called. The myFunc function will take a parameter that was returned by the iteration of Array.from() method. We typecast the number into a string so the type of parameter is a string, but we will typecast it into integer and return it. The value returned by the Array.from() is our result. Example: Javascript var myInt = 235345; // Getting the string as a parameter// and typecasting it into an integerlet myFunc = num => Number(num); var intArr = Array.from(String(myInt), myFunc); // Print the result arrayconsole.log(intArr); Output: [2, 3, 5, 3, 4, 5 ] Method 2: Using map() Method: The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method. Generally, map() method is used to iterate over an array and calling a function on every element of the array. Syntax: array.map(function(currentValue, index, arr), thisValue) Approach: Store the integer value in a variable.Typecast the integer into a string.Using the split() method to make it an array of strings.Iterate over that array using the map() method.Using the map() method returns the array of strings into an array of Integers. Store the integer value in a variable. Typecast the integer into a string. Using the split() method to make it an array of strings. Iterate over that array using the map() method. Using the map() method returns the array of strings into an array of Integers. Javascript // Declare a variable and store an// integer valuevar num = 235345 // Here we typecasting the num// Splitting the num, so that// we got an array of strings// Then use map function to// convert the array of strings// into array of numbers var myArr = String(num).split("").map((num)=>{ return Number(num)}) console.log(myArr) Output: [2, 3, 5, 3, 4, 5] 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. bunnyram19 javascript-array JavaScript Web Technologies Web technologies Questions 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 Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Jul, 2021" }, { "code": null, "e": 151, "s": 52, "text": "We have given a number and the task is to convert the given number into an array using JavaScript." }, { "code": null, "e": 161, "s": 151, "text": "Examples:" }, { "code": null, "e": 294, "s": 161, "text": "Input: 235283\nOutput: [2, 3, 5, 2, 8, 3]\n\nInput: 8998123\nOutput: [8, 9, 9, 8, 1, 2, 3]\n\nInput: 1234567\nOutput: [1, 2, 3, 4, 5, 6, 7]" }, { "code": null, "e": 388, "s": 294, "text": "In this article, we will use two different methods to convert the given number into an array." }, { "code": null, "e": 546, "s": 388, "text": "Method 1: Using Array.from() Method: The JavaScript Array from() method returns an Array object from any object with a length property or an iterable object." }, { "code": null, "e": 555, "s": 546, "text": "Syntax :" }, { "code": null, "e": 598, "s": 555, "text": "Array.from(object, mapFunction, thisValue)" }, { "code": null, "e": 608, "s": 598, "text": "Approach:" }, { "code": null, "e": 1105, "s": 608, "text": "Store a number in a variable.Use Array.from() method and in its first parameter enter the string type cast value.In the second parameter, we use a function i.e. myFunc, at every iteration the function will be called.The myFunc function will take a parameter that was returned by the iteration of Array.from() method. We typecast the number into a string so the type of parameter is a string, but we will typecast it into integer and return it.The value returned by the Array.from() is our result." }, { "code": null, "e": 1135, "s": 1105, "text": "Store a number in a variable." }, { "code": null, "e": 1220, "s": 1135, "text": "Use Array.from() method and in its first parameter enter the string type cast value." }, { "code": null, "e": 1324, "s": 1220, "text": "In the second parameter, we use a function i.e. myFunc, at every iteration the function will be called." }, { "code": null, "e": 1552, "s": 1324, "text": "The myFunc function will take a parameter that was returned by the iteration of Array.from() method. We typecast the number into a string so the type of parameter is a string, but we will typecast it into integer and return it." }, { "code": null, "e": 1606, "s": 1552, "text": "The value returned by the Array.from() is our result." }, { "code": null, "e": 1615, "s": 1606, "text": "Example:" }, { "code": null, "e": 1626, "s": 1615, "text": "Javascript" }, { "code": "var myInt = 235345; // Getting the string as a parameter// and typecasting it into an integerlet myFunc = num => Number(num); var intArr = Array.from(String(myInt), myFunc); // Print the result arrayconsole.log(intArr);", "e": 1849, "s": 1626, "text": null }, { "code": null, "e": 1857, "s": 1849, "text": "Output:" }, { "code": null, "e": 1877, "s": 1857, "text": "[2, 3, 5, 3, 4, 5 ]" }, { "code": null, "e": 2171, "s": 1877, "text": "Method 2: Using map() Method: The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method. Generally, map() method is used to iterate over an array and calling a function on every element of the array." }, { "code": null, "e": 2179, "s": 2171, "text": "Syntax:" }, { "code": null, "e": 2236, "s": 2179, "text": "array.map(function(currentValue, index, arr), thisValue)" }, { "code": null, "e": 2246, "s": 2236, "text": "Approach:" }, { "code": null, "e": 2501, "s": 2246, "text": "Store the integer value in a variable.Typecast the integer into a string.Using the split() method to make it an array of strings.Iterate over that array using the map() method.Using the map() method returns the array of strings into an array of Integers." }, { "code": null, "e": 2540, "s": 2501, "text": "Store the integer value in a variable." }, { "code": null, "e": 2576, "s": 2540, "text": "Typecast the integer into a string." }, { "code": null, "e": 2633, "s": 2576, "text": "Using the split() method to make it an array of strings." }, { "code": null, "e": 2681, "s": 2633, "text": "Iterate over that array using the map() method." }, { "code": null, "e": 2760, "s": 2681, "text": "Using the map() method returns the array of strings into an array of Integers." }, { "code": null, "e": 2771, "s": 2760, "text": "Javascript" }, { "code": "// Declare a variable and store an// integer valuevar num = 235345 // Here we typecasting the num// Splitting the num, so that// we got an array of strings// Then use map function to// convert the array of strings// into array of numbers var myArr = String(num).split(\"\").map((num)=>{ return Number(num)}) console.log(myArr)", "e": 3100, "s": 2771, "text": null }, { "code": null, "e": 3108, "s": 3100, "text": "Output:" }, { "code": null, "e": 3127, "s": 3108, "text": "[2, 3, 5, 3, 4, 5]" }, { "code": null, "e": 3346, "s": 3127, "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": 3357, "s": 3346, "text": "bunnyram19" }, { "code": null, "e": 3374, "s": 3357, "text": "javascript-array" }, { "code": null, "e": 3385, "s": 3374, "text": "JavaScript" }, { "code": null, "e": 3402, "s": 3385, "text": "Web Technologies" }, { "code": null, "e": 3429, "s": 3402, "text": "Web technologies Questions" }, { "code": null, "e": 3527, "s": 3429, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3588, "s": 3527, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3660, "s": 3588, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3700, "s": 3660, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3742, "s": 3700, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3783, "s": 3742, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3816, "s": 3783, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3878, "s": 3816, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3939, "s": 3878, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3989, "s": 3939, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python | Remove spaces from dictionary keys
18 Dec, 2018 In Python, dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written with curly brackets, and they have keys and values. It is used to hash a particular key. Let’s see how to remove spaces from dictionary keys in Python. Method #1:Using translate() function here we visit each key one by one and remove space with the none. Here translate function takes parameter 32, none where 32 is ASCII value of space ‘ ‘ and replaces it with none. # Python program to remove space from keys # creating a dictionary of type string Product_list = {'P 01' : 'DBMS', 'P 02' : 'OS', 'P 0 3 ': 'Soft Computing'} # removing spaces from keys# storing them in sam dictionaryProduct_list = { x.translate({32:None}) : y for x, y in Product_list.items()} # printing new dictionaryprint (" New dictionary : ", Product_list) New dictionary : {'P01': 'DBMS', 'P03': 'Soft Computing', 'P02': 'OS'} Method #2:Using replace() function. In this method, we visit each key in dictionary one by one and replace all spaces in key with no space. This function takes as argument space and second non-space. # Python program to remove space from keys # creating a dictionary of type string Product_list = {'P 01' : 'DBMS', 'P 02' : 'OS', 'P 0 3 ': 'Soft Computing'}; # removing spaces from keys# storing them in sam dictionaryProduct_list = {x.replace(' ', ''): v for x, v in Product_list.items()} # printing new dictionaryprint (" New dictionary : ", Product_list) New dictionary : {'P03': 'Soft Computing', 'P01': 'DBMS', 'P02': 'OS'} Picked Python dictionary-programs python-dict Python Python Programs python-dict 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": "\n18 Dec, 2018" }, { "code": null, "e": 224, "s": 28, "text": "In Python, dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written with curly brackets, and they have keys and values. It is used to hash a particular key." }, { "code": null, "e": 287, "s": 224, "text": "Let’s see how to remove spaces from dictionary keys in Python." }, { "code": null, "e": 503, "s": 287, "text": "Method #1:Using translate() function here we visit each key one by one and remove space with the none. Here translate function takes parameter 32, none where 32 is ASCII value of space ‘ ‘ and replaces it with none." }, { "code": "# Python program to remove space from keys # creating a dictionary of type string Product_list = {'P 01' : 'DBMS', 'P 02' : 'OS', 'P 0 3 ': 'Soft Computing'} # removing spaces from keys# storing them in sam dictionaryProduct_list = { x.translate({32:None}) : y for x, y in Product_list.items()} # printing new dictionaryprint (\" New dictionary : \", Product_list)", "e": 902, "s": 503, "text": null }, { "code": null, "e": 975, "s": 902, "text": "New dictionary : {'P01': 'DBMS', 'P03': 'Soft Computing', 'P02': 'OS'}\n" }, { "code": null, "e": 1176, "s": 975, "text": " Method #2:Using replace() function. In this method, we visit each key in dictionary one by one and replace all spaces in key with no space. This function takes as argument space and second non-space." }, { "code": "# Python program to remove space from keys # creating a dictionary of type string Product_list = {'P 01' : 'DBMS', 'P 02' : 'OS', 'P 0 3 ': 'Soft Computing'}; # removing spaces from keys# storing them in sam dictionaryProduct_list = {x.replace(' ', ''): v for x, v in Product_list.items()} # printing new dictionaryprint (\" New dictionary : \", Product_list)", "e": 1558, "s": 1176, "text": null }, { "code": null, "e": 1631, "s": 1558, "text": "New dictionary : {'P03': 'Soft Computing', 'P01': 'DBMS', 'P02': 'OS'}\n" }, { "code": null, "e": 1638, "s": 1631, "text": "Picked" }, { "code": null, "e": 1665, "s": 1638, "text": "Python dictionary-programs" }, { "code": null, "e": 1677, "s": 1665, "text": "python-dict" }, { "code": null, "e": 1684, "s": 1677, "text": "Python" }, { "code": null, "e": 1700, "s": 1684, "text": "Python Programs" }, { "code": null, "e": 1712, "s": 1700, "text": "python-dict" }, { "code": null, "e": 1810, "s": 1712, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1842, "s": 1810, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1869, "s": 1842, "text": "Python Classes and Objects" }, { "code": null, "e": 1890, "s": 1869, "text": "Python OOPs Concepts" }, { "code": null, "e": 1913, "s": 1890, "text": "Introduction To PYTHON" }, { "code": null, "e": 1969, "s": 1913, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1991, "s": 1969, "text": "Defaultdict in Python" }, { "code": null, "e": 2030, "s": 1991, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2068, "s": 2030, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2105, "s": 2068, "text": "Python Program for Fibonacci numbers" } ]
Numbers with sum of digits equal to the sum of digits of its all prime factor
13 Jun, 2022 Given a range, the task is to find the count of the numbers in the given range such that the sum of its digit is equal to the sum of all its prime factors digits sum.Examples: Input: l = 2, r = 10 Output: 5 2, 3, 4, 5 and 7 are such numbers Input: l = 15, r = 22 Output: 3 17, 19 and 22 are such numbers As, 17 and 19 are already prime. Prime Factors of 22 = 2 * 11 i.e For 22, Sum of digits is 2+2 = 4 For 2 * 11, Sum of digits is 2 + 1 + 1 = 4 Approach: An efficient solution is to modify Sieve of Eratosthenes such that for each non-prime number it stores smallest prime factor(prefactor). Preprocess to find the smallest prime factor for all the numbers between 2 and MAXN. This can be done by breaking up the number into its prime factors in constant time because for each number if it is a prime, it has no prefactor.Otherwise, we can break it up to into a prime factor and the other part of the number which may or may not be prime.And repeat this process of extracting factors till it becomes a prime.Then check if the digits of that number is equal to the digits of prime factors by adding the digits of smallest prime factor i.e Preprocess to find the smallest prime factor for all the numbers between 2 and MAXN. This can be done by breaking up the number into its prime factors in constant time because for each number if it is a prime, it has no prefactor. Otherwise, we can break it up to into a prime factor and the other part of the number which may or may not be prime. And repeat this process of extracting factors till it becomes a prime. Then check if the digits of that number is equal to the digits of prime factors by adding the digits of smallest prime factor i.e Digits_Sum of SPF[n] + Digits_Sum of (n / SPF[n]) Now make prefix sum array that counts how many valid numbers are there up to a number N. For each query, print: Now make prefix sum array that counts how many valid numbers are there up to a number N. For each query, print: ans[R] – ans[L-1] Below is the implementation of above approach: C++ Java Python 3 C# Javascript // C++ program to Find the count of the numbers// in the given range such that the sum of its// digit is equal to the sum of all its prime// factors digits sum.#include <bits/stdc++.h>using namespace std; // maximum size of number#define MAXN 100005 // array to store smallest prime factor of numberint spf[MAXN] = { 0 }; // array to store sum of digits of a numberint sum_digits[MAXN] = { 0 }; // boolean array to check given number is countable// for required answer or not.bool isValid[MAXN] = { 0 }; // prefix array to store answerint ans[MAXN] = { 0 }; // Calculating SPF (Smallest Prime Factor) for every// number till MAXN.void Smallest_prime_factor(){ // marking smallest prime factor for every // number to be itself. for (int i = 1; i < MAXN; i++) spf[i] = i; // separately marking spf for every even // number as 2 for (int i = 4; i < MAXN; i += 2) spf[i] = 2; for (int i = 3; i * i <= MAXN; i += 2) // checking if i is prime if (spf[i] == i) // marking SPF for all numbers divisible by i for (int j = i * i; j < MAXN; j += i) // marking spf[j] if it is not // previously marked if (spf[j] == j) spf[j] = i;} // Function to find sum of digits in a numberint Digit_Sum(int copy){ int d = 0; while (copy) { d += copy % 10; copy /= 10; } return d;} // find sum of digits of all numbers up to MAXNvoid Sum_Of_All_Digits(){ for (int n = 2; n < MAXN; n++) { // add sum of digits of least // prime factor and n/spf[n] sum_digits[n] = sum_digits[n / spf[n]] + Digit_Sum(spf[n]); // if it is valid make isValid true if (Digit_Sum(n) == sum_digits[n]) isValid[n] = true; } // prefix sum to compute answer for (int n = 2; n < MAXN; n++) { if (isValid[n]) ans[n] = 1; ans[n] += ans[n - 1]; }} // Driver codeint main(){ Smallest_prime_factor(); Sum_Of_All_Digits(); // decleartion int l, r; // print answer for required range l = 2, r = 3; cout << "Valid numbers in the range " << l << " " << r << " are " << ans[r] - ans[l - 1] << endl; // print answer for required range l = 2, r = 10; cout << "Valid numbers in the range " << l << " " << r << " are " << ans[r] - ans[l - 1] << endl; return 0;} // Java program to Find the count// of the numbers in the given// range such that the sum of its// digit is equal to the sum of// all its prime factors digits sum.import java.io.*; class GFG{ // maximum size of numberstatic int MAXN = 100005; // array to store smallest// prime factor of numberstatic int spf[] = new int[MAXN]; // array to store sum// of digits of a numberstatic int sum_digits[] = new int[MAXN]; // boolean array to check// given number is countable// for required answer or not.static boolean isValid[] = new boolean[MAXN]; // prefix array to store answerstatic int ans[] = new int[MAXN]; // Calculating SPF (Smallest// Prime Factor) for every// number till MAXN.static void Smallest_prime_factor(){ // marking smallest prime factor // for every number to be itself. for (int i = 1; i < MAXN; i++) spf[i] = i; // separately marking spf // for every even number as 2 for (int i = 4; i < MAXN; i += 2) spf[i] = 2; for (int i = 3; i * i <= MAXN; i += 2) // checking if i is prime if (spf[i] == i) // marking SPF for all // numbers divisible by i for (int j = i * i; j < MAXN; j += i) // marking spf[j] if it // is not previously marked if (spf[j] == j) spf[j] = i;} // Function to find sum// of digits in a numberstatic int Digit_Sum(int copy){ int d = 0; while (copy > 0) { d += copy % 10; copy /= 10; } return d;} // find sum of digits of// all numbers up to MAXNstatic void Sum_Of_All_Digits(){ for (int n = 2; n < MAXN; n++) { // add sum of digits of least // prime factor and n/spf[n] sum_digits[n] = sum_digits[n / spf[n]] + Digit_Sum(spf[n]); // if it is valid make isValid true if (Digit_Sum(n) == sum_digits[n]) isValid[n] = true; } // prefix sum to compute answer for (int n = 2; n < MAXN; n++) { if (isValid[n]) ans[n] = 1; ans[n] += ans[n - 1]; }} // Driver codepublic static void main (String[] args){ Smallest_prime_factor(); Sum_Of_All_Digits(); // declaration int l, r; // print answer for required range l = 2; r = 3; System.out.println("Valid numbers in the range " + l + " " + r + " are " + (ans[r] - ans[l - 1] )); // print answer for required range l = 2; r = 10; System.out.println("Valid numbers in the range " + l + " " + r + " are " + (ans[r] - ans[l - 1]));}} // This code is contributed// by Inder # Python 3 program to Find the count of# the numbers in the given range such# that the sum of its digit is equal to# the sum of all its prime factors digits sum. # maximum size of numberMAXN = 100005 # array to store smallest prime# factor of numberspf = [0] * MAXN # array to store sum of digits of a numbersum_digits = [0] * MAXN # boolean array to check given number# is countable for required answer or not.isValid = [0] * MAXN # prefix array to store answerans = [0]*MAXN # Calculating SPF (Smallest Prime Factor)# for every number till MAXN.def Smallest_prime_factor(): # marking smallest prime factor # for every number to be itself. for i in range(1, MAXN): spf[i] = i # separately marking spf for # every even number as 2 for i in range(4, MAXN, 2): spf[i] = 2 i = 3 while i * i <= MAXN: # checking if i is prime if (spf[i] == i): # marking SPF for all numbers # divisible by i for j in range(i * i, MAXN, i): # marking spf[j] if it is not # previously marked if (spf[j] == j): spf[j] = i i += 2 # Function to find sum of digits# in a numberdef Digit_Sum(copy): d = 0 while (copy) : d += copy % 10 copy //= 10 return d # find sum of digits of all# numbers up to MAXNdef Sum_Of_All_Digits(): for n in range(2, MAXN) : # add sum of digits of least # prime factor and n/spf[n] sum_digits[n] = (sum_digits[n // spf[n]] + Digit_Sum(spf[n])) # if it is valid make isValid true if (Digit_Sum(n) == sum_digits[n]): isValid[n] = True # prefix sum to compute answer for n in range(2, MAXN) : if (isValid[n]): ans[n] = 1 ans[n] += ans[n - 1] # Driver codeif __name__ == "__main__": Smallest_prime_factor() Sum_Of_All_Digits() # print answer for required range l = 2 r = 3 print("Valid numbers in the range", l, r, "are", ans[r] - ans[l - 1]) # print answer for required range l = 2 r = 10 print("Valid numbers in the range", l, r, "are", ans[r] - ans[l - 1]) # This code is contributed by ita_c // C# program to Find the count// of the numbers in the given// range such that the sum of its// digit is equal to the sum of// all its prime factors digits sum.using System; class GFG{ // maximum size of numberstatic int MAXN = 100005; // array to store smallest// prime factor of numberstatic int []spf = new int[MAXN]; // array to store sum// of digits of a numberstatic int []sum_digits = new int[MAXN]; // boolean array to check// given number is countable// for required answer or not.static bool []isValid = new bool[MAXN]; // prefix array to store answerstatic int []ans = new int[MAXN]; // Calculating SPF (Smallest// Prime Factor) for every// number till MAXN.static void Smallest_prime_factor(){ // marking smallest prime factor // for every number to be itself. for (int i = 1; i < MAXN; i++) spf[i] = i; // separately marking spf // for every even number as 2 for (int i = 4; i < MAXN; i += 2) spf[i] = 2; for (int i = 3; i * i <= MAXN; i += 2) // checking if i is prime if (spf[i] == i) // marking SPF for all // numbers divisible by i for (int j = i * i; j < MAXN; j += i) // marking spf[j] if it // is not previously marked if (spf[j] == j) spf[j] = i;} // Function to find sum// of digits in a numberstatic int Digit_Sum(int copy){ int d = 0; while (copy > 0) { d += copy % 10; copy /= 10; } return d;} // find sum of digits of// all numbers up to MAXNstatic void Sum_Of_All_Digits(){ for (int n = 2; n < MAXN; n++) { // add sum of digits of least // prime factor and n/spf[n] sum_digits[n] = sum_digits[n / spf[n]] + Digit_Sum(spf[n]); // if it is valid make // isValid true if (Digit_Sum(n) == sum_digits[n]) isValid[n] = true; } // prefix sum to compute answer for (int n = 2; n < MAXN; n++) { if (isValid[n]) ans[n] = 1; ans[n] += ans[n - 1]; }} // Driver codepublic static void Main (){ Smallest_prime_factor(); Sum_Of_All_Digits(); // declaration int l, r; // print answer for required range l = 2; r = 3; Console.WriteLine("Valid numbers in the range " + l + " " + r + " are " + (ans[r] - ans[l - 1] )); // print answer for required range l = 2; r = 10; Console.WriteLine("Valid numbers in the range " + l + " " + r + " are " + (ans[r] - ans[l - 1]));}} // This code is contributed// by Subhadeep <script> // Javascript program to Find the count// of the numbers in the given// range such that the sum of its// digit is equal to the sum of// all its prime factors digits sum. // maximum size of numbervar MAXN = 100005; // array to store smallest// prime factor of numbervar spf = Array.from({length: MAXN}, (_, i) => 0); // array to store sum// of digits of a numbervar sum_digits = Array.from({length: MAXN}, (_, i) => 0); // boolean array to check// given number is countable// for required answer or not.var isValid = Array.from({length: MAXN}, (_, i) => false); // prefix array to store answervar ans = Array.from({length: MAXN}, (_, i) => 0); // Calculating SPF (Smallest// Prime Factor) for every// number till MAXN.function Smallest_prime_factor(){ // marking smallest prime factor // for every number to be itself. for (i = 1; i < MAXN; i++) spf[i] = i; // separately marking spf // for every even number as 2 for (i = 4; i < MAXN; i += 2) spf[i] = 2; for (i = 3; i * i <= MAXN; i += 2) // checking if i is prime if (spf[i] == i) // marking SPF for all // numbers divisible by i for (j = i * i; j < MAXN; j += i) // marking spf[j] if it // is not previously marked if (spf[j] == j) spf[j] = i;} // Function to find sum// of digits in a numberfunction Digit_Sum(copy){ var d = 0; while (copy > 0) { d += copy % 10; copy = parseInt(copy/10); } return d;} // find sum of digits of// all numbers up to MAXNfunction Sum_Of_All_Digits(){ for (n = 2; n < MAXN; n++) { // add sum of digits of least // prime factor and n/spf[n] sum_digits[n] = sum_digits[parseInt(n / spf[n])] + Digit_Sum(spf[n]); // if it is valid make isValid true if (Digit_Sum(n) == sum_digits[n]) isValid[n] = true; } // prefix sum to compute answer for (n = 2; n < MAXN; n++) { if (isValid[n]) ans[n] = 1; ans[n] += ans[n - 1]; }} // Driver codeSmallest_prime_factor();Sum_Of_All_Digits(); // declarationvar l, r; // print answer for required rangel = 2; r = 3;document.write("Valid numbers in the range " + l + " " + r + " are " + (ans[r] - ans[l - 1] )); // print answer for required rangel = 2; r = 10;document.write("<br>Valid numbers in the range " + l + " " + r + " are " + (ans[r] - ans[l - 1])); // This code contributed by shikhasingrajput </script> Valid numbers in the range 2 3 are 2 Valid numbers in the range 2 10 are 5 inderDuMCA tufan_gupta2000 ukasp shikhasingrajput kothavvsaakash number-digits prime-factor Hash Mathematical Hash Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Hashing | A Complete Tutorial Find k numbers with most occurrences in the given array Real-time application of Data Structures Non-Repeating Element Find the length of largest subarray with 0 sum Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jun, 2022" }, { "code": null, "e": 206, "s": 28, "text": "Given a range, the task is to find the count of the numbers in the given range such that the sum of its digit is equal to the sum of all its prime factors digits sum.Examples: " }, { "code": null, "e": 478, "s": 206, "text": "Input: l = 2, r = 10\nOutput: 5\n2, 3, 4, 5 and 7 are such numbers\n\nInput: l = 15, r = 22\nOutput: 3\n17, 19 and 22 are such numbers\nAs, 17 and 19 are already prime.\nPrime Factors of 22 = 2 * 11 i.e \nFor 22, Sum of digits is 2+2 = 4\nFor 2 * 11, Sum of digits is 2 + 1 + 1 = 4" }, { "code": null, "e": 629, "s": 480, "text": "Approach: An efficient solution is to modify Sieve of Eratosthenes such that for each non-prime number it stores smallest prime factor(prefactor). " }, { "code": null, "e": 1175, "s": 629, "text": "Preprocess to find the smallest prime factor for all the numbers between 2 and MAXN. This can be done by breaking up the number into its prime factors in constant time because for each number if it is a prime, it has no prefactor.Otherwise, we can break it up to into a prime factor and the other part of the number which may or may not be prime.And repeat this process of extracting factors till it becomes a prime.Then check if the digits of that number is equal to the digits of prime factors by adding the digits of smallest prime factor i.e" }, { "code": null, "e": 1406, "s": 1175, "text": "Preprocess to find the smallest prime factor for all the numbers between 2 and MAXN. This can be done by breaking up the number into its prime factors in constant time because for each number if it is a prime, it has no prefactor." }, { "code": null, "e": 1523, "s": 1406, "text": "Otherwise, we can break it up to into a prime factor and the other part of the number which may or may not be prime." }, { "code": null, "e": 1594, "s": 1523, "text": "And repeat this process of extracting factors till it becomes a prime." }, { "code": null, "e": 1724, "s": 1594, "text": "Then check if the digits of that number is equal to the digits of prime factors by adding the digits of smallest prime factor i.e" }, { "code": null, "e": 1774, "s": 1724, "text": "Digits_Sum of SPF[n] + Digits_Sum of (n / SPF[n])" }, { "code": null, "e": 1886, "s": 1774, "text": "Now make prefix sum array that counts how many valid numbers are there up to a number N. For each query, print:" }, { "code": null, "e": 1998, "s": 1886, "text": "Now make prefix sum array that counts how many valid numbers are there up to a number N. For each query, print:" }, { "code": null, "e": 2016, "s": 1998, "text": "ans[R] – ans[L-1]" }, { "code": null, "e": 2065, "s": 2016, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 2069, "s": 2065, "text": "C++" }, { "code": null, "e": 2074, "s": 2069, "text": "Java" }, { "code": null, "e": 2083, "s": 2074, "text": "Python 3" }, { "code": null, "e": 2086, "s": 2083, "text": "C#" }, { "code": null, "e": 2097, "s": 2086, "text": "Javascript" }, { "code": "// C++ program to Find the count of the numbers// in the given range such that the sum of its// digit is equal to the sum of all its prime// factors digits sum.#include <bits/stdc++.h>using namespace std; // maximum size of number#define MAXN 100005 // array to store smallest prime factor of numberint spf[MAXN] = { 0 }; // array to store sum of digits of a numberint sum_digits[MAXN] = { 0 }; // boolean array to check given number is countable// for required answer or not.bool isValid[MAXN] = { 0 }; // prefix array to store answerint ans[MAXN] = { 0 }; // Calculating SPF (Smallest Prime Factor) for every// number till MAXN.void Smallest_prime_factor(){ // marking smallest prime factor for every // number to be itself. for (int i = 1; i < MAXN; i++) spf[i] = i; // separately marking spf for every even // number as 2 for (int i = 4; i < MAXN; i += 2) spf[i] = 2; for (int i = 3; i * i <= MAXN; i += 2) // checking if i is prime if (spf[i] == i) // marking SPF for all numbers divisible by i for (int j = i * i; j < MAXN; j += i) // marking spf[j] if it is not // previously marked if (spf[j] == j) spf[j] = i;} // Function to find sum of digits in a numberint Digit_Sum(int copy){ int d = 0; while (copy) { d += copy % 10; copy /= 10; } return d;} // find sum of digits of all numbers up to MAXNvoid Sum_Of_All_Digits(){ for (int n = 2; n < MAXN; n++) { // add sum of digits of least // prime factor and n/spf[n] sum_digits[n] = sum_digits[n / spf[n]] + Digit_Sum(spf[n]); // if it is valid make isValid true if (Digit_Sum(n) == sum_digits[n]) isValid[n] = true; } // prefix sum to compute answer for (int n = 2; n < MAXN; n++) { if (isValid[n]) ans[n] = 1; ans[n] += ans[n - 1]; }} // Driver codeint main(){ Smallest_prime_factor(); Sum_Of_All_Digits(); // decleartion int l, r; // print answer for required range l = 2, r = 3; cout << \"Valid numbers in the range \" << l << \" \" << r << \" are \" << ans[r] - ans[l - 1] << endl; // print answer for required range l = 2, r = 10; cout << \"Valid numbers in the range \" << l << \" \" << r << \" are \" << ans[r] - ans[l - 1] << endl; return 0;}", "e": 4524, "s": 2097, "text": null }, { "code": "// Java program to Find the count// of the numbers in the given// range such that the sum of its// digit is equal to the sum of// all its prime factors digits sum.import java.io.*; class GFG{ // maximum size of numberstatic int MAXN = 100005; // array to store smallest// prime factor of numberstatic int spf[] = new int[MAXN]; // array to store sum// of digits of a numberstatic int sum_digits[] = new int[MAXN]; // boolean array to check// given number is countable// for required answer or not.static boolean isValid[] = new boolean[MAXN]; // prefix array to store answerstatic int ans[] = new int[MAXN]; // Calculating SPF (Smallest// Prime Factor) for every// number till MAXN.static void Smallest_prime_factor(){ // marking smallest prime factor // for every number to be itself. for (int i = 1; i < MAXN; i++) spf[i] = i; // separately marking spf // for every even number as 2 for (int i = 4; i < MAXN; i += 2) spf[i] = 2; for (int i = 3; i * i <= MAXN; i += 2) // checking if i is prime if (spf[i] == i) // marking SPF for all // numbers divisible by i for (int j = i * i; j < MAXN; j += i) // marking spf[j] if it // is not previously marked if (spf[j] == j) spf[j] = i;} // Function to find sum// of digits in a numberstatic int Digit_Sum(int copy){ int d = 0; while (copy > 0) { d += copy % 10; copy /= 10; } return d;} // find sum of digits of// all numbers up to MAXNstatic void Sum_Of_All_Digits(){ for (int n = 2; n < MAXN; n++) { // add sum of digits of least // prime factor and n/spf[n] sum_digits[n] = sum_digits[n / spf[n]] + Digit_Sum(spf[n]); // if it is valid make isValid true if (Digit_Sum(n) == sum_digits[n]) isValid[n] = true; } // prefix sum to compute answer for (int n = 2; n < MAXN; n++) { if (isValid[n]) ans[n] = 1; ans[n] += ans[n - 1]; }} // Driver codepublic static void main (String[] args){ Smallest_prime_factor(); Sum_Of_All_Digits(); // declaration int l, r; // print answer for required range l = 2; r = 3; System.out.println(\"Valid numbers in the range \" + l + \" \" + r + \" are \" + (ans[r] - ans[l - 1] )); // print answer for required range l = 2; r = 10; System.out.println(\"Valid numbers in the range \" + l + \" \" + r + \" are \" + (ans[r] - ans[l - 1]));}} // This code is contributed// by Inder", "e": 7261, "s": 4524, "text": null }, { "code": "# Python 3 program to Find the count of# the numbers in the given range such# that the sum of its digit is equal to# the sum of all its prime factors digits sum. # maximum size of numberMAXN = 100005 # array to store smallest prime# factor of numberspf = [0] * MAXN # array to store sum of digits of a numbersum_digits = [0] * MAXN # boolean array to check given number# is countable for required answer or not.isValid = [0] * MAXN # prefix array to store answerans = [0]*MAXN # Calculating SPF (Smallest Prime Factor)# for every number till MAXN.def Smallest_prime_factor(): # marking smallest prime factor # for every number to be itself. for i in range(1, MAXN): spf[i] = i # separately marking spf for # every even number as 2 for i in range(4, MAXN, 2): spf[i] = 2 i = 3 while i * i <= MAXN: # checking if i is prime if (spf[i] == i): # marking SPF for all numbers # divisible by i for j in range(i * i, MAXN, i): # marking spf[j] if it is not # previously marked if (spf[j] == j): spf[j] = i i += 2 # Function to find sum of digits# in a numberdef Digit_Sum(copy): d = 0 while (copy) : d += copy % 10 copy //= 10 return d # find sum of digits of all# numbers up to MAXNdef Sum_Of_All_Digits(): for n in range(2, MAXN) : # add sum of digits of least # prime factor and n/spf[n] sum_digits[n] = (sum_digits[n // spf[n]] + Digit_Sum(spf[n])) # if it is valid make isValid true if (Digit_Sum(n) == sum_digits[n]): isValid[n] = True # prefix sum to compute answer for n in range(2, MAXN) : if (isValid[n]): ans[n] = 1 ans[n] += ans[n - 1] # Driver codeif __name__ == \"__main__\": Smallest_prime_factor() Sum_Of_All_Digits() # print answer for required range l = 2 r = 3 print(\"Valid numbers in the range\", l, r, \"are\", ans[r] - ans[l - 1]) # print answer for required range l = 2 r = 10 print(\"Valid numbers in the range\", l, r, \"are\", ans[r] - ans[l - 1]) # This code is contributed by ita_c", "e": 9553, "s": 7261, "text": null }, { "code": "// C# program to Find the count// of the numbers in the given// range such that the sum of its// digit is equal to the sum of// all its prime factors digits sum.using System; class GFG{ // maximum size of numberstatic int MAXN = 100005; // array to store smallest// prime factor of numberstatic int []spf = new int[MAXN]; // array to store sum// of digits of a numberstatic int []sum_digits = new int[MAXN]; // boolean array to check// given number is countable// for required answer or not.static bool []isValid = new bool[MAXN]; // prefix array to store answerstatic int []ans = new int[MAXN]; // Calculating SPF (Smallest// Prime Factor) for every// number till MAXN.static void Smallest_prime_factor(){ // marking smallest prime factor // for every number to be itself. for (int i = 1; i < MAXN; i++) spf[i] = i; // separately marking spf // for every even number as 2 for (int i = 4; i < MAXN; i += 2) spf[i] = 2; for (int i = 3; i * i <= MAXN; i += 2) // checking if i is prime if (spf[i] == i) // marking SPF for all // numbers divisible by i for (int j = i * i; j < MAXN; j += i) // marking spf[j] if it // is not previously marked if (spf[j] == j) spf[j] = i;} // Function to find sum// of digits in a numberstatic int Digit_Sum(int copy){ int d = 0; while (copy > 0) { d += copy % 10; copy /= 10; } return d;} // find sum of digits of// all numbers up to MAXNstatic void Sum_Of_All_Digits(){ for (int n = 2; n < MAXN; n++) { // add sum of digits of least // prime factor and n/spf[n] sum_digits[n] = sum_digits[n / spf[n]] + Digit_Sum(spf[n]); // if it is valid make // isValid true if (Digit_Sum(n) == sum_digits[n]) isValid[n] = true; } // prefix sum to compute answer for (int n = 2; n < MAXN; n++) { if (isValid[n]) ans[n] = 1; ans[n] += ans[n - 1]; }} // Driver codepublic static void Main (){ Smallest_prime_factor(); Sum_Of_All_Digits(); // declaration int l, r; // print answer for required range l = 2; r = 3; Console.WriteLine(\"Valid numbers in the range \" + l + \" \" + r + \" are \" + (ans[r] - ans[l - 1] )); // print answer for required range l = 2; r = 10; Console.WriteLine(\"Valid numbers in the range \" + l + \" \" + r + \" are \" + (ans[r] - ans[l - 1]));}} // This code is contributed// by Subhadeep", "e": 12277, "s": 9553, "text": null }, { "code": "<script> // Javascript program to Find the count// of the numbers in the given// range such that the sum of its// digit is equal to the sum of// all its prime factors digits sum. // maximum size of numbervar MAXN = 100005; // array to store smallest// prime factor of numbervar spf = Array.from({length: MAXN}, (_, i) => 0); // array to store sum// of digits of a numbervar sum_digits = Array.from({length: MAXN}, (_, i) => 0); // boolean array to check// given number is countable// for required answer or not.var isValid = Array.from({length: MAXN}, (_, i) => false); // prefix array to store answervar ans = Array.from({length: MAXN}, (_, i) => 0); // Calculating SPF (Smallest// Prime Factor) for every// number till MAXN.function Smallest_prime_factor(){ // marking smallest prime factor // for every number to be itself. for (i = 1; i < MAXN; i++) spf[i] = i; // separately marking spf // for every even number as 2 for (i = 4; i < MAXN; i += 2) spf[i] = 2; for (i = 3; i * i <= MAXN; i += 2) // checking if i is prime if (spf[i] == i) // marking SPF for all // numbers divisible by i for (j = i * i; j < MAXN; j += i) // marking spf[j] if it // is not previously marked if (spf[j] == j) spf[j] = i;} // Function to find sum// of digits in a numberfunction Digit_Sum(copy){ var d = 0; while (copy > 0) { d += copy % 10; copy = parseInt(copy/10); } return d;} // find sum of digits of// all numbers up to MAXNfunction Sum_Of_All_Digits(){ for (n = 2; n < MAXN; n++) { // add sum of digits of least // prime factor and n/spf[n] sum_digits[n] = sum_digits[parseInt(n / spf[n])] + Digit_Sum(spf[n]); // if it is valid make isValid true if (Digit_Sum(n) == sum_digits[n]) isValid[n] = true; } // prefix sum to compute answer for (n = 2; n < MAXN; n++) { if (isValid[n]) ans[n] = 1; ans[n] += ans[n - 1]; }} // Driver codeSmallest_prime_factor();Sum_Of_All_Digits(); // declarationvar l, r; // print answer for required rangel = 2; r = 3;document.write(\"Valid numbers in the range \" + l + \" \" + r + \" are \" + (ans[r] - ans[l - 1] )); // print answer for required rangel = 2; r = 10;document.write(\"<br>Valid numbers in the range \" + l + \" \" + r + \" are \" + (ans[r] - ans[l - 1])); // This code contributed by shikhasingrajput </script>", "e": 14949, "s": 12277, "text": null }, { "code": null, "e": 15024, "s": 14949, "text": "Valid numbers in the range 2 3 are 2\nValid numbers in the range 2 10 are 5" }, { "code": null, "e": 15037, "s": 15026, "text": "inderDuMCA" }, { "code": null, "e": 15053, "s": 15037, "text": "tufan_gupta2000" }, { "code": null, "e": 15059, "s": 15053, "text": "ukasp" }, { "code": null, "e": 15076, "s": 15059, "text": "shikhasingrajput" }, { "code": null, "e": 15091, "s": 15076, "text": "kothavvsaakash" }, { "code": null, "e": 15105, "s": 15091, "text": "number-digits" }, { "code": null, "e": 15118, "s": 15105, "text": "prime-factor" }, { "code": null, "e": 15123, "s": 15118, "text": "Hash" }, { "code": null, "e": 15136, "s": 15123, "text": "Mathematical" }, { "code": null, "e": 15141, "s": 15136, "text": "Hash" }, { "code": null, "e": 15154, "s": 15141, "text": "Mathematical" }, { "code": null, "e": 15252, "s": 15154, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15290, "s": 15252, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 15346, "s": 15290, "text": "Find k numbers with most occurrences in the given array" }, { "code": null, "e": 15387, "s": 15346, "text": "Real-time application of Data Structures" }, { "code": null, "e": 15409, "s": 15387, "text": "Non-Repeating Element" }, { "code": null, "e": 15456, "s": 15409, "text": "Find the length of largest subarray with 0 sum" }, { "code": null, "e": 15486, "s": 15456, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 15529, "s": 15486, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 15589, "s": 15529, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 15604, "s": 15589, "text": "C++ Data Types" } ]
ROTATE Instructions in 8085
28 Apr, 2022 ROTATE is a logical operation of the 8085 microprocessor. It is a 1-byte instruction. This instruction does not require any operand after the opcode. It operates the content of the accumulator and the result is also stored in the accumulator. The Rotate instruction is used to rotate the bits of accumulator. Types of ROTATE Instruction: There are 4 categories of the ROTATE instruction: Rotate accumulator left (RLC), Rotate accumulator left through carrying (RAL), Rotate accumulator right (RRC), Rotate accumulator right through carry (RAR). Among these four instructions; two are for rotating left and two are for rotating right. All of them are explained briefly in the following sections: Rotate accumulator left (RLC) – In this instruction, each bit is shifted to the adjacent left position. Bit D7 becomes D0. Carry flag CY is modified according to the bit D7. For example:- Rotate accumulator left (RLC) – In this instruction, each bit is shifted to the adjacent left position. Bit D7 becomes D0. Carry flag CY is modified according to the bit D7. For example:- A = D7 D6 D5 D4 D3 D2 D1 D0 //before the instruction A = 10101010; CY=0 //after 1st RLC A = 01010101; CY=1 //after 2nd RLC A = 10101010; CY=0 Rotate accumulator left through carry (RAL) – In this instruction, each bit is shifted to the adjacent left position. Bit D7 becomes the carry bit and the carry bit is shifted into D0. Carry flag CY is modified according to the bit D7. For example: Rotate accumulator left through carry (RAL) – In this instruction, each bit is shifted to the adjacent left position. Bit D7 becomes the carry bit and the carry bit is shifted into D0. Carry flag CY is modified according to the bit D7. For example: A = D7 D6 D5 D4 D3 D2 D1 D0 //before the instruction A = 10101010; CY=0 //after 1st RAL A = 01010100; CY=1 //after 2nd RAL A = 10101001; CY=0 Rotate accumulator right (RRC) – In this instruction, each bit is shifted to the adjacent right position. Bit D7 becomes D0. Carry flag CY is modified according to the bit D0. For example: Rotate accumulator right (RRC) – In this instruction, each bit is shifted to the adjacent right position. Bit D7 becomes D0. Carry flag CY is modified according to the bit D0. For example: A = D7 D6 D5 D4 D3 D2 D1 D0 //before the instruction A = 10000001; CY=0 //after 1st RRC A = 11000000; CY=1 //after 2nd RRC A = 01100000; CY=0 Rotate accumulator right through carry (RAR) – In this instruction, each bit is shifted to the adjacent right position. Bit D0 becomes the carry bit and the carry bit is shifted into D7. Carry flag CY is modified according to the bit D0. For example: Rotate accumulator right through carry (RAR) – In this instruction, each bit is shifted to the adjacent right position. Bit D0 becomes the carry bit and the carry bit is shifted into D7. Carry flag CY is modified according to the bit D0. For example: A = D7 D6 D5 D4 D3 D2 D1 D0 //before the instruction A = 10000001; CY=0 //after 1st RAR A = 01000000; CY=1 //after 2nd RAR A = 10100000; CY=0 Applications of ROTATE Instructions: The ROTATE instructions are primarily used in arithmetic multiply and divide operations and for serial data transfer. For example: If A is 0000 1000 = 08H 1. By rotating 08H right : A = 0000 0100 = 04H This is equivalent to dividing by 2. 2. By rotating 08H left : A = 0001 0000 = 10H This is equivalent to multiplying by 2. However, these procedures are invalid when logic 1 is rotated left from D7 to D0 or vice versa. For example, if 80H is rotated left it becomes 01H. SakshamGoyal rajuldubey microprocessor Computer Organization & Architecture GATE CS microprocessor Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Computer Architecture | Flynn's taxonomy I2C Communication Protocol Architecture of Distributed Shared Memory(DSM) ARM processor and its Features Direct Access Media (DMA) Controller in Computer Architecture Layers of OSI Model Three address code in Compiler Types of Operating Systems ACID Properties in DBMS Page Replacement Algorithms in Operating Systems
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Apr, 2022" }, { "code": null, "e": 747, "s": 52, "text": "ROTATE is a logical operation of the 8085 microprocessor. It is a 1-byte instruction. This instruction does not require any operand after the opcode. It operates the content of the accumulator and the result is also stored in the accumulator. The Rotate instruction is used to rotate the bits of accumulator. Types of ROTATE Instruction: There are 4 categories of the ROTATE instruction: Rotate accumulator left (RLC), Rotate accumulator left through carrying (RAL), Rotate accumulator right (RRC), Rotate accumulator right through carry (RAR). Among these four instructions; two are for rotating left and two are for rotating right. All of them are explained briefly in the following sections:" }, { "code": null, "e": 935, "s": 747, "text": "Rotate accumulator left (RLC) – In this instruction, each bit is shifted to the adjacent left position. Bit D7 becomes D0. Carry flag CY is modified according to the bit D7. For example:-" }, { "code": null, "e": 1123, "s": 935, "text": "Rotate accumulator left (RLC) – In this instruction, each bit is shifted to the adjacent left position. Bit D7 becomes D0. Carry flag CY is modified according to the bit D7. For example:-" }, { "code": null, "e": 1289, "s": 1123, "text": "A = D7 D6 D5 D4 D3 D2 D1 D0\n\n//before the instruction\nA = 10101010; CY=0 \n\n//after 1st RLC \nA = 01010101; CY=1 \n\n//after 2nd RLC \nA = 10101010; CY=0 " }, { "code": null, "e": 1538, "s": 1289, "text": "Rotate accumulator left through carry (RAL) – In this instruction, each bit is shifted to the adjacent left position. Bit D7 becomes the carry bit and the carry bit is shifted into D0. Carry flag CY is modified according to the bit D7. For example:" }, { "code": null, "e": 1787, "s": 1538, "text": "Rotate accumulator left through carry (RAL) – In this instruction, each bit is shifted to the adjacent left position. Bit D7 becomes the carry bit and the carry bit is shifted into D0. Carry flag CY is modified according to the bit D7. For example:" }, { "code": null, "e": 1934, "s": 1787, "text": "A = D7 D6 D5 D4 D3 D2 D1 D0\n\n//before the instruction\nA = 10101010; CY=0 \n\n//after 1st RAL\nA = 01010100; CY=1\n\n//after 2nd RAL\nA = 10101001; CY=0 " }, { "code": null, "e": 2123, "s": 1934, "text": "Rotate accumulator right (RRC) – In this instruction, each bit is shifted to the adjacent right position. Bit D7 becomes D0. Carry flag CY is modified according to the bit D0. For example:" }, { "code": null, "e": 2312, "s": 2123, "text": "Rotate accumulator right (RRC) – In this instruction, each bit is shifted to the adjacent right position. Bit D7 becomes D0. Carry flag CY is modified according to the bit D0. For example:" }, { "code": null, "e": 2484, "s": 2312, "text": "A = D7 D6 D5 D4 D3 D2 D1 D0\n\n//before the instruction\nA = 10000001; CY=0 \n\n//after 1st RRC \nA = 11000000; CY=1 \n\n//after 2nd RRC \nA = 01100000; CY=0 " }, { "code": null, "e": 2735, "s": 2484, "text": "Rotate accumulator right through carry (RAR) – In this instruction, each bit is shifted to the adjacent right position. Bit D0 becomes the carry bit and the carry bit is shifted into D7. Carry flag CY is modified according to the bit D0. For example:" }, { "code": null, "e": 2986, "s": 2735, "text": "Rotate accumulator right through carry (RAR) – In this instruction, each bit is shifted to the adjacent right position. Bit D0 becomes the carry bit and the carry bit is shifted into D7. Carry flag CY is modified according to the bit D0. For example:" }, { "code": null, "e": 3158, "s": 2986, "text": "A = D7 D6 D5 D4 D3 D2 D1 D0\n\n//before the instruction\nA = 10000001; CY=0 \n\n//after 1st RAR \nA = 01000000; CY=1 \n\n//after 2nd RAR \nA = 10100000; CY=0 " }, { "code": null, "e": 3326, "s": 3158, "text": "Applications of ROTATE Instructions: The ROTATE instructions are primarily used in arithmetic multiply and divide operations and for serial data transfer. For example:" }, { "code": null, "e": 3532, "s": 3326, "text": "If A is 0000 1000 = 08H \n\n1. By rotating 08H right : A = 0000 0100 = 04H\n This is equivalent to dividing by 2.\n\n2. By rotating 08H left : A = 0001 0000 = 10H\n This is equivalent to multiplying by 2. " }, { "code": null, "e": 3680, "s": 3532, "text": "However, these procedures are invalid when logic 1 is rotated left from D7 to D0 or vice versa. For example, if 80H is rotated left it becomes 01H." }, { "code": null, "e": 3693, "s": 3680, "text": "SakshamGoyal" }, { "code": null, "e": 3704, "s": 3693, "text": "rajuldubey" }, { "code": null, "e": 3719, "s": 3704, "text": "microprocessor" }, { "code": null, "e": 3756, "s": 3719, "text": "Computer Organization & Architecture" }, { "code": null, "e": 3764, "s": 3756, "text": "GATE CS" }, { "code": null, "e": 3779, "s": 3764, "text": "microprocessor" }, { "code": null, "e": 3877, "s": 3779, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3918, "s": 3877, "text": "Computer Architecture | Flynn's taxonomy" }, { "code": null, "e": 3945, "s": 3918, "text": "I2C Communication Protocol" }, { "code": null, "e": 3992, "s": 3945, "text": "Architecture of Distributed Shared Memory(DSM)" }, { "code": null, "e": 4023, "s": 3992, "text": "ARM processor and its Features" }, { "code": null, "e": 4085, "s": 4023, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 4105, "s": 4085, "text": "Layers of OSI Model" }, { "code": null, "e": 4136, "s": 4105, "text": "Three address code in Compiler" }, { "code": null, "e": 4163, "s": 4136, "text": "Types of Operating Systems" }, { "code": null, "e": 4187, "s": 4163, "text": "ACID Properties in DBMS" } ]
CSS border-spacing Property - GeeksforGeeks
22 Aug, 2021 The border-spacing Property is used to set the distance between the borders of neighboring cells in the Table. This property works only when the border-collapse property is set to no-collapse separate. Default Value: 2px Syntax: border-spacing: length|initial|inherit; Property values: length-length: It is used to set the distance between the borders of adjacent cells. It does not allow negative values. If two values are defined, first value defines the horizontal space and second value defines the vertical spacing.If only one value is given then it defines the both horizontal and vertical spacing between the adjacent borders of cells.initial: It sets the property to its default value. length-length: It is used to set the distance between the borders of adjacent cells. It does not allow negative values. If two values are defined, first value defines the horizontal space and second value defines the vertical spacing.If only one value is given then it defines the both horizontal and vertical spacing between the adjacent borders of cells. If two values are defined, first value defines the horizontal space and second value defines the vertical spacing. If only one value is given then it defines the both horizontal and vertical spacing between the adjacent borders of cells. initial: It sets the property to its default value. Syntax: border-spacing:initial; Example: html <!DOCTYPE html><html> <head> <title>border-spacing property</title> <style> table, th, td { border: 2px solid green; text-align: center; } #geeks { border-collapse: separate; background-color: none; border-spacing: initial; } h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h2> The border-spacing Property</h2> <h3>border-spacing: initial;</h3> <table style="width:70%" id="geeks"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Harsh</td> <td>Agarwal</td> <td>15</td> </tr> <tr> <td>Manas</td> <td>Chhabra</td> <td>27</td> </tr> <tr> <td>Ramesh</td> <td>Chandra</td> <td>28</td> </tr> </table> </center></body> </html> Output: Supported Browsers: The browser supported by css border-spacing property are listed below: Google Chrome 1.0 Internet Explorer 8.0 Firefox 1.0 Opera 4.0 Safari 1.0 surinderdawra388 abhishek0719kadiyan kapoorsagar226 hritikbhatnagar2182 CSS-Properties CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? CSS to put icon inside an input element in a form Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript
[ { "code": null, "e": 23656, "s": 23628, "text": "\n22 Aug, 2021" }, { "code": null, "e": 23859, "s": 23656, "text": "The border-spacing Property is used to set the distance between the borders of neighboring cells in the Table. This property works only when the border-collapse property is set to no-collapse separate. " }, { "code": null, "e": 23875, "s": 23859, "text": "Default Value: " }, { "code": null, "e": 23879, "s": 23875, "text": "2px" }, { "code": null, "e": 23889, "s": 23879, "text": "Syntax: " }, { "code": null, "e": 23930, "s": 23889, "text": "border-spacing: length|initial|inherit; " }, { "code": null, "e": 23948, "s": 23930, "text": "Property values: " }, { "code": null, "e": 24356, "s": 23948, "text": "length-length: It is used to set the distance between the borders of adjacent cells. It does not allow negative values. If two values are defined, first value defines the horizontal space and second value defines the vertical spacing.If only one value is given then it defines the both horizontal and vertical spacing between the adjacent borders of cells.initial: It sets the property to its default value." }, { "code": null, "e": 24713, "s": 24356, "text": "length-length: It is used to set the distance between the borders of adjacent cells. It does not allow negative values. If two values are defined, first value defines the horizontal space and second value defines the vertical spacing.If only one value is given then it defines the both horizontal and vertical spacing between the adjacent borders of cells." }, { "code": null, "e": 24828, "s": 24713, "text": "If two values are defined, first value defines the horizontal space and second value defines the vertical spacing." }, { "code": null, "e": 24951, "s": 24828, "text": "If only one value is given then it defines the both horizontal and vertical spacing between the adjacent borders of cells." }, { "code": null, "e": 25003, "s": 24951, "text": "initial: It sets the property to its default value." }, { "code": null, "e": 25012, "s": 25003, "text": "Syntax: " }, { "code": null, "e": 25036, "s": 25012, "text": "border-spacing:initial;" }, { "code": null, "e": 25046, "s": 25036, "text": "Example: " }, { "code": null, "e": 25051, "s": 25046, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>border-spacing property</title> <style> table, th, td { border: 2px solid green; text-align: center; } #geeks { border-collapse: separate; background-color: none; border-spacing: initial; } h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h2> The border-spacing Property</h2> <h3>border-spacing: initial;</h3> <table style=\"width:70%\" id=\"geeks\"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Harsh</td> <td>Agarwal</td> <td>15</td> </tr> <tr> <td>Manas</td> <td>Chhabra</td> <td>27</td> </tr> <tr> <td>Ramesh</td> <td>Chandra</td> <td>28</td> </tr> </table> </center></body> </html> ", "e": 26199, "s": 25051, "text": null }, { "code": null, "e": 26209, "s": 26199, "text": "Output: " }, { "code": null, "e": 26302, "s": 26209, "text": "Supported Browsers: The browser supported by css border-spacing property are listed below: " }, { "code": null, "e": 26320, "s": 26302, "text": "Google Chrome 1.0" }, { "code": null, "e": 26342, "s": 26320, "text": "Internet Explorer 8.0" }, { "code": null, "e": 26354, "s": 26342, "text": "Firefox 1.0" }, { "code": null, "e": 26364, "s": 26354, "text": "Opera 4.0" }, { "code": null, "e": 26375, "s": 26364, "text": "Safari 1.0" }, { "code": null, "e": 26392, "s": 26375, "text": "surinderdawra388" }, { "code": null, "e": 26412, "s": 26392, "text": "abhishek0719kadiyan" }, { "code": null, "e": 26427, "s": 26412, "text": "kapoorsagar226" }, { "code": null, "e": 26447, "s": 26427, "text": "hritikbhatnagar2182" }, { "code": null, "e": 26462, "s": 26447, "text": "CSS-Properties" }, { "code": null, "e": 26466, "s": 26462, "text": "CSS" }, { "code": null, "e": 26483, "s": 26466, "text": "Web Technologies" }, { "code": null, "e": 26581, "s": 26483, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26643, "s": 26581, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26693, "s": 26643, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 26751, "s": 26693, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 26799, "s": 26751, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26849, "s": 26799, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 26891, "s": 26849, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26924, "s": 26891, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26967, "s": 26924, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27029, "s": 26967, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Relative vs Absolute: Understanding Compositional Data with Simulations | by Krishna Yerramsetty | Towards Data Science
One of the things I am constantly asked to do at my work is to compare NGS data across samples. These could be replicates or could be coming from completely different environments or processing steps. We all intuitively understood that these data are always constrained by the sequencing depth and therefore the conclusions need to be drawn carefully. I lacked the vocabulary or the techniques to analyze this data until I saw the pre-print of this paper by @WarrenMcG. That started a few days of digging a little deeper into compositional data, and I generated some synthetic data to understand the nuances a little better. In this post, I try to lay out what I’ve learned and hopefully help spread the word about the dangers of treating compositional data as regular un-constrained data. Compositional data is any data where the numbers make up proportions of a whole. For example, the number of heads and tails you obtain from flipping a coin say 10 times is compositional data. The main feature of these data is that they are ‘closed’ or constrained in the sense that if I tell you we got 6 heads from flipping a 2-sided coin, you know that there are 4 tails without me providing you with any further information. In probability terms, this means not all components in the data are independent of each other. Therefore, compositional data do not exist in the Euclidean space, but in a special constrained space called the simplex. For engineers out there, you might have run into a simplex plot every time you plotted a multi-phase equilibrium plot like this one here for water plotted using the R library Ternary: In essence, a specified fixed amount of water can exist in different phases in different conditions but the total amount of steam, liquid water, and ice should always sum up to the fixed amount we started with. Compositional data exists in more places than we think. Some examples include voting data, nutrient information on food labels, the proportion of different gases in the air you breathe, and even the RGB values on the pixels on your screen right now. There are in general 4 different criteria that any analysis method for compositional data should satisfy according to Aitchison. Traditional analyses generally do not satisfy all these requirements and therefore lead to erroneous results. I will use simulated data to convince myself and hopefully you to understand these pitfalls of traditional analyses methods. I used absSimSeq to generate some dummy RNA-seq like data. In short, I have 4 samples from a control condition and 4 samples from a treatment condition. Each sample is made up of 100 native genes and 92 spike-in (control) genes, and the counts of all genes for a sample sum up to approximately 20K reads. The treatment condition is simulated to have 20% of the native genes differentially expressed (fancy biology term for the change in the number of copies of the gene inside the cells/tissues) compared to the control condition. The exact magnitudes of differential expression do not matter for what we are trying to prove here. Now that we set-up the data lets move onto the 4 criteria that traditional analyses methods generally fail to take into account when dealing with compositional data. You can find all the data and code I used here: https://github.com/kimoyerr/CODA.git A common property of compositional data is that they can be represented using different magnitudes of vectors. Ex: Air is made up of 78% Nitrogen, 21% Oxygen, and the rest is 1% by Volume. In vector notation, this can be written as [78, 21, 1]. In terms of parts per million in volume (ppmv), this can also be specified as [780840, 209460, and 9780]. Despite these very different notations, they represent the same physical sample. Traditional analyses methods like Euclidean distances and hierarchical clustering, however, will be fooled by this difference in representation. Let’s prove this using our simulated RNA-Seq data. In R do the following: load('sim_counts_matrix_100.rda')orig.dist <- dist(t(counts_matrix))orig.dendro <- as.dendrogram(hclust(d = dist(t(counts_matrix))))# Create dendrodendro.plot <- ggdendrogram(data = orig.dendro, rotate = TRUE)# Preview the plotprint(dendro.plot) As expected, we see that the four control samples (samples 1 to 4) cluster together, and the four treatment samples (samples 5 to 8) cluster together. Now let's scale some samples differently as shown below. This can happen for example, if you sequenced some samples to a higher depth than usual but still want to analyze all the samples together. # Scale the samples differentlyscaled.counts_matrix = counts_matrix %*% diag(c(1,1,5,5,1,1,5,5))scaled.dist <- dist(t(scaled.counts_matrix))scaled.dendro <- as.dendrogram(hclust(d = dist(t(scaled.counts_matrix))))# Create dendroscaled.dendro.plot <- ggdendrogram(data = scaled.dendro, rotate = TRUE)# Preview the plotprint(scaled.dendro.plot) The new dendrogram now shows the scaled samples (Samples 3,4, 7, and 8) clustered together, which is not true since the only thing that changed is the total number of reads for these samples, but their individual components are the same relative to each other. This is related to the observation that the conclusions of our analyses should not depend on the units used to represent the compositional data. Going back to the Air composition example, we can represent the data using a mix of percentages and ppmv values like so: [78%, 21%, and 9780ppmv]. This still represents the same physical sample, and we should be able to compare this to another air-like sample, in this new coordinate system and the old coordinate system, and draw the same conclusions. Let's use our simulated data again to calculate the distances between samples in a newer perturbed coordinate space: #Multiply each row (gene) with a scalar valueperturbed.counts_matrix = counts_matrix * c(seq(1,192,1))colnames(perturbed.counts_matrix) = colnames(counts_matrix)perturbed.dist <- dist(t(perturbed.counts_matrix))perturbed.dendro <- as.dendrogram(hclust(d = dist(t(perturbed.counts_matrix))))# Create dendroperturbed.dendro.plot <- ggdendrogram(data = perturbed.dendro, rotate = TRUE)# Preview the plotprint(perturbed.dendro.plot) It's clear from the above plot that this is a much minor problem compared to the scale invariance problem. The samples from the control and treatment condition cluster together, but the distances between samples is different. This can lead to wrong conclusions depending on the question being asked. In the context of comparing samples across conditions as in most RNA-seq or NGS data, perturbation variance isn’t much of a problem. This property ensures that the analyses lead to the same conclusions regardless of which components of the data are included. For example, in our Air example, we can remove the component representing the 1% volume. Now the samples are represented in the 2-dimensional space ([78.5%, 21.5%] )instead of in the original 3-dimensional space ([78%, 21%, 1%]). Any analysis in this lower dimensional space should not differ from the comparison in the original 3-dimensional space. This is an important property from the standpoint of Next Generation Sequencing (NGS) data where we are not always guaranteed to find all the components in our data all the time. This could be for a lot of reasons, sometimes intended and sometimes unintended and unavoidable. To simulate this property (or lack thereof) in traditional analyses methods, I generated a second dataset made up of the first 50 genes + 92 controls from our original dataset made up 100 genes + 92 controls. The 50 genes in the smaller dataset have the same absolute (unconstrained) values as in the original dataset. These unconstrained data are then closed (constrained) by making the total sum of all reads to be ~20K as in the original dataset. The correlation coefficients among the 50 common genes in both datasets are calculated and then compared: load('sim_counts_matrix_100.rda')counts.all <- counts_matrix # Load the sub-compositional data made up of only the first 50 genes (features) + 92 controls from the original data of 100 genes (features) + 92 controlsload('sim_counts_matrix_50.rda')counts.sub.comp <- counts_matrix# Get the correlation between the 50 common genescor.all <- as.vector(cor(t(counts.all[1:50,])))cor.sub.comp <- as.vector(cor(t(counts.sub.comp[1:50,])))tmp <- as.data.frame(cbind(cor.all,cor.sub.comp))names(tmp) <- c('correlation_all', 'correlation_sub_comp')tmp$abs.diff <- as.factor(ifelse(abs(tmp$correlation_all - tmp$correlation_sub_comp)>0.5,1,0))# Plotggplot(tmp,aes(correlation_all,correlation_sub_comp, color=abs.diff)) + geom_point(size=2) + th + scale_colour_manual(values = c("1" = "Red", "0" = "Blue")) + theme(legend.position = "none") In the plot above, we can see that the majority of correlation coefficients are similar in both datasets, with some coefficients that differ significantly (shown in red). Depending on the questions being asked, these differences could lead to significant differences in conclusions. This could be a major problem in gene network analyses. This property means that regardless of the order of the original data, the analyses methods should lead to the same conclusions. Most analyses methods I can think of generally follow this property. Please let me know if you know of any analyses methods that violate this, I will include them in the post. Now that we convinced ourselves that the traditional analyses methods do not always satisfy all 4 properties important for analyzing compositional data, what can we do? Aitchison has done some incredible work over 3 decades to come up with better techniques. Based on my experience dealing with NGS data, I have a feeling that his recommendations have largely fallen on deaf ears. Hopefully, this blog post will convince others to be more cautious when analyzing compositional data. In the next post, I will show some ways to analyze compositional data with emphasis again on NGS data and applications.
[ { "code": null, "e": 962, "s": 172, "text": "One of the things I am constantly asked to do at my work is to compare NGS data across samples. These could be replicates or could be coming from completely different environments or processing steps. We all intuitively understood that these data are always constrained by the sequencing depth and therefore the conclusions need to be drawn carefully. I lacked the vocabulary or the techniques to analyze this data until I saw the pre-print of this paper by @WarrenMcG. That started a few days of digging a little deeper into compositional data, and I generated some synthetic data to understand the nuances a little better. In this post, I try to lay out what I’ve learned and hopefully help spread the word about the dangers of treating compositional data as regular un-constrained data." }, { "code": null, "e": 1791, "s": 962, "text": "Compositional data is any data where the numbers make up proportions of a whole. For example, the number of heads and tails you obtain from flipping a coin say 10 times is compositional data. The main feature of these data is that they are ‘closed’ or constrained in the sense that if I tell you we got 6 heads from flipping a 2-sided coin, you know that there are 4 tails without me providing you with any further information. In probability terms, this means not all components in the data are independent of each other. Therefore, compositional data do not exist in the Euclidean space, but in a special constrained space called the simplex. For engineers out there, you might have run into a simplex plot every time you plotted a multi-phase equilibrium plot like this one here for water plotted using the R library Ternary:" }, { "code": null, "e": 2252, "s": 1791, "text": "In essence, a specified fixed amount of water can exist in different phases in different conditions but the total amount of steam, liquid water, and ice should always sum up to the fixed amount we started with. Compositional data exists in more places than we think. Some examples include voting data, nutrient information on food labels, the proportion of different gases in the air you breathe, and even the RGB values on the pixels on your screen right now." }, { "code": null, "e": 3413, "s": 2252, "text": "There are in general 4 different criteria that any analysis method for compositional data should satisfy according to Aitchison. Traditional analyses generally do not satisfy all these requirements and therefore lead to erroneous results. I will use simulated data to convince myself and hopefully you to understand these pitfalls of traditional analyses methods. I used absSimSeq to generate some dummy RNA-seq like data. In short, I have 4 samples from a control condition and 4 samples from a treatment condition. Each sample is made up of 100 native genes and 92 spike-in (control) genes, and the counts of all genes for a sample sum up to approximately 20K reads. The treatment condition is simulated to have 20% of the native genes differentially expressed (fancy biology term for the change in the number of copies of the gene inside the cells/tissues) compared to the control condition. The exact magnitudes of differential expression do not matter for what we are trying to prove here. Now that we set-up the data lets move onto the 4 criteria that traditional analyses methods generally fail to take into account when dealing with compositional data." }, { "code": null, "e": 3498, "s": 3413, "text": "You can find all the data and code I used here: https://github.com/kimoyerr/CODA.git" }, { "code": null, "e": 4149, "s": 3498, "text": "A common property of compositional data is that they can be represented using different magnitudes of vectors. Ex: Air is made up of 78% Nitrogen, 21% Oxygen, and the rest is 1% by Volume. In vector notation, this can be written as [78, 21, 1]. In terms of parts per million in volume (ppmv), this can also be specified as [780840, 209460, and 9780]. Despite these very different notations, they represent the same physical sample. Traditional analyses methods like Euclidean distances and hierarchical clustering, however, will be fooled by this difference in representation. Let’s prove this using our simulated RNA-Seq data. In R do the following:" }, { "code": null, "e": 4395, "s": 4149, "text": "load('sim_counts_matrix_100.rda')orig.dist <- dist(t(counts_matrix))orig.dendro <- as.dendrogram(hclust(d = dist(t(counts_matrix))))# Create dendrodendro.plot <- ggdendrogram(data = orig.dendro, rotate = TRUE)# Preview the plotprint(dendro.plot)" }, { "code": null, "e": 4546, "s": 4395, "text": "As expected, we see that the four control samples (samples 1 to 4) cluster together, and the four treatment samples (samples 5 to 8) cluster together." }, { "code": null, "e": 4743, "s": 4546, "text": "Now let's scale some samples differently as shown below. This can happen for example, if you sequenced some samples to a higher depth than usual but still want to analyze all the samples together." }, { "code": null, "e": 5086, "s": 4743, "text": "# Scale the samples differentlyscaled.counts_matrix = counts_matrix %*% diag(c(1,1,5,5,1,1,5,5))scaled.dist <- dist(t(scaled.counts_matrix))scaled.dendro <- as.dendrogram(hclust(d = dist(t(scaled.counts_matrix))))# Create dendroscaled.dendro.plot <- ggdendrogram(data = scaled.dendro, rotate = TRUE)# Preview the plotprint(scaled.dendro.plot)" }, { "code": null, "e": 5347, "s": 5086, "text": "The new dendrogram now shows the scaled samples (Samples 3,4, 7, and 8) clustered together, which is not true since the only thing that changed is the total number of reads for these samples, but their individual components are the same relative to each other." }, { "code": null, "e": 5962, "s": 5347, "text": "This is related to the observation that the conclusions of our analyses should not depend on the units used to represent the compositional data. Going back to the Air composition example, we can represent the data using a mix of percentages and ppmv values like so: [78%, 21%, and 9780ppmv]. This still represents the same physical sample, and we should be able to compare this to another air-like sample, in this new coordinate system and the old coordinate system, and draw the same conclusions. Let's use our simulated data again to calculate the distances between samples in a newer perturbed coordinate space:" }, { "code": null, "e": 6391, "s": 5962, "text": "#Multiply each row (gene) with a scalar valueperturbed.counts_matrix = counts_matrix * c(seq(1,192,1))colnames(perturbed.counts_matrix) = colnames(counts_matrix)perturbed.dist <- dist(t(perturbed.counts_matrix))perturbed.dendro <- as.dendrogram(hclust(d = dist(t(perturbed.counts_matrix))))# Create dendroperturbed.dendro.plot <- ggdendrogram(data = perturbed.dendro, rotate = TRUE)# Preview the plotprint(perturbed.dendro.plot)" }, { "code": null, "e": 6824, "s": 6391, "text": "It's clear from the above plot that this is a much minor problem compared to the scale invariance problem. The samples from the control and treatment condition cluster together, but the distances between samples is different. This can lead to wrong conclusions depending on the question being asked. In the context of comparing samples across conditions as in most RNA-seq or NGS data, perturbation variance isn’t much of a problem." }, { "code": null, "e": 7576, "s": 6824, "text": "This property ensures that the analyses lead to the same conclusions regardless of which components of the data are included. For example, in our Air example, we can remove the component representing the 1% volume. Now the samples are represented in the 2-dimensional space ([78.5%, 21.5%] )instead of in the original 3-dimensional space ([78%, 21%, 1%]). Any analysis in this lower dimensional space should not differ from the comparison in the original 3-dimensional space. This is an important property from the standpoint of Next Generation Sequencing (NGS) data where we are not always guaranteed to find all the components in our data all the time. This could be for a lot of reasons, sometimes intended and sometimes unintended and unavoidable." }, { "code": null, "e": 8026, "s": 7576, "text": "To simulate this property (or lack thereof) in traditional analyses methods, I generated a second dataset made up of the first 50 genes + 92 controls from our original dataset made up 100 genes + 92 controls. The 50 genes in the smaller dataset have the same absolute (unconstrained) values as in the original dataset. These unconstrained data are then closed (constrained) by making the total sum of all reads to be ~20K as in the original dataset." }, { "code": null, "e": 8132, "s": 8026, "text": "The correlation coefficients among the 50 common genes in both datasets are calculated and then compared:" }, { "code": null, "e": 8962, "s": 8132, "text": "load('sim_counts_matrix_100.rda')counts.all <- counts_matrix # Load the sub-compositional data made up of only the first 50 genes (features) + 92 controls from the original data of 100 genes (features) + 92 controlsload('sim_counts_matrix_50.rda')counts.sub.comp <- counts_matrix# Get the correlation between the 50 common genescor.all <- as.vector(cor(t(counts.all[1:50,])))cor.sub.comp <- as.vector(cor(t(counts.sub.comp[1:50,])))tmp <- as.data.frame(cbind(cor.all,cor.sub.comp))names(tmp) <- c('correlation_all', 'correlation_sub_comp')tmp$abs.diff <- as.factor(ifelse(abs(tmp$correlation_all - tmp$correlation_sub_comp)>0.5,1,0))# Plotggplot(tmp,aes(correlation_all,correlation_sub_comp, color=abs.diff)) + geom_point(size=2) + th + scale_colour_manual(values = c(\"1\" = \"Red\", \"0\" = \"Blue\")) + theme(legend.position = \"none\")" }, { "code": null, "e": 9301, "s": 8962, "text": "In the plot above, we can see that the majority of correlation coefficients are similar in both datasets, with some coefficients that differ significantly (shown in red). Depending on the questions being asked, these differences could lead to significant differences in conclusions. This could be a major problem in gene network analyses." }, { "code": null, "e": 9606, "s": 9301, "text": "This property means that regardless of the order of the original data, the analyses methods should lead to the same conclusions. Most analyses methods I can think of generally follow this property. Please let me know if you know of any analyses methods that violate this, I will include them in the post." } ]
Pivot Tables with Pandas. An Excel favorite in Python | by Ryan Lewis | Towards Data Science
Most everyone who has worked with any type of data has likely used Microsoft Excel’s PivotTable function. It’s a quick, user-friendly tool that allows users to to calculate, aggregate, and summarize data sets enabling further analysis of patterns and trends. Excel provides an intuitive GUI that allows analysts to simply click, drag and drop data and easily apply whichever aggregation function they choose. It’s fantastic tool to use and aids when building Excel visualizations for business presentations. Python’s Pandas library — which specializes in tabular data, similar to Excel — also has a .pivot_table() function that works in the same concept. It’s a powerful method, comes with a lot of customizable parameters, that should be in every analyst’s Python toolbox. It takes some time to understand the syntax behind the method, but once you’re familiar, it’s a lot faster and more efficient than Excel. Let’s dive into an NBA stats dataset and see how Panda’s .pivot_table() function works! #importing required librariesimport pandas as pdimport numpy as np#reading in the data & selecting needed columnsdf = pd.read_csv('../Data/NBA_Player_seasonal.csv', index_col = 0)df = df[['Player', 'Season', 'Age', 'Tm','WS', 'G','MP','3P','TRB','AST','STL','BLK', 'TOV', 'PF','PTS']]#displaying first 5 rows of dataframedf.head() Above, we can see a preview of our dataset. It’s seasonal totals for every NBA & ABA player dating back to the beginning of the league in 1947. It’s pre-sorted and ranked by highest “WS” — win-share, a metric that calculates the estimated number of wins a player contributes to their team. Let’s say we wanted to see this information, but aggregated by team. We could do something like this: #creating a pivot table where team is the indexdf.pivot_table(index = 'Tm') By default, pivot_table() brings in all numerical columns and aggregates the data using it’s mean. Let’s say we only care about a few of these columns, and instead of the averages, we want to see totals. #pivot table with selected columns & summeddf.pivot_table(df[['PTS', 'AST', 'TRB']], #selected columns index = 'Tm', #indexed by team aggfunc = np.sum) #aggregated by sum Now we can view just the statistics we’re interested in and view totals instead of averages. You are able to pass in a library for the aggfunc argument, allowing users to choose which type of aggregation should be performed on each column. Taking it a step further, pivot_table() allows users to have multiple indexes to further analyze data. Below is an example of the same data set but reshaped as teams statistics over the years. #multi-index pivot tabledf.pivot_table(df[['PTS', 'AST', 'TRB', 'STL','BLK', 'TOV']], index = ['Season', 'Tm'], aggfunc = np.mean).head() In the above pivot table, we’re aggregating on missing data, even some of the basic statistics weren’t recorded until a few seasons after the inaugural one in 1947. Let’s say we want to fill those with zero’s for our analysis. We can accomplish this with a simple addition to our pivot table parameters. #filling in NaN values w/ 0'sdf.pivot_table(df[['PTS', 'AST', 'TRB', 'STL','BLK', 'TOV']], index = ['Season', 'Tm'], aggfunc = np.mean, fill_value = 0).head() This function also enables users to quickly visualize their data in fewer lines of code, than if they were trying to code it directly from the original data set. As an example, let’s plot league-wide seasonal averages over the years via a pivot table line plot. #plotting pivot tabledf.pivot_table(df[['PTS', 'AST', 'TRB', 'STL','BLK', 'TOV']], index = ['Season',], aggfunc = np.mean, fill_value = 0).plot() It’s not the prettiest visual, but it’s quick and provides some vital information. You can quickly identity the 1999 lockout seasons where only 50 games were played in the season compared to the usual 82. These are several of the pivot_table() parameters you can use to customize/reshape your dataset. There are other parameters such as margins which adds totals to columns and rows. Another is columns which provides an additional way to segment your data set. Lastly, each pivot table outputs a new dataframe, that allows you to perform any standard dataframe functions/methods such as filtering on specific criteria, for example if we had only wanted to see Boston Celtics data. I hope this quick tutorial is helpful to understand how powerful Panda’s pivot table function is! Please feel free to reach out with any questions or leave any feedback.
[ { "code": null, "e": 680, "s": 172, "text": "Most everyone who has worked with any type of data has likely used Microsoft Excel’s PivotTable function. It’s a quick, user-friendly tool that allows users to to calculate, aggregate, and summarize data sets enabling further analysis of patterns and trends. Excel provides an intuitive GUI that allows analysts to simply click, drag and drop data and easily apply whichever aggregation function they choose. It’s fantastic tool to use and aids when building Excel visualizations for business presentations." }, { "code": null, "e": 1084, "s": 680, "text": "Python’s Pandas library — which specializes in tabular data, similar to Excel — also has a .pivot_table() function that works in the same concept. It’s a powerful method, comes with a lot of customizable parameters, that should be in every analyst’s Python toolbox. It takes some time to understand the syntax behind the method, but once you’re familiar, it’s a lot faster and more efficient than Excel." }, { "code": null, "e": 1172, "s": 1084, "text": "Let’s dive into an NBA stats dataset and see how Panda’s .pivot_table() function works!" }, { "code": null, "e": 1503, "s": 1172, "text": "#importing required librariesimport pandas as pdimport numpy as np#reading in the data & selecting needed columnsdf = pd.read_csv('../Data/NBA_Player_seasonal.csv', index_col = 0)df = df[['Player', 'Season', 'Age', 'Tm','WS', 'G','MP','3P','TRB','AST','STL','BLK', 'TOV', 'PF','PTS']]#displaying first 5 rows of dataframedf.head()" }, { "code": null, "e": 1895, "s": 1503, "text": "Above, we can see a preview of our dataset. It’s seasonal totals for every NBA & ABA player dating back to the beginning of the league in 1947. It’s pre-sorted and ranked by highest “WS” — win-share, a metric that calculates the estimated number of wins a player contributes to their team. Let’s say we wanted to see this information, but aggregated by team. We could do something like this:" }, { "code": null, "e": 1971, "s": 1895, "text": "#creating a pivot table where team is the indexdf.pivot_table(index = 'Tm')" }, { "code": null, "e": 2175, "s": 1971, "text": "By default, pivot_table() brings in all numerical columns and aggregates the data using it’s mean. Let’s say we only care about a few of these columns, and instead of the averages, we want to see totals." }, { "code": null, "e": 2374, "s": 2175, "text": "#pivot table with selected columns & summeddf.pivot_table(df[['PTS', 'AST', 'TRB']], #selected columns index = 'Tm', #indexed by team aggfunc = np.sum) #aggregated by sum" }, { "code": null, "e": 2614, "s": 2374, "text": "Now we can view just the statistics we’re interested in and view totals instead of averages. You are able to pass in a library for the aggfunc argument, allowing users to choose which type of aggregation should be performed on each column." }, { "code": null, "e": 2807, "s": 2614, "text": "Taking it a step further, pivot_table() allows users to have multiple indexes to further analyze data. Below is an example of the same data set but reshaped as teams statistics over the years." }, { "code": null, "e": 2971, "s": 2807, "text": "#multi-index pivot tabledf.pivot_table(df[['PTS', 'AST', 'TRB', 'STL','BLK', 'TOV']], index = ['Season', 'Tm'], aggfunc = np.mean).head()" }, { "code": null, "e": 3275, "s": 2971, "text": "In the above pivot table, we’re aggregating on missing data, even some of the basic statistics weren’t recorded until a few seasons after the inaugural one in 1947. Let’s say we want to fill those with zero’s for our analysis. We can accomplish this with a simple addition to our pivot table parameters." }, { "code": null, "e": 3473, "s": 3275, "text": "#filling in NaN values w/ 0'sdf.pivot_table(df[['PTS', 'AST', 'TRB', 'STL','BLK', 'TOV']], index = ['Season', 'Tm'], aggfunc = np.mean, fill_value = 0).head()" }, { "code": null, "e": 3735, "s": 3473, "text": "This function also enables users to quickly visualize their data in fewer lines of code, than if they were trying to code it directly from the original data set. As an example, let’s plot league-wide seasonal averages over the years via a pivot table line plot." }, { "code": null, "e": 3924, "s": 3735, "text": "#plotting pivot tabledf.pivot_table(df[['PTS', 'AST', 'TRB', 'STL','BLK', 'TOV']], index = ['Season',], aggfunc = np.mean, fill_value = 0).plot()" }, { "code": null, "e": 4129, "s": 3924, "text": "It’s not the prettiest visual, but it’s quick and provides some vital information. You can quickly identity the 1999 lockout seasons where only 50 games were played in the season compared to the usual 82." }, { "code": null, "e": 4606, "s": 4129, "text": "These are several of the pivot_table() parameters you can use to customize/reshape your dataset. There are other parameters such as margins which adds totals to columns and rows. Another is columns which provides an additional way to segment your data set. Lastly, each pivot table outputs a new dataframe, that allows you to perform any standard dataframe functions/methods such as filtering on specific criteria, for example if we had only wanted to see Boston Celtics data." } ]
How to Upload Project on GitHub from Jupyter Notebook? - GeeksforGeeks
05 Aug, 2021 A Jupyter notebook is neither a simple text editor nor a full-featured IDE, rather it is an electronic file which contains both programming code and text descriptions. It can also contain embedded charts, plots, images, videos, and links. They run in a web browser like Firefox or Google Chrome. They can contain code of various programming languages, though are mainly popular for Python with .py extension, they also support Markdowns with .md extension. One way to think of a Jupyter notebook is as a combination of the Python REPL and a Python module .py file with a markdown .md file thrown in between code sections. The simplest way to install Jupyter notebooks is to download and install the Anaconda distribution of Python. The Anaconda distribution of Python comes with Jupyter notebook included and no further installation steps are necessary. You can install of Anaconda in windows. Once it is installed, open the Anaconda Navigator to get started with jupyter Notebook. Here, launch the Jupyter Notebook. A Jupyter file browser will open in a web browser tab, you will see your base(home) directory. There in the upper right section, you can click the New(dropdown) -> Python3 After that, a New tab of Jupyter notebook will open in you browser. Now, click on the Untitled -> Rename prompt will open -> Rename your file. You can also click the code dropdown and select the Markdown field for explanation(paragraphs) or the Heading field for heading. Then write some code in the Notebook. To Run the code, press the Run button as depicted in the picture above. So, this is our code: Click on File -> Download as -> Notebook(.ipynb)Make a new repository into Github.Click Add Files -> Create New File.Browse through your directory and upload your file (example filename: GeeksForGeeks.ipynb) and click Open.Commit the changes. Click on File -> Download as -> Notebook(.ipynb) Make a new repository into Github. Click Add Files -> Create New File. Browse through your directory and upload your file (example filename: GeeksForGeeks.ipynb) and click Open. Commit the changes. Note: Git should be installed in the system. Open the download location of the file (example filename: GeeksForGeeks.ipynb) in command prompt. Then, make a new repository in GitHub. And use the below commands in command prompt: 1. git init 2. git add README.md 3. git add GeeksForGeeks.ipynb 4. git commit -m "notebook first commit" 5. git remote add origin https://github.com/{Your repo}/GeeksForGeeks.git 6. git push -u origin master Great! Now you have uploaded your first Notebook Code into GitHub. pavanmarri varshagumber28 python-utility Git Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference Between Git Push Origin and Git Push Origin Master How to Push Git Branch to Remote? How to Export Eclipse projects to GitHub? Git - Difference Between Git Fetch and Git Pull Merge Conflicts and How to handle them Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24557, "s": 24529, "text": "\n05 Aug, 2021" }, { "code": null, "e": 24854, "s": 24557, "text": "A Jupyter notebook is neither a simple text editor nor a full-featured IDE, rather it is an electronic file which contains both programming code and text descriptions. It can also contain embedded charts, plots, images, videos, and links. They run in a web browser like Firefox or Google Chrome. " }, { "code": null, "e": 25180, "s": 24854, "text": "They can contain code of various programming languages, though are mainly popular for Python with .py extension, they also support Markdowns with .md extension. One way to think of a Jupyter notebook is as a combination of the Python REPL and a Python module .py file with a markdown .md file thrown in between code sections." }, { "code": null, "e": 25413, "s": 25180, "text": "The simplest way to install Jupyter notebooks is to download and install the Anaconda distribution of Python. The Anaconda distribution of Python comes with Jupyter notebook included and no further installation steps are necessary. " }, { "code": null, "e": 25453, "s": 25413, "text": "You can install of Anaconda in windows." }, { "code": null, "e": 25542, "s": 25453, "text": "Once it is installed, open the Anaconda Navigator to get started with jupyter Notebook. " }, { "code": null, "e": 25577, "s": 25542, "text": "Here, launch the Jupyter Notebook." }, { "code": null, "e": 25673, "s": 25577, "text": "A Jupyter file browser will open in a web browser tab, you will see your base(home) directory. " }, { "code": null, "e": 25750, "s": 25673, "text": "There in the upper right section, you can click the New(dropdown) -> Python3" }, { "code": null, "e": 25818, "s": 25750, "text": "After that, a New tab of Jupyter notebook will open in you browser." }, { "code": null, "e": 25893, "s": 25818, "text": "Now, click on the Untitled -> Rename prompt will open -> Rename your file." }, { "code": null, "e": 26022, "s": 25893, "text": "You can also click the code dropdown and select the Markdown field for explanation(paragraphs) or the Heading field for heading." }, { "code": null, "e": 26133, "s": 26022, "text": "Then write some code in the Notebook. To Run the code, press the Run button as depicted in the picture above. " }, { "code": null, "e": 26155, "s": 26133, "text": "So, this is our code:" }, { "code": null, "e": 26398, "s": 26155, "text": "Click on File -> Download as -> Notebook(.ipynb)Make a new repository into Github.Click Add Files -> Create New File.Browse through your directory and upload your file (example filename: GeeksForGeeks.ipynb) and click Open.Commit the changes." }, { "code": null, "e": 26447, "s": 26398, "text": "Click on File -> Download as -> Notebook(.ipynb)" }, { "code": null, "e": 26482, "s": 26447, "text": "Make a new repository into Github." }, { "code": null, "e": 26518, "s": 26482, "text": "Click Add Files -> Create New File." }, { "code": null, "e": 26625, "s": 26518, "text": "Browse through your directory and upload your file (example filename: GeeksForGeeks.ipynb) and click Open." }, { "code": null, "e": 26645, "s": 26625, "text": "Commit the changes." }, { "code": null, "e": 26690, "s": 26645, "text": "Note: Git should be installed in the system." }, { "code": null, "e": 26788, "s": 26690, "text": "Open the download location of the file (example filename: GeeksForGeeks.ipynb) in command prompt." }, { "code": null, "e": 26873, "s": 26788, "text": "Then, make a new repository in GitHub. And use the below commands in command prompt:" }, { "code": null, "e": 27086, "s": 26873, "text": "1. git init\n2. git add README.md \n3. git add GeeksForGeeks.ipynb\n4. git commit -m \"notebook first commit\" \n5. git remote add origin https://github.com/{Your repo}/GeeksForGeeks.git \n6. git push -u origin master " }, { "code": null, "e": 27153, "s": 27086, "text": "Great! Now you have uploaded your first Notebook Code into GitHub." }, { "code": null, "e": 27164, "s": 27153, "text": "pavanmarri" }, { "code": null, "e": 27179, "s": 27164, "text": "varshagumber28" }, { "code": null, "e": 27194, "s": 27179, "text": "python-utility" }, { "code": null, "e": 27198, "s": 27194, "text": "Git" }, { "code": null, "e": 27205, "s": 27198, "text": "Python" }, { "code": null, "e": 27303, "s": 27205, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27312, "s": 27303, "text": "Comments" }, { "code": null, "e": 27325, "s": 27312, "text": "Old Comments" }, { "code": null, "e": 27387, "s": 27325, "text": "Difference Between Git Push Origin and Git Push Origin Master" }, { "code": null, "e": 27421, "s": 27387, "text": "How to Push Git Branch to Remote?" }, { "code": null, "e": 27463, "s": 27421, "text": "How to Export Eclipse projects to GitHub?" }, { "code": null, "e": 27511, "s": 27463, "text": "Git - Difference Between Git Fetch and Git Pull" }, { "code": null, "e": 27550, "s": 27511, "text": "Merge Conflicts and How to handle them" }, { "code": null, "e": 27578, "s": 27550, "text": "Read JSON file using Python" }, { "code": null, "e": 27628, "s": 27578, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 27650, "s": 27628, "text": "Python map() function" } ]
ArrayDeque peek() Method in Java - GeeksforGeeks
10 Dec, 2018 The java.util.ArrayDeque.peek() method in Java is used to retrieve or fetch the element at the head of the Deque. The element retrieved does not get deleted or removed from the Queue instead the method just returns it. If no element is present in the deque then Null is returned. Syntax: Array_Deque.peek() Parameters: The method does not take any parameter. Return Value: The method returns the element at the head of the Deque. Below programs illustrate the Java.util.ArrayDeque.peek() method:Program 1: // Java code to illustrate peek()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque ArrayDeque<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add("Welcome"); de_que.add("To"); de_que.add("Geeks"); de_que.add("4"); de_que.add("Geeks"); // Displaying the ArrayDeque System.out.println("Initial ArrayDeque: " + de_que); // Displaying the head System.out.println("The element at head is: " + de_que.peek()); // Displaying the ArrayDeque after operation System.out.println("Final ArrayDeque: " + de_que); }} Initial ArrayDeque: [Welcome, To, Geeks, 4, Geeks] The element at head is: Welcome Final ArrayDeque: [Welcome, To, Geeks, 4, Geeks] Program 2: // Java code to illustrate peek()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque ArrayDeque<Integer> de_que = new ArrayDeque<Integer>(); // Use add() method to add elements into the Deque de_que.add(10); de_que.add(15); de_que.add(30); de_que.add(20); de_que.add(5); // Displaying the ArrayDeque System.out.println("Initial ArrayDeque: " + de_que); // Displaying the head System.out.println("The element at head is: " + de_que.peek()); // Displaying the ArrayDeque after operation System.out.println("Final ArrayDeque: " + de_que); }} Initial ArrayDeque: [10, 15, 30, 20, 5] The element at head is: 10 Final ArrayDeque: [10, 15, 30, 20, 5] Program 3: For an empty deque: // Java code to illustrate peek()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque ArrayDeque<Integer> de_que = new ArrayDeque<Integer>(); // Displaying the ArrayDeque System.out.println("ArrayDeque: " + de_que); // Displaying the head System.out.println("The element at head is: " + de_que.peek()); }} ArrayDeque: [] The element at head is: null Java - util package Java-ArrayDeque Java-Collections Java-Functions Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java HashMap in Java with Examples Object Oriented Programming (OOPs) Concept in Java Initialize an ArrayList in Java Interfaces in Java How to iterate any Map in Java
[ { "code": null, "e": 24120, "s": 24092, "text": "\n10 Dec, 2018" }, { "code": null, "e": 24400, "s": 24120, "text": "The java.util.ArrayDeque.peek() method in Java is used to retrieve or fetch the element at the head of the Deque. The element retrieved does not get deleted or removed from the Queue instead the method just returns it. If no element is present in the deque then Null is returned." }, { "code": null, "e": 24408, "s": 24400, "text": "Syntax:" }, { "code": null, "e": 24427, "s": 24408, "text": "Array_Deque.peek()" }, { "code": null, "e": 24479, "s": 24427, "text": "Parameters: The method does not take any parameter." }, { "code": null, "e": 24550, "s": 24479, "text": "Return Value: The method returns the element at the head of the Deque." }, { "code": null, "e": 24626, "s": 24550, "text": "Below programs illustrate the Java.util.ArrayDeque.peek() method:Program 1:" }, { "code": "// Java code to illustrate peek()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque ArrayDeque<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add(\"Welcome\"); de_que.add(\"To\"); de_que.add(\"Geeks\"); de_que.add(\"4\"); de_que.add(\"Geeks\"); // Displaying the ArrayDeque System.out.println(\"Initial ArrayDeque: \" + de_que); // Displaying the head System.out.println(\"The element at head is: \" + de_que.peek()); // Displaying the ArrayDeque after operation System.out.println(\"Final ArrayDeque: \" + de_que); }}", "e": 25414, "s": 24626, "text": null }, { "code": null, "e": 25547, "s": 25414, "text": "Initial ArrayDeque: [Welcome, To, Geeks, 4, Geeks]\nThe element at head is: Welcome\nFinal ArrayDeque: [Welcome, To, Geeks, 4, Geeks]\n" }, { "code": null, "e": 25558, "s": 25547, "text": "Program 2:" }, { "code": "// Java code to illustrate peek()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque ArrayDeque<Integer> de_que = new ArrayDeque<Integer>(); // Use add() method to add elements into the Deque de_que.add(10); de_que.add(15); de_que.add(30); de_que.add(20); de_que.add(5); // Displaying the ArrayDeque System.out.println(\"Initial ArrayDeque: \" + de_que); // Displaying the head System.out.println(\"The element at head is: \" + de_que.peek()); // Displaying the ArrayDeque after operation System.out.println(\"Final ArrayDeque: \" + de_que); }}", "e": 26327, "s": 25558, "text": null }, { "code": null, "e": 26433, "s": 26327, "text": "Initial ArrayDeque: [10, 15, 30, 20, 5]\nThe element at head is: 10\nFinal ArrayDeque: [10, 15, 30, 20, 5]\n" }, { "code": null, "e": 26464, "s": 26433, "text": "Program 3: For an empty deque:" }, { "code": "// Java code to illustrate peek()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque ArrayDeque<Integer> de_que = new ArrayDeque<Integer>(); // Displaying the ArrayDeque System.out.println(\"ArrayDeque: \" + de_que); // Displaying the head System.out.println(\"The element at head is: \" + de_que.peek()); }}", "e": 26896, "s": 26464, "text": null }, { "code": null, "e": 26941, "s": 26896, "text": "ArrayDeque: []\nThe element at head is: null\n" }, { "code": null, "e": 26961, "s": 26941, "text": "Java - util package" }, { "code": null, "e": 26977, "s": 26961, "text": "Java-ArrayDeque" }, { "code": null, "e": 26994, "s": 26977, "text": "Java-Collections" }, { "code": null, "e": 27009, "s": 26994, "text": "Java-Functions" }, { "code": null, "e": 27014, "s": 27009, "text": "Java" }, { "code": null, "e": 27019, "s": 27014, "text": "Java" }, { "code": null, "e": 27036, "s": 27019, "text": "Java-Collections" }, { "code": null, "e": 27134, "s": 27036, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27143, "s": 27134, "text": "Comments" }, { "code": null, "e": 27156, "s": 27143, "text": "Old Comments" }, { "code": null, "e": 27171, "s": 27156, "text": "Arrays in Java" }, { "code": null, "e": 27215, "s": 27171, "text": "Split() String method in Java with examples" }, { "code": null, "e": 27237, "s": 27215, "text": "For-each loop in Java" }, { "code": null, "e": 27273, "s": 27237, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 27298, "s": 27273, "text": "Reverse a string in Java" }, { "code": null, "e": 27328, "s": 27298, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27379, "s": 27328, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27411, "s": 27379, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27430, "s": 27411, "text": "Interfaces in Java" } ]
Object Detection with YOLOv3 using Keras | by Renu Khandelwal | Towards Data Science
Part 1- CNN, R-CNN, Fast R-CNN, Faster R-CNN Part 2 —Understanding YOLO, YOLOv2, YOLO v3 This is the third article in the series where we will predict the bounding boxes and classes using YOLOv3. Code available at github You only look once (YOLO) at an image to predict what objects are present and where they are present using a single convolutional network. YOLO predicts multiple bounding boxes and class probabilities for those boxes. This code will use pre-trained weights from yolo v3 and then predict the bounding boxes and class probabilities using keras library The code is strongly inspired by experiencor’s keras-yolo3 project for performing object detection with a YOLOv3 model. Code is broken code into simple steps to predict the bounding boxes and classes using yolov3 model. The original code is available at github from Huynh Ngoc Anh.Yolo3 pre-trained weights can be downloaded from YOLOv3 pre-trained weights. YOLOv3 model uses pre-trained weights for standard object detection problems such as a kangaroo dataset, racoon dataset, red blood cell detection, and others. This model will be used for object detection on new images. Step 1: Importing the required libraries import osimport scipy.ioimport scipy.miscimport numpy as npimport pandas as pdimport PILimport structimport cv2from numpy import expand_dimsimport tensorflow as tffrom skimage.transform import resizefrom keras import backend as Kfrom keras.layers import Input, Lambda, Conv2D, BatchNormalization, LeakyReLU, ZeroPadding2D, UpSampling2Dfrom keras.models import load_model, Modelfrom keras.layers.merge import add, concatenatefrom keras.preprocessing.image import load_imgfrom keras.preprocessing.image import img_to_arrayimport matplotlib.pyplot as pltfrom matplotlib.pyplot import imshowfrom matplotlib.patches import Rectangle%matplotlib inline Step 2: Create a class WeightReader to load the pre-trained weights for yolov3 WeightReader class will parse the file and load the model weights into memory to set it in our Keras model. # class to load the pretrained Weightsclass WeightReader: def __init__(self, weight_file): with open(weight_file, 'rb') as w_f: major, = struct.unpack('i', w_f.read(4)) minor, = struct.unpack('i', w_f.read(4)) revision, = struct.unpack('i', w_f.read(4))if (major*10 + minor) >= 2 and major < 1000 and minor < 1000: w_f.read(8) else: w_f.read(4)transpose = (major > 1000) or (minor > 1000) binary = w_f.read()self.offset = 0 self.all_weights = np.frombuffer(binary, dtype='float32') def read_bytes(self, size): self.offset = self.offset + size return self.all_weights[self.offset-size:self.offset]def load_weights(self, model): for i in range(106): try: conv_layer = model.get_layer('conv_' + str(i)) print("loading weights of convolution #" + str(i))if i not in [81, 93, 105]: norm_layer = model.get_layer('bnorm_' + str(i))size = np.prod(norm_layer.get_weights()[0].shape)beta = self.read_bytes(size) # bias gamma = self.read_bytes(size) # scale mean = self.read_bytes(size) # mean var = self.read_bytes(size) # varianceweights = norm_layer.set_weights([gamma, beta, mean, var])if len(conv_layer.get_weights()) > 1: bias = self.read_bytes(np.prod(conv_layer.get_weights()[1].shape)) kernel = self.read_bytes(np.prod(conv_layer.get_weights()[0].shape)) kernel = kernel.reshape(list(reversed(conv_layer.get_weights()[0].shape))) kernel = kernel.transpose([2,3,1,0]) conv_layer.set_weights([kernel, bias]) else: kernel = self.read_bytes(np.prod(conv_layer.get_weights()[0].shape)) kernel = kernel.reshape(list(reversed(conv_layer.get_weights()[0].shape))) kernel = kernel.transpose([2,3,1,0]) conv_layer.set_weights([kernel]) except ValueError: print("no convolution #" + str(i)) def reset(self): self.offset = 0 Step 3: Create the Yolo v3 model. We first create a function for creating the Convolutional blocks def _conv_block(inp, convs, skip=True): x = inp count = 0 for conv in convs: if count == (len(convs) - 2) and skip: skip_connection = x count += 1 if conv['stride'] > 1: x = ZeroPadding2D(((1,0),(1,0)))(x) # peculiar padding as darknet prefer left and top x = Conv2D(conv['filter'], conv['kernel'], strides=conv['stride'], padding='valid' if conv['stride'] > 1 else 'same', # peculiar padding as darknet prefer left and top name='conv_' + str(conv['layer_idx']), use_bias=False if conv['bnorm'] else True)(x) if conv['bnorm']: x = BatchNormalization(epsilon=0.001, name='bnorm_' + str(conv['layer_idx']))(x) if conv['leaky']: x = LeakyReLU(alpha=0.1, name='leaky_' + str(conv['layer_idx']))(x)return add([skip_connection, x]) if skip else x Next, we create a Darknet with 108 convolutional layers. I am running it on CPU, On a GPU it is almost 500 times faster # creating the YOLO modeldef make_yolov3_model(): input_image = Input(shape=(None, None, 3))# Layer 0 => 4 x = _conv_block(input_image, [{'filter': 32, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 0}, {'filter': 64, 'kernel': 3, 'stride': 2, 'bnorm': True, 'leaky': True, 'layer_idx': 1}, {'filter': 32, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 2}, {'filter': 64, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 3}])# Layer 5 => 8 x = _conv_block(x, [{'filter': 128, 'kernel': 3, 'stride': 2, 'bnorm': True, 'leaky': True, 'layer_idx': 5}, {'filter': 64, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 6}, {'filter': 128, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 7}])# Layer 9 => 11 x = _conv_block(x, [{'filter': 64, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 9}, {'filter': 128, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 10}])# Layer 12 => 15 x = _conv_block(x, [{'filter': 256, 'kernel': 3, 'stride': 2, 'bnorm': True, 'leaky': True, 'layer_idx': 12}, {'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 13}, {'filter': 256, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 14}])# Layer 16 => 36 for i in range(7): x = _conv_block(x, [{'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 16+i*3}, {'filter': 256, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 17+i*3}]) skip_36 = x # Layer 37 => 40 x = _conv_block(x, [{'filter': 512, 'kernel': 3, 'stride': 2, 'bnorm': True, 'leaky': True, 'layer_idx': 37}, {'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 38}, {'filter': 512, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 39}])# Layer 41 => 61 for i in range(7): x = _conv_block(x, [{'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 41+i*3}, {'filter': 512, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 42+i*3}]) skip_61 = x # Layer 62 => 65 x = _conv_block(x, [{'filter': 1024, 'kernel': 3, 'stride': 2, 'bnorm': True, 'leaky': True, 'layer_idx': 62}, {'filter': 512, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 63}, {'filter': 1024, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 64}])# Layer 66 => 74 for i in range(3): x = _conv_block(x, [{'filter': 512, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 66+i*3}, {'filter': 1024, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 67+i*3}]) # Layer 75 => 79 x = _conv_block(x, [{'filter': 512, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 75}, {'filter': 1024, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 76}, {'filter': 512, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 77}, {'filter': 1024, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 78}, {'filter': 512, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 79}], skip=False)# Layer 80 => 82 yolo_82 = _conv_block(x, [{'filter': 1024, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 80}, {'filter': 255, 'kernel': 1, 'stride': 1, 'bnorm': False, 'leaky': False, 'layer_idx': 81}], skip=False)# Layer 83 => 86 x = _conv_block(x, [{'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 84}], skip=False) x = UpSampling2D(2)(x) x = concatenate([x, skip_61])# Layer 87 => 91 x = _conv_block(x, [{'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 87}, {'filter': 512, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 88}, {'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 89}, {'filter': 512, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 90}, {'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 91}], skip=False)# Layer 92 => 94 yolo_94 = _conv_block(x, [{'filter': 512, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 92}, {'filter': 255, 'kernel': 1, 'stride': 1, 'bnorm': False, 'leaky': False, 'layer_idx': 93}], skip=False)# Layer 95 => 98 x = _conv_block(x, [{'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 96}], skip=False) x = UpSampling2D(2)(x) x = concatenate([x, skip_36])# Layer 99 => 106 yolo_106 = _conv_block(x, [{'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 99}, {'filter': 256, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 100}, {'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 101}, {'filter': 256, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 102}, {'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 103}, {'filter': 256, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 104}, {'filter': 255, 'kernel': 1, 'stride': 1, 'bnorm': False, 'leaky': False, 'layer_idx': 105}], skip=False)model = Model(input_image, [yolo_82, yolo_94, yolo_106]) return model Step 4: we now create the yolo model and load the pre-trained weights # create the yolo v3yolov3 = make_yolov3_model()# load the weights trained on COCO into the modelweight_reader = WeightReader(‘yolov3.weights’)weight_reader.load_weights(yolov3) Step 5: Setting up the variables. Input image size for Yolov3 is 416 x 416 which we set using net_h and net_w. Object threshold is set to 0.5 and Non-max suppression threshold is set to 0.45 We set the anchor boxes and then define the 80 labels for the Common Objects in Context (COCO) model to predict net_h, net_w = 416, 416obj_thresh, nms_thresh = 0.5, 0.45anchors = [[116,90, 156,198, 373,326], [30,61, 62,45, 59,119], [10,13, 16,30, 33,23]]labels = [“person”, “bicycle”, “car”, “motorbike”, “aeroplane”, “bus”, “train”, “truck”, “boat”, “traffic light”, “fire hydrant”, “stop sign”, “parking meter”, “bench”, “bird”, “cat”, “dog”, “horse”, “sheep”, “cow”, “elephant”, “bear”, “zebra”, “giraffe”, \ “backpack”, “umbrella”, “handbag”, “tie”, “suitcase”, “frisbee”, “skis”, “snowboard”, “sports ball”, “kite”, “baseball bat”, “baseball glove”, “skateboard”, “surfboard”, “tennis racket”, “bottle”, “wine glass”, “cup”, “fork”, “knife”, “spoon”, “bowl”, “banana”, “apple”, “sandwich”, “orange”, “broccoli”, “carrot”, “hot dog”, “pizza”, “donut”, “cake”, “chair”, “sofa”, “pottedplant”, “bed”, “diningtable”, “toilet”, “tvmonitor”, “laptop”, “mouse”, \ “remote”, “keyboard”, “cell phone”, “microwave”, “oven”, “toaster”, “sink”, “refrigerator”, “book”, “clock”, “vase”, “scissors”, “teddy bear”, “hair drier”, “toothbrush”] Step 6: Loading the image into the right input shape of 416 x 416 from numpy import expand_dimsdef load_image_pixels(filename, shape): # load the image to get its shape image = load_img(filename) width, height = image.size # load the image with the required size image = load_img(filename, target_size=shape) # convert to numpy array image = img_to_array(image) # scale pixel values to [0, 1] image = image.astype(‘float32’) image /= 255.0 # add a dimension so that we have one sample image = expand_dims(image, 0) return image, width, height Step 7: Create a class for the Bounding Box. BoundBox defines the corners of each bounding box in the context of the input image shape and class probabilities. class BoundBox: def __init__(self, xmin, ymin, xmax, ymax, objness = None, classes = None): self.xmin = xmin self.ymin = ymin self.xmax = xmax self.ymax = ymax self.objness = objness self.classes = classesself.label = -1 self.score = -1def get_label(self): if self.label == -1: self.label = np.argmax(self.classes) return self.label def get_score(self): if self.score == -1: self.score = self.classes[self.get_label()] return self.score Step 8: Define functions for Interval overlap — checks if two intervals overlap. Two intervals do not overlap when one ends before the other begins. Intersection over Union(IoU) of two boxes Non-Max Suppression which takes boxes that have the presence of objects in them along with non-max threshold as a parameter Sigmoid function def _sigmoid(x): return 1. / (1. + np.exp(-x))def _interval_overlap(interval_a, interval_b): x1, x2 = interval_a x3, x4 = interval_bif x3 < x1: if x4 < x1: return 0 else: return min(x2,x4) — x1 else: if x2 < x3: return 0 else: return min(x2,x4) — x3 def bbox_iou(box1, box2): intersect_w = _interval_overlap([box1.xmin, box1.xmax], [box2.xmin, box2.xmax]) intersect_h = _interval_overlap([box1.ymin, box1.ymax], [box2.ymin, box2.ymax]) intersect = intersect_w * intersect_hw1, h1 = box1.xmax-box1.xmin, box1.ymax-box1.ymin w2, h2 = box2.xmax-box2.xmin, box2.ymax-box2.ymin union = w1*h1 + w2*h2 — intersect return float(intersect) / uniondef do_nms(boxes, nms_thresh): if len(boxes) > 0: nb_class = len(boxes[0].classes) else: return for c in range(nb_class): sorted_indices = np.argsort([-box.classes[c] for box in boxes])for i in range(len(sorted_indices)): index_i = sorted_indices[i]if boxes[index_i].classes[c] == 0: continuefor j in range(i+1, len(sorted_indices)): index_j = sorted_indices[j]if bbox_iou(boxes[index_i], boxes[index_j]) >= nms_thresh: boxes[index_j].classes[c] = 0 Step 9: Decode the output of the network. We will iterate through each of the each one of the NumPy arrays, one at a time and decode the candidate bounding boxes and class predictions based on the object threshold. The first 4 elements will be the coordinates of the Bounding box, 5th element will be object score followed by the class probabilities def decode_netout(netout, anchors, obj_thresh, net_h, net_w): grid_h, grid_w = netout.shape[:2] nb_box = 3 netout = netout.reshape((grid_h, grid_w, nb_box, -1)) nb_class = netout.shape[-1] — 5boxes = [] netout[..., :2] = _sigmoid(netout[..., :2]) netout[..., 4:] = _sigmoid(netout[..., 4:]) netout[..., 5:] = netout[..., 4][..., np.newaxis] * netout[..., 5:] netout[..., 5:] *= netout[..., 5:] > obj_threshfor i in range(grid_h*grid_w): row = i / grid_w col = i % grid_w for b in range(nb_box): # 4th element is objectness score objectness = netout[int(row)][int(col)][b][4] #objectness = netout[..., :4] if(objectness.all() <= obj_thresh): continue # first 4 elements are x, y, w, and h x, y, w, h = netout[int(row)][int(col)][b][:4]x = (col + x) / grid_w # center position, unit: image width y = (row + y) / grid_h # center position, unit: image height w = anchors[2 * b + 0] * np.exp(w) / net_w # unit: image width h = anchors[2 * b + 1] * np.exp(h) / net_h # unit: image height # last elements are class probabilities classes = netout[int(row)][col][b][5:] box = BoundBox(x-w/2, y-h/2, x+w/2, y+h/2, objectness, classes) boxes.append(box)return boxes Step 10: Correcting the Yolo boxes. We have the bounding boxes but they need to be stretched back into the shape of the original image. This will allow plotting the original image and draw the bounding boxes, detecting real objects. def correct_yolo_boxes(boxes, image_h, image_w, net_h, net_w): if (float(net_w)/image_w) < (float(net_h)/image_h): new_w = net_w new_h = (image_h*net_w)/image_w else: new_h = net_w new_w = (image_w*net_h)/image_h for i in range(len(boxes)): x_offset, x_scale = (net_w — new_w)/2./net_w, float(new_w)/net_w y_offset, y_scale = (net_h — new_h)/2./net_h, float(new_h)/net_h boxes[i].xmin = int((boxes[i].xmin — x_offset) / x_scale * image_w) boxes[i].xmax = int((boxes[i].xmax — x_offset) / x_scale * image_w) boxes[i].ymin = int((boxes[i].ymin — y_offset) / y_scale * image_h) boxes[i].ymax = int((boxes[i].ymax — y_offset) / y_scale * image_h) Step 11: Get all boxes above the specified threshold. get_boxes function takes the list of boxes, labels, and threshold as arguments and returns parallel lists of boxes, labels, and scores. def get_boxes(boxes, labels, thresh): v_boxes, v_labels, v_scores = list(), list(), list() # enumerate all boxes for box in boxes: # enumerate all possible labels for i in range(len(labels)): # check if the threshold for this label is high enough if box.classes[i] > thresh: v_boxes.append(box) v_labels.append(labels[i]) v_scores.append(box.classes[i]*100) # don't break, many labels may trigger for one box return v_boxes, v_labels, v_scores Step 12: Drawing a white box around the object present in the image. from matplotlib.patches import Rectangledef draw_boxes(filename, v_boxes, v_labels, v_scores): # load the image data = plt.imread(filename) # plot the image plt.imshow(data) # get the context for drawing boxes ax = plt.gca() # plot each box for i in range(len(v_boxes)):box = v_boxes[i] # get coordinates y1, x1, y2, x2 = box.ymin, box.xmin, box.ymax, box.xmax # calculate width and height of the box width, height = x2 - x1, y2 - y1 # create the shape rect = Rectangle((x1, y1), width, height, fill=False, color='red') # draw the box ax.add_patch(rect) # draw text and score in top left corner label = "%s (%.3f)" % (v_labels[i], v_scores[i]) plt.text(x1, y1, label, color='red') # show the plotplt.show() Finally, we tie the code to make the prediction on a new image. First we load the image into the input shape of 416 x 416 using load_image_pixels() function. Predict the boxes suing yolov3 predict () method Yolov3 model will be predicting multiple boxes for the same object. We then decode the candidate bounding boxes and class predictions based on the object threshold using decode_netout() function we correct the bounding boxes by using correct_yolo_boxes() function to be stretched back into the shape of the original image Bounding boxes will be filtered based on the overlap defined by IoU and then applying the non-max suppression using the do_nms() function. we get the boxes using get_boxes() which are above the specified class threshold of 0.6 and the then plot the boxes using draw_boxes() function on the image. # define our new imagephoto_filename = 'eagle.png'# load and prepare imageimage, image_w, image_h = load_image_pixels(photo_filename, (net_w, net_w))# make predictionyolos = yolov3.predict(image)# summarize the shape of the list of arraysprint([a.shape for a in yolos])# define the anchorsanchors = [[116,90, 156,198, 373,326], [30,61, 62,45, 59,119], [10,13, 16,30, 33,23]]# define the probability threshold for detected objectsclass_threshold = 0.6boxes = list()for i in range(len(yolos)): # decode the output of the network boxes += decode_netout(yolos[i][0], anchors[i], obj_thresh, nms_thresh, net_h, net_w)# correct the sizes of the bounding boxescorrect_yolo_boxes(boxes, image_h, image_w, net_h, net_w)# suppress non-maximal boxesdo_nms(boxes, nms_thresh)# get the details of the detected objectsv_boxes, v_labels, v_scores = get_boxes(boxes, labels, class_threshold)# summarize what we foundfor i in range(len(v_boxes)): print(v_labels[i], v_scores[i])# draw what we founddraw_boxes(photo_filename, v_boxes, v_labels, v_scores) Original image Image after plotting the bounding box and class Code is available at Github YOLO V3 paper by Joseph Redmon, Ali Farhadi
[ { "code": null, "e": 217, "s": 172, "text": "Part 1- CNN, R-CNN, Fast R-CNN, Faster R-CNN" }, { "code": null, "e": 261, "s": 217, "text": "Part 2 —Understanding YOLO, YOLOv2, YOLO v3" }, { "code": null, "e": 393, "s": 261, "text": "This is the third article in the series where we will predict the bounding boxes and classes using YOLOv3. Code available at github" }, { "code": null, "e": 611, "s": 393, "text": "You only look once (YOLO) at an image to predict what objects are present and where they are present using a single convolutional network. YOLO predicts multiple bounding boxes and class probabilities for those boxes." }, { "code": null, "e": 743, "s": 611, "text": "This code will use pre-trained weights from yolo v3 and then predict the bounding boxes and class probabilities using keras library" }, { "code": null, "e": 1101, "s": 743, "text": "The code is strongly inspired by experiencor’s keras-yolo3 project for performing object detection with a YOLOv3 model. Code is broken code into simple steps to predict the bounding boxes and classes using yolov3 model. The original code is available at github from Huynh Ngoc Anh.Yolo3 pre-trained weights can be downloaded from YOLOv3 pre-trained weights." }, { "code": null, "e": 1320, "s": 1101, "text": "YOLOv3 model uses pre-trained weights for standard object detection problems such as a kangaroo dataset, racoon dataset, red blood cell detection, and others. This model will be used for object detection on new images." }, { "code": null, "e": 1361, "s": 1320, "text": "Step 1: Importing the required libraries" }, { "code": null, "e": 2007, "s": 1361, "text": "import osimport scipy.ioimport scipy.miscimport numpy as npimport pandas as pdimport PILimport structimport cv2from numpy import expand_dimsimport tensorflow as tffrom skimage.transform import resizefrom keras import backend as Kfrom keras.layers import Input, Lambda, Conv2D, BatchNormalization, LeakyReLU, ZeroPadding2D, UpSampling2Dfrom keras.models import load_model, Modelfrom keras.layers.merge import add, concatenatefrom keras.preprocessing.image import load_imgfrom keras.preprocessing.image import img_to_arrayimport matplotlib.pyplot as pltfrom matplotlib.pyplot import imshowfrom matplotlib.patches import Rectangle%matplotlib inline" }, { "code": null, "e": 2086, "s": 2007, "text": "Step 2: Create a class WeightReader to load the pre-trained weights for yolov3" }, { "code": null, "e": 2194, "s": 2086, "text": "WeightReader class will parse the file and load the model weights into memory to set it in our Keras model." }, { "code": null, "e": 4431, "s": 2194, "text": "# class to load the pretrained Weightsclass WeightReader: def __init__(self, weight_file): with open(weight_file, 'rb') as w_f: major, = struct.unpack('i', w_f.read(4)) minor, = struct.unpack('i', w_f.read(4)) revision, = struct.unpack('i', w_f.read(4))if (major*10 + minor) >= 2 and major < 1000 and minor < 1000: w_f.read(8) else: w_f.read(4)transpose = (major > 1000) or (minor > 1000) binary = w_f.read()self.offset = 0 self.all_weights = np.frombuffer(binary, dtype='float32') def read_bytes(self, size): self.offset = self.offset + size return self.all_weights[self.offset-size:self.offset]def load_weights(self, model): for i in range(106): try: conv_layer = model.get_layer('conv_' + str(i)) print(\"loading weights of convolution #\" + str(i))if i not in [81, 93, 105]: norm_layer = model.get_layer('bnorm_' + str(i))size = np.prod(norm_layer.get_weights()[0].shape)beta = self.read_bytes(size) # bias gamma = self.read_bytes(size) # scale mean = self.read_bytes(size) # mean var = self.read_bytes(size) # varianceweights = norm_layer.set_weights([gamma, beta, mean, var])if len(conv_layer.get_weights()) > 1: bias = self.read_bytes(np.prod(conv_layer.get_weights()[1].shape)) kernel = self.read_bytes(np.prod(conv_layer.get_weights()[0].shape)) kernel = kernel.reshape(list(reversed(conv_layer.get_weights()[0].shape))) kernel = kernel.transpose([2,3,1,0]) conv_layer.set_weights([kernel, bias]) else: kernel = self.read_bytes(np.prod(conv_layer.get_weights()[0].shape)) kernel = kernel.reshape(list(reversed(conv_layer.get_weights()[0].shape))) kernel = kernel.transpose([2,3,1,0]) conv_layer.set_weights([kernel]) except ValueError: print(\"no convolution #\" + str(i)) def reset(self): self.offset = 0" }, { "code": null, "e": 4465, "s": 4431, "text": "Step 3: Create the Yolo v3 model." }, { "code": null, "e": 4530, "s": 4465, "text": "We first create a function for creating the Convolutional blocks" }, { "code": null, "e": 5439, "s": 4530, "text": "def _conv_block(inp, convs, skip=True): x = inp count = 0 for conv in convs: if count == (len(convs) - 2) and skip: skip_connection = x count += 1 if conv['stride'] > 1: x = ZeroPadding2D(((1,0),(1,0)))(x) # peculiar padding as darknet prefer left and top x = Conv2D(conv['filter'], conv['kernel'], strides=conv['stride'], padding='valid' if conv['stride'] > 1 else 'same', # peculiar padding as darknet prefer left and top name='conv_' + str(conv['layer_idx']), use_bias=False if conv['bnorm'] else True)(x) if conv['bnorm']: x = BatchNormalization(epsilon=0.001, name='bnorm_' + str(conv['layer_idx']))(x) if conv['leaky']: x = LeakyReLU(alpha=0.1, name='leaky_' + str(conv['layer_idx']))(x)return add([skip_connection, x]) if skip else x" }, { "code": null, "e": 5559, "s": 5439, "text": "Next, we create a Darknet with 108 convolutional layers. I am running it on CPU, On a GPU it is almost 500 times faster" }, { "code": null, "e": 11854, "s": 5559, "text": "# creating the YOLO modeldef make_yolov3_model(): input_image = Input(shape=(None, None, 3))# Layer 0 => 4 x = _conv_block(input_image, [{'filter': 32, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 0}, {'filter': 64, 'kernel': 3, 'stride': 2, 'bnorm': True, 'leaky': True, 'layer_idx': 1}, {'filter': 32, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 2}, {'filter': 64, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 3}])# Layer 5 => 8 x = _conv_block(x, [{'filter': 128, 'kernel': 3, 'stride': 2, 'bnorm': True, 'leaky': True, 'layer_idx': 5}, {'filter': 64, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 6}, {'filter': 128, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 7}])# Layer 9 => 11 x = _conv_block(x, [{'filter': 64, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 9}, {'filter': 128, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 10}])# Layer 12 => 15 x = _conv_block(x, [{'filter': 256, 'kernel': 3, 'stride': 2, 'bnorm': True, 'leaky': True, 'layer_idx': 12}, {'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 13}, {'filter': 256, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 14}])# Layer 16 => 36 for i in range(7): x = _conv_block(x, [{'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 16+i*3}, {'filter': 256, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 17+i*3}]) skip_36 = x # Layer 37 => 40 x = _conv_block(x, [{'filter': 512, 'kernel': 3, 'stride': 2, 'bnorm': True, 'leaky': True, 'layer_idx': 37}, {'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 38}, {'filter': 512, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 39}])# Layer 41 => 61 for i in range(7): x = _conv_block(x, [{'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 41+i*3}, {'filter': 512, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 42+i*3}]) skip_61 = x # Layer 62 => 65 x = _conv_block(x, [{'filter': 1024, 'kernel': 3, 'stride': 2, 'bnorm': True, 'leaky': True, 'layer_idx': 62}, {'filter': 512, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 63}, {'filter': 1024, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 64}])# Layer 66 => 74 for i in range(3): x = _conv_block(x, [{'filter': 512, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 66+i*3}, {'filter': 1024, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 67+i*3}]) # Layer 75 => 79 x = _conv_block(x, [{'filter': 512, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 75}, {'filter': 1024, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 76}, {'filter': 512, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 77}, {'filter': 1024, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 78}, {'filter': 512, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 79}], skip=False)# Layer 80 => 82 yolo_82 = _conv_block(x, [{'filter': 1024, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 80}, {'filter': 255, 'kernel': 1, 'stride': 1, 'bnorm': False, 'leaky': False, 'layer_idx': 81}], skip=False)# Layer 83 => 86 x = _conv_block(x, [{'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 84}], skip=False) x = UpSampling2D(2)(x) x = concatenate([x, skip_61])# Layer 87 => 91 x = _conv_block(x, [{'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 87}, {'filter': 512, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 88}, {'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 89}, {'filter': 512, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 90}, {'filter': 256, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 91}], skip=False)# Layer 92 => 94 yolo_94 = _conv_block(x, [{'filter': 512, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 92}, {'filter': 255, 'kernel': 1, 'stride': 1, 'bnorm': False, 'leaky': False, 'layer_idx': 93}], skip=False)# Layer 95 => 98 x = _conv_block(x, [{'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 96}], skip=False) x = UpSampling2D(2)(x) x = concatenate([x, skip_36])# Layer 99 => 106 yolo_106 = _conv_block(x, [{'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 99}, {'filter': 256, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 100}, {'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 101}, {'filter': 256, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 102}, {'filter': 128, 'kernel': 1, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 103}, {'filter': 256, 'kernel': 3, 'stride': 1, 'bnorm': True, 'leaky': True, 'layer_idx': 104}, {'filter': 255, 'kernel': 1, 'stride': 1, 'bnorm': False, 'leaky': False, 'layer_idx': 105}], skip=False)model = Model(input_image, [yolo_82, yolo_94, yolo_106]) return model" }, { "code": null, "e": 11924, "s": 11854, "text": "Step 4: we now create the yolo model and load the pre-trained weights" }, { "code": null, "e": 12102, "s": 11924, "text": "# create the yolo v3yolov3 = make_yolov3_model()# load the weights trained on COCO into the modelweight_reader = WeightReader(‘yolov3.weights’)weight_reader.load_weights(yolov3)" }, { "code": null, "e": 12136, "s": 12102, "text": "Step 5: Setting up the variables." }, { "code": null, "e": 12213, "s": 12136, "text": "Input image size for Yolov3 is 416 x 416 which we set using net_h and net_w." }, { "code": null, "e": 12293, "s": 12213, "text": "Object threshold is set to 0.5 and Non-max suppression threshold is set to 0.45" }, { "code": null, "e": 12405, "s": 12293, "text": "We set the anchor boxes and then define the 80 labels for the Common Objects in Context (COCO) model to predict" }, { "code": null, "e": 13426, "s": 12405, "text": "net_h, net_w = 416, 416obj_thresh, nms_thresh = 0.5, 0.45anchors = [[116,90, 156,198, 373,326], [30,61, 62,45, 59,119], [10,13, 16,30, 33,23]]labels = [“person”, “bicycle”, “car”, “motorbike”, “aeroplane”, “bus”, “train”, “truck”, “boat”, “traffic light”, “fire hydrant”, “stop sign”, “parking meter”, “bench”, “bird”, “cat”, “dog”, “horse”, “sheep”, “cow”, “elephant”, “bear”, “zebra”, “giraffe”, \\ “backpack”, “umbrella”, “handbag”, “tie”, “suitcase”, “frisbee”, “skis”, “snowboard”, “sports ball”, “kite”, “baseball bat”, “baseball glove”, “skateboard”, “surfboard”, “tennis racket”, “bottle”, “wine glass”, “cup”, “fork”, “knife”, “spoon”, “bowl”, “banana”, “apple”, “sandwich”, “orange”, “broccoli”, “carrot”, “hot dog”, “pizza”, “donut”, “cake”, “chair”, “sofa”, “pottedplant”, “bed”, “diningtable”, “toilet”, “tvmonitor”, “laptop”, “mouse”, \\ “remote”, “keyboard”, “cell phone”, “microwave”, “oven”, “toaster”, “sink”, “refrigerator”, “book”, “clock”, “vase”, “scissors”, “teddy bear”, “hair drier”, “toothbrush”]" }, { "code": null, "e": 13492, "s": 13426, "text": "Step 6: Loading the image into the right input shape of 416 x 416" }, { "code": null, "e": 13969, "s": 13492, "text": "from numpy import expand_dimsdef load_image_pixels(filename, shape): # load the image to get its shape image = load_img(filename) width, height = image.size # load the image with the required size image = load_img(filename, target_size=shape) # convert to numpy array image = img_to_array(image) # scale pixel values to [0, 1] image = image.astype(‘float32’) image /= 255.0 # add a dimension so that we have one sample image = expand_dims(image, 0) return image, width, height" }, { "code": null, "e": 14014, "s": 13969, "text": "Step 7: Create a class for the Bounding Box." }, { "code": null, "e": 14129, "s": 14014, "text": "BoundBox defines the corners of each bounding box in the context of the input image shape and class probabilities." }, { "code": null, "e": 14570, "s": 14129, "text": "class BoundBox: def __init__(self, xmin, ymin, xmax, ymax, objness = None, classes = None): self.xmin = xmin self.ymin = ymin self.xmax = xmax self.ymax = ymax self.objness = objness self.classes = classesself.label = -1 self.score = -1def get_label(self): if self.label == -1: self.label = np.argmax(self.classes) return self.label def get_score(self): if self.score == -1: self.score = self.classes[self.get_label()] return self.score" }, { "code": null, "e": 14599, "s": 14570, "text": "Step 8: Define functions for" }, { "code": null, "e": 14719, "s": 14599, "text": "Interval overlap — checks if two intervals overlap. Two intervals do not overlap when one ends before the other begins." }, { "code": null, "e": 14761, "s": 14719, "text": "Intersection over Union(IoU) of two boxes" }, { "code": null, "e": 14885, "s": 14761, "text": "Non-Max Suppression which takes boxes that have the presence of objects in them along with non-max threshold as a parameter" }, { "code": null, "e": 14902, "s": 14885, "text": "Sigmoid function" }, { "code": null, "e": 15994, "s": 14902, "text": "def _sigmoid(x): return 1. / (1. + np.exp(-x))def _interval_overlap(interval_a, interval_b): x1, x2 = interval_a x3, x4 = interval_bif x3 < x1: if x4 < x1: return 0 else: return min(x2,x4) — x1 else: if x2 < x3: return 0 else: return min(x2,x4) — x3 def bbox_iou(box1, box2): intersect_w = _interval_overlap([box1.xmin, box1.xmax], [box2.xmin, box2.xmax]) intersect_h = _interval_overlap([box1.ymin, box1.ymax], [box2.ymin, box2.ymax]) intersect = intersect_w * intersect_hw1, h1 = box1.xmax-box1.xmin, box1.ymax-box1.ymin w2, h2 = box2.xmax-box2.xmin, box2.ymax-box2.ymin union = w1*h1 + w2*h2 — intersect return float(intersect) / uniondef do_nms(boxes, nms_thresh): if len(boxes) > 0: nb_class = len(boxes[0].classes) else: return for c in range(nb_class): sorted_indices = np.argsort([-box.classes[c] for box in boxes])for i in range(len(sorted_indices)): index_i = sorted_indices[i]if boxes[index_i].classes[c] == 0: continuefor j in range(i+1, len(sorted_indices)): index_j = sorted_indices[j]if bbox_iou(boxes[index_i], boxes[index_j]) >= nms_thresh: boxes[index_j].classes[c] = 0" }, { "code": null, "e": 16036, "s": 15994, "text": "Step 9: Decode the output of the network." }, { "code": null, "e": 16209, "s": 16036, "text": "We will iterate through each of the each one of the NumPy arrays, one at a time and decode the candidate bounding boxes and class predictions based on the object threshold." }, { "code": null, "e": 16344, "s": 16209, "text": "The first 4 elements will be the coordinates of the Bounding box, 5th element will be object score followed by the class probabilities" }, { "code": null, "e": 17505, "s": 16344, "text": "def decode_netout(netout, anchors, obj_thresh, net_h, net_w): grid_h, grid_w = netout.shape[:2] nb_box = 3 netout = netout.reshape((grid_h, grid_w, nb_box, -1)) nb_class = netout.shape[-1] — 5boxes = [] netout[..., :2] = _sigmoid(netout[..., :2]) netout[..., 4:] = _sigmoid(netout[..., 4:]) netout[..., 5:] = netout[..., 4][..., np.newaxis] * netout[..., 5:] netout[..., 5:] *= netout[..., 5:] > obj_threshfor i in range(grid_h*grid_w): row = i / grid_w col = i % grid_w for b in range(nb_box): # 4th element is objectness score objectness = netout[int(row)][int(col)][b][4] #objectness = netout[..., :4] if(objectness.all() <= obj_thresh): continue # first 4 elements are x, y, w, and h x, y, w, h = netout[int(row)][int(col)][b][:4]x = (col + x) / grid_w # center position, unit: image width y = (row + y) / grid_h # center position, unit: image height w = anchors[2 * b + 0] * np.exp(w) / net_w # unit: image width h = anchors[2 * b + 1] * np.exp(h) / net_h # unit: image height # last elements are class probabilities classes = netout[int(row)][col][b][5:] box = BoundBox(x-w/2, y-h/2, x+w/2, y+h/2, objectness, classes) boxes.append(box)return boxes" }, { "code": null, "e": 17541, "s": 17505, "text": "Step 10: Correcting the Yolo boxes." }, { "code": null, "e": 17738, "s": 17541, "text": "We have the bounding boxes but they need to be stretched back into the shape of the original image. This will allow plotting the original image and draw the bounding boxes, detecting real objects." }, { "code": null, "e": 18383, "s": 17738, "text": "def correct_yolo_boxes(boxes, image_h, image_w, net_h, net_w): if (float(net_w)/image_w) < (float(net_h)/image_h): new_w = net_w new_h = (image_h*net_w)/image_w else: new_h = net_w new_w = (image_w*net_h)/image_h for i in range(len(boxes)): x_offset, x_scale = (net_w — new_w)/2./net_w, float(new_w)/net_w y_offset, y_scale = (net_h — new_h)/2./net_h, float(new_h)/net_h boxes[i].xmin = int((boxes[i].xmin — x_offset) / x_scale * image_w) boxes[i].xmax = int((boxes[i].xmax — x_offset) / x_scale * image_w) boxes[i].ymin = int((boxes[i].ymin — y_offset) / y_scale * image_h) boxes[i].ymax = int((boxes[i].ymax — y_offset) / y_scale * image_h)" }, { "code": null, "e": 18437, "s": 18383, "text": "Step 11: Get all boxes above the specified threshold." }, { "code": null, "e": 18573, "s": 18437, "text": "get_boxes function takes the list of boxes, labels, and threshold as arguments and returns parallel lists of boxes, labels, and scores." }, { "code": null, "e": 19125, "s": 18573, "text": "def get_boxes(boxes, labels, thresh): v_boxes, v_labels, v_scores = list(), list(), list() # enumerate all boxes for box in boxes: # enumerate all possible labels for i in range(len(labels)): # check if the threshold for this label is high enough if box.classes[i] > thresh: v_boxes.append(box) v_labels.append(labels[i]) v_scores.append(box.classes[i]*100) # don't break, many labels may trigger for one box return v_boxes, v_labels, v_scores" }, { "code": null, "e": 19194, "s": 19125, "text": "Step 12: Drawing a white box around the object present in the image." }, { "code": null, "e": 19981, "s": 19194, "text": "from matplotlib.patches import Rectangledef draw_boxes(filename, v_boxes, v_labels, v_scores): # load the image data = plt.imread(filename) # plot the image plt.imshow(data) # get the context for drawing boxes ax = plt.gca() # plot each box for i in range(len(v_boxes)):box = v_boxes[i] # get coordinates y1, x1, y2, x2 = box.ymin, box.xmin, box.ymax, box.xmax # calculate width and height of the box width, height = x2 - x1, y2 - y1 # create the shape rect = Rectangle((x1, y1), width, height, fill=False, color='red') # draw the box ax.add_patch(rect) # draw text and score in top left corner label = \"%s (%.3f)\" % (v_labels[i], v_scores[i]) plt.text(x1, y1, label, color='red') # show the plotplt.show()" }, { "code": null, "e": 20045, "s": 19981, "text": "Finally, we tie the code to make the prediction on a new image." }, { "code": null, "e": 20139, "s": 20045, "text": "First we load the image into the input shape of 416 x 416 using load_image_pixels() function." }, { "code": null, "e": 20188, "s": 20139, "text": "Predict the boxes suing yolov3 predict () method" }, { "code": null, "e": 20256, "s": 20188, "text": "Yolov3 model will be predicting multiple boxes for the same object." }, { "code": null, "e": 20383, "s": 20256, "text": "We then decode the candidate bounding boxes and class predictions based on the object threshold using decode_netout() function" }, { "code": null, "e": 20510, "s": 20383, "text": "we correct the bounding boxes by using correct_yolo_boxes() function to be stretched back into the shape of the original image" }, { "code": null, "e": 20649, "s": 20510, "text": "Bounding boxes will be filtered based on the overlap defined by IoU and then applying the non-max suppression using the do_nms() function." }, { "code": null, "e": 20807, "s": 20649, "text": "we get the boxes using get_boxes() which are above the specified class threshold of 0.6 and the then plot the boxes using draw_boxes() function on the image." }, { "code": null, "e": 21857, "s": 20807, "text": "# define our new imagephoto_filename = 'eagle.png'# load and prepare imageimage, image_w, image_h = load_image_pixels(photo_filename, (net_w, net_w))# make predictionyolos = yolov3.predict(image)# summarize the shape of the list of arraysprint([a.shape for a in yolos])# define the anchorsanchors = [[116,90, 156,198, 373,326], [30,61, 62,45, 59,119], [10,13, 16,30, 33,23]]# define the probability threshold for detected objectsclass_threshold = 0.6boxes = list()for i in range(len(yolos)): # decode the output of the network boxes += decode_netout(yolos[i][0], anchors[i], obj_thresh, nms_thresh, net_h, net_w)# correct the sizes of the bounding boxescorrect_yolo_boxes(boxes, image_h, image_w, net_h, net_w)# suppress non-maximal boxesdo_nms(boxes, nms_thresh)# get the details of the detected objectsv_boxes, v_labels, v_scores = get_boxes(boxes, labels, class_threshold)# summarize what we foundfor i in range(len(v_boxes)): print(v_labels[i], v_scores[i])# draw what we founddraw_boxes(photo_filename, v_boxes, v_labels, v_scores)" }, { "code": null, "e": 21872, "s": 21857, "text": "Original image" }, { "code": null, "e": 21920, "s": 21872, "text": "Image after plotting the bounding box and class" }, { "code": null, "e": 21948, "s": 21920, "text": "Code is available at Github" } ]
How can we add a FOREIGN KEY constraint to the field of an existing MySQL table?
We can add a FOREIGN KEY constraint to a column of an existing MySQL table with the help of ALTER TABLE statement. ALTER TABLE table_name ADD FOREIGN KEY (colum_name) REFERENCES table having Primary Key(column_name); Suppose we want to add a FOREIGN KEY constraint on the table ‘Orders1’ referencing to the table ‘Customer’ which have column ‘Cust_Id’ as the Primary Key. It can be done with the help of the following query − mysql> Alter table orders1 add FOREIGN KEY(Cust_id) REFERENCES Customer(Cust_id); Query OK, 0 rows affected (0.21 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> Describe ORDERS1; +--------------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------------+-------------+------+-----+---------+-------+ | order_id | int(11) | NO | PRI | NULL | | | Product_name | varchar(25) | YES | | NULL | | | orderdate | date | YES | | NULL | | | Cust_id | int(11) | YES | MUL | NULL | | +--------------+-------------+------+-----+---------+-------+ 4 rows in set (0.05 sec)
[ { "code": null, "e": 1177, "s": 1062, "text": "We can add a FOREIGN KEY constraint to a column of an existing MySQL table with the help of ALTER TABLE statement." }, { "code": null, "e": 1279, "s": 1177, "text": "ALTER TABLE table_name ADD FOREIGN KEY (colum_name) REFERENCES table having Primary Key(column_name);" }, { "code": null, "e": 1488, "s": 1279, "text": "Suppose we want to add a FOREIGN KEY constraint on the table ‘Orders1’ referencing to the table ‘Customer’ which have column ‘Cust_Id’ as the Primary Key. It can be done with the help of the following query −" }, { "code": null, "e": 2195, "s": 1488, "text": "mysql> Alter table orders1 add FOREIGN KEY(Cust_id) REFERENCES Customer(Cust_id);\nQuery OK, 0 rows affected (0.21 sec)\nRecords: 0 Duplicates: 0 Warnings: 0 \n\nmysql> Describe ORDERS1;\n+--------------+-------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+--------------+-------------+------+-----+---------+-------+\n| order_id | int(11) | NO | PRI | NULL | |\n| Product_name | varchar(25) | YES | | NULL | |\n| orderdate | date | YES | | NULL | |\n| Cust_id | int(11) | YES | MUL | NULL | |\n+--------------+-------------+------+-----+---------+-------+\n4 rows in set (0.05 sec)" } ]
Exploring the full-text search index in Neo4j on a movies dataset | by Tomaz Bratanic | Towards Data Science
The full-text search index was introduced in Neo4j version 3.5 with Apache Lucene powering the index. The agenda of this blog post is to introduce basic Lucene query language and describe how to use it in Neo4j. As you will see, we can also combine Lucene with Cypher to manipulate results. I got most of the inspiration for this blog post from Christophe Willemsen, who is part of the Graphaware team. He has described the use of FTS very nicely for noobies like me, thank you! Blog: Deep Dive into Neo4j 3.5 Full Text Search Webinar: To be or not to be. Full Text Search tips and tricks. We will be using the Movie dialog corpus dataset available on kaggle. It is rich with meta-data as it contains all the conversations between the characters in 617 different films. I have a couple of blog posts lined up using this dataset, but for starters, we will only use the data about the movies to explore the full-text search index capabilities. We have two labels(Movie, MovieTag) in our graph. They are connected with the HAS_TAG relationship. Movies can have additional attributes like release year, IMDB rating, and the number of votes on IMDB. Create constraints To optimize import and later queries, we define unique constraints for both movies and movie tags. CREATE CONSTRAINT ON (m:Movie) ASSERT m.id IS UNIQUE;CREATE CONSTRAINT ON (m:MovieTag) ASSERT m.id IS UNIQUE; Copy the movie_titles_metadata.tsv file to $Neo4j/import folder before running the import query. LOAD CSV FROM "file:///movie_titles_metadata.tsv" as row FIELDTERMINATOR "\t"MERGE (m:Movie{id:row[0]})SET m.title = row[1], m.release_year = toInteger(row[2]), m.imdb_rating = toFloat(row[3]), m.no_votes = toInteger(row[4])WITH m, apoc.convert.fromJsonList( replace(row[5]," ",",")) as tagsUNWIND tags as tagMERGE (mt:MovieTag{id:tag})MERGE (m)-[:HAS_TAG]->(mt) In simplified terms, the lucene indexing pipeline consists of two steps. The first step is the “Analyzer” step, which takes care of the preprocessing of the text. In the second step, the “IndexWriter” stores the results of the “Analyzer” to the index. In this blog post, we will be using the default “standard” analyzer in Neo4j. It tokenizes on non-letter and filters out English stop words and punctuation. Does no stemming, but takes care to keep likely product names, URLs, and email addresses as single terms. You can check out other available analyzers. CALL db.index.fulltext.listAvailableAnalyzers; First, we have to transform all of the attributes, that contain numbers, to strings as we can’t index integers or floats. The indexing process silently ignores numbers. IMDB rating attribute is a number with a single decimal point. To convert it to a string, we will first multiply it by ten and then convert it to a string. For example, rating 6.1 will be saved as “61”. MATCH (m:Movie)SET m.string_rating = toString(toInteger(m.imdb_rating * 10)), m.string_release_year = toString(m.release_year) When using range queries, we have to be careful as the ordering is done lexicologically(alphabetically). In our case, all of the ratings are between “00” and “99”, so there should be no issue. If, for example, the range spanned to “150”, we would have an issue, as looking for intervals between “50” and “150” will not work by default. The workaround is described in Lucene range blog post. To allow range search between numbers with different count of digits, we need to preprocess the values by prepending zeros to them to ensure that all values have the same count of digits. In this example, we preprocess all the numbers to have seven digits. WITH 7 as total_lengthMATCH (m:Movie)WHERE exists (m.imdb_rating)WITH m, total_length, toString(toInteger(m.imdb_rating * 10)) as string_ratingWITH m, total_length — length(string_rating) as zeros, string_ratingWITH m, apoc.text.join([x in range(1,zeros) | “0”],””) + string_rating as final_ratingSET m.range_rating = final_rating Now we create the “MovieIndex” index, which contains nodes with label Movie and the four specified attributes. The first parameter is the name of the index. The second parameter defines the labels of the nodes, and the third parameter the attributes we want to index. CALL db.index.fulltext.createNodeIndex("MovieIndex",["Movie"],["title","string_rating","range_rating","string_release_year"]) Let’s take a look at some basic lucene query operators. Specific attribute Search for movies that have the word “dream” in their title. CALL db.index.fulltext.queryNodes("MovieIndex", "title:dream") YIELD node, scoreRETURN node.title as title, score Results Logical operator There are two logical operators available, “OR” and “AND”. Search for movies that were released in 1999 or 2000. CALL db.index.fulltext.queryNodes("MovieIndex", "string_release_year:1999 or 2000") YIELD node, scoreRETURN node.title as title, scoreLIMIT 5 Results Single-character wildcard The single character wildcard operator ? looks for terms that match that with the single character replaced. CALL db.index.fulltext.queryNodes("MovieIndex", "title:th?") YIELD node, scoreRETURN node.title as title, score Results One thing to note is that “the matrix” movie does not show up in results because the standard analyzer removes the stop words like “the”. Multi-character wildcard The multi-character wildcard operator looks for zero or more characters. You can also put the operator in the middle of the term like dre*am. To prevent extremely slow wildcard queries, a term should not start with the wildcard *dream . CALL db.index.fulltext.queryNodes("MovieIndex", "title:drea*") YIELD node, scoreRETURN node.title as title, score Results Fuzzy search Fuzzy search works by using mathematical formulae that calculate the similarity between two words. A commonly used method for calculating similarity is Levenshtein distance. CALL db.index.fulltext.queryNodes("MovieIndex", "title:dream~") YIELD node, scoreRETURN node.title as title, scoreLIMIT 5 Results Range query Lucene differentiates between range operators with inclusive or exclusive ends. Operators: {} ->excluding edges [] -> including edges CALL db.index.fulltext.queryNodes("MovieIndex", "string_rating:[50 TO 99}") YIELD node, scoreRETURN node.title as title,scoreLIMIT 5 Results To demonstrate why we need numbers with the same amount of digits when doing range search, let’s try the following query. CALL db.index.fulltext.queryNodes("MovieIndex", "string_rating:[50 TO 100]") YIELD node, scoreRETURN node.title as title,score Intuitively you would expect it to work just fine, but because of lexicological ordering, this is not the case. The workaround we used to solve this issue is the range_rating attribute, where values are prepended with zeros to allow alphabetical sorting between numbers with a different order of magnitude. CALL db.index.fulltext.queryNodes(“MovieIndex”, “range_rating:[0000050 TO 0000150]”) YIELD node, scoreRETURN node.title as title,scoreLIMIT 5 Results Lucene query language also supports boosting the score of the results with the caret (^) operator. Boost results that have the string_rating between 50 and 99. CALL db.index.fulltext.queryNodes("MovieIndex", "title:dream string_rating:[50 TO 99]^2") YIELD node, scoreRETURN node.title as title,scoreLIMIT 5 Results Time decay I saw a lucene time decay query in the Nodes 2019 webinar by Christophe Willemsen and wanted to replicate it. Basically, we combine many boosting parameters to achieve a time decay effect. To show what that means we will use apoc.text.join() to generate nine boosting parameters. RETURN apoc.text.join([ x in range(0,8) | "string_release_date:" + toString((date().year - x)) + "^" + toString(10-x)]," ") Results string_release_date:2019^10 string_release_date:2018^9 string_release_date:2017^8 string_release_date:2016^7 string_release_date:2015^6 string_release_date:2014^5 string_release_date:2013^4 string_release_date:2012^3 string_release_date:2011^2 As you can see movies with the release year 2019 will be boosted by a factor of ten, movies from 2018 will be boosted by nine and so on. To wrap this blog post, let’s combine the rating-boosting and the time decay effect in a single query. And just so you know you can always manipulate results later with cypher, let’s add a filter that will return only thrillers. WITH apoc.text.join([x in range(0,10) | "string_release_date:" + toString((date().year — x)) + "^" + toString(10-x)]," ") as time_decayCALL db.index.fulltext.queryNodes("MovieIndex", "title:dream string_rating:[50 TO 99]^2 "+ time_decay) YIELD node, score// filter only thrillersMATCH (node)-[:HAS_TAG]->(:MovieTag{id:'thriller'})RETURN node.title as title,scoreLIMIT 5 Results Full-text search is a very welcomed feature, that can help us develop better and faster Neo4j applications and also solve other problems. Join the Neo4j community forum if you have any questions or feedback. All the code is available on Github.
[ { "code": null, "e": 462, "s": 171, "text": "The full-text search index was introduced in Neo4j version 3.5 with Apache Lucene powering the index. The agenda of this blog post is to introduce basic Lucene query language and describe how to use it in Neo4j. As you will see, we can also combine Lucene with Cypher to manipulate results." }, { "code": null, "e": 650, "s": 462, "text": "I got most of the inspiration for this blog post from Christophe Willemsen, who is part of the Graphaware team. He has described the use of FTS very nicely for noobies like me, thank you!" }, { "code": null, "e": 698, "s": 650, "text": "Blog: Deep Dive into Neo4j 3.5 Full Text Search" }, { "code": null, "e": 761, "s": 698, "text": "Webinar: To be or not to be. Full Text Search tips and tricks." }, { "code": null, "e": 1113, "s": 761, "text": "We will be using the Movie dialog corpus dataset available on kaggle. It is rich with meta-data as it contains all the conversations between the characters in 617 different films. I have a couple of blog posts lined up using this dataset, but for starters, we will only use the data about the movies to explore the full-text search index capabilities." }, { "code": null, "e": 1316, "s": 1113, "text": "We have two labels(Movie, MovieTag) in our graph. They are connected with the HAS_TAG relationship. Movies can have additional attributes like release year, IMDB rating, and the number of votes on IMDB." }, { "code": null, "e": 1335, "s": 1316, "text": "Create constraints" }, { "code": null, "e": 1434, "s": 1335, "text": "To optimize import and later queries, we define unique constraints for both movies and movie tags." }, { "code": null, "e": 1544, "s": 1434, "text": "CREATE CONSTRAINT ON (m:Movie) ASSERT m.id IS UNIQUE;CREATE CONSTRAINT ON (m:MovieTag) ASSERT m.id IS UNIQUE;" }, { "code": null, "e": 1641, "s": 1544, "text": "Copy the movie_titles_metadata.tsv file to $Neo4j/import folder before running the import query." }, { "code": null, "e": 2022, "s": 1641, "text": "LOAD CSV FROM \"file:///movie_titles_metadata.tsv\" as row FIELDTERMINATOR \"\\t\"MERGE (m:Movie{id:row[0]})SET m.title = row[1], m.release_year = toInteger(row[2]), m.imdb_rating = toFloat(row[3]), m.no_votes = toInteger(row[4])WITH m, apoc.convert.fromJsonList( replace(row[5],\" \",\",\")) as tagsUNWIND tags as tagMERGE (mt:MovieTag{id:tag})MERGE (m)-[:HAS_TAG]->(mt)" }, { "code": null, "e": 2274, "s": 2022, "text": "In simplified terms, the lucene indexing pipeline consists of two steps. The first step is the “Analyzer” step, which takes care of the preprocessing of the text. In the second step, the “IndexWriter” stores the results of the “Analyzer” to the index." }, { "code": null, "e": 2537, "s": 2274, "text": "In this blog post, we will be using the default “standard” analyzer in Neo4j. It tokenizes on non-letter and filters out English stop words and punctuation. Does no stemming, but takes care to keep likely product names, URLs, and email addresses as single terms." }, { "code": null, "e": 2582, "s": 2537, "text": "You can check out other available analyzers." }, { "code": null, "e": 2629, "s": 2582, "text": "CALL db.index.fulltext.listAvailableAnalyzers;" }, { "code": null, "e": 2798, "s": 2629, "text": "First, we have to transform all of the attributes, that contain numbers, to strings as we can’t index integers or floats. The indexing process silently ignores numbers." }, { "code": null, "e": 3001, "s": 2798, "text": "IMDB rating attribute is a number with a single decimal point. To convert it to a string, we will first multiply it by ten and then convert it to a string. For example, rating 6.1 will be saved as “61”." }, { "code": null, "e": 3131, "s": 3001, "text": "MATCH (m:Movie)SET m.string_rating = toString(toInteger(m.imdb_rating * 10)), m.string_release_year = toString(m.release_year)" }, { "code": null, "e": 3710, "s": 3131, "text": "When using range queries, we have to be careful as the ordering is done lexicologically(alphabetically). In our case, all of the ratings are between “00” and “99”, so there should be no issue. If, for example, the range spanned to “150”, we would have an issue, as looking for intervals between “50” and “150” will not work by default. The workaround is described in Lucene range blog post. To allow range search between numbers with different count of digits, we need to preprocess the values by prepending zeros to them to ensure that all values have the same count of digits." }, { "code": null, "e": 3779, "s": 3710, "text": "In this example, we preprocess all the numbers to have seven digits." }, { "code": null, "e": 4155, "s": 3779, "text": "WITH 7 as total_lengthMATCH (m:Movie)WHERE exists (m.imdb_rating)WITH m, total_length, toString(toInteger(m.imdb_rating * 10)) as string_ratingWITH m, total_length — length(string_rating) as zeros, string_ratingWITH m, apoc.text.join([x in range(1,zeros) | “0”],””) + string_rating as final_ratingSET m.range_rating = final_rating" }, { "code": null, "e": 4423, "s": 4155, "text": "Now we create the “MovieIndex” index, which contains nodes with label Movie and the four specified attributes. The first parameter is the name of the index. The second parameter defines the labels of the nodes, and the third parameter the attributes we want to index." }, { "code": null, "e": 4549, "s": 4423, "text": "CALL db.index.fulltext.createNodeIndex(\"MovieIndex\",[\"Movie\"],[\"title\",\"string_rating\",\"range_rating\",\"string_release_year\"])" }, { "code": null, "e": 4605, "s": 4549, "text": "Let’s take a look at some basic lucene query operators." }, { "code": null, "e": 4624, "s": 4605, "text": "Specific attribute" }, { "code": null, "e": 4685, "s": 4624, "text": "Search for movies that have the word “dream” in their title." }, { "code": null, "e": 4799, "s": 4685, "text": "CALL db.index.fulltext.queryNodes(\"MovieIndex\", \"title:dream\") YIELD node, scoreRETURN node.title as title, score" }, { "code": null, "e": 4807, "s": 4799, "text": "Results" }, { "code": null, "e": 4824, "s": 4807, "text": "Logical operator" }, { "code": null, "e": 4883, "s": 4824, "text": "There are two logical operators available, “OR” and “AND”." }, { "code": null, "e": 4937, "s": 4883, "text": "Search for movies that were released in 1999 or 2000." }, { "code": null, "e": 5084, "s": 4937, "text": "CALL db.index.fulltext.queryNodes(\"MovieIndex\", \"string_release_year:1999 or 2000\") YIELD node, scoreRETURN node.title as title, scoreLIMIT 5" }, { "code": null, "e": 5092, "s": 5084, "text": "Results" }, { "code": null, "e": 5118, "s": 5092, "text": "Single-character wildcard" }, { "code": null, "e": 5227, "s": 5118, "text": "The single character wildcard operator ? looks for terms that match that with the single character replaced." }, { "code": null, "e": 5339, "s": 5227, "text": "CALL db.index.fulltext.queryNodes(\"MovieIndex\", \"title:th?\") YIELD node, scoreRETURN node.title as title, score" }, { "code": null, "e": 5347, "s": 5339, "text": "Results" }, { "code": null, "e": 5485, "s": 5347, "text": "One thing to note is that “the matrix” movie does not show up in results because the standard analyzer removes the stop words like “the”." }, { "code": null, "e": 5510, "s": 5485, "text": "Multi-character wildcard" }, { "code": null, "e": 5747, "s": 5510, "text": "The multi-character wildcard operator looks for zero or more characters. You can also put the operator in the middle of the term like dre*am. To prevent extremely slow wildcard queries, a term should not start with the wildcard *dream ." }, { "code": null, "e": 5861, "s": 5747, "text": "CALL db.index.fulltext.queryNodes(\"MovieIndex\", \"title:drea*\") YIELD node, scoreRETURN node.title as title, score" }, { "code": null, "e": 5869, "s": 5861, "text": "Results" }, { "code": null, "e": 5882, "s": 5869, "text": "Fuzzy search" }, { "code": null, "e": 6056, "s": 5882, "text": "Fuzzy search works by using mathematical formulae that calculate the similarity between two words. A commonly used method for calculating similarity is Levenshtein distance." }, { "code": null, "e": 6178, "s": 6056, "text": "CALL db.index.fulltext.queryNodes(\"MovieIndex\", \"title:dream~\") YIELD node, scoreRETURN node.title as title, scoreLIMIT 5" }, { "code": null, "e": 6186, "s": 6178, "text": "Results" }, { "code": null, "e": 6198, "s": 6186, "text": "Range query" }, { "code": null, "e": 6278, "s": 6198, "text": "Lucene differentiates between range operators with inclusive or exclusive ends." }, { "code": null, "e": 6289, "s": 6278, "text": "Operators:" }, { "code": null, "e": 6310, "s": 6289, "text": "{} ->excluding edges" }, { "code": null, "e": 6332, "s": 6310, "text": "[] -> including edges" }, { "code": null, "e": 6465, "s": 6332, "text": "CALL db.index.fulltext.queryNodes(\"MovieIndex\", \"string_rating:[50 TO 99}\") YIELD node, scoreRETURN node.title as title,scoreLIMIT 5" }, { "code": null, "e": 6473, "s": 6465, "text": "Results" }, { "code": null, "e": 6595, "s": 6473, "text": "To demonstrate why we need numbers with the same amount of digits when doing range search, let’s try the following query." }, { "code": null, "e": 6722, "s": 6595, "text": "CALL db.index.fulltext.queryNodes(\"MovieIndex\", \"string_rating:[50 TO 100]\") YIELD node, scoreRETURN node.title as title,score" }, { "code": null, "e": 7029, "s": 6722, "text": "Intuitively you would expect it to work just fine, but because of lexicological ordering, this is not the case. The workaround we used to solve this issue is the range_rating attribute, where values are prepended with zeros to allow alphabetical sorting between numbers with a different order of magnitude." }, { "code": null, "e": 7171, "s": 7029, "text": "CALL db.index.fulltext.queryNodes(“MovieIndex”, “range_rating:[0000050 TO 0000150]”) YIELD node, scoreRETURN node.title as title,scoreLIMIT 5" }, { "code": null, "e": 7179, "s": 7171, "text": "Results" }, { "code": null, "e": 7278, "s": 7179, "text": "Lucene query language also supports boosting the score of the results with the caret (^) operator." }, { "code": null, "e": 7339, "s": 7278, "text": "Boost results that have the string_rating between 50 and 99." }, { "code": null, "e": 7486, "s": 7339, "text": "CALL db.index.fulltext.queryNodes(\"MovieIndex\", \"title:dream string_rating:[50 TO 99]^2\") YIELD node, scoreRETURN node.title as title,scoreLIMIT 5" }, { "code": null, "e": 7494, "s": 7486, "text": "Results" }, { "code": null, "e": 7505, "s": 7494, "text": "Time decay" }, { "code": null, "e": 7785, "s": 7505, "text": "I saw a lucene time decay query in the Nodes 2019 webinar by Christophe Willemsen and wanted to replicate it. Basically, we combine many boosting parameters to achieve a time decay effect. To show what that means we will use apoc.text.join() to generate nine boosting parameters." }, { "code": null, "e": 7910, "s": 7785, "text": "RETURN apoc.text.join([ x in range(0,8) | \"string_release_date:\" + toString((date().year - x)) + \"^\" + toString(10-x)],\" \")" }, { "code": null, "e": 7918, "s": 7910, "text": "Results" }, { "code": null, "e": 8162, "s": 7918, "text": "string_release_date:2019^10 string_release_date:2018^9 string_release_date:2017^8 string_release_date:2016^7 string_release_date:2015^6 string_release_date:2014^5 string_release_date:2013^4 string_release_date:2012^3 string_release_date:2011^2" }, { "code": null, "e": 8299, "s": 8162, "text": "As you can see movies with the release year 2019 will be boosted by a factor of ten, movies from 2018 will be boosted by nine and so on." }, { "code": null, "e": 8528, "s": 8299, "text": "To wrap this blog post, let’s combine the rating-boosting and the time decay effect in a single query. And just so you know you can always manipulate results later with cypher, let’s add a filter that will return only thrillers." }, { "code": null, "e": 8902, "s": 8528, "text": "WITH apoc.text.join([x in range(0,10) | \"string_release_date:\" + toString((date().year — x)) + \"^\" + toString(10-x)],\" \") as time_decayCALL db.index.fulltext.queryNodes(\"MovieIndex\", \"title:dream string_rating:[50 TO 99]^2 \"+ time_decay) YIELD node, score// filter only thrillersMATCH (node)-[:HAS_TAG]->(:MovieTag{id:'thriller'})RETURN node.title as title,scoreLIMIT 5" }, { "code": null, "e": 8910, "s": 8902, "text": "Results" }, { "code": null, "e": 9118, "s": 8910, "text": "Full-text search is a very welcomed feature, that can help us develop better and faster Neo4j applications and also solve other problems. Join the Neo4j community forum if you have any questions or feedback." } ]
PHP | compact() Function - GeeksforGeeks
29 Nov, 2019 The compact() function is an inbuilt function in PHP and it is used to create an array using variables. This function is opposite of extract() function. It creates an associative array whose keys are variable names and their corresponding values are array values. Syntax: array compact("variable 1", "variable 2"...) Parameters: This function accepts a variable number of arguments separated by comma operator (‘,’). These arguments are of string data type and specify the name of variables which we want to use to create the array. We can also pass an array as an argument to this function, in that case, all of the elements in the array passed as a parameter will be added to the output array. Return Value: This function returns an array with all the variables added to it. Note: Any string passed as a parameter which does not match with a valid variable name will be skipped and will not be added to the array. Examples: Input : $AS="ASSAM", $OR="ORISSA", $KR="KERELA" compact("AS", "OR", "KR"); Output : Array ( [AS] => ASSAM [OR] => ORISSA [KR] => KERELA ) Below program illustrate the working of compact() function in PHP: Example-1: <?php// PHP program to illustrate compact() // Function $AS = "ASSAM";$OR = "ORISSA";$KR = "KERELA"; $stats = compact("AS", "OR", "KR"); print_r($states); ?> Output: Array ( [AS] => ASSAM [OR] => ORISSA [KR] => KERELA ) Example-2: <?php// PHP program to illustrate compact() // function when an array is passed as// a parameter $username = "max";$password = "many";$age = "31"; $NAME = array("username", "password"); $result = compact($NAME, "age"); print_r($result); ?> Output: Array ( [username] => max [password] => many [age] => 31 ) Reference:http://php.net/manual/en/function.compact.php Akanksha_Rai PHP-array PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? Different ways for passing data to view in Laravel Create a drop-down list that options fetched from a MySQL database in PHP How to create admin login page using PHP? How to generate PDF file using PHP ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript
[ { "code": null, "e": 24972, "s": 24944, "text": "\n29 Nov, 2019" }, { "code": null, "e": 25236, "s": 24972, "text": "The compact() function is an inbuilt function in PHP and it is used to create an array using variables. This function is opposite of extract() function. It creates an associative array whose keys are variable names and their corresponding values are array values." }, { "code": null, "e": 25244, "s": 25236, "text": "Syntax:" }, { "code": null, "e": 25290, "s": 25244, "text": "array compact(\"variable 1\", \"variable 2\"...)\n" }, { "code": null, "e": 25669, "s": 25290, "text": "Parameters: This function accepts a variable number of arguments separated by comma operator (‘,’). These arguments are of string data type and specify the name of variables which we want to use to create the array. We can also pass an array as an argument to this function, in that case, all of the elements in the array passed as a parameter will be added to the output array." }, { "code": null, "e": 25750, "s": 25669, "text": "Return Value: This function returns an array with all the variables added to it." }, { "code": null, "e": 25889, "s": 25750, "text": "Note: Any string passed as a parameter which does not match with a valid variable name will be skipped and will not be added to the array." }, { "code": null, "e": 25899, "s": 25889, "text": "Examples:" }, { "code": null, "e": 26058, "s": 25899, "text": "Input : $AS=\"ASSAM\", $OR=\"ORISSA\", $KR=\"KERELA\"\n compact(\"AS\", \"OR\", \"KR\");\nOutput :\nArray\n(\n [AS] => ASSAM\n [OR] => ORISSA\n [KR] => KERELA\n)\n" }, { "code": null, "e": 26125, "s": 26058, "text": "Below program illustrate the working of compact() function in PHP:" }, { "code": null, "e": 26136, "s": 26125, "text": "Example-1:" }, { "code": "<?php// PHP program to illustrate compact() // Function $AS = \"ASSAM\";$OR = \"ORISSA\";$KR = \"KERELA\"; $stats = compact(\"AS\", \"OR\", \"KR\"); print_r($states); ?>", "e": 26306, "s": 26136, "text": null }, { "code": null, "e": 26314, "s": 26306, "text": "Output:" }, { "code": null, "e": 26381, "s": 26314, "text": "Array\n(\n [AS] => ASSAM\n [OR] => ORISSA\n [KR] => KERELA\n)\n" }, { "code": null, "e": 26392, "s": 26381, "text": "Example-2:" }, { "code": "<?php// PHP program to illustrate compact() // function when an array is passed as// a parameter $username = \"max\";$password = \"many\";$age = \"31\"; $NAME = array(\"username\", \"password\"); $result = compact($NAME, \"age\"); print_r($result); ?>", "e": 26641, "s": 26392, "text": null }, { "code": null, "e": 26649, "s": 26641, "text": "Output:" }, { "code": null, "e": 26721, "s": 26649, "text": "Array\n(\n [username] => max\n [password] => many\n [age] => 31\n)\n" }, { "code": null, "e": 26777, "s": 26721, "text": "Reference:http://php.net/manual/en/function.compact.php" }, { "code": null, "e": 26790, "s": 26777, "text": "Akanksha_Rai" }, { "code": null, "e": 26800, "s": 26790, "text": "PHP-array" }, { "code": null, "e": 26813, "s": 26800, "text": "PHP-function" }, { "code": null, "e": 26817, "s": 26813, "text": "PHP" }, { "code": null, "e": 26834, "s": 26817, "text": "Web Technologies" }, { "code": null, "e": 26838, "s": 26834, "text": "PHP" }, { "code": null, "e": 26936, "s": 26838, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27018, "s": 26936, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 27069, "s": 27018, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 27143, "s": 27069, "text": "Create a drop-down list that options fetched from a MySQL database in PHP" }, { "code": null, "e": 27185, "s": 27143, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 27222, "s": 27185, "text": "How to generate PDF file using PHP ?" }, { "code": null, "e": 27264, "s": 27222, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27297, "s": 27264, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27340, "s": 27297, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27402, "s": 27340, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Continuous Integration - Build Scripts
Now let’s look at certain aspects of the MSBuild file to see what they mean. These aspects are important to know from a Continuous Integration Cycle. Build scripts are used to build the solution which will be a part of the entire continuous Integration cycle. Let’s look at the general build script which is created as a part of Visual Studio in .Net for our sample solution. The build script is a pretty big one, even for a simple solution, so we will go through the most important parts of it. By default, the build script will be stored in a file with the same name as the main solution in Visual Studio. So in our case, if you open the file Simple.csproj, you will see all the settings which will be used to build the solution. Dependency on the MSBuild version used − The following settings will use the MSBuild files installed on the CI server. Dependency on the MSBuild version used − The following settings will use the MSBuild files installed on the CI server. <VisualStudioVersion Condition = "'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion> <VSToolsPath Condition = "'$(VSToolsPath)' == ''"> $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) </VSToolsPath> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <Import Project = "$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <Import Project = "$(VSToolsPath)\WebApplications\ Microsoft.WebApplication.targets" Condition = "'$(VSToolsPath)' ! = ''" /> <Import Project = "$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\ WebApplications\Microsoft.WebApplication.targets" Condition = "false" /> What files are required to build the solution properly – The ItemGroup tag will contain all the necessary .Net files which are required for the project to build successfully. These files will need to reside on the build server accordingly. What files are required to build the solution properly – The ItemGroup tag will contain all the necessary .Net files which are required for the project to build successfully. These files will need to reside on the build server accordingly. <ItemGroup> <Reference Include = "Microsoft.CSharp" /> <Reference Include = "System.Web.DynamicData" /> <Reference Include = "System.Web.Entity" /> <Reference Include = "System.Web.ApplicationServices" /> <Reference Include = "System.ComponentModel.DataAnnotations" /> <Reference Include = "System" /> <Reference Include = "System.Data" /> <Reference Include = "System.Core" /> <Reference Include = "System.Data.DataSetExtensions" /> <Reference Include = "System.Web.Extensions" /> <Reference Include = "System.Xml.Linq" /> <Reference Include = "System.Drawing" /> <Reference Include = "System.Web" /> <Reference Include = "System.Xml" /> <Reference Include = "System.Configuration" /> <Reference Include = "System.Web.Services" /> <Reference Include = "System.EnterpriseServices"/> </ItemGroup> What are the Web server settings to be used − When we visit our topic of Continuous Deployment, you will see how MSBuild will be used to override these settings and deploy this to our server of choice. What are the Web server settings to be used − When we visit our topic of Continuous Deployment, you will see how MSBuild will be used to override these settings and deploy this to our server of choice. <UseIIS>True</UseIIS> <AutoAssignPort>True</AutoAssignPort> <DevelopmentServerPort>59495</DevelopmentServerPort> <DevelopmentServerVPath>/</DevelopmentServerVPath> <IISUrl></IISUrl> <NTLMAuthentication>False</NTLMAuthentication> <UseCustomServer>False</UseCustomServer> 16 Lectures 1.5 hours Christopher Frewin 67 Lectures 8 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2136, "s": 1986, "text": "Now let’s look at certain aspects of the MSBuild file to see what they mean. These aspects are important to know from a Continuous Integration Cycle." }, { "code": null, "e": 2718, "s": 2136, "text": "Build scripts are used to build the solution which will be a part of the entire continuous Integration cycle. Let’s look at the general build script which is created as a part of Visual Studio in .Net for our sample solution. The build script is a pretty big one, even for a simple solution, so we will go through the most important parts of it. By default, the build script will be stored in a file with the same name as the main solution in Visual Studio. So in our case, if you open the file Simple.csproj, you will see all the settings which will be used to build the solution." }, { "code": null, "e": 2837, "s": 2718, "text": "Dependency on the MSBuild version used − The following settings will use the MSBuild files installed on the CI server." }, { "code": null, "e": 2956, "s": 2837, "text": "Dependency on the MSBuild version used − The following settings will use the MSBuild files installed on the CI server." }, { "code": null, "e": 3602, "s": 2956, "text": "<VisualStudioVersion Condition = \"'$(VisualStudioVersion)' == \n ''\">10.0</VisualStudioVersion>\n\n<VSToolsPath Condition = \"'$(VSToolsPath)' == ''\"> \n $(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)\n</VSToolsPath>\n\n<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\n\n<Import Project = \"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\n<Import Project = \"$(VSToolsPath)\\WebApplications\\\n Microsoft.WebApplication.targets\" Condition = \"'$(VSToolsPath)' ! = ''\" />\n\n<Import Project = \"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v10.0\\\n WebApplications\\Microsoft.WebApplication.targets\" Condition = \"false\" />" }, { "code": null, "e": 3842, "s": 3602, "text": "What files are required to build the solution properly – The ItemGroup tag will contain all the necessary .Net files which are required for the project to build successfully. These files will need to reside on the build server accordingly." }, { "code": null, "e": 4082, "s": 3842, "text": "What files are required to build the solution properly – The ItemGroup tag will contain all the necessary .Net files which are required for the project to build successfully. These files will need to reside on the build server accordingly." }, { "code": null, "e": 4929, "s": 4082, "text": "<ItemGroup>\n <Reference Include = \"Microsoft.CSharp\" />\n <Reference Include = \"System.Web.DynamicData\" />\n <Reference Include = \"System.Web.Entity\" />\n <Reference Include = \"System.Web.ApplicationServices\" />\n <Reference Include = \"System.ComponentModel.DataAnnotations\" />\n <Reference Include = \"System\" />\n <Reference Include = \"System.Data\" />\n <Reference Include = \"System.Core\" />\n <Reference Include = \"System.Data.DataSetExtensions\" />\n <Reference Include = \"System.Web.Extensions\" />\n <Reference Include = \"System.Xml.Linq\" />\n <Reference Include = \"System.Drawing\" />\n <Reference Include = \"System.Web\" />\n <Reference Include = \"System.Xml\" />\n <Reference Include = \"System.Configuration\" />\n <Reference Include = \"System.Web.Services\" />\n <Reference Include = \"System.EnterpriseServices\"/>\n</ItemGroup>" }, { "code": null, "e": 5131, "s": 4929, "text": "What are the Web server settings to be used − When we visit our topic of Continuous Deployment, you will see how MSBuild will be used to override these settings and deploy this to our server of choice." }, { "code": null, "e": 5333, "s": 5131, "text": "What are the Web server settings to be used − When we visit our topic of Continuous Deployment, you will see how MSBuild will be used to override these settings and deploy this to our server of choice." }, { "code": null, "e": 5603, "s": 5333, "text": "<UseIIS>True</UseIIS>\n<AutoAssignPort>True</AutoAssignPort>\n<DevelopmentServerPort>59495</DevelopmentServerPort>\n<DevelopmentServerVPath>/</DevelopmentServerVPath>\n<IISUrl></IISUrl>\n<NTLMAuthentication>False</NTLMAuthentication>\n<UseCustomServer>False</UseCustomServer>" }, { "code": null, "e": 5638, "s": 5603, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5658, "s": 5638, "text": " Christopher Frewin" }, { "code": null, "e": 5691, "s": 5658, "text": "\n 67 Lectures \n 8 hours \n" }, { "code": null, "e": 5709, "s": 5691, "text": " Packt Publishing" }, { "code": null, "e": 5716, "s": 5709, "text": " Print" }, { "code": null, "e": 5727, "s": 5716, "text": " Add Notes" } ]
Apache Commons IO - FileUtils
Provides method to manipulates files like moving, opening, checking existence, reading of file etc. These methods use File Object. Following is the declaration for org.apache.commons.io.FileUtils Class − public class FileUtils extends Object The features of FileUtils are stated below − Methods to write to a file. Methods to read from a file. Methods to make a directory including parent directories. Methods to copy files and directories. Methods to delete files and directories. Methods to convert to and from a URL. Methods to list files and directories by filter and extension. Methods to compare file content. Methods to file last changed date. Methods to calculating a checksum. Here is the input file we need to parse − Welcome to TutorialsPoint. Simply Easy Learning. IOTester.java import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import org.apache.commons.io.FileUtils; public class IOTester { public static void main(String[] args) { try { //Using FileUtils usingFileUtils(); } catch(IOException e) { System.out.println(e.getMessage()); } } public static void usingFileUtils() throws IOException { //get the file object File file = FileUtils.getFile("input.txt"); //get the temp directory File tmpDir = FileUtils.getTempDirectory(); System.out.println(tmpDir.getName()); //copy file to temp directory FileUtils.copyFileToDirectory(file, tmpDir); //create a new file File newTempFile = FileUtils.getFile(tmpDir, file.getName()); //get the content String data = FileUtils.readFileToString(newTempFile, Charset.defaultCharset()); //print the content System.out.println(data); } } It will print the following result. Temp Welcome to TutorialsPoint. Simply Easy Learning. Print Add Notes Bookmark this page
[ { "code": null, "e": 2535, "s": 2404, "text": "Provides method to manipulates files like moving, opening, checking existence, reading of file etc. These methods use File Object." }, { "code": null, "e": 2608, "s": 2535, "text": "Following is the declaration for org.apache.commons.io.FileUtils Class −" }, { "code": null, "e": 2649, "s": 2608, "text": "public class FileUtils\n extends Object" }, { "code": null, "e": 2694, "s": 2649, "text": "The features of FileUtils are stated below −" }, { "code": null, "e": 2722, "s": 2694, "text": "Methods to write to a file." }, { "code": null, "e": 2751, "s": 2722, "text": "Methods to read from a file." }, { "code": null, "e": 2809, "s": 2751, "text": "Methods to make a directory including parent directories." }, { "code": null, "e": 2848, "s": 2809, "text": "Methods to copy files and directories." }, { "code": null, "e": 2889, "s": 2848, "text": "Methods to delete files and directories." }, { "code": null, "e": 2927, "s": 2889, "text": "Methods to convert to and from a URL." }, { "code": null, "e": 2990, "s": 2927, "text": "Methods to list files and directories by filter and extension." }, { "code": null, "e": 3023, "s": 2990, "text": "Methods to compare file content." }, { "code": null, "e": 3058, "s": 3023, "text": "Methods to file last changed date." }, { "code": null, "e": 3093, "s": 3058, "text": "Methods to calculating a checksum." }, { "code": null, "e": 3135, "s": 3093, "text": "Here is the input file we need to parse −" }, { "code": null, "e": 3185, "s": 3135, "text": "Welcome to TutorialsPoint. Simply Easy Learning.\n" }, { "code": null, "e": 3199, "s": 3185, "text": "IOTester.java" }, { "code": null, "e": 4173, "s": 3199, "text": "import java.io.File;\nimport java.io.IOException;\nimport java.nio.charset.Charset;\n\nimport org.apache.commons.io.FileUtils;\n\npublic class IOTester {\n public static void main(String[] args) {\n try {\n //Using FileUtils\n usingFileUtils();\n } catch(IOException e) {\n System.out.println(e.getMessage());\n }\n }\n\n public static void usingFileUtils() throws IOException {\n //get the file object\n File file = FileUtils.getFile(\"input.txt\");\n\n //get the temp directory\n File tmpDir = FileUtils.getTempDirectory();\n\n System.out.println(tmpDir.getName());\n\n //copy file to temp directory\n FileUtils.copyFileToDirectory(file, tmpDir);\n\n //create a new file\n File newTempFile = FileUtils.getFile(tmpDir, file.getName());\n\n //get the content\n String data = FileUtils.readFileToString(newTempFile, Charset.defaultCharset());\n\n //print the content\n System.out.println(data);\n }\n}" }, { "code": null, "e": 4209, "s": 4173, "text": "It will print the following result." }, { "code": null, "e": 4264, "s": 4209, "text": "Temp\nWelcome to TutorialsPoint. Simply Easy Learning.\n" }, { "code": null, "e": 4271, "s": 4264, "text": " Print" }, { "code": null, "e": 4282, "s": 4271, "text": " Add Notes" } ]
AI with Python – Reinforcement Learning
In this chapter, you will learn in detail about the concepts reinforcement learning in AI with Python. This type of learning is used to reinforce or strengthen the network based on critic information. That is, a network being trained under reinforcement learning, receives some feedback from the environment. However, the feedback is evaluative and not instructive as in the case of supervised learning. Based on this feedback, the network performs the adjustments of the weights to obtain better critic information in future. This learning process is similar to supervised learning but we might have very less information. The following figure gives the block diagram of reinforcement learning − Environment and Agent are main building blocks of reinforcement learning in AI. This section discusses them in detail − An agent is anything that can perceive its environment through sensors and acts upon that environment through effectors. A human agent has sensory organs such as eyes, ears, nose, tongue and skin parallel to the sensors, and other organs such as hands, legs, mouth, for effectors. A human agent has sensory organs such as eyes, ears, nose, tongue and skin parallel to the sensors, and other organs such as hands, legs, mouth, for effectors. A robotic agent replaces cameras and infrared range finders for the sensors, and various motors and actuators for effectors. A robotic agent replaces cameras and infrared range finders for the sensors, and various motors and actuators for effectors. A software agent has encoded bit strings as its programs and actions. A software agent has encoded bit strings as its programs and actions. The following terms are more frequently used in reinforcement learning in AI − Performance Measure of Agent − It is the criteria, which determines how successful an agent is. Performance Measure of Agent − It is the criteria, which determines how successful an agent is. Behavior of Agent − It is the action that agent performs after any given sequence of percepts. Behavior of Agent − It is the action that agent performs after any given sequence of percepts. Percept − It is agent’s perceptual inputs at a given instance. Percept − It is agent’s perceptual inputs at a given instance. Percept Sequence − It is the history of all that an agent has perceived till date. Percept Sequence − It is the history of all that an agent has perceived till date. Agent Function − It is a map from the precept sequence to an action. Agent Function − It is a map from the precept sequence to an action. Some programs operate in an entirely artificial environment confined to keyboard input, database, computer file systems and character output on a screen. In contrast, some software agents, such as software robots or softbots, exist in rich and unlimited softbot domains. The simulator has a very detailed, and complex environment. The software agent needs to choose from a long array of actions in real time. For example, a softbot designed to scan the online preferences of the customer and display interesting items to the customer works in the real as well as an artificial environment. The environment has multifold properties as discussed below − Discrete/Continuous − If there are a limited number of distinct, clearly defined, states of the environment, the environment is discrete , otherwise it is continuous. For example, chess is a discrete environment and driving is a continuous environment. Discrete/Continuous − If there are a limited number of distinct, clearly defined, states of the environment, the environment is discrete , otherwise it is continuous. For example, chess is a discrete environment and driving is a continuous environment. Observable/Partially Observable − If it is possible to determine the complete state of the environment at each time point from the percepts, it is observable; otherwise it is only partially observable. Observable/Partially Observable − If it is possible to determine the complete state of the environment at each time point from the percepts, it is observable; otherwise it is only partially observable. Static/Dynamic − If the environment does not change while an agent is acting, then it is static; otherwise it is dynamic. Static/Dynamic − If the environment does not change while an agent is acting, then it is static; otherwise it is dynamic. Single agent/Multiple agents − The environment may contain other agents which may be of the same or different kind as that of the agent. Single agent/Multiple agents − The environment may contain other agents which may be of the same or different kind as that of the agent. Accessible/Inaccessible − If the agent’s sensory apparatus can have access to the complete state of the environment, then the environment is accessible to that agent; otherwise it is inaccessible. Accessible/Inaccessible − If the agent’s sensory apparatus can have access to the complete state of the environment, then the environment is accessible to that agent; otherwise it is inaccessible. Deterministic/Non-deterministic − If the next state of the environment is completely determined by the current state and the actions of the agent, then the environment is deterministic; otherwise it is non-deterministic. Deterministic/Non-deterministic − If the next state of the environment is completely determined by the current state and the actions of the agent, then the environment is deterministic; otherwise it is non-deterministic. Episodic/Non-episodic − In an episodic environment, each episode consists of the agent perceiving and then acting. The quality of its action depends just on the episode itself. Subsequent episodes do not depend on the actions in the previous episodes. Episodic environments are much simpler because the agent does not need to think ahead. Episodic/Non-episodic − In an episodic environment, each episode consists of the agent perceiving and then acting. The quality of its action depends just on the episode itself. Subsequent episodes do not depend on the actions in the previous episodes. Episodic environments are much simpler because the agent does not need to think ahead. For building reinforcement learning agent, we will be using the OpenAI Gym package which can be installed with the help of the following command − pip install gym There are various environments in OpenAI gym which can be used for various purposes. Few of them are Cartpole-v0, Hopper-v1, and MsPacman-v0. They require different engines. The detail documentation of OpenAI Gym can be found on https://gym.openai.com/docs/#environments. The following code shows an example of Python code for cartpole-v0 environment − import gym env = gym.make('CartPole-v0') env.reset() for _ in range(1000): env.render() env.step(env.action_space.sample()) You can construct other environments in a similar way. For building reinforcement learning agent, we will be using the OpenAI Gym package as shown − import gym env = gym.make('CartPole-v0') for _ in range(20): observation = env.reset() for i in range(100): env.render() print(observation) action = env.action_space.sample() observation, reward, done, info = env.step(action) if done: print("Episode finished after {} timesteps".format(i+1)) break Observe that the cartpole can balance itself. 78 Lectures 7 hours Arnab Chakraborty 87 Lectures 9.5 hours DigiFisk (Programming Is Fun) 10 Lectures 1 hours Nikoloz Sanakoevi 15 Lectures 54 mins Mukund Kumar Mishra 11 Lectures 1 hours Gilad James, PhD 20 Lectures 2 hours Gilad James, PhD Print Add Notes Bookmark this page
[ { "code": null, "e": 2308, "s": 2205, "text": "In this chapter, you will learn in detail about the concepts reinforcement learning in AI with Python." }, { "code": null, "e": 2732, "s": 2308, "text": "This type of learning is used to reinforce or strengthen the network based on critic information. That is, a network being trained under reinforcement learning, receives some feedback from the environment. However, the feedback is evaluative and not instructive as in the case of supervised learning. Based on this feedback, the network performs the adjustments of the weights to obtain better critic information in future." }, { "code": null, "e": 2902, "s": 2732, "text": "This learning process is similar to supervised learning but we might have very less information. The following figure gives the block diagram of reinforcement learning −" }, { "code": null, "e": 3022, "s": 2902, "text": "Environment and Agent are main building blocks of reinforcement learning in AI. This section discusses them in detail −" }, { "code": null, "e": 3143, "s": 3022, "text": "An agent is anything that can perceive its environment through sensors and acts upon that environment through effectors." }, { "code": null, "e": 3303, "s": 3143, "text": "A human agent has sensory organs such as eyes, ears, nose, tongue and skin parallel to the sensors, and other organs such as hands, legs, mouth, for effectors." }, { "code": null, "e": 3463, "s": 3303, "text": "A human agent has sensory organs such as eyes, ears, nose, tongue and skin parallel to the sensors, and other organs such as hands, legs, mouth, for effectors." }, { "code": null, "e": 3588, "s": 3463, "text": "A robotic agent replaces cameras and infrared range finders for the sensors, and various motors and actuators for effectors." }, { "code": null, "e": 3713, "s": 3588, "text": "A robotic agent replaces cameras and infrared range finders for the sensors, and various motors and actuators for effectors." }, { "code": null, "e": 3783, "s": 3713, "text": "A software agent has encoded bit strings as its programs and actions." }, { "code": null, "e": 3853, "s": 3783, "text": "A software agent has encoded bit strings as its programs and actions." }, { "code": null, "e": 3932, "s": 3853, "text": "The following terms are more frequently used in reinforcement learning in AI −" }, { "code": null, "e": 4028, "s": 3932, "text": "Performance Measure of Agent − It is the criteria, which determines how successful an agent is." }, { "code": null, "e": 4124, "s": 4028, "text": "Performance Measure of Agent − It is the criteria, which determines how successful an agent is." }, { "code": null, "e": 4219, "s": 4124, "text": "Behavior of Agent − It is the action that agent performs after any given sequence of percepts." }, { "code": null, "e": 4314, "s": 4219, "text": "Behavior of Agent − It is the action that agent performs after any given sequence of percepts." }, { "code": null, "e": 4377, "s": 4314, "text": "Percept − It is agent’s perceptual inputs at a given instance." }, { "code": null, "e": 4440, "s": 4377, "text": "Percept − It is agent’s perceptual inputs at a given instance." }, { "code": null, "e": 4523, "s": 4440, "text": "Percept Sequence − It is the history of all that an agent has perceived till date." }, { "code": null, "e": 4606, "s": 4523, "text": "Percept Sequence − It is the history of all that an agent has perceived till date." }, { "code": null, "e": 4675, "s": 4606, "text": "Agent Function − It is a map from the precept sequence to an action." }, { "code": null, "e": 4744, "s": 4675, "text": "Agent Function − It is a map from the precept sequence to an action." }, { "code": null, "e": 4898, "s": 4744, "text": "Some programs operate in an entirely artificial environment confined to keyboard input, database, computer file systems and character output on a screen." }, { "code": null, "e": 5153, "s": 4898, "text": "In contrast, some software agents, such as software robots or softbots, exist in rich and unlimited softbot domains. The simulator has a very detailed, and complex environment. The software agent needs to choose from a long array of actions in real time." }, { "code": null, "e": 5334, "s": 5153, "text": "For example, a softbot designed to scan the online preferences of the customer and display interesting items to the customer works in the real as well as an artificial environment." }, { "code": null, "e": 5396, "s": 5334, "text": "The environment has multifold properties as discussed below −" }, { "code": null, "e": 5649, "s": 5396, "text": "Discrete/Continuous − If there are a limited number of distinct, clearly defined, states of the environment, the environment is discrete , otherwise it is continuous. For example, chess is a discrete environment and driving is a continuous environment." }, { "code": null, "e": 5902, "s": 5649, "text": "Discrete/Continuous − If there are a limited number of distinct, clearly defined, states of the environment, the environment is discrete , otherwise it is continuous. For example, chess is a discrete environment and driving is a continuous environment." }, { "code": null, "e": 6104, "s": 5902, "text": "Observable/Partially Observable − If it is possible to determine the complete state of the environment at each time point from the percepts, it is observable; otherwise it is only partially observable." }, { "code": null, "e": 6306, "s": 6104, "text": "Observable/Partially Observable − If it is possible to determine the complete state of the environment at each time point from the percepts, it is observable; otherwise it is only partially observable." }, { "code": null, "e": 6428, "s": 6306, "text": "Static/Dynamic − If the environment does not change while an agent is acting, then it is static; otherwise it is dynamic." }, { "code": null, "e": 6550, "s": 6428, "text": "Static/Dynamic − If the environment does not change while an agent is acting, then it is static; otherwise it is dynamic." }, { "code": null, "e": 6687, "s": 6550, "text": "Single agent/Multiple agents − The environment may contain other agents which may be of the same or different kind as that of the agent." }, { "code": null, "e": 6824, "s": 6687, "text": "Single agent/Multiple agents − The environment may contain other agents which may be of the same or different kind as that of the agent." }, { "code": null, "e": 7021, "s": 6824, "text": "Accessible/Inaccessible − If the agent’s sensory apparatus can have access to the complete state of the environment, then the environment is accessible to that agent; otherwise it is inaccessible." }, { "code": null, "e": 7218, "s": 7021, "text": "Accessible/Inaccessible − If the agent’s sensory apparatus can have access to the complete state of the environment, then the environment is accessible to that agent; otherwise it is inaccessible." }, { "code": null, "e": 7439, "s": 7218, "text": "Deterministic/Non-deterministic − If the next state of the environment is completely determined by the current state and the actions of the agent, then the environment is deterministic; otherwise it is non-deterministic." }, { "code": null, "e": 7660, "s": 7439, "text": "Deterministic/Non-deterministic − If the next state of the environment is completely determined by the current state and the actions of the agent, then the environment is deterministic; otherwise it is non-deterministic." }, { "code": null, "e": 7999, "s": 7660, "text": "Episodic/Non-episodic − In an episodic environment, each episode consists of the agent perceiving and then acting. The quality of its action depends just on the episode itself. Subsequent episodes do not depend on the actions in the previous episodes. Episodic environments are much simpler because the agent does not need to think ahead." }, { "code": null, "e": 8338, "s": 7999, "text": "Episodic/Non-episodic − In an episodic environment, each episode consists of the agent perceiving and then acting. The quality of its action depends just on the episode itself. Subsequent episodes do not depend on the actions in the previous episodes. Episodic environments are much simpler because the agent does not need to think ahead." }, { "code": null, "e": 8485, "s": 8338, "text": "For building reinforcement learning agent, we will be using the OpenAI Gym package which can be installed with the help of the following command −" }, { "code": null, "e": 8502, "s": 8485, "text": "pip install gym\n" }, { "code": null, "e": 8774, "s": 8502, "text": "There are various environments in OpenAI gym which can be used for various purposes. Few of them are Cartpole-v0, Hopper-v1, and MsPacman-v0. They require different engines. The detail documentation of OpenAI Gym can be found on https://gym.openai.com/docs/#environments." }, { "code": null, "e": 8855, "s": 8774, "text": "The following code shows an example of Python code for cartpole-v0 environment −" }, { "code": null, "e": 8986, "s": 8855, "text": "import gym\nenv = gym.make('CartPole-v0')\nenv.reset()\nfor _ in range(1000):\n env.render()\n env.step(env.action_space.sample())\n" }, { "code": null, "e": 9041, "s": 8986, "text": "You can construct other environments in a similar way." }, { "code": null, "e": 9135, "s": 9041, "text": "For building reinforcement learning agent, we will be using the OpenAI Gym package as shown −" }, { "code": null, "e": 9487, "s": 9135, "text": "import gym\nenv = gym.make('CartPole-v0')\nfor _ in range(20):\n observation = env.reset()\n for i in range(100):\n env.render()\n print(observation)\n action = env.action_space.sample()\n observation, reward, done, info = env.step(action)\n if done:\n print(\"Episode finished after {} timesteps\".format(i+1))\n break" }, { "code": null, "e": 9533, "s": 9487, "text": "Observe that the cartpole can balance itself." }, { "code": null, "e": 9566, "s": 9533, "text": "\n 78 Lectures \n 7 hours \n" }, { "code": null, "e": 9585, "s": 9566, "text": " Arnab Chakraborty" }, { "code": null, "e": 9620, "s": 9585, "text": "\n 87 Lectures \n 9.5 hours \n" }, { "code": null, "e": 9651, "s": 9620, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 9684, "s": 9651, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 9703, "s": 9684, "text": " Nikoloz Sanakoevi" }, { "code": null, "e": 9735, "s": 9703, "text": "\n 15 Lectures \n 54 mins\n" }, { "code": null, "e": 9756, "s": 9735, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 9789, "s": 9756, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 9807, "s": 9789, "text": " Gilad James, PhD" }, { "code": null, "e": 9840, "s": 9807, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 9858, "s": 9840, "text": " Gilad James, PhD" }, { "code": null, "e": 9865, "s": 9858, "text": " Print" }, { "code": null, "e": 9876, "s": 9865, "text": " Add Notes" } ]
Laravel - Hashing
Hashing is the process of transforming a string of characters into a shorter fixed value or a key that represents the original string. Laravel uses the Hash facade which provides a secure way for storing passwords in a hashed manner. The following screenshot shows how to create a controller named passwordController which is used for storing and updating passwords − The following lines of code explain the functionality and usage of the passwordController − <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use App\Http\Controllers\Controller class passwordController extends Controller{ /** * Updating the password for the user. * * @param Request $request * @return Response */ public function update(Request $request) { // Validate the new password length... $request->user()->fill([ 'password' => Hash::make($request->newPassword) // Hashing passwords ])->save(); } } The hashed passwords are stored using make method. This method allows managing the work factor of the bcrypt hashing algorithm, which is popularly used in Laravel. You should verify the password against hash to check the string which was used for conversion. For this you can use the check method. This is shown in the code given below − if (Hash::check('plain-text', $hashedPassword)) { // The passwords match... } Note that the check method compares the plain-text with the hashedPassword variable and if the result is true, it returns a true value. 13 Lectures 3 hours Sebastian Sulinski 35 Lectures 3.5 hours Antonio Papa 7 Lectures 1.5 hours Sebastian Sulinski 42 Lectures 1 hours Skillbakerystudios 165 Lectures 13 hours Paul Carlo Tordecilla 116 Lectures 13 hours Hafizullah Masoudi Print Add Notes Bookmark this page
[ { "code": null, "e": 2706, "s": 2472, "text": "Hashing is the process of transforming a string of characters into a shorter fixed value or a key that represents the original string. Laravel uses the Hash facade which provides a secure way for storing passwords in a hashed manner." }, { "code": null, "e": 2840, "s": 2706, "text": "The following screenshot shows how to create a controller named passwordController which is used for storing and updating passwords −" }, { "code": null, "e": 2932, "s": 2840, "text": "The following lines of code explain the functionality and usage of the passwordController −" }, { "code": null, "e": 3471, "s": 2932, "text": "<?php\n\nnamespace App\\Http\\Controllers;\n\nuse Illuminate\\Http\\Request;\nuse Illuminate\\Support\\Facades\\Hash;\nuse App\\Http\\Controllers\\Controller\n\nclass passwordController extends Controller{\n /**\n * Updating the password for the user.\n *\n * @param Request $request\n * @return Response\n */\n \n public function update(Request $request) {\n // Validate the new password length...\n $request->user()->fill([\n 'password' => Hash::make($request->newPassword) // Hashing passwords\n ])->save();\n }\n}" }, { "code": null, "e": 3635, "s": 3471, "text": "The hashed passwords are stored using make method. This method allows managing the work factor of the bcrypt hashing algorithm, which is popularly used in Laravel." }, { "code": null, "e": 3809, "s": 3635, "text": "You should verify the password against hash to check the string which was used for conversion. For this you can use the check method. This is shown in the code given below −" }, { "code": null, "e": 3891, "s": 3809, "text": "if (Hash::check('plain-text', $hashedPassword)) {\n // The passwords match...\n}\n" }, { "code": null, "e": 4027, "s": 3891, "text": "Note that the check method compares the plain-text with the hashedPassword variable and if the result is true, it returns a true value." }, { "code": null, "e": 4060, "s": 4027, "text": "\n 13 Lectures \n 3 hours \n" }, { "code": null, "e": 4080, "s": 4060, "text": " Sebastian Sulinski" }, { "code": null, "e": 4115, "s": 4080, "text": "\n 35 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4129, "s": 4115, "text": " Antonio Papa" }, { "code": null, "e": 4163, "s": 4129, "text": "\n 7 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4183, "s": 4163, "text": " Sebastian Sulinski" }, { "code": null, "e": 4216, "s": 4183, "text": "\n 42 Lectures \n 1 hours \n" }, { "code": null, "e": 4236, "s": 4216, "text": " Skillbakerystudios" }, { "code": null, "e": 4271, "s": 4236, "text": "\n 165 Lectures \n 13 hours \n" }, { "code": null, "e": 4294, "s": 4271, "text": " Paul Carlo Tordecilla" }, { "code": null, "e": 4329, "s": 4294, "text": "\n 116 Lectures \n 13 hours \n" }, { "code": null, "e": 4349, "s": 4329, "text": " Hafizullah Masoudi" }, { "code": null, "e": 4356, "s": 4349, "text": " Print" }, { "code": null, "e": 4367, "s": 4356, "text": " Add Notes" } ]
How To Simulate Traffic On Urban Networks Using SUMO | by Skanda Vivek | Towards Data Science
Understanding, predicting, and ultimately — reducing traffic congestion in urban networks is a complex problem. Even understanding the emergence of traffic congestion in the most simple case — a single lane road, is challenging. The Simulation of Urban Mobility (SUMO) platform is an open source platform that enables simulation of traffic flows in complex environments. But apart from the SUMO documentation, a few Stack Overflow posts, and some YouTube videos, there aren’t many tutorials I’ve come across that teach you how to create a complex traffic simulation from start to finish. This article is going to do this exact thing, using a case-study of traffic on grid networks. The article is structured as follows: Why study traffic in urban networks?Getting Started with SUMOSimulating traffic in grid networksAnalysis of key traffic performance metricsFuture directions in simulating realistic traffic Why study traffic in urban networks? Getting Started with SUMO Simulating traffic in grid networks Analysis of key traffic performance metrics Future directions in simulating realistic traffic In a previous article, I discuss the first paper that conclusively showed how traffic “phantom” shock-waves emerge from nothing, except driver interactions. Recent research suggests that streamlined interactions between autonomous vehicles could potentially reduce traffic jams for artificial scenarios like vehicles driving in a circle. But what happens when you have multiple roads, as in typical urban road networks? Interestingly, just increasing capacity through more lanes or longer roads might not work as well as you thing, in road networks. In another article I show how “Braess’s Paradox” leads to the unusual result, that increasing the number of roads in an urban network, could make traffic worse! Before engaging in intensive infrastructure projects such as building new roads, adding lanes, traffic lights, etc. — it is important to have realistic simulations of traffic flows so that the proposed projects have a best chance of succeeding in alleviating traffic. The situation gets more complicated when integrating major events such as concerts, sporting events, etc. or public buildings like airports and hospitals into the picture. In the near future, it’s important to simulate the effects of proposed connected vehicle and intelligent transportation technological innovations, to best realize their potential in streamlining traffic flows. Traffic simulations seem to belong to a niche community of traffic flow researchers, or engineering contracting companies. For example, Anylogic, VISSIM, and Aimsun are companies that offer traffic and mobility modeling solutions. However, SUMO is open access and is fairly easy to get started in. There are multiple ways to install SUMO, but I prefer the pip install way, that installs SUMO as well as the python libraries to interface with SUMO. python -m pip install sumo That’s it! Now let’s get to creating your first simulation of traffic flow on a network! In urban planning, grid road networks are pretty common. In SUMO, we setup a 5x5 grid with each road of length 200m, and 3 lanes, as below: netgenerate — grid — grid.number=5 -L=3 — grid.length=200 — output-file=grid.net.xml Next, we use randomTrips.py located in the tools folder within the SUMO home directory (sumo -> tools), to generate random trips for a certain number of vehicles (200 vehicles in the example below). The begin and end times denote the times during which the vehicles enter the simulation. I’ve chosen 0&1, meaning all vehicles enter the simulation in the first 1 second of the simulation. Period denotes the arrival rate of vehicles. randomTrips.py -n grid.net.xml -o flows.xml — begin 0 — end 1 — period 1 — flows 200 Next, we generate the routes taken by individual vehicles using SUMO’s jtrrouter, between times 0 to 10000. jtrrouter — flow-files=flows.xml — net-file=grid.net.xml — output-file=grid.rou.xml — begin 0 — end 10000 — accept-all-destinations Finally, for simplicity we want to maintain a constant density. The most obvious way to do this is by vehicles driving randomly, and not exiting the simulation. For this, we use the Manhattan traffic model, where vehicles encountering an intersection choose to either go straight, left, or right based on set probabilities. By default in SUMO, vehicles exit the simulation once they reach their destination. However, SUMO has an implementation of the Manhattan model, using a continuous rerouter python script. generateContinuousRerouters.py -n grid.net.xml — end 10000 -o rerouter.add.xml Next, we create a sumo config file, in order to run the simulation in SUMO, which is basically a .xml file with certain attributes, containing the names of the network file, route file, and additional rerouting file for vehicles to stay in the simulation until the simulation is completed. We define an output file, to store the detailed vehicle information during the traffic simulation. <configuration> <input> <net-file value=”grid.net.xml”/> <route-files value=”grid.rou.xml”/> <additional-files value=”rerouter.add.xml”/> </input> <time> <begin value=”0"/> <end value=”10000"/> </time> <output> <fcd-output value=”grid.output.xml”/> </output></configuration> Finally, we run the simulation in the terminal as below. Period denotes the time interval at which data is saved — 100 denotes saving vehicular information i.e. speed and position, every 100 timesteps. sumo-gui -c grid.sumocfg — device.fcd.period 100 Running this pops up the SUMO GUI, where you can see the entire simulation! Vehicle colors indicate their speeds from slowest (red) to fastest (green). It is quite annoying to manually go and change every parameter and output file by hand. This adds up if you have 100+ runs for exploring how traffic changes with different parameters such as the number of vehicles, and multiple runs for statistical averaging. For this, I interfaced SUMO on the command prompt with python using the OS module: The SUMO xml outputs contain information on individual vehicle time, position, and velocity at every time step. I want to analyze how velocity depends on density, or number of vehicles in the simulation — basically obtain velocity at each time step, averaging over all vehicles in the simulation. Finally, I plot velocity vs density where each simulation run has an individual density. As you can see, as density increases, velocity decreases. This is because the more the vehicles in the simulation, the more the congestion, resulting in lower travel speeds. This is something all of us have seen on the highway, especially during rush hour. Another commonly used parameter in traffic simulations is flux. As I discuss in a previous article, flux measures the number of vehicles per time that pass through a given point, and is a measure of vehicle throughput. Flux is given as: Where the summation is over all vehicle velocities within a length L, and number of lanes=n_l. At low densities, every vehicle is basically traveling at the speed limit so flux increases linearly with density (red line in the plot below). However, at higher densities, vehicles can’t travel at the speed limit and at a certain point, the effect of a larger number of vehicles is countered by each vehicle traveling at a smaller speed, resulting in a reduced flux. Above a characteristic density (~0.1–0.2 in this simulation), traffic jams emerge and flux decays with density. I’ve shown how to set up basic traffic simulations and ensemble runs in representative grid networks using SUMO+Python. However, this is by no means a comprehensive simulation on urban networks. In a recent study leveraging OpenStreetMap urban street network data and OSMnx, it was found that some cities feature prominent grid like networks, whereas some other’s don’t. SUMO includes the ability to simulate traffic in urban street networks, by converting OpenStreetMap data into SUMO .net files. But apart from simulations on realistic city networks, there is also the issue of calibrating these traffic simulations to match daily traffic patterns. To match detailed traffic patterns that are seen in daily life, one needs to account for the ebbs and flows in people entering roads — where they enter, when they enter, and when/where they leave. This becomes an extremely complex problem as it is not possible to know every vehicle trajectory. Many vehicles nowadays transmit GPS data to companies like INRIX and HERE technologies. Companies like Google and Apple make use of cell-phone data for sparse location and speed information. However, this can only provide information on a small sample of the entire population. Traffic flow is a highly non — linear problem; meaning small changes can have extreme consequences. At the same time, you want your traffic simulation results to be robust to initial conditions. The results should clearly indicate whether or not a proposed project has a significant traffic flow improvement or not — for a broad range of scenarios. It is a challenge to have detailed large-scale traffic simulations, that run in a feasible amount of time, and are realistic. On the SUMO page, there’s only a handful of such realistic scenarios. The top of the page reads: Building a scenario is a lot of work. If you have built a SUMO scenario you can share (under a sufficiently open license), please contact us. Hopefully the democratization of traffic mobility data, increasing availability of computational resources, and open-source traffic modeling platforms will make these large-scale simulations more accessible. Urban traffic is a wonderfully complex game that provides insights into breathing, living cities. The code for this project is available on GitHub: github.com References: R. E. Stern, et al. “Dissipation of stop-and-go waves via control of autonomous vehicles: Field experiments,” arXiv (2017).G. Boeing, “Urban spatial order: street network orientation, configuration, and entropy,” Applied Network Science (2019).P. L. Alvarez, et al. “Microscopic traffic simulation using SUMO,” International Conference on Intelligent Transportation Systems. IEEE (2018). R. E. Stern, et al. “Dissipation of stop-and-go waves via control of autonomous vehicles: Field experiments,” arXiv (2017). G. Boeing, “Urban spatial order: street network orientation, configuration, and entropy,” Applied Network Science (2019). P. L. Alvarez, et al. “Microscopic traffic simulation using SUMO,” International Conference on Intelligent Transportation Systems. IEEE (2018). Follow me if you liked this article. Subscribe to my newsletter if you enjoy holistic perspectives on the interconnections between technology and modern societies.
[ { "code": null, "e": 892, "s": 172, "text": "Understanding, predicting, and ultimately — reducing traffic congestion in urban networks is a complex problem. Even understanding the emergence of traffic congestion in the most simple case — a single lane road, is challenging. The Simulation of Urban Mobility (SUMO) platform is an open source platform that enables simulation of traffic flows in complex environments. But apart from the SUMO documentation, a few Stack Overflow posts, and some YouTube videos, there aren’t many tutorials I’ve come across that teach you how to create a complex traffic simulation from start to finish. This article is going to do this exact thing, using a case-study of traffic on grid networks. The article is structured as follows:" }, { "code": null, "e": 1081, "s": 892, "text": "Why study traffic in urban networks?Getting Started with SUMOSimulating traffic in grid networksAnalysis of key traffic performance metricsFuture directions in simulating realistic traffic" }, { "code": null, "e": 1118, "s": 1081, "text": "Why study traffic in urban networks?" }, { "code": null, "e": 1144, "s": 1118, "text": "Getting Started with SUMO" }, { "code": null, "e": 1180, "s": 1144, "text": "Simulating traffic in grid networks" }, { "code": null, "e": 1224, "s": 1180, "text": "Analysis of key traffic performance metrics" }, { "code": null, "e": 1274, "s": 1224, "text": "Future directions in simulating realistic traffic" }, { "code": null, "e": 1431, "s": 1274, "text": "In a previous article, I discuss the first paper that conclusively showed how traffic “phantom” shock-waves emerge from nothing, except driver interactions." }, { "code": null, "e": 1985, "s": 1431, "text": "Recent research suggests that streamlined interactions between autonomous vehicles could potentially reduce traffic jams for artificial scenarios like vehicles driving in a circle. But what happens when you have multiple roads, as in typical urban road networks? Interestingly, just increasing capacity through more lanes or longer roads might not work as well as you thing, in road networks. In another article I show how “Braess’s Paradox” leads to the unusual result, that increasing the number of roads in an urban network, could make traffic worse!" }, { "code": null, "e": 2635, "s": 1985, "text": "Before engaging in intensive infrastructure projects such as building new roads, adding lanes, traffic lights, etc. — it is important to have realistic simulations of traffic flows so that the proposed projects have a best chance of succeeding in alleviating traffic. The situation gets more complicated when integrating major events such as concerts, sporting events, etc. or public buildings like airports and hospitals into the picture. In the near future, it’s important to simulate the effects of proposed connected vehicle and intelligent transportation technological innovations, to best realize their potential in streamlining traffic flows." }, { "code": null, "e": 2933, "s": 2635, "text": "Traffic simulations seem to belong to a niche community of traffic flow researchers, or engineering contracting companies. For example, Anylogic, VISSIM, and Aimsun are companies that offer traffic and mobility modeling solutions. However, SUMO is open access and is fairly easy to get started in." }, { "code": null, "e": 3083, "s": 2933, "text": "There are multiple ways to install SUMO, but I prefer the pip install way, that installs SUMO as well as the python libraries to interface with SUMO." }, { "code": null, "e": 3110, "s": 3083, "text": "python -m pip install sumo" }, { "code": null, "e": 3199, "s": 3110, "text": "That’s it! Now let’s get to creating your first simulation of traffic flow on a network!" }, { "code": null, "e": 3339, "s": 3199, "text": "In urban planning, grid road networks are pretty common. In SUMO, we setup a 5x5 grid with each road of length 200m, and 3 lanes, as below:" }, { "code": null, "e": 3424, "s": 3339, "text": "netgenerate — grid — grid.number=5 -L=3 — grid.length=200 — output-file=grid.net.xml" }, { "code": null, "e": 3857, "s": 3424, "text": "Next, we use randomTrips.py located in the tools folder within the SUMO home directory (sumo -> tools), to generate random trips for a certain number of vehicles (200 vehicles in the example below). The begin and end times denote the times during which the vehicles enter the simulation. I’ve chosen 0&1, meaning all vehicles enter the simulation in the first 1 second of the simulation. Period denotes the arrival rate of vehicles." }, { "code": null, "e": 3942, "s": 3857, "text": "randomTrips.py -n grid.net.xml -o flows.xml — begin 0 — end 1 — period 1 — flows 200" }, { "code": null, "e": 4050, "s": 3942, "text": "Next, we generate the routes taken by individual vehicles using SUMO’s jtrrouter, between times 0 to 10000." }, { "code": null, "e": 4182, "s": 4050, "text": "jtrrouter — flow-files=flows.xml — net-file=grid.net.xml — output-file=grid.rou.xml — begin 0 — end 10000 — accept-all-destinations" }, { "code": null, "e": 4693, "s": 4182, "text": "Finally, for simplicity we want to maintain a constant density. The most obvious way to do this is by vehicles driving randomly, and not exiting the simulation. For this, we use the Manhattan traffic model, where vehicles encountering an intersection choose to either go straight, left, or right based on set probabilities. By default in SUMO, vehicles exit the simulation once they reach their destination. However, SUMO has an implementation of the Manhattan model, using a continuous rerouter python script." }, { "code": null, "e": 4772, "s": 4693, "text": "generateContinuousRerouters.py -n grid.net.xml — end 10000 -o rerouter.add.xml" }, { "code": null, "e": 5161, "s": 4772, "text": "Next, we create a sumo config file, in order to run the simulation in SUMO, which is basically a .xml file with certain attributes, containing the names of the network file, route file, and additional rerouting file for vehicles to stay in the simulation until the simulation is completed. We define an output file, to store the detailed vehicle information during the traffic simulation." }, { "code": null, "e": 5463, "s": 5161, "text": "<configuration> <input> <net-file value=”grid.net.xml”/> <route-files value=”grid.rou.xml”/> <additional-files value=”rerouter.add.xml”/> </input> <time> <begin value=”0\"/> <end value=”10000\"/> </time> <output> <fcd-output value=”grid.output.xml”/> </output></configuration>" }, { "code": null, "e": 5665, "s": 5463, "text": "Finally, we run the simulation in the terminal as below. Period denotes the time interval at which data is saved — 100 denotes saving vehicular information i.e. speed and position, every 100 timesteps." }, { "code": null, "e": 5714, "s": 5665, "text": "sumo-gui -c grid.sumocfg — device.fcd.period 100" }, { "code": null, "e": 5790, "s": 5714, "text": "Running this pops up the SUMO GUI, where you can see the entire simulation!" }, { "code": null, "e": 5866, "s": 5790, "text": "Vehicle colors indicate their speeds from slowest (red) to fastest (green)." }, { "code": null, "e": 6126, "s": 5866, "text": "It is quite annoying to manually go and change every parameter and output file by hand. This adds up if you have 100+ runs for exploring how traffic changes with different parameters such as the number of vehicles, and multiple runs for statistical averaging." }, { "code": null, "e": 6209, "s": 6126, "text": "For this, I interfaced SUMO on the command prompt with python using the OS module:" }, { "code": null, "e": 6506, "s": 6209, "text": "The SUMO xml outputs contain information on individual vehicle time, position, and velocity at every time step. I want to analyze how velocity depends on density, or number of vehicles in the simulation — basically obtain velocity at each time step, averaging over all vehicles in the simulation." }, { "code": null, "e": 6595, "s": 6506, "text": "Finally, I plot velocity vs density where each simulation run has an individual density." }, { "code": null, "e": 6852, "s": 6595, "text": "As you can see, as density increases, velocity decreases. This is because the more the vehicles in the simulation, the more the congestion, resulting in lower travel speeds. This is something all of us have seen on the highway, especially during rush hour." }, { "code": null, "e": 7089, "s": 6852, "text": "Another commonly used parameter in traffic simulations is flux. As I discuss in a previous article, flux measures the number of vehicles per time that pass through a given point, and is a measure of vehicle throughput. Flux is given as:" }, { "code": null, "e": 7184, "s": 7089, "text": "Where the summation is over all vehicle velocities within a length L, and number of lanes=n_l." }, { "code": null, "e": 7665, "s": 7184, "text": "At low densities, every vehicle is basically traveling at the speed limit so flux increases linearly with density (red line in the plot below). However, at higher densities, vehicles can’t travel at the speed limit and at a certain point, the effect of a larger number of vehicles is countered by each vehicle traveling at a smaller speed, resulting in a reduced flux. Above a characteristic density (~0.1–0.2 in this simulation), traffic jams emerge and flux decays with density." }, { "code": null, "e": 8163, "s": 7665, "text": "I’ve shown how to set up basic traffic simulations and ensemble runs in representative grid networks using SUMO+Python. However, this is by no means a comprehensive simulation on urban networks. In a recent study leveraging OpenStreetMap urban street network data and OSMnx, it was found that some cities feature prominent grid like networks, whereas some other’s don’t. SUMO includes the ability to simulate traffic in urban street networks, by converting OpenStreetMap data into SUMO .net files." }, { "code": null, "e": 8989, "s": 8163, "text": "But apart from simulations on realistic city networks, there is also the issue of calibrating these traffic simulations to match daily traffic patterns. To match detailed traffic patterns that are seen in daily life, one needs to account for the ebbs and flows in people entering roads — where they enter, when they enter, and when/where they leave. This becomes an extremely complex problem as it is not possible to know every vehicle trajectory. Many vehicles nowadays transmit GPS data to companies like INRIX and HERE technologies. Companies like Google and Apple make use of cell-phone data for sparse location and speed information. However, this can only provide information on a small sample of the entire population. Traffic flow is a highly non — linear problem; meaning small changes can have extreme consequences." }, { "code": null, "e": 9364, "s": 8989, "text": "At the same time, you want your traffic simulation results to be robust to initial conditions. The results should clearly indicate whether or not a proposed project has a significant traffic flow improvement or not — for a broad range of scenarios. It is a challenge to have detailed large-scale traffic simulations, that run in a feasible amount of time, and are realistic." }, { "code": null, "e": 9461, "s": 9364, "text": "On the SUMO page, there’s only a handful of such realistic scenarios. The top of the page reads:" }, { "code": null, "e": 9603, "s": 9461, "text": "Building a scenario is a lot of work. If you have built a SUMO scenario you can share (under a sufficiently open license), please contact us." }, { "code": null, "e": 9909, "s": 9603, "text": "Hopefully the democratization of traffic mobility data, increasing availability of computational resources, and open-source traffic modeling platforms will make these large-scale simulations more accessible. Urban traffic is a wonderfully complex game that provides insights into breathing, living cities." }, { "code": null, "e": 9959, "s": 9909, "text": "The code for this project is available on GitHub:" }, { "code": null, "e": 9970, "s": 9959, "text": "github.com" }, { "code": null, "e": 9982, "s": 9970, "text": "References:" }, { "code": null, "e": 10370, "s": 9982, "text": "R. E. Stern, et al. “Dissipation of stop-and-go waves via control of autonomous vehicles: Field experiments,” arXiv (2017).G. Boeing, “Urban spatial order: street network orientation, configuration, and entropy,” Applied Network Science (2019).P. L. Alvarez, et al. “Microscopic traffic simulation using SUMO,” International Conference on Intelligent Transportation Systems. IEEE (2018)." }, { "code": null, "e": 10494, "s": 10370, "text": "R. E. Stern, et al. “Dissipation of stop-and-go waves via control of autonomous vehicles: Field experiments,” arXiv (2017)." }, { "code": null, "e": 10616, "s": 10494, "text": "G. Boeing, “Urban spatial order: street network orientation, configuration, and entropy,” Applied Network Science (2019)." }, { "code": null, "e": 10760, "s": 10616, "text": "P. L. Alvarez, et al. “Microscopic traffic simulation using SUMO,” International Conference on Intelligent Transportation Systems. IEEE (2018)." }, { "code": null, "e": 10797, "s": 10760, "text": "Follow me if you liked this article." } ]
Angular ng Bootstrap Pagination Component - GeeksforGeeks
08 Sep, 2021 Angular ng bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. In this article, we will see how to use Pagination in angular ng bootstrap. Pagination is used to make a group of pages. Installation syntax: ng add @ng-bootstrap/ng-bootstrap Approach: First, install the angular ng bootstrap using the above-mentioned command. Import ng bootstrap module in module.tsimport { NgbModule } from '@ng-bootstrap/ng-bootstrap'; imports: [ NgbModule ] import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; imports: [ NgbModule ] In app.component.html make a pagination component. Serve the app using ng serve. Example 1: In this example, we are making a pagination with boundary link. app.component.html <br/><h1>GeeksforGeeks</h1><h3>Angular ng bootstrap</h3><ngb-pagination [collectionSize]="70" [(page)]="page" [boundaryLinks]="true" ></ngb-pagination> app.module.ts import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule }from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { } app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { page = 4;} Output: Example 2: In this example, we have set the pagination with boundary link to false. app.component.html <br/><h1>GeeksforGeeks</h1><h3>Angular ng bootstrap</h3><ngb-pagination [collectionSize]="70" [(page)]="page" [boundaryLinks]="false" ></ngb-pagination> app.module.ts import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule }from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import { AppComponent } from './app.component';import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { } app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { page = 4;} Output: Reference: https://ng-bootstrap.github.io/#/components/pagination/overview sumitgumber28 Angular-ng-bootstrap AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Calendar Component Angular PrimeNG Messages Component Angular PrimeNG Dropdown Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? 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": 26464, "s": 26436, "text": "\n08 Sep, 2021" }, { "code": null, "e": 26648, "s": 26464, "text": "Angular ng bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites." }, { "code": null, "e": 26769, "s": 26648, "text": "In this article, we will see how to use Pagination in angular ng bootstrap. Pagination is used to make a group of pages." }, { "code": null, "e": 26790, "s": 26769, "text": "Installation syntax:" }, { "code": null, "e": 26824, "s": 26790, "text": "ng add @ng-bootstrap/ng-bootstrap" }, { "code": null, "e": 26834, "s": 26824, "text": "Approach:" }, { "code": null, "e": 26909, "s": 26834, "text": "First, install the angular ng bootstrap using the above-mentioned command." }, { "code": null, "e": 27031, "s": 26909, "text": "Import ng bootstrap module in module.tsimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\n\nimports: [\n NgbModule\n]\n" }, { "code": null, "e": 27114, "s": 27031, "text": "import { NgbModule } from '@ng-bootstrap/ng-bootstrap';\n\nimports: [\n NgbModule\n]\n" }, { "code": null, "e": 27165, "s": 27114, "text": "In app.component.html make a pagination component." }, { "code": null, "e": 27195, "s": 27165, "text": "Serve the app using ng serve." }, { "code": null, "e": 27272, "s": 27197, "text": "Example 1: In this example, we are making a pagination with boundary link." }, { "code": null, "e": 27291, "s": 27272, "text": "app.component.html" }, { "code": "<br/><h1>GeeksforGeeks</h1><h3>Angular ng bootstrap</h3><ngb-pagination [collectionSize]=\"70\" [(page)]=\"page\" [boundaryLinks]=\"true\" ></ngb-pagination>", "e": 27449, "s": 27291, "text": null }, { "code": null, "e": 27463, "s": 27449, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule }from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }", "e": 28068, "s": 27463, "text": null }, { "code": null, "e": 28085, "s": 28068, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { page = 4;}", "e": 28288, "s": 28085, "text": null }, { "code": null, "e": 28296, "s": 28288, "text": "Output:" }, { "code": null, "e": 28380, "s": 28296, "text": "Example 2: In this example, we have set the pagination with boundary link to false." }, { "code": null, "e": 28399, "s": 28380, "text": "app.component.html" }, { "code": "<br/><h1>GeeksforGeeks</h1><h3>Angular ng bootstrap</h3><ngb-pagination [collectionSize]=\"70\" [(page)]=\"page\" [boundaryLinks]=\"false\" ></ngb-pagination>", "e": 28557, "s": 28399, "text": null }, { "code": null, "e": 28571, "s": 28557, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule }from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import { AppComponent } from './app.component';import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }", "e": 29172, "s": 28571, "text": null }, { "code": null, "e": 29189, "s": 29172, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { page = 4;}", "e": 29392, "s": 29189, "text": null }, { "code": null, "e": 29400, "s": 29392, "text": "Output:" }, { "code": null, "e": 29475, "s": 29400, "text": "Reference: https://ng-bootstrap.github.io/#/components/pagination/overview" }, { "code": null, "e": 29489, "s": 29475, "text": "sumitgumber28" }, { "code": null, "e": 29510, "s": 29489, "text": "Angular-ng-bootstrap" }, { "code": null, "e": 29520, "s": 29510, "text": "AngularJS" }, { "code": null, "e": 29537, "s": 29520, "text": "Web Technologies" }, { "code": null, "e": 29635, "s": 29537, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29670, "s": 29635, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 29705, "s": 29670, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 29740, "s": 29705, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 29764, "s": 29740, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 29817, "s": 29764, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 29857, "s": 29817, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29890, "s": 29857, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29935, "s": 29890, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29978, "s": 29935, "text": "How to fetch data from an API in ReactJS ?" } ]
Concatenate multiple rows and columns in a single row with MySQL
To concatenate multiple rows and columns in single row, you can use GROUP_CONCAT() along with CONCAT(). Let us first create a table − mysql> create table DemoTable1463 -> ( -> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> ClientName varchar(20), -> ClientAge int -> ); Query OK, 0 rows affected (1.37 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1463(ClientName,ClientAge) values('Adam Smith',34); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1463(ClientName,ClientAge) values('John Doe',29); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable1463(ClientName,ClientAge) values('David Miller',NULL); Query OK, 1 row affected (0.28 sec) mysql> insert into DemoTable1463(ClientName,ClientAge) values('John Smith',32); Query OK, 1 row affected (0.14 sec) Display all records from the table using select statement − mysql> select * from DemoTable1463; This will produce the following output − +----------+--------------+-----------+ | ClientId | ClientName | ClientAge | +----------+--------------+-----------+ | 1 | Adam Smith | 34 | | 2 | John Doe | 29 | | 3 | David Miller | NULL | | 4 | John Smith | 32 | +----------+--------------+-----------+ 4 rows in set (0.00 sec) Following is the query to concatenate multiple rows and columns in a single row − mysql> select group_concat(concat(ClientId,':',ClientName,':',IFNULL(ClientAge,''))) from DemoTable1463; This will produce the following output − +------------------------------------------------------------------------+ | group_concat(concat(ClientId,':',ClientName,':',IFNULL(ClientAge,''))) | +------------------------------------------------------------------------+ | 1:Adam Smith:34,2:John Doe:29,3:David Miller:,4:John Smith:32 | +------------------------------------------------------------------------+ 1 row in set (0.04 sec)
[ { "code": null, "e": 1196, "s": 1062, "text": "To concatenate multiple rows and columns in single row, you can use GROUP_CONCAT() along with CONCAT(). Let us first create a table −" }, { "code": null, "e": 1390, "s": 1196, "text": "mysql> create table DemoTable1463\n -> (\n -> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> ClientName varchar(20),\n -> ClientAge int\n -> );\nQuery OK, 0 rows affected (1.37 sec)" }, { "code": null, "e": 1446, "s": 1390, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1912, "s": 1446, "text": "mysql> insert into DemoTable1463(ClientName,ClientAge) values('Adam Smith',34);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable1463(ClientName,ClientAge) values('John Doe',29);\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into DemoTable1463(ClientName,ClientAge) values('David Miller',NULL);\nQuery OK, 1 row affected (0.28 sec)\nmysql> insert into DemoTable1463(ClientName,ClientAge) values('John Smith',32);\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 1972, "s": 1912, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2008, "s": 1972, "text": "mysql> select * from DemoTable1463;" }, { "code": null, "e": 2049, "s": 2008, "text": "This will produce the following output −" }, { "code": null, "e": 2394, "s": 2049, "text": "+----------+--------------+-----------+\n| ClientId | ClientName | ClientAge |\n+----------+--------------+-----------+\n| 1 | Adam Smith | 34 |\n| 2 | John Doe | 29 |\n| 3 | David Miller | NULL |\n| 4 | John Smith | 32 |\n+----------+--------------+-----------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2476, "s": 2394, "text": "Following is the query to concatenate multiple rows and columns in a single row −" }, { "code": null, "e": 2581, "s": 2476, "text": "mysql> select group_concat(concat(ClientId,':',ClientName,':',IFNULL(ClientAge,''))) from DemoTable1463;" }, { "code": null, "e": 2622, "s": 2581, "text": "This will produce the following output −" }, { "code": null, "e": 3021, "s": 2622, "text": "+------------------------------------------------------------------------+\n| group_concat(concat(ClientId,':',ClientName,':',IFNULL(ClientAge,''))) |\n+------------------------------------------------------------------------+\n| 1:Adam Smith:34,2:John Doe:29,3:David Miller:,4:John Smith:32 |\n+------------------------------------------------------------------------+\n1 row in set (0.04 sec)" } ]
Deploy Python Flask App on Heroku
19 Oct, 2021 Flask is a web application framework written in Python. Flask is based on the Werkzeug WSGI toolkit and Jinja2 template engine. Both are Pocco projects. This article revolves around how to deploy a flask app on Heroku. To demonstrate this, we are first going to create a sample application for a better understanding of the process. Python pip Heroku CLI Git Let’s create a simple flask application first and then it can be deployed to heroku. Create a folder named “eflask” and open the command line and cd inside the “eflask” directory. Follow the following steps to create the sample application for this tutorial.STEP 1 : Create a virtual environment with pipenv and install Flask and Gunicorn . $ pipenv install flask gunicorn STEP 2 : Create a “Procfile” and write the following code. $ touch Procfile STEP 3 : Create “runtime.txt” and write the following code. $ touch runtime.txt STEP 4 : Create a folder named “app” and enter the folder. $ mkdir app $ cd app STEP 5 : Create a python file, “main.py” and enter the sample code. touch main.py Python3 from flask import Flask app = Flask(__name__) @app.route("/")def home_view(): return "<h1>Welcome to Geeks for Geeks</h1>" STEP 6 :Get back to the previous directory “eflask”.Create a file“wsgi.py” and insert the following code. $ cd ../ $ touch wsgi.py Python3 from app.main import app if __name__ == "__main__": app.run() STEP 7 : Run the virtual environment. $ pipenv shell STEP 8 : Initialize an empty repo, add the files in the repo and commit all the changes. $ git init $ git add . $ git commit -m "Initial Commit" STEP 9 : Login to heroku CLI using heroku login Now, Create a unique name for your Web app. $ heroku create eflask-app STEP 10 : Push your code from local to the heroku remote. $ git push heroku master Finally, web app will be deployed on http://eflask-app.herokuapp.com. rajeev0719singh Articles Git Python Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Complexity and Space Complexity SQL Interview Questions Understanding "extern" keyword in C Java Tutorial SQL | Views Working on Git for GUI How to Set Git Username and Password in GitBash? How to integrate Git Bash with Visual Studio Code? Git - Difference Between Git Fetch and Git Pull Working on Git Bash
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Oct, 2021" }, { "code": null, "e": 386, "s": 52, "text": "Flask is a web application framework written in Python. Flask is based on the Werkzeug WSGI toolkit and Jinja2 template engine. Both are Pocco projects. This article revolves around how to deploy a flask app on Heroku. To demonstrate this, we are first going to create a sample application for a better understanding of the process. " }, { "code": null, "e": 393, "s": 386, "text": "Python" }, { "code": null, "e": 397, "s": 393, "text": "pip" }, { "code": null, "e": 408, "s": 397, "text": "Heroku CLI" }, { "code": null, "e": 412, "s": 408, "text": "Git" }, { "code": null, "e": 756, "s": 414, "text": "Let’s create a simple flask application first and then it can be deployed to heroku. Create a folder named “eflask” and open the command line and cd inside the “eflask” directory. Follow the following steps to create the sample application for this tutorial.STEP 1 : Create a virtual environment with pipenv and install Flask and Gunicorn . " }, { "code": null, "e": 789, "s": 756, "text": "$ pipenv install flask gunicorn " }, { "code": null, "e": 850, "s": 789, "text": "STEP 2 : Create a “Procfile” and write the following code. " }, { "code": null, "e": 868, "s": 850, "text": "$ touch Procfile " }, { "code": null, "e": 931, "s": 870, "text": "STEP 3 : Create “runtime.txt” and write the following code. " }, { "code": null, "e": 952, "s": 931, "text": "$ touch runtime.txt " }, { "code": null, "e": 1015, "s": 954, "text": "STEP 4 : Create a folder named “app” and enter the folder. " }, { "code": null, "e": 1039, "s": 1015, "text": "$ mkdir app\n$ cd app\n " }, { "code": null, "e": 1108, "s": 1039, "text": "STEP 5 : Create a python file, “main.py” and enter the sample code. " }, { "code": null, "e": 1124, "s": 1108, "text": " touch main.py " }, { "code": null, "e": 1134, "s": 1126, "text": "Python3" }, { "code": "from flask import Flask app = Flask(__name__) @app.route(\"/\")def home_view(): return \"<h1>Welcome to Geeks for Geeks</h1>\"", "e": 1264, "s": 1134, "text": null }, { "code": null, "e": 1371, "s": 1264, "text": "STEP 6 :Get back to the previous directory “eflask”.Create a file“wsgi.py” and insert the following code. " }, { "code": null, "e": 1396, "s": 1371, "text": "$ cd ../\n$ touch wsgi.py" }, { "code": null, "e": 1406, "s": 1398, "text": "Python3" }, { "code": "from app.main import app if __name__ == \"__main__\": app.run()", "e": 1475, "s": 1406, "text": null }, { "code": null, "e": 1514, "s": 1475, "text": "STEP 7 : Run the virtual environment. " }, { "code": null, "e": 1530, "s": 1514, "text": "$ pipenv shell " }, { "code": null, "e": 1620, "s": 1530, "text": "STEP 8 : Initialize an empty repo, add the files in the repo and commit all the changes. " }, { "code": null, "e": 1677, "s": 1620, "text": "$ git init \n$ git add .\n$ git commit -m \"Initial Commit\"" }, { "code": null, "e": 1714, "s": 1677, "text": "STEP 9 : Login to heroku CLI using " }, { "code": null, "e": 1727, "s": 1714, "text": "heroku login" }, { "code": null, "e": 1772, "s": 1727, "text": "Now, Create a unique name for your Web app. " }, { "code": null, "e": 1799, "s": 1772, "text": "$ heroku create eflask-app" }, { "code": null, "e": 1861, "s": 1801, "text": "STEP 10 : Push your code from local to the heroku remote. " }, { "code": null, "e": 1886, "s": 1861, "text": "$ git push heroku master" }, { "code": null, "e": 1960, "s": 1888, "text": "Finally, web app will be deployed on http://eflask-app.herokuapp.com. " }, { "code": null, "e": 1978, "s": 1962, "text": "rajeev0719singh" }, { "code": null, "e": 1987, "s": 1978, "text": "Articles" }, { "code": null, "e": 1991, "s": 1987, "text": "Git" }, { "code": null, "e": 1998, "s": 1991, "text": "Python" }, { "code": null, "e": 2015, "s": 1998, "text": "Web Technologies" }, { "code": null, "e": 2113, "s": 2015, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2150, "s": 2113, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 2174, "s": 2150, "text": "SQL Interview Questions" }, { "code": null, "e": 2210, "s": 2174, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 2224, "s": 2210, "text": "Java Tutorial" }, { "code": null, "e": 2236, "s": 2224, "text": "SQL | Views" }, { "code": null, "e": 2259, "s": 2236, "text": "Working on Git for GUI" }, { "code": null, "e": 2308, "s": 2259, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 2359, "s": 2308, "text": "How to integrate Git Bash with Visual Studio Code?" }, { "code": null, "e": 2407, "s": 2359, "text": "Git - Difference Between Git Fetch and Git Pull" } ]
How to align block elements to center using CSS ?
12 Aug, 2021 The “blocks” are known for taking full line space, forcing other elements to start on a new line. In other words, they have a width of 100% of the webpage or container holding the block. In this article, we are going to see how to block elements that usually behave and how to center them using CSS. Block Elements Behaviour: Any element can be set to behave like a block by setting their display property to the block “display: block”. There are some other elements like headers, div tags which are by default block. So they take the full line or full width of the web page or container holding it. Even if our content is taking 20% of the width of the webpage still the block property will reserve the full 100% width of the web page or container holding it. How to center these block elements: We have seen that how this block element behaves, we observe that as they take full line width, to center them we only have the margin property that is controlling them horizontally. The margin can control the position of the block element both horizontally and vertically. To center them, we can adjust the margin property such that it is placed in the center. Note: We can see that the “text-align : center” is not centering the block elements. They are only centering the non-block or inline-block elements. Center block elements using margin property: We need to specify the margin from left and right such that it looks centered. We do not need to do this manually, we have one property value “auto” which will automatically set the margin such that our block element is placed in the center. Use the below CSS property to center your block element. margin: auto Example 1: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <style> h2, p { text-align: center; } .myblock { margin: auto; border: 2px solid red; width: fit-content; padding: 15px; text-align: center; background-color: lightyellow; } header { font-size: 40px; background-color: lightgreen; margin: auto; width: fit-content; } .myinline { padding: 10px; border: 2px solid blue; } .holder { text-align: center; } </style></head> <body> <h2>Welcome To GFG</h2> <p>Default code has been loaded into the Editor.</p> <header>hello</header> <div class="myblock"> div who has default display : block </div> <div class="holder"> <div style="display: inline-block" class="myinline"> inline block paragraph 1 </div> <div style="display: inline-block" class="myinline"> inline block paragraph 2 </div> </div></body> </html> Output: centered block Example 2: We have one image that has some space around it, so by default the non-block element will come next to the img tag and not on the next line. After setting the “display: block” property, we can make our image to block element. It can be centered using “margin: auto” property. Note: The body tag has been set to the “text-align: center” property. We know that it is not affecting the block elements. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <style> header { font-size: 20px; margin: auto; width: 30%; background-color: lightgreen; margin-bottom: 10px; } p { display: inline-block; } img { display: block; margin: auto; } </style></head> <body> <header> centering image using display: block </header> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210810104012/geeksimage.png" alt="image here" width="500" height="400" /> <p> paragraph came to the new line even if it is inline, because the img is set to block </p></body> </html> Output: CSS-Properties CSS-Questions HTML-Questions Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Form validation using jQuery Design a web page using HTML and CSS REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? HTTP headers | Content-Type
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Aug, 2021" }, { "code": null, "e": 329, "s": 28, "text": "The “blocks” are known for taking full line space, forcing other elements to start on a new line. In other words, they have a width of 100% of the webpage or container holding the block. In this article, we are going to see how to block elements that usually behave and how to center them using CSS." }, { "code": null, "e": 790, "s": 329, "text": "Block Elements Behaviour: Any element can be set to behave like a block by setting their display property to the block “display: block”. There are some other elements like headers, div tags which are by default block. So they take the full line or full width of the web page or container holding it. Even if our content is taking 20% of the width of the webpage still the block property will reserve the full 100% width of the web page or container holding it." }, { "code": null, "e": 1009, "s": 790, "text": "How to center these block elements: We have seen that how this block element behaves, we observe that as they take full line width, to center them we only have the margin property that is controlling them horizontally." }, { "code": null, "e": 1188, "s": 1009, "text": "The margin can control the position of the block element both horizontally and vertically. To center them, we can adjust the margin property such that it is placed in the center." }, { "code": null, "e": 1337, "s": 1188, "text": "Note: We can see that the “text-align : center” is not centering the block elements. They are only centering the non-block or inline-block elements." }, { "code": null, "e": 1681, "s": 1337, "text": "Center block elements using margin property: We need to specify the margin from left and right such that it looks centered. We do not need to do this manually, we have one property value “auto” which will automatically set the margin such that our block element is placed in the center. Use the below CSS property to center your block element." }, { "code": null, "e": 1694, "s": 1681, "text": "margin: auto" }, { "code": null, "e": 1705, "s": 1694, "text": "Example 1:" }, { "code": null, "e": 1710, "s": 1705, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <style> h2, p { text-align: center; } .myblock { margin: auto; border: 2px solid red; width: fit-content; padding: 15px; text-align: center; background-color: lightyellow; } header { font-size: 40px; background-color: lightgreen; margin: auto; width: fit-content; } .myinline { padding: 10px; border: 2px solid blue; } .holder { text-align: center; } </style></head> <body> <h2>Welcome To GFG</h2> <p>Default code has been loaded into the Editor.</p> <header>hello</header> <div class=\"myblock\"> div who has default display : block </div> <div class=\"holder\"> <div style=\"display: inline-block\" class=\"myinline\"> inline block paragraph 1 </div> <div style=\"display: inline-block\" class=\"myinline\"> inline block paragraph 2 </div> </div></body> </html>", "e": 3048, "s": 1710, "text": null }, { "code": null, "e": 3056, "s": 3048, "text": "Output:" }, { "code": null, "e": 3071, "s": 3056, "text": "centered block" }, { "code": null, "e": 3358, "s": 3071, "text": "Example 2: We have one image that has some space around it, so by default the non-block element will come next to the img tag and not on the next line. After setting the “display: block” property, we can make our image to block element. It can be centered using “margin: auto” property." }, { "code": null, "e": 3481, "s": 3358, "text": "Note: The body tag has been set to the “text-align: center” property. We know that it is not affecting the block elements." }, { "code": null, "e": 3486, "s": 3481, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <style> header { font-size: 20px; margin: auto; width: 30%; background-color: lightgreen; margin-bottom: 10px; } p { display: inline-block; } img { display: block; margin: auto; } </style></head> <body> <header> centering image using display: block </header> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210810104012/geeksimage.png\" alt=\"image here\" width=\"500\" height=\"400\" /> <p> paragraph came to the new line even if it is inline, because the img is set to block </p></body> </html>", "e": 4408, "s": 3486, "text": null }, { "code": null, "e": 4416, "s": 4408, "text": "Output:" }, { "code": null, "e": 4431, "s": 4416, "text": "CSS-Properties" }, { "code": null, "e": 4445, "s": 4431, "text": "CSS-Questions" }, { "code": null, "e": 4460, "s": 4445, "text": "HTML-Questions" }, { "code": null, "e": 4467, "s": 4460, "text": "Picked" }, { "code": null, "e": 4471, "s": 4467, "text": "CSS" }, { "code": null, "e": 4476, "s": 4471, "text": "HTML" }, { "code": null, "e": 4493, "s": 4476, "text": "Web Technologies" }, { "code": null, "e": 4498, "s": 4493, "text": "HTML" }, { "code": null, "e": 4596, "s": 4498, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4635, "s": 4596, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 4674, "s": 4635, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 4713, "s": 4674, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 4742, "s": 4713, "text": "Form validation using jQuery" }, { "code": null, "e": 4779, "s": 4742, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 4803, "s": 4779, "text": "REST API (Introduction)" }, { "code": null, "e": 4856, "s": 4803, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 4916, "s": 4856, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 4977, "s": 4916, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Python PostgreSQL – Drop Table
23 Aug, 2021 In this article, we are going to see how to drop tables in PostgreSQL using pyscopg2 module Python. In PostgreSQL DROP TABLE is used to remove the existing table from the database. It removes table definition and all associated data, indexes, rules, triggers, and constraints for that table. If the particular table doesn’t exist then it shows an error. Syntax: DROP TABLE table_name; Here, we are using the accounts table for demonstration. Now let’s drops this table, for we will use will psycopg2 module to connect the PostgreSQL and execute the SQL query in cursor.execute(query) object. Syntax: cursor.execute(sql_query); Here we are going to drop the table using the DELETE clause. Syntax: DROP TABLE table_name; Code: Python3 # importing psycopg2import psycopg2 conn=psycopg2.connect( database="test", user="postgres", password="password", host="localhost", port="5432") # Creating a cursor object using the cursor() # methodcursor = conn.cursor() # drop table accountssql = '''DROP TABLE accounts ''' # Executing the querycursor.execute(sql)print("Table dropped !") # Commit your changes in the databaseconn.commit() # Closing the connectionconn.close() Output: Table dropped ! If you try to delete the same table again, since you have already deleted it, you will get an error saying “table does not exist”, so we can resolve using the IF EXIST clause. Syntax: DROP TABLE table_name IF EXITS table_name; Code: Python3 # importing psycopg2import psycopg2 conn=psycopg2.connect( database="geeks", user="postgres", password="root", host="localhost", port="5432") # Creating a cursor object using the cursor()# methodcursor = conn.cursor() # drop table accountssql = '''DROP table IF EXISTS accounts ''' # Executing the querycursor.execute(sql) print("Table dropped !")# Commit your changes in the databaseconn.commit() # Closing the connectionconn.close() Output: Table dropped ! After execution of the scripts, let check the table in PostgreSQL: Picked Python PostgreSQL Python Pyscopg2 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Aug, 2021" }, { "code": null, "e": 409, "s": 54, "text": "In this article, we are going to see how to drop tables in PostgreSQL using pyscopg2 module Python. In PostgreSQL DROP TABLE is used to remove the existing table from the database. It removes table definition and all associated data, indexes, rules, triggers, and constraints for that table. If the particular table doesn’t exist then it shows an error. " }, { "code": null, "e": 440, "s": 409, "text": "Syntax: DROP TABLE table_name;" }, { "code": null, "e": 497, "s": 440, "text": "Here, we are using the accounts table for demonstration." }, { "code": null, "e": 647, "s": 497, "text": "Now let’s drops this table, for we will use will psycopg2 module to connect the PostgreSQL and execute the SQL query in cursor.execute(query) object." }, { "code": null, "e": 682, "s": 647, "text": "Syntax: cursor.execute(sql_query);" }, { "code": null, "e": 743, "s": 682, "text": "Here we are going to drop the table using the DELETE clause." }, { "code": null, "e": 774, "s": 743, "text": "Syntax: DROP TABLE table_name;" }, { "code": null, "e": 780, "s": 774, "text": "Code:" }, { "code": null, "e": 788, "s": 780, "text": "Python3" }, { "code": "# importing psycopg2import psycopg2 conn=psycopg2.connect( database=\"test\", user=\"postgres\", password=\"password\", host=\"localhost\", port=\"5432\") # Creating a cursor object using the cursor() # methodcursor = conn.cursor() # drop table accountssql = '''DROP TABLE accounts ''' # Executing the querycursor.execute(sql)print(\"Table dropped !\") # Commit your changes in the databaseconn.commit() # Closing the connectionconn.close()", "e": 1240, "s": 788, "text": null }, { "code": null, "e": 1248, "s": 1240, "text": "Output:" }, { "code": null, "e": 1264, "s": 1248, "text": "Table dropped !" }, { "code": null, "e": 1441, "s": 1264, "text": "If you try to delete the same table again, since you have already deleted it, you will get an error saying “table does not exist”, so we can resolve using the IF EXIST clause." }, { "code": null, "e": 1492, "s": 1441, "text": "Syntax: DROP TABLE table_name IF EXITS table_name;" }, { "code": null, "e": 1498, "s": 1492, "text": "Code:" }, { "code": null, "e": 1506, "s": 1498, "text": "Python3" }, { "code": "# importing psycopg2import psycopg2 conn=psycopg2.connect( database=\"geeks\", user=\"postgres\", password=\"root\", host=\"localhost\", port=\"5432\") # Creating a cursor object using the cursor()# methodcursor = conn.cursor() # drop table accountssql = '''DROP table IF EXISTS accounts ''' # Executing the querycursor.execute(sql) print(\"Table dropped !\")# Commit your changes in the databaseconn.commit() # Closing the connectionconn.close()", "e": 1964, "s": 1506, "text": null }, { "code": null, "e": 1972, "s": 1964, "text": "Output:" }, { "code": null, "e": 1988, "s": 1972, "text": "Table dropped !" }, { "code": null, "e": 2055, "s": 1988, "text": "After execution of the scripts, let check the table in PostgreSQL:" }, { "code": null, "e": 2062, "s": 2055, "text": "Picked" }, { "code": null, "e": 2080, "s": 2062, "text": "Python PostgreSQL" }, { "code": null, "e": 2096, "s": 2080, "text": "Python Pyscopg2" }, { "code": null, "e": 2103, "s": 2096, "text": "Python" }, { "code": null, "e": 2201, "s": 2103, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2233, "s": 2201, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2260, "s": 2233, "text": "Python Classes and Objects" }, { "code": null, "e": 2281, "s": 2260, "text": "Python OOPs Concepts" }, { "code": null, "e": 2304, "s": 2281, "text": "Introduction To PYTHON" }, { "code": null, "e": 2360, "s": 2304, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2391, "s": 2360, "text": "Python | os.path.join() method" }, { "code": null, "e": 2433, "s": 2391, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2475, "s": 2433, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2514, "s": 2475, "text": "Python | Get unique values from a list" } ]