title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Carousel using Materialize CSS - GeeksforGeeks
|
09 Oct, 2021
Materialize CSS is a UI component library that is created and designed by Google. It is a design language that combines the classic principles of successful design along with innovation and technology.
Features:
Responsive front-end CSS framework.
It is browser-independent.
Extensible.
It is free to use.
Its emphasis is on different actions and components.
Requires usage of jQuery JavaScript library.
In this article, we are going to create a 3D carousel using materialize CSS which is very interesting as well as easy to design. Materialize CSS carousel is a robust and versatile component. It is touch-enabled which makes it smooth to use on mobile.
Syntax:
HTML
<div class="carousel"> <a class="carousel-item" href="#one!"> <img src=""> </a> <a class="carousel-item" href="#two!"> <img src=""> </a> <a class="carousel-item" href="#three!"> <img src=""> </a> <a class="carousel-item" href="#four!"> <img src=""> </a> <a class="carousel-item" href="#five!"> <img src="" ></a></div>
jQuery/JavaScript for initialization:
Javascript
document.addEventListener('DOMContentLoaded', function() { var elems = document.querySelectorAll('.carousel'); var instances = M.Carousel.init(elems, options);}); $(document).ready(function(){ $('.carousel').carousel();});
Example 1: Using the above code snippets, we can easily create our carousel by giving the source for the images and hyperlinks (if needed) for those images. Let us look at the example below.
HTML
<!DOCTYPE html><html> <head> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.0.min.js"> </script> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"> </script> <script> $(document).ready(function () { $('.carousel').carousel(); }); </script> <style> body { margin: 0; padding: 0; background-color: coral; } a { height: 900px; width: 650px; } .carousel { height: 800px; perspective: 950px; transform: translateY(-100px); } .carousel carousel-item { width: 7050px; } img { width: 100%; height: 200px; } h4 { margin: 0; padding: 0; background: #fff; color: #000; box-sizing: border-box; padding: 10px 5px; font-weight: bold; font-size: 20px; text-align: center; } </style></head> <body> <div class="carousel"> <div class="carousel-item"> <a href="https://www.geeksforgeeks.org/how-to-create-responsive-image-gallery-using-html-css-jquery-and-bootstrap/"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200130114641/responsivegallary1.png"> </a> <h4>Responsive image gallery</h4> </div> <div class="carousel-item"> <a href="https://www.geeksforgeeks.org/how-to-create-a-tab-image-gallery/"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20191205124138/5510.png"> </a> <h4>Tab image gallery</h4> </div> <div class="carousel-item"> <a href="https://www.geeksforgeeks.org/html-course-building-header-of-the-website/"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/Screenshot-25-1024x453.png"> </a> <h4>Building header of a website</h4> </div> <div class="carousel-item"> <a href="https://www.geeksforgeeks.org/how-to-design-image-slider-using-jquery/"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200214124104/imageslider1.png"> </a> <h4>image slider</h4> </div> <div class="carousel-item"> <a href="https://www.geeksforgeeks.org/how-to-create-image-lightbox-gallery-using-html-css-and-javascript/"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200320161020/Screenshot-from-2020-03-20-16-06-36.png"> </a> <h4>image lightbox gallery</h4> </div> </div></body> </html>
Output:
Full-width slider: In the same manner, we can also create a full-width slider by setting the jQuery fullWidth option to true. We can also have indicators that show up at the bottom of the slider. This slider is also touched compatible.
To create this type of slider we have a class as “carousel carousel-slider” and inside this div, we place the images used to create the slider as shown below.
HTML
<div class="carousel carousel-slider"> <a class="carousel-item" href="#one!"> <img src=""> </a> <a class="carousel-item" href="#two!"> <img src=""> </a> <a class="carousel-item" href="#three!"> <img src=""> </a> <a class="carousel-item" href="#four!"> <img src=""> </a></div>
jQuery script will be changed as shown below.
Javascript
$('.carousel.carousel-slider').carousel({ fullWidth: true});
Example 2:
HTML
<!DOCTYPE html><html> <head> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.0.min.js"> </script> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"> </script> <script> $(document).ready(function () { $('.carousel.carousel-slider').carousel( { fullWidth: true, indicators: true } ); }); </script></head> <body> <div class="carousel carousel-slider center"> <div class="carousel-item pink" href="#one!"> <h2>First Panel</h2> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210818182611/Blogathon-2021-Write-From-Home-Contest-By-GeeksforGeeks.png"> </div> <div class="carousel-item blue" href="#two!"> <h2>Second Panel</h2> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210818192517/Blogathon-2021-Prizes.png"> </div> <div class="carousel-item grey" href="#three!"> <h2>Third Panel</h2> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200921183727/about-carousel.png"> </div> <div class="carousel-item yellow" href="#four!"> <h2>Fourth Panel</h2> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200727190538/Group-4362.png"> </div> </div></body> </html>
Output:
CSS-Questions
Materialize-CSS
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24985,
"s": 24957,
"text": "\n09 Oct, 2021"
},
{
"code": null,
"e": 25187,
"s": 24985,
"text": "Materialize CSS is a UI component library that is created and designed by Google. It is a design language that combines the classic principles of successful design along with innovation and technology."
},
{
"code": null,
"e": 25197,
"s": 25187,
"text": "Features:"
},
{
"code": null,
"e": 25233,
"s": 25197,
"text": "Responsive front-end CSS framework."
},
{
"code": null,
"e": 25260,
"s": 25233,
"text": "It is browser-independent."
},
{
"code": null,
"e": 25272,
"s": 25260,
"text": "Extensible."
},
{
"code": null,
"e": 25291,
"s": 25272,
"text": "It is free to use."
},
{
"code": null,
"e": 25344,
"s": 25291,
"text": "Its emphasis is on different actions and components."
},
{
"code": null,
"e": 25389,
"s": 25344,
"text": "Requires usage of jQuery JavaScript library."
},
{
"code": null,
"e": 25641,
"s": 25389,
"text": "In this article, we are going to create a 3D carousel using materialize CSS which is very interesting as well as easy to design. Materialize CSS carousel is a robust and versatile component. It is touch-enabled which makes it smooth to use on mobile. "
},
{
"code": null,
"e": 25651,
"s": 25643,
"text": "Syntax:"
},
{
"code": null,
"e": 25656,
"s": 25651,
"text": "HTML"
},
{
"code": "<div class=\"carousel\"> <a class=\"carousel-item\" href=\"#one!\"> <img src=\"\"> </a> <a class=\"carousel-item\" href=\"#two!\"> <img src=\"\"> </a> <a class=\"carousel-item\" href=\"#three!\"> <img src=\"\"> </a> <a class=\"carousel-item\" href=\"#four!\"> <img src=\"\"> </a> <a class=\"carousel-item\" href=\"#five!\"> <img src=\"\" ></a></div>",
"e": 26039,
"s": 25656,
"text": null
},
{
"code": null,
"e": 26077,
"s": 26039,
"text": "jQuery/JavaScript for initialization:"
},
{
"code": null,
"e": 26088,
"s": 26077,
"text": "Javascript"
},
{
"code": "document.addEventListener('DOMContentLoaded', function() { var elems = document.querySelectorAll('.carousel'); var instances = M.Carousel.init(elems, options);}); $(document).ready(function(){ $('.carousel').carousel();});",
"e": 26323,
"s": 26088,
"text": null
},
{
"code": null,
"e": 26514,
"s": 26323,
"text": "Example 1: Using the above code snippets, we can easily create our carousel by giving the source for the images and hyperlinks (if needed) for those images. Let us look at the example below."
},
{
"code": null,
"e": 26519,
"s": 26514,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Compiled and minified CSS --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-1.12.0.min.js\"> </script> <!-- Compiled and minified JavaScript --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js\"> </script> <script> $(document).ready(function () { $('.carousel').carousel(); }); </script> <style> body { margin: 0; padding: 0; background-color: coral; } a { height: 900px; width: 650px; } .carousel { height: 800px; perspective: 950px; transform: translateY(-100px); } .carousel carousel-item { width: 7050px; } img { width: 100%; height: 200px; } h4 { margin: 0; padding: 0; background: #fff; color: #000; box-sizing: border-box; padding: 10px 5px; font-weight: bold; font-size: 20px; text-align: center; } </style></head> <body> <div class=\"carousel\"> <div class=\"carousel-item\"> <a href=\"https://www.geeksforgeeks.org/how-to-create-responsive-image-gallery-using-html-css-jquery-and-bootstrap/\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200130114641/responsivegallary1.png\"> </a> <h4>Responsive image gallery</h4> </div> <div class=\"carousel-item\"> <a href=\"https://www.geeksforgeeks.org/how-to-create-a-tab-image-gallery/\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20191205124138/5510.png\"> </a> <h4>Tab image gallery</h4> </div> <div class=\"carousel-item\"> <a href=\"https://www.geeksforgeeks.org/html-course-building-header-of-the-website/\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/Screenshot-25-1024x453.png\"> </a> <h4>Building header of a website</h4> </div> <div class=\"carousel-item\"> <a href=\"https://www.geeksforgeeks.org/how-to-design-image-slider-using-jquery/\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200214124104/imageslider1.png\"> </a> <h4>image slider</h4> </div> <div class=\"carousel-item\"> <a href=\"https://www.geeksforgeeks.org/how-to-create-image-lightbox-gallery-using-html-css-and-javascript/\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200320161020/Screenshot-from-2020-03-20-16-06-36.png\"> </a> <h4>image lightbox gallery</h4> </div> </div></body> </html>",
"e": 29619,
"s": 26519,
"text": null
},
{
"code": null,
"e": 29627,
"s": 29619,
"text": "Output:"
},
{
"code": null,
"e": 29863,
"s": 29627,
"text": "Full-width slider: In the same manner, we can also create a full-width slider by setting the jQuery fullWidth option to true. We can also have indicators that show up at the bottom of the slider. This slider is also touched compatible."
},
{
"code": null,
"e": 30022,
"s": 29863,
"text": "To create this type of slider we have a class as “carousel carousel-slider” and inside this div, we place the images used to create the slider as shown below."
},
{
"code": null,
"e": 30027,
"s": 30022,
"text": "HTML"
},
{
"code": "<div class=\"carousel carousel-slider\"> <a class=\"carousel-item\" href=\"#one!\"> <img src=\"\"> </a> <a class=\"carousel-item\" href=\"#two!\"> <img src=\"\"> </a> <a class=\"carousel-item\" href=\"#three!\"> <img src=\"\"> </a> <a class=\"carousel-item\" href=\"#four!\"> <img src=\"\"> </a></div>",
"e": 30355,
"s": 30027,
"text": null
},
{
"code": null,
"e": 30401,
"s": 30355,
"text": "jQuery script will be changed as shown below."
},
{
"code": null,
"e": 30412,
"s": 30401,
"text": "Javascript"
},
{
"code": "$('.carousel.carousel-slider').carousel({ fullWidth: true});",
"e": 30476,
"s": 30412,
"text": null
},
{
"code": null,
"e": 30487,
"s": 30476,
"text": "Example 2:"
},
{
"code": null,
"e": 30492,
"s": 30487,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Compiled and minified CSS --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-1.12.0.min.js\"> </script> <!-- Compiled and minified JavaScript --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js\"> </script> <script> $(document).ready(function () { $('.carousel.carousel-slider').carousel( { fullWidth: true, indicators: true } ); }); </script></head> <body> <div class=\"carousel carousel-slider center\"> <div class=\"carousel-item pink\" href=\"#one!\"> <h2>First Panel</h2> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210818182611/Blogathon-2021-Write-From-Home-Contest-By-GeeksforGeeks.png\"> </div> <div class=\"carousel-item blue\" href=\"#two!\"> <h2>Second Panel</h2> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210818192517/Blogathon-2021-Prizes.png\"> </div> <div class=\"carousel-item grey\" href=\"#three!\"> <h2>Third Panel</h2> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200921183727/about-carousel.png\"> </div> <div class=\"carousel-item yellow\" href=\"#four!\"> <h2>Fourth Panel</h2> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200727190538/Group-4362.png\"> </div> </div></body> </html>",
"e": 32249,
"s": 30492,
"text": null
},
{
"code": null,
"e": 32257,
"s": 32249,
"text": "Output:"
},
{
"code": null,
"e": 32271,
"s": 32257,
"text": "CSS-Questions"
},
{
"code": null,
"e": 32287,
"s": 32271,
"text": "Materialize-CSS"
},
{
"code": null,
"e": 32291,
"s": 32287,
"text": "CSS"
},
{
"code": null,
"e": 32308,
"s": 32291,
"text": "Web Technologies"
},
{
"code": null,
"e": 32406,
"s": 32308,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32415,
"s": 32406,
"text": "Comments"
},
{
"code": null,
"e": 32428,
"s": 32415,
"text": "Old Comments"
},
{
"code": null,
"e": 32465,
"s": 32428,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 32494,
"s": 32465,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 32533,
"s": 32494,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 32575,
"s": 32533,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 32610,
"s": 32575,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 32666,
"s": 32610,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 32699,
"s": 32666,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32742,
"s": 32699,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 32803,
"s": 32742,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
Resolve Unknown database in JDBC error with Java-MySQL?
|
This type of error occurs if you select any database that does not exist in MySQL. Let us first display the error of unknown database in JDBC.
The Java code is as follows. Here, we have set the database as ‘onlinebookstore’, which does not exist:
import java.sql.Connection;
import java.sql.DriverManager;
public class UnknownDatabaseDemo {
public static void main(String[] args) {
String JdbcURL = "jdbc:mysql://localhost:3306/onlinebookstore?useSSL=false";
String Username = "root";
String password = "123456";
Connection con = null;
try {
con = DriverManager.getConnection(JdbcURL, Username, password);
System.out.println("Connected to MySQL database");
} catch (Exception e) {
e.printStackTrace();
}
}
}
The following is the output displaying the same error
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'onlinebookstore'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:944)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3978)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3914)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:871)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1714)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1224)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2199)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2230)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2025)
at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:778)
at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:386)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at UnknowDatabaseDemo.main(UnknowDatabaseDemo.java:15)
The screenshot of the error is as follows
To remove this type of error, just go to MySQL command line and show all database names and use the chosen one from there i.e. the database which really exist.
Here, we have lots of database and I am going to choose database ‘hb_student_tracker’. The following is the list of all database names, we got using SHOW DATABASES command:
Here is the JDBC code that connects the database “hb_student_tracker”. The code is as follows:
import java.sql.Connection;
import java.sql.DriverManager;
public class UnknownDatabaseDemo {
public static void main(String[] args) {
String JdbcURL = "jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false";
String Username = "root";
String password = "123456";
Connection con = null;
try {
con = DriverManager.getConnection(JdbcURL, Username, password);
System.out.println("Connected to MySQL database");
} catch (Exception e) {
e.printStackTrace();
}
}
}
The screenshot is as follows displaying the output:
|
[
{
"code": null,
"e": 1205,
"s": 1062,
"text": "This type of error occurs if you select any database that does not exist in MySQL. Let us first display the error of unknown database in JDBC."
},
{
"code": null,
"e": 1309,
"s": 1205,
"text": "The Java code is as follows. Here, we have set the database as ‘onlinebookstore’, which does not exist:"
},
{
"code": null,
"e": 1845,
"s": 1309,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\npublic class UnknownDatabaseDemo {\n public static void main(String[] args) {\n String JdbcURL = \"jdbc:mysql://localhost:3306/onlinebookstore?useSSL=false\";\n String Username = \"root\";\n String password = \"123456\";\n Connection con = null;\n try {\n con = DriverManager.getConnection(JdbcURL, Username, password);\n System.out.println(\"Connected to MySQL database\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 1899,
"s": 1845,
"text": "The following is the output displaying the same error"
},
{
"code": null,
"e": 3853,
"s": 1899,
"text": "com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'onlinebookstore'\n at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)\n at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)\n at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)\n at java.lang.reflect.Constructor.newInstance(Unknown Source)\n at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)\n at com.mysql.jdbc.Util.getInstance(Util.java:408)\n at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:944)\n at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3978)\n at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3914)\n at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:871)\n at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1714)\n at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1224)\n at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2199)\n at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2230)\n at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2025)\n at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:778)\n at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:47)\n at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)\n at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)\n at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)\n at java.lang.reflect.Constructor.newInstance(Unknown Source)\n at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)\n at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:386)\n at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)\n at java.sql.DriverManager.getConnection(Unknown Source)\n at java.sql.DriverManager.getConnection(Unknown Source)\n at UnknowDatabaseDemo.main(UnknowDatabaseDemo.java:15)"
},
{
"code": null,
"e": 3895,
"s": 3853,
"text": "The screenshot of the error is as follows"
},
{
"code": null,
"e": 4055,
"s": 3895,
"text": "To remove this type of error, just go to MySQL command line and show all database names and use the chosen one from there i.e. the database which really exist."
},
{
"code": null,
"e": 4228,
"s": 4055,
"text": "Here, we have lots of database and I am going to choose database ‘hb_student_tracker’. The following is the list of all database names, we got using SHOW DATABASES command:"
},
{
"code": null,
"e": 4323,
"s": 4228,
"text": "Here is the JDBC code that connects the database “hb_student_tracker”. The code is as follows:"
},
{
"code": null,
"e": 4862,
"s": 4323,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\npublic class UnknownDatabaseDemo {\n public static void main(String[] args) {\n String JdbcURL = \"jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false\";\n String Username = \"root\";\n String password = \"123456\";\n Connection con = null;\n try {\n con = DriverManager.getConnection(JdbcURL, Username, password);\n System.out.println(\"Connected to MySQL database\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 4914,
"s": 4862,
"text": "The screenshot is as follows displaying the output:"
}
] |
How to Create Simple News Summarization from Scratch using Python | by Fahmi Nurfikri | Towards Data Science
|
If you are new to the world of machine learning, specifically Natural Language Processing (NLP) and you hear about Automatic News Summarization and you are interested in it. You must be wondering, like “How to make a good model?”, “What should I learn?” and “Where should I start?”.
Then you start searching for what methods are good for automatic summaries and find methods such as Bart, then you try the pre-trained model, and impressed about its result. Then you are interested in training the model for your native language. But there’s a problem, you live in 3rd words country and no pre-trained models are available or you don’t have any supercomputer to run or you don’t even find a dataset for your language and you’re too lazy to labelled it alone.
So in this post, I’ll give a simple solutions for you to make your simple news summarization. First, let’s talk about approaches in news summarization.
In general, the news summarization approach is divided into two, namely extractive and abstractive. Extractive summarization means identifying important parts of the text and making it verbatim produce a subset of sentences from the original text; while abstractive summarization reproduces important material in new ways after the interpretation and examination of texts using advanced natural language techniques to produce new, shorter texts that convey the most critical information from the original.
Since our initial goal is to make a simple summarizer, here we will use the Extractive summarization approach. Let’s get started, if you want to see the full code of this article, please visit my github.
First, import package that will be used
import numpy as npimport nltkimport re
Here we use the NumPy, nltk, and re libraries. NumPy is a library for numerical calculations, nltk is a library that is widely used for NLP, and re is a library for regular expressions.
After that, we define the preprocessing functions that will be performed. It aims to concentrate words and eliminate characters that are not needed. Here there are 3 preprocessing functions, namely:
Case folding: change all letters to lowercase
Cleaning: removes all punctuation and numbers, leaving only the alphabet characters
Tokenization: converts sentences into tokens
Here is the code for the preprocessing process
def casefolding(sentence): return sentence.lower()def cleaning(sentence): return re.sub(r'[^a-z]', ' ', re.sub("’", '', sentence))def tokenization(sentence): return sentence.split()
In addition, you can also add other functions such as stopwords removal, stemming, or lemmatization. However, because the usage can be different for each language, so the function will not be explained in this article, but an example is in the Github link that I have provided.
Next, we also need a function to turn the whole story into a collection of sentences
def sentence_split(paragraph): return nltk.sent_tokenize(paragraph)
Next we will define a function to count the number of each word in the document. This process is carried out to give weight to words that aim to determine whether the word has an effect or not. Here is the code for the process
def word_freq(data): w = [] for sentence in data: for words in sentence: w.append(words) bag = list(set(w)) res = {} for word in bag: res[word] = w.count(word) return res
Then, we will make a function to calculate the weight of each sentence. This process is carried out to determine which sentence is considered to best represent the whole story.
def sentence_weight(data): weights = [] for words in data: temp = 0 for word in words: temp += wordfreq[word] weights.append(temp) return weights
Now, all the functions we will use are defined. Let’s take a case example. For example, I will use an article from Politico entitled “The New York Times Surrendered to an Outrage Mob. Journalism Will Suffer For It“.
We will start by inserting news on the site into a variable by doing copy-paste manually. If you don’t want to do copy-paste and are interested in web scraping, you can read my previous article titled Web Scraping News with 4 lines using Python.
towardsdatascience.com
news = """IIn a time in which even a virus has become the subject of partisan disinformation and myth-making, it’s essential that mainstream journalistic institutions reaffirm their bona fides as disinterested purveyors of fact and honest brokers of controversy. In this regard, a recent course of action by the New York Times is cause for alarm.On December 27, 2019, the Times published a column by their opinion journalist Bret Stephens, “The Secrets of Jewish Genius,” and the ensuing controversy led to an extraordinary response by the editors.Stephens took up the question of why Ashkenazi Jews are statistically overrepresented in intellectual and creative fields. This disparity has been documented for many years, such as in the 1995 book Jews and the New American Scene by the eminent sociologists Seymour Martin Lipset and Earl Raab. In his Times column, Stephens cited statistics from a more recent peer-reviewed academic paper, coauthored by an elected member of the National Academy of Sciences. Though the authors of that paper advanced a genetic hypothesis for the overrepresentation, arguing that Ashkenazi Jews have the highest average IQ of any ethnic group because of inherited traits, Stephens did not take up that argument. In fact, his essay quickly set it aside and argued that the real roots of Jewish achievement are culturally and historically engendered habits of mind.Nonetheless, the column incited a furious and ad hominem response. Detractors discovered that one of the authors of the paper Stephens had cited went on to express racist views, and falsely claimed that Stephens himself had advanced ideas that were “genetic” (he did not), “racist” (he made no remarks about any race) and “eugenicist” (alluding to the discredited political movement to improve the human species by selective breeding, which was not remotely related to anything Stephens wrote).It would have been appropriate for the New York Times to acknowledge the controversy, to publish one or more replies, and to allow Stephens and his critics to clarify the issues. Instead, the editors deleted parts of the column—not because anything in it had been shown to be factually incorrect but because it had become controversial.Worse, the explanation for the deletions in the Editors’ Note was not accurate about the edits the paper made after publication. The editors did not just remove “reference to the study.” They expurgated the article’s original subtitle (which explicitly stated “It’s not about having higher IQs”), two mentions of Jewish IQs, and a list of statistics about Jewish accomplishment: “During the 20th century, [Ashkenazi Jews] made up about 3 percent of the U.S. population but won 27 percent of the U.S. Nobel science prizes and 25 percent of the ACM Turing awards. They account for more than half of world chess champions.” These statistics about Jewish accomplishments were quoted directly from the study, but they originated in other studies. So, even if the Times editors wanted to disavow the paper Stephens referenced, the newspaper could have replaced the passage with quotes from the original sources.The Times’ handling of this column sets three pernicious precedents for American journalism.First, while we cannot know what drove the editors’ decision, the outward appearance is that they surrendered to an outrage mob, in the process giving an imprimatur of legitimacy to the false and ad hominem attacks against Stephens. The Editors’ Note explains that Stephens “was not endorsing the study or its authors’ views,” and that it was not his intent to “leave an impression with many readers that [he] was arguing that Jews are genetically superior.” The combination of the explanation and the post-publication revision implied that such an impression was reasonable. It was not.Unless the Times reverses course, we can expect to see more such mobs, more retractions, and also preemptive rejections from editors fearful of having to make such retractions. Newspapers risk forfeiting decisions to air controversial or unorthodox ideas to outrage mobs, which are driven by the passions of their most ideological police rather than the health of the intellectual commons.Second, the Times redacted a published essay based on concerns about retroactive moral pollution, not about accuracy. While it is true that an author of the paper Stephens mentioned, the late anthropologist Henry Harpending, made some deplorable racist remarks, that does not mean that every point in every paper he ever coauthored must be deemed radioactive. Facts and arguments must be evaluated on their content. Will the Times and other newspapers now monitor the speech of scientists and scholars and censor articles that cite any of them who, years later, say something offensive? Will it crowdsource that job to Twitter and then redact its online editions whenever anyone quoted in the Times is later “canceled”?Third, for the Times to “disappear” passages of a published article into an inaccessible memory hole is an Orwellian act that, thanks to the newspaper’s actions, might now be seen as acceptable journalistic practice. It is all the worse when the editors’ published account of what they deleted is itself inaccurate. This does a disservice to readers, historians and journalists, who are left unable to determine for themselves what the controversy was about, and to Stephens, who is left unable to defend himself against readers’ worst suspicions.We strongly oppose racism, anti-Semitism and all forms of bigotry. And we believe that the best means of combating them is the open exchange of ideas. The Times’ retroactive censoring of passages of a published article appears to endorse a different view. And in doing so, it hands ammunition to the cynics and obfuscators who claim that every news source is merely an organ for its political coalition."""
After that we will process the news by cutting it into sentence form, then for each sentence the preprocessing is done using the function that we have defined above.
sentence_list = sentence_split(news)data = []for sentence in sentence_list: data.append(tokenization(cleaning(casefolding(sentence))))data = (list(filter(None, data)))
After that, we will count the number of each word in the document from the function we have defined.
wordfreq = word_freq(data)
Then, from the results of word calculation we only need to calculate the weight of each sentence.
rank = sentence_rank(data)
After that we determine how many main sentences we want to output as a representation of the news. For example I will output 2 sentences, so here I fill n with 2. Then the system will take the top 2 sentences which have the highest weight. It depends on you to choose many sentences to appear.
n = 2result = ''sort_list = np.argsort(ranking)[::-1][:n]for i in range(n): result += '{} '.format(sentence_list[sort_list[i]])
To display the results, use the following code
print(result)
So results will appear like this.
The editors did not just remove “reference to the study.” They expurgated the article’s original subtitle (which explicitly stated “It’s not about having higher IQs”), two mentions of Jewish IQs, and a list of statistics about Jewish accomplishment: “During the 20th century, [Ashkenazi Jews] made up about 3 percent of the U.S. population but won 27 percent of the U.S. Nobel science prizes and 25 percent of the ACM Turing awards. Detractors discovered that one of the authors of the paper Stephens had cited went on to express racist views, and falsely claimed that Stephens himself had advanced ideas that were “genetic” (he did not), “racist” (he made no remarks about any race) and “eugenicist” (alluding to the discredited political movement to improve the human species by selective breeding, which was not remotely related to anything Stephens wrote).
Not bad, right? Although it may not be as good as if we use state-of-the-art methods, we can quite understand the essence of our brief news. And tips from me, by using this method, you can generate your own dataset, although it still has limitations because the results obtained are not always the way you want.
Good luck!
If you like this post, I want to recommend an article that inspired me.
|
[
{
"code": null,
"e": 455,
"s": 172,
"text": "If you are new to the world of machine learning, specifically Natural Language Processing (NLP) and you hear about Automatic News Summarization and you are interested in it. You must be wondering, like “How to make a good model?”, “What should I learn?” and “Where should I start?”."
},
{
"code": null,
"e": 930,
"s": 455,
"text": "Then you start searching for what methods are good for automatic summaries and find methods such as Bart, then you try the pre-trained model, and impressed about its result. Then you are interested in training the model for your native language. But there’s a problem, you live in 3rd words country and no pre-trained models are available or you don’t have any supercomputer to run or you don’t even find a dataset for your language and you’re too lazy to labelled it alone."
},
{
"code": null,
"e": 1082,
"s": 930,
"text": "So in this post, I’ll give a simple solutions for you to make your simple news summarization. First, let’s talk about approaches in news summarization."
},
{
"code": null,
"e": 1588,
"s": 1082,
"text": "In general, the news summarization approach is divided into two, namely extractive and abstractive. Extractive summarization means identifying important parts of the text and making it verbatim produce a subset of sentences from the original text; while abstractive summarization reproduces important material in new ways after the interpretation and examination of texts using advanced natural language techniques to produce new, shorter texts that convey the most critical information from the original."
},
{
"code": null,
"e": 1792,
"s": 1588,
"text": "Since our initial goal is to make a simple summarizer, here we will use the Extractive summarization approach. Let’s get started, if you want to see the full code of this article, please visit my github."
},
{
"code": null,
"e": 1832,
"s": 1792,
"text": "First, import package that will be used"
},
{
"code": null,
"e": 1871,
"s": 1832,
"text": "import numpy as npimport nltkimport re"
},
{
"code": null,
"e": 2057,
"s": 1871,
"text": "Here we use the NumPy, nltk, and re libraries. NumPy is a library for numerical calculations, nltk is a library that is widely used for NLP, and re is a library for regular expressions."
},
{
"code": null,
"e": 2256,
"s": 2057,
"text": "After that, we define the preprocessing functions that will be performed. It aims to concentrate words and eliminate characters that are not needed. Here there are 3 preprocessing functions, namely:"
},
{
"code": null,
"e": 2302,
"s": 2256,
"text": "Case folding: change all letters to lowercase"
},
{
"code": null,
"e": 2386,
"s": 2302,
"text": "Cleaning: removes all punctuation and numbers, leaving only the alphabet characters"
},
{
"code": null,
"e": 2431,
"s": 2386,
"text": "Tokenization: converts sentences into tokens"
},
{
"code": null,
"e": 2478,
"s": 2431,
"text": "Here is the code for the preprocessing process"
},
{
"code": null,
"e": 2669,
"s": 2478,
"text": "def casefolding(sentence): return sentence.lower()def cleaning(sentence): return re.sub(r'[^a-z]', ' ', re.sub(\"’\", '', sentence))def tokenization(sentence): return sentence.split()"
},
{
"code": null,
"e": 2947,
"s": 2669,
"text": "In addition, you can also add other functions such as stopwords removal, stemming, or lemmatization. However, because the usage can be different for each language, so the function will not be explained in this article, but an example is in the Github link that I have provided."
},
{
"code": null,
"e": 3032,
"s": 2947,
"text": "Next, we also need a function to turn the whole story into a collection of sentences"
},
{
"code": null,
"e": 3103,
"s": 3032,
"text": "def sentence_split(paragraph): return nltk.sent_tokenize(paragraph)"
},
{
"code": null,
"e": 3330,
"s": 3103,
"text": "Next we will define a function to count the number of each word in the document. This process is carried out to give weight to words that aim to determine whether the word has an effect or not. Here is the code for the process"
},
{
"code": null,
"e": 3544,
"s": 3330,
"text": "def word_freq(data): w = [] for sentence in data: for words in sentence: w.append(words) bag = list(set(w)) res = {} for word in bag: res[word] = w.count(word) return res"
},
{
"code": null,
"e": 3721,
"s": 3544,
"text": "Then, we will make a function to calculate the weight of each sentence. This process is carried out to determine which sentence is considered to best represent the whole story."
},
{
"code": null,
"e": 3908,
"s": 3721,
"text": "def sentence_weight(data): weights = [] for words in data: temp = 0 for word in words: temp += wordfreq[word] weights.append(temp) return weights"
},
{
"code": null,
"e": 4124,
"s": 3908,
"text": "Now, all the functions we will use are defined. Let’s take a case example. For example, I will use an article from Politico entitled “The New York Times Surrendered to an Outrage Mob. Journalism Will Suffer For It“."
},
{
"code": null,
"e": 4370,
"s": 4124,
"text": "We will start by inserting news on the site into a variable by doing copy-paste manually. If you don’t want to do copy-paste and are interested in web scraping, you can read my previous article titled Web Scraping News with 4 lines using Python."
},
{
"code": null,
"e": 4393,
"s": 4370,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 10265,
"s": 4393,
"text": "news = \"\"\"IIn a time in which even a virus has become the subject of partisan disinformation and myth-making, it’s essential that mainstream journalistic institutions reaffirm their bona fides as disinterested purveyors of fact and honest brokers of controversy. In this regard, a recent course of action by the New York Times is cause for alarm.On December 27, 2019, the Times published a column by their opinion journalist Bret Stephens, “The Secrets of Jewish Genius,” and the ensuing controversy led to an extraordinary response by the editors.Stephens took up the question of why Ashkenazi Jews are statistically overrepresented in intellectual and creative fields. This disparity has been documented for many years, such as in the 1995 book Jews and the New American Scene by the eminent sociologists Seymour Martin Lipset and Earl Raab. In his Times column, Stephens cited statistics from a more recent peer-reviewed academic paper, coauthored by an elected member of the National Academy of Sciences. Though the authors of that paper advanced a genetic hypothesis for the overrepresentation, arguing that Ashkenazi Jews have the highest average IQ of any ethnic group because of inherited traits, Stephens did not take up that argument. In fact, his essay quickly set it aside and argued that the real roots of Jewish achievement are culturally and historically engendered habits of mind.Nonetheless, the column incited a furious and ad hominem response. Detractors discovered that one of the authors of the paper Stephens had cited went on to express racist views, and falsely claimed that Stephens himself had advanced ideas that were “genetic” (he did not), “racist” (he made no remarks about any race) and “eugenicist” (alluding to the discredited political movement to improve the human species by selective breeding, which was not remotely related to anything Stephens wrote).It would have been appropriate for the New York Times to acknowledge the controversy, to publish one or more replies, and to allow Stephens and his critics to clarify the issues. Instead, the editors deleted parts of the column—not because anything in it had been shown to be factually incorrect but because it had become controversial.Worse, the explanation for the deletions in the Editors’ Note was not accurate about the edits the paper made after publication. The editors did not just remove “reference to the study.” They expurgated the article’s original subtitle (which explicitly stated “It’s not about having higher IQs”), two mentions of Jewish IQs, and a list of statistics about Jewish accomplishment: “During the 20th century, [Ashkenazi Jews] made up about 3 percent of the U.S. population but won 27 percent of the U.S. Nobel science prizes and 25 percent of the ACM Turing awards. They account for more than half of world chess champions.” These statistics about Jewish accomplishments were quoted directly from the study, but they originated in other studies. So, even if the Times editors wanted to disavow the paper Stephens referenced, the newspaper could have replaced the passage with quotes from the original sources.The Times’ handling of this column sets three pernicious precedents for American journalism.First, while we cannot know what drove the editors’ decision, the outward appearance is that they surrendered to an outrage mob, in the process giving an imprimatur of legitimacy to the false and ad hominem attacks against Stephens. The Editors’ Note explains that Stephens “was not endorsing the study or its authors’ views,” and that it was not his intent to “leave an impression with many readers that [he] was arguing that Jews are genetically superior.” The combination of the explanation and the post-publication revision implied that such an impression was reasonable. It was not.Unless the Times reverses course, we can expect to see more such mobs, more retractions, and also preemptive rejections from editors fearful of having to make such retractions. Newspapers risk forfeiting decisions to air controversial or unorthodox ideas to outrage mobs, which are driven by the passions of their most ideological police rather than the health of the intellectual commons.Second, the Times redacted a published essay based on concerns about retroactive moral pollution, not about accuracy. While it is true that an author of the paper Stephens mentioned, the late anthropologist Henry Harpending, made some deplorable racist remarks, that does not mean that every point in every paper he ever coauthored must be deemed radioactive. Facts and arguments must be evaluated on their content. Will the Times and other newspapers now monitor the speech of scientists and scholars and censor articles that cite any of them who, years later, say something offensive? Will it crowdsource that job to Twitter and then redact its online editions whenever anyone quoted in the Times is later “canceled”?Third, for the Times to “disappear” passages of a published article into an inaccessible memory hole is an Orwellian act that, thanks to the newspaper’s actions, might now be seen as acceptable journalistic practice. It is all the worse when the editors’ published account of what they deleted is itself inaccurate. This does a disservice to readers, historians and journalists, who are left unable to determine for themselves what the controversy was about, and to Stephens, who is left unable to defend himself against readers’ worst suspicions.We strongly oppose racism, anti-Semitism and all forms of bigotry. And we believe that the best means of combating them is the open exchange of ideas. The Times’ retroactive censoring of passages of a published article appears to endorse a different view. And in doing so, it hands ammunition to the cynics and obfuscators who claim that every news source is merely an organ for its political coalition.\"\"\""
},
{
"code": null,
"e": 10431,
"s": 10265,
"text": "After that we will process the news by cutting it into sentence form, then for each sentence the preprocessing is done using the function that we have defined above."
},
{
"code": null,
"e": 10602,
"s": 10431,
"text": "sentence_list = sentence_split(news)data = []for sentence in sentence_list: data.append(tokenization(cleaning(casefolding(sentence))))data = (list(filter(None, data)))"
},
{
"code": null,
"e": 10703,
"s": 10602,
"text": "After that, we will count the number of each word in the document from the function we have defined."
},
{
"code": null,
"e": 10730,
"s": 10703,
"text": "wordfreq = word_freq(data)"
},
{
"code": null,
"e": 10828,
"s": 10730,
"text": "Then, from the results of word calculation we only need to calculate the weight of each sentence."
},
{
"code": null,
"e": 10855,
"s": 10828,
"text": "rank = sentence_rank(data)"
},
{
"code": null,
"e": 11149,
"s": 10855,
"text": "After that we determine how many main sentences we want to output as a representation of the news. For example I will output 2 sentences, so here I fill n with 2. Then the system will take the top 2 sentences which have the highest weight. It depends on you to choose many sentences to appear."
},
{
"code": null,
"e": 11280,
"s": 11149,
"text": "n = 2result = ''sort_list = np.argsort(ranking)[::-1][:n]for i in range(n): result += '{} '.format(sentence_list[sort_list[i]])"
},
{
"code": null,
"e": 11327,
"s": 11280,
"text": "To display the results, use the following code"
},
{
"code": null,
"e": 11341,
"s": 11327,
"text": "print(result)"
},
{
"code": null,
"e": 11375,
"s": 11341,
"text": "So results will appear like this."
},
{
"code": null,
"e": 12236,
"s": 11375,
"text": "The editors did not just remove “reference to the study.” They expurgated the article’s original subtitle (which explicitly stated “It’s not about having higher IQs”), two mentions of Jewish IQs, and a list of statistics about Jewish accomplishment: “During the 20th century, [Ashkenazi Jews] made up about 3 percent of the U.S. population but won 27 percent of the U.S. Nobel science prizes and 25 percent of the ACM Turing awards. Detractors discovered that one of the authors of the paper Stephens had cited went on to express racist views, and falsely claimed that Stephens himself had advanced ideas that were “genetic” (he did not), “racist” (he made no remarks about any race) and “eugenicist” (alluding to the discredited political movement to improve the human species by selective breeding, which was not remotely related to anything Stephens wrote)."
},
{
"code": null,
"e": 12548,
"s": 12236,
"text": "Not bad, right? Although it may not be as good as if we use state-of-the-art methods, we can quite understand the essence of our brief news. And tips from me, by using this method, you can generate your own dataset, although it still has limitations because the results obtained are not always the way you want."
},
{
"code": null,
"e": 12559,
"s": 12548,
"text": "Good luck!"
}
] |
How to populate XDocument from String in C#?
|
XML is a self-describing language and it gives the data as well as the rules to identify what information it contains. Like HTML, XML is a subset of SGML - Standard
Generalized Markup Language.
The XDocument class contains the information necessary for a valid XML document.
This includes an XML declaration, processing instructions, and comments.
Note that we only have to create XDocument objects if we require the specific
functionality provided by the XDocument class. In many circumstances, we can work
directly with XElement. Working directly with XElement is a simpler programming
model.
XDocument derives from XContainer. Therefore, it can contain child nodes. However, XDocument objects can have only one child XElement node. This reflects the XML standard that there can be only one root element in an XML document. The XDocument is available in System.Xml.Linq namespace.
Let us consider below string which is in XML format and need to be populated as
XML.
<Departments>
<Department>Account</Department>
<Department>Sales</Department>
<Department>Pre-Sales</Department>
<Department>Marketing</Department>
</Departments>
using System;
using System.Xml.Linq;
namespace DemoApplication{
public class Program{
public static void Main(){
string xmlString = @"<Departments>
<Department>Account</Department>
<Department>Sales</Department>
<Department>Pre-Sales</Department>
<Department>Marketing</Department>
</Departments>";
XDocument xml = XDocument.Parse(xmlString);
Console.ReadLine();
}
}
}
Similarly, if we want to convert a file containing xml to XDocument we can use XDocument.Load(path).
using System;
using System.Xml.Linq;
namespace DemoApplication{
public class Program{
public static void Main(){
string xmlPath = @"D:\DemoXml.txt";
XDocument xml = XDocument.Load(xmlPath);
Console.ReadLine();
}
}
}
In both the above cases the xmlString is converted to Xdocumet like below.
|
[
{
"code": null,
"e": 1256,
"s": 1062,
"text": "XML is a self-describing language and it gives the data as well as the rules to identify what information it contains. Like HTML, XML is a subset of SGML - Standard\nGeneralized Markup Language."
},
{
"code": null,
"e": 1410,
"s": 1256,
"text": "The XDocument class contains the information necessary for a valid XML document.\nThis includes an XML declaration, processing instructions, and comments."
},
{
"code": null,
"e": 1657,
"s": 1410,
"text": "Note that we only have to create XDocument objects if we require the specific\nfunctionality provided by the XDocument class. In many circumstances, we can work\ndirectly with XElement. Working directly with XElement is a simpler programming\nmodel."
},
{
"code": null,
"e": 1945,
"s": 1657,
"text": "XDocument derives from XContainer. Therefore, it can contain child nodes. However, XDocument objects can have only one child XElement node. This reflects the XML standard that there can be only one root element in an XML document. The XDocument is available in System.Xml.Linq namespace."
},
{
"code": null,
"e": 2030,
"s": 1945,
"text": "Let us consider below string which is in XML format and need to be populated as\nXML."
},
{
"code": null,
"e": 2676,
"s": 2030,
"text": "<Departments>\n <Department>Account</Department>\n <Department>Sales</Department>\n <Department>Pre-Sales</Department>\n <Department>Marketing</Department>\n</Departments>\nusing System;\nusing System.Xml.Linq;\nnamespace DemoApplication{\n public class Program{\n public static void Main(){\n string xmlString = @\"<Departments>\n <Department>Account</Department>\n <Department>Sales</Department>\n <Department>Pre-Sales</Department>\n <Department>Marketing</Department>\n </Departments>\";\n XDocument xml = XDocument.Parse(xmlString);\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 2777,
"s": 2676,
"text": "Similarly, if we want to convert a file containing xml to XDocument we can use XDocument.Load(path)."
},
{
"code": null,
"e": 3038,
"s": 2777,
"text": "using System;\nusing System.Xml.Linq;\nnamespace DemoApplication{\n public class Program{\n public static void Main(){\n string xmlPath = @\"D:\\DemoXml.txt\";\n XDocument xml = XDocument.Load(xmlPath);\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 3113,
"s": 3038,
"text": "In both the above cases the xmlString is converted to Xdocumet like below."
}
] |
time.Month.String() Function in Golang With Examples - GeeksforGeeks
|
21 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Month.String() function in Go language is used to find the English name of the month. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func (m Month) String() string
Here, “m” is the type Month.
Return Value: It returns a string which is the English name of the month.
Example 1:
// Golang program to illustrate the usage of// (Month) String() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Calling time.Month // with its parameter // of type int var m = time.Month(2) // Prints the English // name of the month fmt.Println(m.String())}
Output:
February
Example 2:
// Golang program to illustrate the usage of// (Month) String() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Calling time.Month // with its parameter // of type int var m = time.Month(12) // Prints the English name of // the month fmt.Println(m.String())}
Output:
December
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Strings in Golang
Time Durations in Golang
How to Parse JSON in Golang?
6 Best Books to Learn Go Programming Language
Structures in Golang
Defer Keyword in Golang
How to iterate over an Array using for loop in Golang?
Rune in Golang
Class and Object in Golang
Loops in Go Language
|
[
{
"code": null,
"e": 25703,
"s": 25675,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 26023,
"s": 25703,
"text": "In Go language, time packages supplies functionality for determining as well as viewing time. The Month.String() function in Go language is used to find the English name of the month. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions."
},
{
"code": null,
"e": 26031,
"s": 26023,
"text": "Syntax:"
},
{
"code": null,
"e": 26063,
"s": 26031,
"text": "func (m Month) String() string\n"
},
{
"code": null,
"e": 26092,
"s": 26063,
"text": "Here, “m” is the type Month."
},
{
"code": null,
"e": 26166,
"s": 26092,
"text": "Return Value: It returns a string which is the English name of the month."
},
{
"code": null,
"e": 26177,
"s": 26166,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate the usage of// (Month) String() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Calling time.Month // with its parameter // of type int var m = time.Month(2) // Prints the English // name of the month fmt.Println(m.String())}",
"e": 26546,
"s": 26177,
"text": null
},
{
"code": null,
"e": 26554,
"s": 26546,
"text": "Output:"
},
{
"code": null,
"e": 26564,
"s": 26554,
"text": "February\n"
},
{
"code": null,
"e": 26575,
"s": 26564,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate the usage of// (Month) String() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Calling time.Month // with its parameter // of type int var m = time.Month(12) // Prints the English name of // the month fmt.Println(m.String())}",
"e": 26945,
"s": 26575,
"text": null
},
{
"code": null,
"e": 26953,
"s": 26945,
"text": "Output:"
},
{
"code": null,
"e": 26963,
"s": 26953,
"text": "December\n"
},
{
"code": null,
"e": 26975,
"s": 26963,
"text": "GoLang-time"
},
{
"code": null,
"e": 26987,
"s": 26975,
"text": "Go Language"
},
{
"code": null,
"e": 27085,
"s": 26987,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27103,
"s": 27085,
"text": "Strings in Golang"
},
{
"code": null,
"e": 27128,
"s": 27103,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 27157,
"s": 27128,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 27203,
"s": 27157,
"text": "6 Best Books to Learn Go Programming Language"
},
{
"code": null,
"e": 27224,
"s": 27203,
"text": "Structures in Golang"
},
{
"code": null,
"e": 27248,
"s": 27224,
"text": "Defer Keyword in Golang"
},
{
"code": null,
"e": 27303,
"s": 27248,
"text": "How to iterate over an Array using for loop in Golang?"
},
{
"code": null,
"e": 27318,
"s": 27303,
"text": "Rune in Golang"
},
{
"code": null,
"e": 27345,
"s": 27318,
"text": "Class and Object in Golang"
}
] |
List listIterator() Method in Java with Examples - GeeksforGeeks
|
02 Jan, 2019
This method returns a list iterator over the elements in the mentioned list (in proper sequence), starting at the specified position in the list.
Syntax:
ListIterator listIterator(int index)
Parameters: This method has only argument, i.e, index – index of the first element to be returned from the list iterator (by a call to next).
Returns: This method returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
Exception: This method throws an exception IndexOutOfBoundsException – if the index is out of range (index size())
Below programs show the implementation of this method.
Program 1:
// Java program to demonstrate// listIterator() method// for List interfaceimport java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of List<Integer> List<Integer> arrlist = new ArrayList<>(); // adding element to arrlist arrlist.add(1); arrlist.add(3); arrlist.add(6); arrlist.add(9); // print arrlist System.out.println("ArrayList: " + arrlist); // Creating object of ListIterator<String> // using listIterator() method ListIterator<Integer> iterator = arrlist.listIterator(); // Printing the iterated value System.out.println("\nUsing ListIterator:\n"); while (iterator.hasNext()) { System.out.println("Value is : " + iterator.next()); } } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } }}
ArrayList: [1, 3, 6, 9]
Using ListIterator:
Value is : 1
Value is : 3
Value is : 6
Value is : 9
Program 2: Below is the code to show implementation of list.subList() using Linkedlist.
// Java program to demonstrate// listIterator() method// for List interfaceimport java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of List<Integer> List<String> arrlist = new ArrayList<String>(); // adding element to arrlist arrlist.add("A"); arrlist.add("B"); arrlist.add("C"); arrlist.add("D"); // print arrlist System.out.println("ArrayList: " + arrlist); // Creating object of ListIterator<String> // using listIterator() method ListIterator<String> iterator = arrlist.listIterator(); // Printing the iterated value System.out.println("\nUsing ListIterator:\n"); while (iterator.hasNext()) { System.out.println("Value is : " + iterator.next()); } } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } }}
ArrayList: [A, B, C, D]
Using ListIterator:
Value is : A
Value is : B
Value is : C
Value is : D
Reference:Oracle Docs
Java - util package
Java-Collections
Java-Functions
java-list
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
How to remove an element from ArrayList in Java?
|
[
{
"code": null,
"e": 25373,
"s": 25345,
"text": "\n02 Jan, 2019"
},
{
"code": null,
"e": 25519,
"s": 25373,
"text": "This method returns a list iterator over the elements in the mentioned list (in proper sequence), starting at the specified position in the list."
},
{
"code": null,
"e": 25527,
"s": 25519,
"text": "Syntax:"
},
{
"code": null,
"e": 25564,
"s": 25527,
"text": "ListIterator listIterator(int index)"
},
{
"code": null,
"e": 25706,
"s": 25564,
"text": "Parameters: This method has only argument, i.e, index – index of the first element to be returned from the list iterator (by a call to next)."
},
{
"code": null,
"e": 25852,
"s": 25706,
"text": "Returns: This method returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list."
},
{
"code": null,
"e": 25967,
"s": 25852,
"text": "Exception: This method throws an exception IndexOutOfBoundsException – if the index is out of range (index size())"
},
{
"code": null,
"e": 26022,
"s": 25967,
"text": "Below programs show the implementation of this method."
},
{
"code": null,
"e": 26033,
"s": 26022,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// listIterator() method// for List interfaceimport java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of List<Integer> List<Integer> arrlist = new ArrayList<>(); // adding element to arrlist arrlist.add(1); arrlist.add(3); arrlist.add(6); arrlist.add(9); // print arrlist System.out.println(\"ArrayList: \" + arrlist); // Creating object of ListIterator<String> // using listIterator() method ListIterator<Integer> iterator = arrlist.listIterator(); // Printing the iterated value System.out.println(\"\\nUsing ListIterator:\\n\"); while (iterator.hasNext()) { System.out.println(\"Value is : \" + iterator.next()); } } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 27157,
"s": 26033,
"text": null
},
{
"code": null,
"e": 27256,
"s": 27157,
"text": "ArrayList: [1, 3, 6, 9]\n\nUsing ListIterator:\n\nValue is : 1\nValue is : 3\nValue is : 6\nValue is : 9\n"
},
{
"code": null,
"e": 27344,
"s": 27256,
"text": "Program 2: Below is the code to show implementation of list.subList() using Linkedlist."
},
{
"code": "// Java program to demonstrate// listIterator() method// for List interfaceimport java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of List<Integer> List<String> arrlist = new ArrayList<String>(); // adding element to arrlist arrlist.add(\"A\"); arrlist.add(\"B\"); arrlist.add(\"C\"); arrlist.add(\"D\"); // print arrlist System.out.println(\"ArrayList: \" + arrlist); // Creating object of ListIterator<String> // using listIterator() method ListIterator<String> iterator = arrlist.listIterator(); // Printing the iterated value System.out.println(\"\\nUsing ListIterator:\\n\"); while (iterator.hasNext()) { System.out.println(\"Value is : \" + iterator.next()); } } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 28480,
"s": 27344,
"text": null
},
{
"code": null,
"e": 28579,
"s": 28480,
"text": "ArrayList: [A, B, C, D]\n\nUsing ListIterator:\n\nValue is : A\nValue is : B\nValue is : C\nValue is : D\n"
},
{
"code": null,
"e": 28601,
"s": 28579,
"text": "Reference:Oracle Docs"
},
{
"code": null,
"e": 28621,
"s": 28601,
"text": "Java - util package"
},
{
"code": null,
"e": 28638,
"s": 28621,
"text": "Java-Collections"
},
{
"code": null,
"e": 28653,
"s": 28638,
"text": "Java-Functions"
},
{
"code": null,
"e": 28663,
"s": 28653,
"text": "java-list"
},
{
"code": null,
"e": 28668,
"s": 28663,
"text": "Java"
},
{
"code": null,
"e": 28673,
"s": 28668,
"text": "Java"
},
{
"code": null,
"e": 28690,
"s": 28673,
"text": "Java-Collections"
},
{
"code": null,
"e": 28788,
"s": 28690,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28803,
"s": 28788,
"text": "Stream In Java"
},
{
"code": null,
"e": 28822,
"s": 28803,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28843,
"s": 28822,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28873,
"s": 28843,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28919,
"s": 28873,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28936,
"s": 28919,
"text": "Generics in Java"
},
{
"code": null,
"e": 28957,
"s": 28936,
"text": "Introduction to Java"
},
{
"code": null,
"e": 29000,
"s": 28957,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 29022,
"s": 29000,
"text": "PriorityQueue in Java"
}
] |
p5.js | orbitControl() Function - GeeksforGeeks
|
13 Jan, 2022
The orbitControl() function in p5.js is used to enable the movement around a 3D sketch using a mouse or trackpad. The left mouse button can be used to rotate the camera position about the center of the scene. The right mouse button can be used to pan the camera without any rotation. The mouse scroll wheel can be used to move the camera closer or further to the center of the scene.The function can be given optional parameters that are used to control the sensitivity of the movement along the axes. The default sensitivity along all axes is 1. A negative value of sensitivity can be used to reverse the direction of the movement.Syntax:
orbitControl( [sensitivityX], [sensitivityY], [sensitivityZ] )
Parameters: This function accepts three parameters as mentioned above and described below:
sensitivityX: It is a number which determines the sensitivity to mouse movement along the x-axis. It is an optional parameter.
sensitivityY: It is a number which determines the sensitivity to mouse movement along the y-axis. It is an optional parameter.
sensitivityZ: It is a number which determines the sensitivity to mouse movement along the z-axis. It is an optional parameter.
Below examples illustrate the orbitControl() function in p5.js:Example 1:
javascript
let newFont;let orbitControlEnable = false; function preload() { newFont = loadFont('fonts/Montserrat.otf');} function setup() { createCanvas(600, 300, WEBGL); textFont(newFont, 18); orbitControlCheck = createCheckbox( "Enable Orbit Control", false); orbitControlCheck.position(20, 60); // Toggle default light orbitControlCheck.changed(() => { orbitControlEnable = !orbitControlEnable; });} function draw() { background("green"); text("Click on the checkbox to toggle the " + "orbitControl() function.", -285, -125); noStroke(); // Enable default lights lights(); // If checkbox is enabled if (orbitControlEnable) { // Enable orbit control orbitControl(); text("Orbit Control Enabled", -285, 125); } else { text("Orbit Control Disabled", -285, 125); } box(100);}
Output:
Example 2:
javascript
let newFont;let orbitControlEnable = false; function preload() { newFont = loadFont('fonts/Montserrat.otf');} function setup() { createCanvas(600, 300, WEBGL); textFont(newFont, 18); xSensitivitySlider = createSlider(0, 5, 1, 0.1); xSensitivitySlider.position(20, 50); ySensitivitySlider = createSlider(0, 5, 1, 0.1); ySensitivitySlider.position(20, 80); zSensitivitySlider = createSlider(0, 5, 1, 0.1); zSensitivitySlider.position(20, 110);} function draw() { background("green"); text("Move the sliders to modify the x, y and" + " z orbit sensitivity", -285, -125); noStroke(); xSensitivity = xSensitivitySlider.value(); ySensitivity = ySensitivitySlider.value(); zSensitivity = zSensitivitySlider.value(); text("x Sensitivity is: " + xSensitivity, -285, 100); text("y Sensitivity is: " + ySensitivity, -285, 120); text("z Sensitivity is: " + zSensitivity, -285, 140); // Enable default lights lights(); orbitControl(xSensitivity, ySensitivity, zSensitivity); box(100);}
Output:
Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/Reference: https://p5js.org/reference/#/p5/orbitControl
adnanirshad158
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 44937,
"s": 44909,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 45579,
"s": 44937,
"text": "The orbitControl() function in p5.js is used to enable the movement around a 3D sketch using a mouse or trackpad. The left mouse button can be used to rotate the camera position about the center of the scene. The right mouse button can be used to pan the camera without any rotation. The mouse scroll wheel can be used to move the camera closer or further to the center of the scene.The function can be given optional parameters that are used to control the sensitivity of the movement along the axes. The default sensitivity along all axes is 1. A negative value of sensitivity can be used to reverse the direction of the movement.Syntax: "
},
{
"code": null,
"e": 45642,
"s": 45579,
"text": "orbitControl( [sensitivityX], [sensitivityY], [sensitivityZ] )"
},
{
"code": null,
"e": 45735,
"s": 45642,
"text": "Parameters: This function accepts three parameters as mentioned above and described below: "
},
{
"code": null,
"e": 45862,
"s": 45735,
"text": "sensitivityX: It is a number which determines the sensitivity to mouse movement along the x-axis. It is an optional parameter."
},
{
"code": null,
"e": 45989,
"s": 45862,
"text": "sensitivityY: It is a number which determines the sensitivity to mouse movement along the y-axis. It is an optional parameter."
},
{
"code": null,
"e": 46116,
"s": 45989,
"text": "sensitivityZ: It is a number which determines the sensitivity to mouse movement along the z-axis. It is an optional parameter."
},
{
"code": null,
"e": 46192,
"s": 46116,
"text": "Below examples illustrate the orbitControl() function in p5.js:Example 1: "
},
{
"code": null,
"e": 46203,
"s": 46192,
"text": "javascript"
},
{
"code": "let newFont;let orbitControlEnable = false; function preload() { newFont = loadFont('fonts/Montserrat.otf');} function setup() { createCanvas(600, 300, WEBGL); textFont(newFont, 18); orbitControlCheck = createCheckbox( \"Enable Orbit Control\", false); orbitControlCheck.position(20, 60); // Toggle default light orbitControlCheck.changed(() => { orbitControlEnable = !orbitControlEnable; });} function draw() { background(\"green\"); text(\"Click on the checkbox to toggle the \" + \"orbitControl() function.\", -285, -125); noStroke(); // Enable default lights lights(); // If checkbox is enabled if (orbitControlEnable) { // Enable orbit control orbitControl(); text(\"Orbit Control Enabled\", -285, 125); } else { text(\"Orbit Control Disabled\", -285, 125); } box(100);}",
"e": 47021,
"s": 46203,
"text": null
},
{
"code": null,
"e": 47031,
"s": 47021,
"text": "Output: "
},
{
"code": null,
"e": 47044,
"s": 47031,
"text": "Example 2: "
},
{
"code": null,
"e": 47055,
"s": 47044,
"text": "javascript"
},
{
"code": "let newFont;let orbitControlEnable = false; function preload() { newFont = loadFont('fonts/Montserrat.otf');} function setup() { createCanvas(600, 300, WEBGL); textFont(newFont, 18); xSensitivitySlider = createSlider(0, 5, 1, 0.1); xSensitivitySlider.position(20, 50); ySensitivitySlider = createSlider(0, 5, 1, 0.1); ySensitivitySlider.position(20, 80); zSensitivitySlider = createSlider(0, 5, 1, 0.1); zSensitivitySlider.position(20, 110);} function draw() { background(\"green\"); text(\"Move the sliders to modify the x, y and\" + \" z orbit sensitivity\", -285, -125); noStroke(); xSensitivity = xSensitivitySlider.value(); ySensitivity = ySensitivitySlider.value(); zSensitivity = zSensitivitySlider.value(); text(\"x Sensitivity is: \" + xSensitivity, -285, 100); text(\"y Sensitivity is: \" + ySensitivity, -285, 120); text(\"z Sensitivity is: \" + zSensitivity, -285, 140); // Enable default lights lights(); orbitControl(xSensitivity, ySensitivity, zSensitivity); box(100);}",
"e": 48066,
"s": 47055,
"text": null
},
{
"code": null,
"e": 48076,
"s": 48066,
"text": "Output: "
},
{
"code": null,
"e": 48269,
"s": 48076,
"text": "Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/Reference: https://p5js.org/reference/#/p5/orbitControl "
},
{
"code": null,
"e": 48284,
"s": 48269,
"text": "adnanirshad158"
},
{
"code": null,
"e": 48301,
"s": 48284,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 48312,
"s": 48301,
"text": "JavaScript"
},
{
"code": null,
"e": 48329,
"s": 48312,
"text": "Web Technologies"
},
{
"code": null,
"e": 48427,
"s": 48329,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 48467,
"s": 48427,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 48512,
"s": 48467,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 48573,
"s": 48512,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 48645,
"s": 48573,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 48714,
"s": 48645,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 48754,
"s": 48714,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 48787,
"s": 48754,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 48832,
"s": 48787,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 48875,
"s": 48832,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
HTML | DOM toggleAttribute() Method - GeeksforGeeks
|
29 May, 2020
The toggleAttribute() method of the element interface toggles a Boolean attribute on the given element. Attributes of an element can be changed using this method.
Syntax:
Element.toggleAttribute("attribute_name");
Parameters:
Name_of_attribute: Name of the attribute to be toggled. The attribute name is automatically converted to all lower-case when toggleAttribute() is called on an HTML element in an HTML document.
Return Value: It returns true if attribute name is present, false otherwise.
Example: In this example, we will toggle attribute of input element to readonly. The attribute name is automatically converted to all lower-case when toggleAttribute() is called on an HTML element in an HTML document.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>ToggleAttribute</title> <script> function change() { var input = document.querySelector("input"); input.toggleAttribute("readonly"); } </script></head> <body> <h1>GeeksforGeeks</h1> <input class="input" value="This is editable"> <button onclick="change()"> Click to change attribute </button></body> </html>
Output:
In this output, you can see that after clicking on button , attribute of input element changes to “readonly”, Hence it becomes uneditable.
Supported Browsers: The browsers supported by DOM toggleAttribute() method are listed below:
Google Chrome
Firefox
Apple Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-DOM
HTML-Methods
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
|
[
{
"code": null,
"e": 25717,
"s": 25689,
"text": "\n29 May, 2020"
},
{
"code": null,
"e": 25880,
"s": 25717,
"text": "The toggleAttribute() method of the element interface toggles a Boolean attribute on the given element. Attributes of an element can be changed using this method."
},
{
"code": null,
"e": 25888,
"s": 25880,
"text": "Syntax:"
},
{
"code": null,
"e": 25932,
"s": 25888,
"text": "Element.toggleAttribute(\"attribute_name\");\n"
},
{
"code": null,
"e": 25945,
"s": 25932,
"text": "Parameters: "
},
{
"code": null,
"e": 26138,
"s": 25945,
"text": "Name_of_attribute: Name of the attribute to be toggled. The attribute name is automatically converted to all lower-case when toggleAttribute() is called on an HTML element in an HTML document."
},
{
"code": null,
"e": 26215,
"s": 26138,
"text": "Return Value: It returns true if attribute name is present, false otherwise."
},
{
"code": null,
"e": 26433,
"s": 26215,
"text": "Example: In this example, we will toggle attribute of input element to readonly. The attribute name is automatically converted to all lower-case when toggleAttribute() is called on an HTML element in an HTML document."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>ToggleAttribute</title> <script> function change() { var input = document.querySelector(\"input\"); input.toggleAttribute(\"readonly\"); } </script></head> <body> <h1>GeeksforGeeks</h1> <input class=\"input\" value=\"This is editable\"> <button onclick=\"change()\"> Click to change attribute </button></body> </html>",
"e": 26918,
"s": 26433,
"text": null
},
{
"code": null,
"e": 26926,
"s": 26918,
"text": "Output:"
},
{
"code": null,
"e": 27065,
"s": 26926,
"text": "In this output, you can see that after clicking on button , attribute of input element changes to “readonly”, Hence it becomes uneditable."
},
{
"code": null,
"e": 27158,
"s": 27065,
"text": "Supported Browsers: The browsers supported by DOM toggleAttribute() method are listed below:"
},
{
"code": null,
"e": 27172,
"s": 27158,
"text": "Google Chrome"
},
{
"code": null,
"e": 27180,
"s": 27172,
"text": "Firefox"
},
{
"code": null,
"e": 27193,
"s": 27180,
"text": "Apple Safari"
},
{
"code": null,
"e": 27199,
"s": 27193,
"text": "Opera"
},
{
"code": null,
"e": 27336,
"s": 27199,
"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": 27345,
"s": 27336,
"text": "HTML-DOM"
},
{
"code": null,
"e": 27358,
"s": 27345,
"text": "HTML-Methods"
},
{
"code": null,
"e": 27363,
"s": 27358,
"text": "HTML"
},
{
"code": null,
"e": 27374,
"s": 27363,
"text": "JavaScript"
},
{
"code": null,
"e": 27391,
"s": 27374,
"text": "Web Technologies"
},
{
"code": null,
"e": 27396,
"s": 27391,
"text": "HTML"
},
{
"code": null,
"e": 27494,
"s": 27396,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27542,
"s": 27494,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 27566,
"s": 27542,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 27616,
"s": 27566,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 27666,
"s": 27616,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 27703,
"s": 27666,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 27743,
"s": 27703,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27788,
"s": 27743,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27849,
"s": 27788,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27921,
"s": 27849,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Month of() method in Java - GeeksforGeeks
|
22 Mar, 2019
The of() method is a built-in method of the Month ENUM which is used to generate a Month instance from an integer value. The integer value should be in the range 1-12 representing any of the 12 months and the method generates a Month instance from it representing a month-of-year.
Syntax:
public static Month of(int month)
Parameters: This method accepts a single parameter month, which is of integer type.
Return Value: This method returns the corresponding Month instance generated using the parameter passed.
Exception: This method throws a DateTimeException if the month of year passed to the parameter is not valid.
Below programs illustrate the above method:
Program 1:
import java.time.*;import java.time.Month;import java.time.temporal.ChronoField; class monthEnum { public static void main(String[] args) { // Create a month instance Month month = Month.of(2); // Print the month Instance System.out.println(month); }}
FEBRUARY
Program 2:
import java.time.*;import java.time.Month;import java.time.temporal.ChronoField; class monthEnum { public static void main(String[] args) { // Create a month instance Month month = Month.of(12); // Print the month Instance System.out.println(month); }}
DECEMBER
Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Month.html#of-int-
Java-Functions
Java-Month
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
|
[
{
"code": null,
"e": 25696,
"s": 25668,
"text": "\n22 Mar, 2019"
},
{
"code": null,
"e": 25977,
"s": 25696,
"text": "The of() method is a built-in method of the Month ENUM which is used to generate a Month instance from an integer value. The integer value should be in the range 1-12 representing any of the 12 months and the method generates a Month instance from it representing a month-of-year."
},
{
"code": null,
"e": 25985,
"s": 25977,
"text": "Syntax:"
},
{
"code": null,
"e": 26020,
"s": 25985,
"text": "public static Month of(int month)\n"
},
{
"code": null,
"e": 26104,
"s": 26020,
"text": "Parameters: This method accepts a single parameter month, which is of integer type."
},
{
"code": null,
"e": 26209,
"s": 26104,
"text": "Return Value: This method returns the corresponding Month instance generated using the parameter passed."
},
{
"code": null,
"e": 26318,
"s": 26209,
"text": "Exception: This method throws a DateTimeException if the month of year passed to the parameter is not valid."
},
{
"code": null,
"e": 26362,
"s": 26318,
"text": "Below programs illustrate the above method:"
},
{
"code": null,
"e": 26373,
"s": 26362,
"text": "Program 1:"
},
{
"code": "import java.time.*;import java.time.Month;import java.time.temporal.ChronoField; class monthEnum { public static void main(String[] args) { // Create a month instance Month month = Month.of(2); // Print the month Instance System.out.println(month); }}",
"e": 26665,
"s": 26373,
"text": null
},
{
"code": null,
"e": 26675,
"s": 26665,
"text": "FEBRUARY\n"
},
{
"code": null,
"e": 26686,
"s": 26675,
"text": "Program 2:"
},
{
"code": "import java.time.*;import java.time.Month;import java.time.temporal.ChronoField; class monthEnum { public static void main(String[] args) { // Create a month instance Month month = Month.of(12); // Print the month Instance System.out.println(month); }}",
"e": 26979,
"s": 26686,
"text": null
},
{
"code": null,
"e": 26989,
"s": 26979,
"text": "DECEMBER\n"
},
{
"code": null,
"e": 27071,
"s": 26989,
"text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Month.html#of-int-"
},
{
"code": null,
"e": 27086,
"s": 27071,
"text": "Java-Functions"
},
{
"code": null,
"e": 27097,
"s": 27086,
"text": "Java-Month"
},
{
"code": null,
"e": 27115,
"s": 27097,
"text": "Java-time package"
},
{
"code": null,
"e": 27120,
"s": 27115,
"text": "Java"
},
{
"code": null,
"e": 27125,
"s": 27120,
"text": "Java"
},
{
"code": null,
"e": 27223,
"s": 27125,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27274,
"s": 27223,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27304,
"s": 27274,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27319,
"s": 27304,
"text": "Stream In Java"
},
{
"code": null,
"e": 27338,
"s": 27319,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27369,
"s": 27338,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27387,
"s": 27369,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27419,
"s": 27387,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27439,
"s": 27419,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27471,
"s": 27439,
"text": "Multidimensional Arrays in Java"
}
] |
ASP Full Form - GeeksforGeeks
|
20 Oct, 2021
ASP stands for active server pages and it is a server-side script engine for building web pages. ASP is basically a server page that contains embedded programs in it. The programs in it are processed on the Microsoft server. The ASP server-side engine basically performs the task of reading and executing the ASP file and then return the file to the browser. It is basically a web-based framework that helps programmers to build dynamic web pages. ASP can contain scripts as well as standard HTML.History: ASP was firstly introduced in December 1996 as part of IIS (Internet information services) 3.0 which was called ASP 1.0. Then its subsequent versions came in 1997 and 2000 named ASP 2.0 and ASP 3.0 respectively. ASP 3.0 had some additional features so ASP 3.0 increased its performance.Syntax:
html
<html> <head> <title>ASP page</title> </head> <body> <% response.write("Welcome to GeeksForGeeks!") %> </body></html>
Output
Welcome to GeeksForGeeks
Characteristics:
User Control: The creation of user controls supports the making of reusable components.
Custom Controls: We can make custom controls from ASP. Here the code is compiled into a Dynamic Link Library file.
Rendering Techniques: ASP uses visited composite rendering technique in which composite tree is built.
Code-Behind Model: Microsoft recommends to use the code-behind model for dealing with dynamic program code.
Use of ASP: ASP is mainly used because of its high speed, language-independent nature, and low cost. We can make ASP pages in any language so it is not dependent on a particular language. It is used to develop dynamic websites in a more efficient way.
Advantages:
ASP reduces the line of code for building the complex applications.
It has smart caching technologies.
ASP is language independent so any language can be used for coding it.
ASP is much faster than other applications.
ASP is more used now-a-days.
Disadvantages:
There is a lot of complexity in pages and there are many performance issues.
It is dependent on IIS(Internet information services) so it is problematic.
It has limited development and debugging tools.
There is no real state management in ASP.
pp_pankaj
hritikbhatnagar2182
Full Form
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CDMA Full Form
SCTP Full Form
RSA Full Form
Peripheral Component Interconnect (PCI)
FDDI Full Form
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": 25067,
"s": 25039,
"text": "\n20 Oct, 2021"
},
{
"code": null,
"e": 25869,
"s": 25067,
"text": "ASP stands for active server pages and it is a server-side script engine for building web pages. ASP is basically a server page that contains embedded programs in it. The programs in it are processed on the Microsoft server. The ASP server-side engine basically performs the task of reading and executing the ASP file and then return the file to the browser. It is basically a web-based framework that helps programmers to build dynamic web pages. ASP can contain scripts as well as standard HTML.History: ASP was firstly introduced in December 1996 as part of IIS (Internet information services) 3.0 which was called ASP 1.0. Then its subsequent versions came in 1997 and 2000 named ASP 2.0 and ASP 3.0 respectively. ASP 3.0 had some additional features so ASP 3.0 increased its performance.Syntax: "
},
{
"code": null,
"e": 25874,
"s": 25869,
"text": "html"
},
{
"code": "<html> <head> <title>ASP page</title> </head> <body> <% response.write(\"Welcome to GeeksForGeeks!\") %> </body></html>",
"e": 26018,
"s": 25874,
"text": null
},
{
"code": null,
"e": 26026,
"s": 26018,
"text": "Output "
},
{
"code": null,
"e": 26051,
"s": 26026,
"text": "Welcome to GeeksForGeeks"
},
{
"code": null,
"e": 26069,
"s": 26051,
"text": "Characteristics: "
},
{
"code": null,
"e": 26157,
"s": 26069,
"text": "User Control: The creation of user controls supports the making of reusable components."
},
{
"code": null,
"e": 26272,
"s": 26157,
"text": "Custom Controls: We can make custom controls from ASP. Here the code is compiled into a Dynamic Link Library file."
},
{
"code": null,
"e": 26375,
"s": 26272,
"text": "Rendering Techniques: ASP uses visited composite rendering technique in which composite tree is built."
},
{
"code": null,
"e": 26483,
"s": 26375,
"text": "Code-Behind Model: Microsoft recommends to use the code-behind model for dealing with dynamic program code."
},
{
"code": null,
"e": 26736,
"s": 26483,
"text": "Use of ASP: ASP is mainly used because of its high speed, language-independent nature, and low cost. We can make ASP pages in any language so it is not dependent on a particular language. It is used to develop dynamic websites in a more efficient way. "
},
{
"code": null,
"e": 26750,
"s": 26736,
"text": "Advantages: "
},
{
"code": null,
"e": 26818,
"s": 26750,
"text": "ASP reduces the line of code for building the complex applications."
},
{
"code": null,
"e": 26853,
"s": 26818,
"text": "It has smart caching technologies."
},
{
"code": null,
"e": 26924,
"s": 26853,
"text": "ASP is language independent so any language can be used for coding it."
},
{
"code": null,
"e": 26968,
"s": 26924,
"text": "ASP is much faster than other applications."
},
{
"code": null,
"e": 26997,
"s": 26968,
"text": "ASP is more used now-a-days."
},
{
"code": null,
"e": 27013,
"s": 26997,
"text": "Disadvantages: "
},
{
"code": null,
"e": 27090,
"s": 27013,
"text": "There is a lot of complexity in pages and there are many performance issues."
},
{
"code": null,
"e": 27166,
"s": 27090,
"text": "It is dependent on IIS(Internet information services) so it is problematic."
},
{
"code": null,
"e": 27214,
"s": 27166,
"text": "It has limited development and debugging tools."
},
{
"code": null,
"e": 27256,
"s": 27214,
"text": "There is no real state management in ASP."
},
{
"code": null,
"e": 27268,
"s": 27258,
"text": "pp_pankaj"
},
{
"code": null,
"e": 27288,
"s": 27268,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 27298,
"s": 27288,
"text": "Full Form"
},
{
"code": null,
"e": 27315,
"s": 27298,
"text": "Web Technologies"
},
{
"code": null,
"e": 27342,
"s": 27315,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 27440,
"s": 27342,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27455,
"s": 27440,
"text": "CDMA Full Form"
},
{
"code": null,
"e": 27470,
"s": 27455,
"text": "SCTP Full Form"
},
{
"code": null,
"e": 27484,
"s": 27470,
"text": "RSA Full Form"
},
{
"code": null,
"e": 27524,
"s": 27484,
"text": "Peripheral Component Interconnect (PCI)"
},
{
"code": null,
"e": 27539,
"s": 27524,
"text": "FDDI Full Form"
},
{
"code": null,
"e": 27579,
"s": 27539,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27612,
"s": 27579,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27657,
"s": 27612,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27700,
"s": 27657,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Expressing a fraction as a natural number under modulo 'm' - GeeksforGeeks
|
13 Sep, 2021
Given two integers A and B where A is not divisible by B, the task is to express A / B as a natural number modulo m where m = 1000000007. Note: This representation is useful where we need to express Probability of an event, Area of Curves and polygons etc.Examples:
Input: A = 2, B = 6 Output: 333333336Input: A = 4, B = 5 Output: 600000005
Approach: We know that, A / B can be written as A * (1 / B) i.e. A * (B ^ -1).It is known that the modulo(%) operator satisfies the relation:
(a * b) % m = ( (a % m) * (b % m) ) % m
So, we can write:
(b ^ -1) % m = (b ^ m-2) % m (Fermat's little theorem)
Therefore the result will be:
( (A mod m) * ( power(B, m-2) % m) ) % m
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define ll long long int#define m 1000000007 // Function to return the GCD of given numbersint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Recursive function to return (x ^ n) % mll modexp(ll x, ll n){ if (n == 0) { return 1; } else if (n % 2 == 0) { return modexp((x * x) % m, n / 2); } else { return (x * modexp((x * x) % m, (n - 1) / 2) % m); }} // Function to return the fraction modulo modll getFractionModulo(ll a, ll b){ ll c = gcd(a, b); a = a / c; b = b / c; // (b ^ m-2) % m ll d = modexp(b, m - 2); // Final answer ll ans = ((a % m) * (d % m)) % m; return ans;} // Driver codeint main(){ ll a = 2, b = 6; cout << getFractionModulo(a, b) << endl; return 0;}
// Java implementation of the approach import java.io.*; class GFG { static long m = 1000000007; // Function to return the GCD of given numbers static long gcd(long a, long b){ if (a == 0) return b; return gcd(b % a, a);} // Recursive function to return (x ^ n) % mstatic long modexp(long x, long n){ if (n == 0) { return 1; } else if (n % 2 == 0) { return modexp((x * x) % m, n / 2); } else { return (x * modexp((x * x) % m, (n - 1) / 2) % m); }} // Function to return the fraction modulo mod static long getFractionModulo(long a, long b){ long c = gcd(a, b); a = a / c; b = b / c; // (b ^ m-2) % m long d = modexp(b, m - 2); // Final answer long ans = ((a % m) * (d % m)) % m; return ans;} // Driver code public static void main (String[] args) { long a = 2, b = 6; System.out.println(getFractionModulo(a, b)); }}// This code is contributed by inder_verma
# Python3 implementation of the approachm = 1000000007 # Function to return the GCD# of given numbersdef gcd(a, b): if (a == 0): return b return gcd(b % a, a) # Recursive function to return (x ^ n) % mdef modexp(x, n): if (n == 0) : return 1 elif (n % 2 == 0) : return modexp((x * x) % m, n // 2) else : return (x * modexp((x * x) % m, (n - 1) / 2) % m) # Function to return the fraction modulo moddef getFractionModulo(a, b): c = gcd(a, b) a = a // c b = b // c # (b ^ m-2) % m d = modexp(b, m - 2) # Final answer ans = ((a % m) * (d % m)) % m return ans # Driver codeif __name__ == "__main__": a = 2 b = 6 print ( getFractionModulo(a, b)) # This code is contributed by ita_c
//C# implementation of the approach using System; public class GFG{ static long m = 1000000007; // Function to return the GCD of given numbersstatic long gcd(long a, long b){ if (a == 0) return b; return gcd(b % a, a);} // Recursive function to return (x ^ n) % mstatic long modexp(long x, long n){ if (n == 0) { return 1; } else if (n % 2 == 0) { return modexp((x * x) % m, n / 2); } else { return (x * modexp((x * x) % m, (n - 1) / 2) % m); }} // Function to return the fraction modulo modstatic long getFractionModulo(long a, long b){ long c = gcd(a, b); a = a / c; b = b / c; // (b ^ m-2) % m long d = modexp(b, m - 2); // Final answer long ans = ((a % m) * (d % m)) % m; return ans;} // Driver code static public void Main (){ long a = 2, b = 6; Console.WriteLine(getFractionModulo(a, b)); }}
<?php// PHP implementation of the approach // Function to return the GCD of// given numbersfunction abc($a, $b){ if ($a == 0) return $b; return abc($b % $a, $a);} // Recursive function to return (x ^ n) % mfunction modexp($x, $n){ $m = 1000000007; if ($n == 0) { return 1; } else if ($n % 2 == 0) { return modexp(($x * $x) % $m, $n / 2); } else { return ($x * modexp(($x * $x) % $m, ($n - 1) / 2) % $m); }} // Function to return the fraction// modulo modfunction getFractionModulo($a, $b){ $m = 1000000007; $c = abc($a, $b); $a = $a / $c; $b = $b / $c; // (b ^ m-2) % m $d = modexp($b, $m - 2); // Final answer $ans = (($a % $m) * ($d % $m)) % $m; return $ans;} // Driver code$a = 2;$b = 6; echo(getFractionModulo($a, $b)) ; // This code is contributed// by Shivi_Aggarwal?>
<script>// javascript implementation of the approach var m = 100000007; // Function to return the GCD of given numbers function gcd(a , b) { if (a == 0) return b; return gcd(b % a, a); } // Recursive function to return (x ^ n) % m function modexp(x , n) { if (n == 0) { return 1; } else if (n % 2 == 0) { return modexp((x * x) % m, n / 2); } else { return (x * modexp((x * x) % m, (n - 1) / 2) % m); } } // Function to return the fraction modulo mod function getFractionModulo(a , b) { var c = gcd(a, b); a = a / c; b = b / c; // (b ^ m-2) % m var d = modexp(b, m - 2); // Final answer var ans = ((a % m) * (d % m)) % m; return ans; } // Driver code var a = 2, b = 6; document.write(getFractionModulo(a, b)); // This code is contributed by umadevi9616</script>
333333336
Time Complexity: O(log(min(a, b) + logm) Auxiliary Space: O(log(min(a, b) + logm)
inderDuMCA
Sach_Code
Shivi_Aggarwal
ukasp
pankajsharmagfg
umadevi9616
C Basics
inversion
Modular Arithmetic
Algorithms
C++ Programs
Competitive Programming
Mathematical
Mathematical
Modular Arithmetic
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
Difference between Algorithm, Pseudocode and Program
K means Clustering - Introduction
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Sorting a Map by value in C++ STL
|
[
{
"code": null,
"e": 25943,
"s": 25915,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 26211,
"s": 25943,
"text": "Given two integers A and B where A is not divisible by B, the task is to express A / B as a natural number modulo m where m = 1000000007. Note: This representation is useful where we need to express Probability of an event, Area of Curves and polygons etc.Examples: "
},
{
"code": null,
"e": 26288,
"s": 26211,
"text": "Input: A = 2, B = 6 Output: 333333336Input: A = 4, B = 5 Output: 600000005 "
},
{
"code": null,
"e": 26434,
"s": 26290,
"text": "Approach: We know that, A / B can be written as A * (1 / B) i.e. A * (B ^ -1).It is known that the modulo(%) operator satisfies the relation: "
},
{
"code": null,
"e": 26474,
"s": 26434,
"text": "(a * b) % m = ( (a % m) * (b % m) ) % m"
},
{
"code": null,
"e": 26494,
"s": 26474,
"text": "So, we can write: "
},
{
"code": null,
"e": 26549,
"s": 26494,
"text": "(b ^ -1) % m = (b ^ m-2) % m (Fermat's little theorem)"
},
{
"code": null,
"e": 26581,
"s": 26549,
"text": "Therefore the result will be: "
},
{
"code": null,
"e": 26622,
"s": 26581,
"text": "( (A mod m) * ( power(B, m-2) % m) ) % m"
},
{
"code": null,
"e": 26675,
"s": 26622,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26679,
"s": 26675,
"text": "C++"
},
{
"code": null,
"e": 26684,
"s": 26679,
"text": "Java"
},
{
"code": null,
"e": 26692,
"s": 26684,
"text": "Python3"
},
{
"code": null,
"e": 26695,
"s": 26692,
"text": "C#"
},
{
"code": null,
"e": 26699,
"s": 26695,
"text": "PHP"
},
{
"code": null,
"e": 26710,
"s": 26699,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define ll long long int#define m 1000000007 // Function to return the GCD of given numbersint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Recursive function to return (x ^ n) % mll modexp(ll x, ll n){ if (n == 0) { return 1; } else if (n % 2 == 0) { return modexp((x * x) % m, n / 2); } else { return (x * modexp((x * x) % m, (n - 1) / 2) % m); }} // Function to return the fraction modulo modll getFractionModulo(ll a, ll b){ ll c = gcd(a, b); a = a / c; b = b / c; // (b ^ m-2) % m ll d = modexp(b, m - 2); // Final answer ll ans = ((a % m) * (d % m)) % m; return ans;} // Driver codeint main(){ ll a = 2, b = 6; cout << getFractionModulo(a, b) << endl; return 0;}",
"e": 27573,
"s": 26710,
"text": null
},
{
"code": "// Java implementation of the approach import java.io.*; class GFG { static long m = 1000000007; // Function to return the GCD of given numbers static long gcd(long a, long b){ if (a == 0) return b; return gcd(b % a, a);} // Recursive function to return (x ^ n) % mstatic long modexp(long x, long n){ if (n == 0) { return 1; } else if (n % 2 == 0) { return modexp((x * x) % m, n / 2); } else { return (x * modexp((x * x) % m, (n - 1) / 2) % m); }} // Function to return the fraction modulo mod static long getFractionModulo(long a, long b){ long c = gcd(a, b); a = a / c; b = b / c; // (b ^ m-2) % m long d = modexp(b, m - 2); // Final answer long ans = ((a % m) * (d % m)) % m; return ans;} // Driver code public static void main (String[] args) { long a = 2, b = 6; System.out.println(getFractionModulo(a, b)); }}// This code is contributed by inder_verma",
"e": 28537,
"s": 27573,
"text": null
},
{
"code": "# Python3 implementation of the approachm = 1000000007 # Function to return the GCD# of given numbersdef gcd(a, b): if (a == 0): return b return gcd(b % a, a) # Recursive function to return (x ^ n) % mdef modexp(x, n): if (n == 0) : return 1 elif (n % 2 == 0) : return modexp((x * x) % m, n // 2) else : return (x * modexp((x * x) % m, (n - 1) / 2) % m) # Function to return the fraction modulo moddef getFractionModulo(a, b): c = gcd(a, b) a = a // c b = b // c # (b ^ m-2) % m d = modexp(b, m - 2) # Final answer ans = ((a % m) * (d % m)) % m return ans # Driver codeif __name__ == \"__main__\": a = 2 b = 6 print ( getFractionModulo(a, b)) # This code is contributed by ita_c",
"e": 29336,
"s": 28537,
"text": null
},
{
"code": "//C# implementation of the approach using System; public class GFG{ static long m = 1000000007; // Function to return the GCD of given numbersstatic long gcd(long a, long b){ if (a == 0) return b; return gcd(b % a, a);} // Recursive function to return (x ^ n) % mstatic long modexp(long x, long n){ if (n == 0) { return 1; } else if (n % 2 == 0) { return modexp((x * x) % m, n / 2); } else { return (x * modexp((x * x) % m, (n - 1) / 2) % m); }} // Function to return the fraction modulo modstatic long getFractionModulo(long a, long b){ long c = gcd(a, b); a = a / c; b = b / c; // (b ^ m-2) % m long d = modexp(b, m - 2); // Final answer long ans = ((a % m) * (d % m)) % m; return ans;} // Driver code static public void Main (){ long a = 2, b = 6; Console.WriteLine(getFractionModulo(a, b)); }}",
"e": 30254,
"s": 29336,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to return the GCD of// given numbersfunction abc($a, $b){ if ($a == 0) return $b; return abc($b % $a, $a);} // Recursive function to return (x ^ n) % mfunction modexp($x, $n){ $m = 1000000007; if ($n == 0) { return 1; } else if ($n % 2 == 0) { return modexp(($x * $x) % $m, $n / 2); } else { return ($x * modexp(($x * $x) % $m, ($n - 1) / 2) % $m); }} // Function to return the fraction// modulo modfunction getFractionModulo($a, $b){ $m = 1000000007; $c = abc($a, $b); $a = $a / $c; $b = $b / $c; // (b ^ m-2) % m $d = modexp($b, $m - 2); // Final answer $ans = (($a % $m) * ($d % $m)) % $m; return $ans;} // Driver code$a = 2;$b = 6; echo(getFractionModulo($a, $b)) ; // This code is contributed// by Shivi_Aggarwal?>",
"e": 31151,
"s": 30254,
"text": null
},
{
"code": "<script>// javascript implementation of the approach var m = 100000007; // Function to return the GCD of given numbers function gcd(a , b) { if (a == 0) return b; return gcd(b % a, a); } // Recursive function to return (x ^ n) % m function modexp(x , n) { if (n == 0) { return 1; } else if (n % 2 == 0) { return modexp((x * x) % m, n / 2); } else { return (x * modexp((x * x) % m, (n - 1) / 2) % m); } } // Function to return the fraction modulo mod function getFractionModulo(a , b) { var c = gcd(a, b); a = a / c; b = b / c; // (b ^ m-2) % m var d = modexp(b, m - 2); // Final answer var ans = ((a % m) * (d % m)) % m; return ans; } // Driver code var a = 2, b = 6; document.write(getFractionModulo(a, b)); // This code is contributed by umadevi9616</script>",
"e": 32115,
"s": 31151,
"text": null
},
{
"code": null,
"e": 32125,
"s": 32115,
"text": "333333336"
},
{
"code": null,
"e": 32210,
"s": 32127,
"text": "Time Complexity: O(log(min(a, b) + logm) Auxiliary Space: O(log(min(a, b) + logm) "
},
{
"code": null,
"e": 32221,
"s": 32210,
"text": "inderDuMCA"
},
{
"code": null,
"e": 32231,
"s": 32221,
"text": "Sach_Code"
},
{
"code": null,
"e": 32246,
"s": 32231,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 32252,
"s": 32246,
"text": "ukasp"
},
{
"code": null,
"e": 32268,
"s": 32252,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 32280,
"s": 32268,
"text": "umadevi9616"
},
{
"code": null,
"e": 32289,
"s": 32280,
"text": "C Basics"
},
{
"code": null,
"e": 32299,
"s": 32289,
"text": "inversion"
},
{
"code": null,
"e": 32318,
"s": 32299,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 32329,
"s": 32318,
"text": "Algorithms"
},
{
"code": null,
"e": 32342,
"s": 32329,
"text": "C++ Programs"
},
{
"code": null,
"e": 32366,
"s": 32342,
"text": "Competitive Programming"
},
{
"code": null,
"e": 32379,
"s": 32366,
"text": "Mathematical"
},
{
"code": null,
"e": 32392,
"s": 32379,
"text": "Mathematical"
},
{
"code": null,
"e": 32411,
"s": 32392,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 32422,
"s": 32411,
"text": "Algorithms"
},
{
"code": null,
"e": 32520,
"s": 32422,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32545,
"s": 32520,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 32572,
"s": 32545,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 32625,
"s": 32572,
"text": "Difference between Algorithm, Pseudocode and Program"
},
{
"code": null,
"e": 32659,
"s": 32625,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 32726,
"s": 32659,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 32761,
"s": 32726,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 32805,
"s": 32761,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 32864,
"s": 32805,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 32890,
"s": 32864,
"text": "C++ Program for QuickSort"
}
] |
Python | Custom List slicing Sum - GeeksforGeeks
|
18 Feb, 2020
The problem of slicing a list has been dealt earlier, but sometimes we need to perform the slicing in variable lengths and its summation according to the input given in other list. This problem has its potential application in web development. Let’s discuss certain ways in which this can be done.
Method #1 : Using itertools.islice() + sum() + list comprehensionThe list comprehension can be used to iterate through the list and the component issue is solved using the islice function. Summation is performed by sum().
# Python3 code to demonstrate# Custom List slicing Sum# using itertools.islice() + sum() + list comprehensionfrom itertools import islice # initializing test listtest_list = [1, 5, 3, 7, 8, 10, 11, 16, 9, 12] # initializing slice list slice_list = [2, 1, 3, 4] # printing original list print("The original list : " + str(test_list)) # printing slice list print("The slice list : " + str(slice_list)) # using itertools.islice() + sum() + list comprehension# Custom List slicing Sumtemp = iter(test_list)res = [sum(list(islice(temp, part))) for part in slice_list] # print resultprint("The variable sliced sum list is : " + str(res))
The original list : [1, 5, 3, 7, 8, 10, 11, 16, 9, 12]
The slice list : [2, 1, 3, 4]
The variable sliced sum list is : [6, 3, 25, 48]
Method #2 : Using zip() + accumulate() + sum() + list slicingApart from using the list comprehension to perform the task of binding, this method uses zip function to hold sublist element together, accumulate function joins the elements, and slicing is used to construct the required slicing. Summation is performed by sum().
# Python3 code to demonstrate# Custom List slicing Sum# using zip() + accumulate() + sum() + list slicingfrom itertools import accumulate # initializing test listtest_list = [1, 5, 3, 7, 8, 10, 11, 16, 9, 12] # initializing slice list slice_list = [2, 1, 3, 4] # printing original list print("The original list : " + str(test_list)) # printing slice list print("The slice list : " + str(slice_list)) # using zip() + accumulate() + sum() + list slicing# Custom List slicing Sumres = [sum(test_list[i - j: i]) for i, j in zip(accumulate(slice_list), slice_list)] # print resultprint("The variable sliced sum list is : " + str(res))
The original list : [1, 5, 3, 7, 8, 10, 11, 16, 9, 12]
The slice list : [2, 1, 3, 4]
The variable sliced sum list is : [6, 3, 25, 48]
Python list-programs
Python
Python Programs
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
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 25915,
"s": 25887,
"text": "\n18 Feb, 2020"
},
{
"code": null,
"e": 26213,
"s": 25915,
"text": "The problem of slicing a list has been dealt earlier, but sometimes we need to perform the slicing in variable lengths and its summation according to the input given in other list. This problem has its potential application in web development. Let’s discuss certain ways in which this can be done."
},
{
"code": null,
"e": 26435,
"s": 26213,
"text": "Method #1 : Using itertools.islice() + sum() + list comprehensionThe list comprehension can be used to iterate through the list and the component issue is solved using the islice function. Summation is performed by sum()."
},
{
"code": "# Python3 code to demonstrate# Custom List slicing Sum# using itertools.islice() + sum() + list comprehensionfrom itertools import islice # initializing test listtest_list = [1, 5, 3, 7, 8, 10, 11, 16, 9, 12] # initializing slice list slice_list = [2, 1, 3, 4] # printing original list print(\"The original list : \" + str(test_list)) # printing slice list print(\"The slice list : \" + str(slice_list)) # using itertools.islice() + sum() + list comprehension# Custom List slicing Sumtemp = iter(test_list)res = [sum(list(islice(temp, part))) for part in slice_list] # print resultprint(\"The variable sliced sum list is : \" + str(res))",
"e": 27073,
"s": 26435,
"text": null
},
{
"code": null,
"e": 27208,
"s": 27073,
"text": "The original list : [1, 5, 3, 7, 8, 10, 11, 16, 9, 12]\nThe slice list : [2, 1, 3, 4]\nThe variable sliced sum list is : [6, 3, 25, 48]\n"
},
{
"code": null,
"e": 27535,
"s": 27210,
"text": "Method #2 : Using zip() + accumulate() + sum() + list slicingApart from using the list comprehension to perform the task of binding, this method uses zip function to hold sublist element together, accumulate function joins the elements, and slicing is used to construct the required slicing. Summation is performed by sum()."
},
{
"code": "# Python3 code to demonstrate# Custom List slicing Sum# using zip() + accumulate() + sum() + list slicingfrom itertools import accumulate # initializing test listtest_list = [1, 5, 3, 7, 8, 10, 11, 16, 9, 12] # initializing slice list slice_list = [2, 1, 3, 4] # printing original list print(\"The original list : \" + str(test_list)) # printing slice list print(\"The slice list : \" + str(slice_list)) # using zip() + accumulate() + sum() + list slicing# Custom List slicing Sumres = [sum(test_list[i - j: i]) for i, j in zip(accumulate(slice_list), slice_list)] # print resultprint(\"The variable sliced sum list is : \" + str(res))",
"e": 28171,
"s": 27535,
"text": null
},
{
"code": null,
"e": 28306,
"s": 28171,
"text": "The original list : [1, 5, 3, 7, 8, 10, 11, 16, 9, 12]\nThe slice list : [2, 1, 3, 4]\nThe variable sliced sum list is : [6, 3, 25, 48]\n"
},
{
"code": null,
"e": 28327,
"s": 28306,
"text": "Python list-programs"
},
{
"code": null,
"e": 28334,
"s": 28327,
"text": "Python"
},
{
"code": null,
"e": 28350,
"s": 28334,
"text": "Python Programs"
},
{
"code": null,
"e": 28448,
"s": 28350,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28466,
"s": 28448,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28501,
"s": 28466,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28533,
"s": 28501,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28555,
"s": 28533,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28597,
"s": 28555,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28640,
"s": 28597,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28662,
"s": 28640,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28701,
"s": 28662,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28747,
"s": 28701,
"text": "Python | Split string into list of characters"
}
] |
Get number of elements of array in Julia - length() Method - GeeksforGeeks
|
26 Mar, 2020
The length() is an inbuilt function in julia which is used to return the number of elements present in the specified array.
Syntax: length(A::AbstractArray)
Parameters:
A: Specified array
Returns: It returns the number of elements present in the specified array.
Example 1:
# Julia program to illustrate # the use of Array length() method # Finding the number of elements present in# the specified 1D array A.A = [5, 10, 15, 20]println(length(A)) # Finding the number of elements present in# the specified 2D array B of size 2 * 2B = [5 10; 15 20]println(length(B)) # Finding the number of elements present in# the specified 3D array C of size 2 * 2*2C = cat([1 2; 3 4], [5 6; 7 8], [9 10; 11 12], dims = 3)println(length(C))
Output:
Example 2:
# Julia program to illustrate # the use of Array length() method # Finding the number of elements present in# the specified 1D array A.A = [1, 2, 3];println(length(A)) # Finding the number of elements present in# the specified 2D array B of size 2 * 2B = [2 4; 6 8; 10 12];println(length(B)) # Finding the number of elements present in# the specified 3D array C of size 2 * 2*2C = cat([1 2; 3 4], [5 6; 7 8], [9 10; 11 12], [13 14; 15 16], dims = 4);println(length(C))
Output:
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Get array dimensions and size of a dimension in Julia - size() Method
Exception handling in Julia
Searching in Array for a given element in Julia
Find maximum element along with its index in Julia - findmax() Method
Join an array of strings into a single string in Julia - join() Method
Working with Excel Files in Julia
File Handling in Julia
Getting last element of an array in Julia - last() Method
Getting the maximum value from a list in Julia - max() Method
|
[
{
"code": null,
"e": 25789,
"s": 25761,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 25913,
"s": 25789,
"text": "The length() is an inbuilt function in julia which is used to return the number of elements present in the specified array."
},
{
"code": null,
"e": 25946,
"s": 25913,
"text": "Syntax: length(A::AbstractArray)"
},
{
"code": null,
"e": 25958,
"s": 25946,
"text": "Parameters:"
},
{
"code": null,
"e": 25977,
"s": 25958,
"text": "A: Specified array"
},
{
"code": null,
"e": 26052,
"s": 25977,
"text": "Returns: It returns the number of elements present in the specified array."
},
{
"code": null,
"e": 26063,
"s": 26052,
"text": "Example 1:"
},
{
"code": "# Julia program to illustrate # the use of Array length() method # Finding the number of elements present in# the specified 1D array A.A = [5, 10, 15, 20]println(length(A)) # Finding the number of elements present in# the specified 2D array B of size 2 * 2B = [5 10; 15 20]println(length(B)) # Finding the number of elements present in# the specified 3D array C of size 2 * 2*2C = cat([1 2; 3 4], [5 6; 7 8], [9 10; 11 12], dims = 3)println(length(C))",
"e": 26528,
"s": 26063,
"text": null
},
{
"code": null,
"e": 26536,
"s": 26528,
"text": "Output:"
},
{
"code": null,
"e": 26547,
"s": 26536,
"text": "Example 2:"
},
{
"code": "# Julia program to illustrate # the use of Array length() method # Finding the number of elements present in# the specified 1D array A.A = [1, 2, 3];println(length(A)) # Finding the number of elements present in# the specified 2D array B of size 2 * 2B = [2 4; 6 8; 10 12];println(length(B)) # Finding the number of elements present in# the specified 3D array C of size 2 * 2*2C = cat([1 2; 3 4], [5 6; 7 8], [9 10; 11 12], [13 14; 15 16], dims = 4);println(length(C))",
"e": 27033,
"s": 26547,
"text": null
},
{
"code": null,
"e": 27041,
"s": 27033,
"text": "Output:"
},
{
"code": null,
"e": 27047,
"s": 27041,
"text": "Julia"
},
{
"code": null,
"e": 27145,
"s": 27047,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27218,
"s": 27145,
"text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)"
},
{
"code": null,
"e": 27288,
"s": 27218,
"text": "Get array dimensions and size of a dimension in Julia - size() Method"
},
{
"code": null,
"e": 27316,
"s": 27288,
"text": "Exception handling in Julia"
},
{
"code": null,
"e": 27364,
"s": 27316,
"text": "Searching in Array for a given element in Julia"
},
{
"code": null,
"e": 27434,
"s": 27364,
"text": "Find maximum element along with its index in Julia - findmax() Method"
},
{
"code": null,
"e": 27505,
"s": 27434,
"text": "Join an array of strings into a single string in Julia - join() Method"
},
{
"code": null,
"e": 27539,
"s": 27505,
"text": "Working with Excel Files in Julia"
},
{
"code": null,
"e": 27562,
"s": 27539,
"text": "File Handling in Julia"
},
{
"code": null,
"e": 27620,
"s": 27562,
"text": "Getting last element of an array in Julia - last() Method"
}
] |
PLSQL | RTRIM Function - GeeksforGeeks
|
04 Feb, 2021
The PLSQL RTRIM function is used for removing all specified characters from the right-hand side of a string. The PLSQL RTRIM function accepts two parameters which are input_string and trim_string.
If the user does not specify trim_string, it defaults to a single blank.
If char is a character literal, then you must enclose it in single quotes.
Oracle Database begins scanning char from its first character and removes all characters that appear in trim_string until reaching a character not in trim_string and then returns the result.
Syntax:
RTRIM( input_string [, trim_string] )
Parameters Used:
input_string – It is used to specify the string whose characters need to be trimmed from the right hand side.trim_string – It is an optional parameter which is used to specify the string that will be removed from the right-hand side of input_string. If this parameter is omitted, the RTRIM function removes all leading spaces from input_string.
input_string – It is used to specify the string whose characters need to be trimmed from the right hand side.
trim_string – It is an optional parameter which is used to specify the string that will be removed from the right-hand side of input_string. If this parameter is omitted, the RTRIM function removes all leading spaces from input_string.
Supported Versions of Oracle/PLSQL:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Example-1:
DECLARE
Test_String string(25) := 'Geeksforgeeks ';
BEGIN
dbms_output.put_line(RTRIM(Test_String));
END;
Output:
Geeksforgeeks
Example-2:
DECLARE
Test_String string(25) := 'Geeksforgeeks ';
BEGIN
dbms_output.put_line(RTRIM(Test_String, ' '));
END;
Output:
Geeksforgeeks
Example-3:
DECLARE
Test_String string(25) := 'Geeksforgeeks123';
BEGIN
dbms_output.put_line(RTRIM(Test_String, '123'));
END;
Output:
Geeksforgeeks
Example-4:
DECLARE
Test_String string(25) := 'Geeksforgeeks123123';
BEGIN
dbms_output.put_line(RTRIM(Test_String, '123'));
END;
Output:
Geeksforgeeks
Example-5:
DECLARE
Test_String string(25) := 'Geeks123forgeeks123';
BEGIN
dbms_output.put_line(RTRIM(Test_String, '123'));
END;
Output:
Geeks123forgeeks
simranarora5sos
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL | Subquery
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
|
[
{
"code": null,
"e": 25513,
"s": 25485,
"text": "\n04 Feb, 2021"
},
{
"code": null,
"e": 25711,
"s": 25513,
"text": "The PLSQL RTRIM function is used for removing all specified characters from the right-hand side of a string. The PLSQL RTRIM function accepts two parameters which are input_string and trim_string. "
},
{
"code": null,
"e": 25785,
"s": 25711,
"text": "If the user does not specify trim_string, it defaults to a single blank. "
},
{
"code": null,
"e": 25861,
"s": 25785,
"text": "If char is a character literal, then you must enclose it in single quotes. "
},
{
"code": null,
"e": 26053,
"s": 25861,
"text": "Oracle Database begins scanning char from its first character and removes all characters that appear in trim_string until reaching a character not in trim_string and then returns the result. "
},
{
"code": null,
"e": 26063,
"s": 26053,
"text": "Syntax: "
},
{
"code": null,
"e": 26101,
"s": 26063,
"text": "RTRIM( input_string [, trim_string] )"
},
{
"code": null,
"e": 26120,
"s": 26101,
"text": "Parameters Used: "
},
{
"code": null,
"e": 26466,
"s": 26120,
"text": "input_string – It is used to specify the string whose characters need to be trimmed from the right hand side.trim_string – It is an optional parameter which is used to specify the string that will be removed from the right-hand side of input_string. If this parameter is omitted, the RTRIM function removes all leading spaces from input_string. "
},
{
"code": null,
"e": 26576,
"s": 26466,
"text": "input_string – It is used to specify the string whose characters need to be trimmed from the right hand side."
},
{
"code": null,
"e": 26813,
"s": 26576,
"text": "trim_string – It is an optional parameter which is used to specify the string that will be removed from the right-hand side of input_string. If this parameter is omitted, the RTRIM function removes all leading spaces from input_string. "
},
{
"code": null,
"e": 26851,
"s": 26813,
"text": "Supported Versions of Oracle/PLSQL: "
},
{
"code": null,
"e": 26900,
"s": 26851,
"text": "Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i"
},
{
"code": null,
"e": 26911,
"s": 26900,
"text": "Oracle 12c"
},
{
"code": null,
"e": 26922,
"s": 26911,
"text": "Oracle 11g"
},
{
"code": null,
"e": 26933,
"s": 26922,
"text": "Oracle 10g"
},
{
"code": null,
"e": 26943,
"s": 26933,
"text": "Oracle 9i"
},
{
"code": null,
"e": 26953,
"s": 26943,
"text": "Oracle 8i"
},
{
"code": null,
"e": 26966,
"s": 26953,
"text": "Example-1: "
},
{
"code": null,
"e": 27094,
"s": 26966,
"text": "DECLARE \n Test_String string(25) := 'Geeksforgeeks ';\n \nBEGIN \n dbms_output.put_line(RTRIM(Test_String)); \n \nEND; "
},
{
"code": null,
"e": 27104,
"s": 27094,
"text": "Output: "
},
{
"code": null,
"e": 27119,
"s": 27104,
"text": "Geeksforgeeks "
},
{
"code": null,
"e": 27132,
"s": 27119,
"text": "Example-2: "
},
{
"code": null,
"e": 27267,
"s": 27132,
"text": "DECLARE \n Test_String string(25) := 'Geeksforgeeks ';\n \nBEGIN \n dbms_output.put_line(RTRIM(Test_String, ' ')); \n \nEND; "
},
{
"code": null,
"e": 27277,
"s": 27267,
"text": "Output: "
},
{
"code": null,
"e": 27292,
"s": 27277,
"text": "Geeksforgeeks "
},
{
"code": null,
"e": 27305,
"s": 27292,
"text": "Example-3: "
},
{
"code": null,
"e": 27437,
"s": 27305,
"text": "DECLARE \n Test_String string(25) := 'Geeksforgeeks123';\n \nBEGIN \n dbms_output.put_line(RTRIM(Test_String, '123')); \n \nEND; "
},
{
"code": null,
"e": 27447,
"s": 27437,
"text": "Output: "
},
{
"code": null,
"e": 27462,
"s": 27447,
"text": "Geeksforgeeks "
},
{
"code": null,
"e": 27475,
"s": 27462,
"text": "Example-4: "
},
{
"code": null,
"e": 27612,
"s": 27475,
"text": "DECLARE \n Test_String string(25) := 'Geeksforgeeks123123';\n \nBEGIN \n dbms_output.put_line(RTRIM(Test_String, '123')); \n \nEND; "
},
{
"code": null,
"e": 27622,
"s": 27612,
"text": "Output: "
},
{
"code": null,
"e": 27637,
"s": 27622,
"text": "Geeksforgeeks "
},
{
"code": null,
"e": 27650,
"s": 27637,
"text": "Example-5: "
},
{
"code": null,
"e": 27788,
"s": 27650,
"text": "DECLARE \n Test_String string(25) := 'Geeks123forgeeks123';\n \nBEGIN \n dbms_output.put_line(RTRIM(Test_String, '123')); \n \nEND; "
},
{
"code": null,
"e": 27798,
"s": 27788,
"text": "Output: "
},
{
"code": null,
"e": 27816,
"s": 27798,
"text": "Geeks123forgeeks "
},
{
"code": null,
"e": 27834,
"s": 27818,
"text": "simranarora5sos"
},
{
"code": null,
"e": 27845,
"s": 27834,
"text": "SQL-PL/SQL"
},
{
"code": null,
"e": 27849,
"s": 27845,
"text": "SQL"
},
{
"code": null,
"e": 27853,
"s": 27849,
"text": "SQL"
},
{
"code": null,
"e": 27951,
"s": 27853,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28017,
"s": 27951,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 28074,
"s": 28017,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 28106,
"s": 28074,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 28121,
"s": 28106,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 28199,
"s": 28121,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 28235,
"s": 28199,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 28252,
"s": 28235,
"text": "SQL using Python"
},
{
"code": null,
"e": 28318,
"s": 28252,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 28380,
"s": 28318,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
}
] |
Move all zeroes to end of array - GeeksforGeeks
|
14 Dec, 2021
Given an array of random numbers, Push all the zero’s of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same. Expected time complexity is O(n) and extra space is O(1).Example:
Input : arr[] = {1, 2, 0, 4, 3, 0, 5, 0};
Output : arr[] = {1, 2, 4, 3, 5, 0, 0, 0};
Input : arr[] = {1, 2, 0, 0, 0, 3, 6};
Output : arr[] = {1, 2, 3, 6, 0, 0, 0};
There can be many ways to solve this problem. Following is a simple and interesting way to solve this problem. Traverse the given array ‘arr’ from left to right. While traversing, maintain count of non-zero elements in array. Let the count be ‘count’. For every non-zero element arr[i], put the element at ‘arr[count]’ and increment ‘count’. After complete traversal, all non-zero elements have already been shifted to front end and ‘count’ is set as index of first 0. Now all we need to do is that run a loop which makes all elements zero from ‘count’ till end of the array.Below is the implementation of the above approach.
C
C++
Java
Python3
C#
PHP
Javascript
// A C program to move all zeroes at the end of array#include <stdio.h> // Function which pushes all zeros to end of an array.void pushZerosToEnd(int arr[], int n){ int count = {0}; // Count of non-zero elements // Traverse the array. If element encountered is non- // zero, then replace the element at index 'count' // with this element for (int i = 0; i < n; i++) if (arr[i] != 0) arr[count++] = arr[i]; // here count is // incremented // Now all non-zero elements have been shifted to // front and 'count' is set as index of first 0. // Make all elements 0 from count to end. while (count < n) arr[count++] = 0;} // Driver program to test above functionint main(){ int arr[] = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}; int n = sizeof(arr) / sizeof(arr[0]); pushZerosToEnd(arr, n); printf("%s\n", "Array after pushing all zeros to end of array:"); for (int i = 0; i < n; i++) printf("%d ", arr[i]); return 0;}
#include <algorithm>#include <iostream>#include <vector> void push_zeros_to_end(std::vector<int>& arr){ std::stable_partition(arr.begin(), arr.end(), [](int n) { return n != 0; });} int main(){ std::vector<int> arr{1,9,8,4,0,0,2,7,0,6,0,9}; push_zeros_to_end(arr); for(const auto& i : arr) std::cout << i << ' '; std::cout << "\n"; return 0;}
/* Java program to push zeroes to back of array */import java.io.*; class PushZero{ // Function which pushes all zeros to end of an array. static void pushZerosToEnd(int arr[], int n) { int count = 0; // Count of non-zero elements // Traverse the array. If element encountered is // non-zero, then replace the element at index 'count' // with this element for (int i = 0; i < n; i++) if (arr[i] != 0) arr[count++] = arr[i]; // here count is // incremented // Now all non-zero elements have been shifted to // front and 'count' is set as index of first 0. // Make all elements 0 from count to end. while (count < n) arr[count++] = 0; } /*Driver function to check for above functions*/ public static void main (String[] args) { int arr[] = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}; int n = arr.length; pushZerosToEnd(arr, n); System.out.println("Array after pushing zeros to the back: "); for (int i=0; i<n; i++) System.out.print(arr[i]+" "); }}/* This code is contributed by Devesh Agrawal */
# Python3 code to move all zeroes# at the end of array # Function which pushes all# zeros to end of an array.def pushZerosToEnd(arr, n): count = 0 # Count of non-zero elements # Traverse the array. If element # encountered is non-zero, then # replace the element at index # 'count' with this element for i in range(n): if arr[i] != 0: # here count is incremented arr[count] = arr[i] count+=1 # Now all non-zero elements have been # shifted to front and 'count' is set # as index of first 0. Make all # elements 0 from count to end. while count < n: arr[count] = 0 count += 1 # Driver codearr = [1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9]n = len(arr)pushZerosToEnd(arr, n)print("Array after pushing all zeros to end of array:")print(arr) # This code is contributed by "Abhishek Sharma 44"
/* C# program to push zeroes to back of array */using System; class PushZero{ // Function which pushes all zeros // to end of an array. static void pushZerosToEnd(int []arr, int n) { // Count of non-zero elements int count = 0; // Traverse the array. If element encountered is // non-zero, then replace the element // at index â..countâ.. with this element for (int i = 0; i < n; i++) if (arr[i] != 0) // here count is incremented arr[count++] = arr[i]; // Now all non-zero elements have been shifted to // front and â..countâ.. is set as index of first 0. // Make all elements 0 from count to end. while (count < n) arr[count++] = 0; } // Driver function public static void Main () { int []arr = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}; int n = arr.Length; pushZerosToEnd(arr, n); Console.WriteLine("Array after pushing all zeros to the back: "); for (int i = 0; i < n; i++) Console.Write(arr[i] +" "); }}/* This code is contributed by Anant Agrawal */
<?php// A PHP program to move all// zeroes at the end of array // Function which pushes all// zeros to end of an array.function pushZerosToEnd(&$arr, $n){ // Count of non-zero elements $count = 0; // Traverse the array. If // element encountered is // non-zero, then replace // the element at index // 'count' with this element for ($i = 0; $i < $n; $i++) if ($arr[$i] != 0) // here count is incremented $arr[$count++] = $arr[$i]; // Now all non-zero elements // have been shifted to front // and 'count' is set as index // of first 0. Make all elements // 0 from count to end. while ($count < $n) $arr[$count++] = 0;} // Driver Code$arr = array(1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9);$n = sizeof($arr);pushZerosToEnd($arr, $n);echo "Array after pushing all " . "zeros to end of array :\n"; for ($i = 0; $i < $n; $i++)echo $arr[$i] . " "; // This code is contributed// by ChitraNayal?>
<script>// A JavaScript program to move all zeroes at the end of array // Function which pushes all zeros to end of an array.function pushZerosToEnd(arr, n){ let count = 0; // Count of non-zero elements // Traverse the array. If element encountered is non- // zero, then replace the element at index 'count' // with this element for (let i = 0; i < n; i++) if (arr[i] != 0) arr[count++] = arr[i]; // here count is // incremented // Now all non-zero elements have been shifted to // front and 'count' is set as index of first 0. // Make all elements 0 from count to end. while (count < n) arr[count++] = 0;} // Driver code let arr = [1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9]; let n = arr.length; pushZerosToEnd(arr, n); document.write("Array after pushing all zeros to end of array :<br>"); for (let i = 0; i < n; i++) document.write(arr[i] + " "); // This code is contributed by Surbhi Tyagi.</script>
Array after pushing all zeros to end of array :
1 9 8 4 2 7 6 9 0 0 0 0
Output:
Array after pushing all zeros to end of array :
1 9 8 4 2 7 6 9 0 0 0 0
Time Complexity: O(n) where n is number of elements in input array.Auxiliary Space: O(1)
YouTubeGeeksforGeeks507K subscribersMove all zeroes to end of array | 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 / 6:23•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=0jXTju134Hw" 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 Chandra Prakash. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ukasp
surbhityagi15
adityakhosla0
deadmarshal
Amazon
Bloomberg
Linkedin
Paytm
Samsung
SAP Labs
Arrays
Paytm
Amazon
Samsung
SAP Labs
Linkedin
Bloomberg
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Linked List vs Array
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
Queue | Set 1 (Introduction and Array Implementation)
Array of Strings in C++ (5 Different Ways to Create)
Find the Missing Number
Subset Sum Problem | DP-25
K'th Smallest/Largest Element in Unsorted Array | Set 1
Find Second largest element in an array
|
[
{
"code": null,
"e": 26761,
"s": 26733,
"text": "\n14 Dec, 2021"
},
{
"code": null,
"e": 27103,
"s": 26761,
"text": "Given an array of random numbers, Push all the zero’s of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same. Expected time complexity is O(n) and extra space is O(1).Example: "
},
{
"code": null,
"e": 27270,
"s": 27103,
"text": "Input : arr[] = {1, 2, 0, 4, 3, 0, 5, 0};\nOutput : arr[] = {1, 2, 4, 3, 5, 0, 0, 0};\n\nInput : arr[] = {1, 2, 0, 0, 0, 3, 6};\nOutput : arr[] = {1, 2, 3, 6, 0, 0, 0};"
},
{
"code": null,
"e": 27900,
"s": 27272,
"text": "There can be many ways to solve this problem. Following is a simple and interesting way to solve this problem. Traverse the given array ‘arr’ from left to right. While traversing, maintain count of non-zero elements in array. Let the count be ‘count’. For every non-zero element arr[i], put the element at ‘arr[count]’ and increment ‘count’. After complete traversal, all non-zero elements have already been shifted to front end and ‘count’ is set as index of first 0. Now all we need to do is that run a loop which makes all elements zero from ‘count’ till end of the array.Below is the implementation of the above approach. "
},
{
"code": null,
"e": 27902,
"s": 27900,
"text": "C"
},
{
"code": null,
"e": 27906,
"s": 27902,
"text": "C++"
},
{
"code": null,
"e": 27911,
"s": 27906,
"text": "Java"
},
{
"code": null,
"e": 27919,
"s": 27911,
"text": "Python3"
},
{
"code": null,
"e": 27922,
"s": 27919,
"text": "C#"
},
{
"code": null,
"e": 27926,
"s": 27922,
"text": "PHP"
},
{
"code": null,
"e": 27937,
"s": 27926,
"text": "Javascript"
},
{
"code": "// A C program to move all zeroes at the end of array#include <stdio.h> // Function which pushes all zeros to end of an array.void pushZerosToEnd(int arr[], int n){ int count = {0}; // Count of non-zero elements // Traverse the array. If element encountered is non- // zero, then replace the element at index 'count' // with this element for (int i = 0; i < n; i++) if (arr[i] != 0) arr[count++] = arr[i]; // here count is // incremented // Now all non-zero elements have been shifted to // front and 'count' is set as index of first 0. // Make all elements 0 from count to end. while (count < n) arr[count++] = 0;} // Driver program to test above functionint main(){ int arr[] = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}; int n = sizeof(arr) / sizeof(arr[0]); pushZerosToEnd(arr, n); printf(\"%s\\n\", \"Array after pushing all zeros to end of array:\"); for (int i = 0; i < n; i++) printf(\"%d \", arr[i]); return 0;}",
"e": 28958,
"s": 27937,
"text": null
},
{
"code": "#include <algorithm>#include <iostream>#include <vector> void push_zeros_to_end(std::vector<int>& arr){ std::stable_partition(arr.begin(), arr.end(), [](int n) { return n != 0; });} int main(){ std::vector<int> arr{1,9,8,4,0,0,2,7,0,6,0,9}; push_zeros_to_end(arr); for(const auto& i : arr) std::cout << i << ' '; std::cout << \"\\n\"; return 0;}",
"e": 29340,
"s": 28958,
"text": null
},
{
"code": "/* Java program to push zeroes to back of array */import java.io.*; class PushZero{ // Function which pushes all zeros to end of an array. static void pushZerosToEnd(int arr[], int n) { int count = 0; // Count of non-zero elements // Traverse the array. If element encountered is // non-zero, then replace the element at index 'count' // with this element for (int i = 0; i < n; i++) if (arr[i] != 0) arr[count++] = arr[i]; // here count is // incremented // Now all non-zero elements have been shifted to // front and 'count' is set as index of first 0. // Make all elements 0 from count to end. while (count < n) arr[count++] = 0; } /*Driver function to check for above functions*/ public static void main (String[] args) { int arr[] = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}; int n = arr.length; pushZerosToEnd(arr, n); System.out.println(\"Array after pushing zeros to the back: \"); for (int i=0; i<n; i++) System.out.print(arr[i]+\" \"); }}/* This code is contributed by Devesh Agrawal */",
"e": 30540,
"s": 29340,
"text": null
},
{
"code": "# Python3 code to move all zeroes# at the end of array # Function which pushes all# zeros to end of an array.def pushZerosToEnd(arr, n): count = 0 # Count of non-zero elements # Traverse the array. If element # encountered is non-zero, then # replace the element at index # 'count' with this element for i in range(n): if arr[i] != 0: # here count is incremented arr[count] = arr[i] count+=1 # Now all non-zero elements have been # shifted to front and 'count' is set # as index of first 0. Make all # elements 0 from count to end. while count < n: arr[count] = 0 count += 1 # Driver codearr = [1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9]n = len(arr)pushZerosToEnd(arr, n)print(\"Array after pushing all zeros to end of array:\")print(arr) # This code is contributed by \"Abhishek Sharma 44\"",
"e": 31439,
"s": 30540,
"text": null
},
{
"code": "/* C# program to push zeroes to back of array */using System; class PushZero{ // Function which pushes all zeros // to end of an array. static void pushZerosToEnd(int []arr, int n) { // Count of non-zero elements int count = 0; // Traverse the array. If element encountered is // non-zero, then replace the element // at index â..countâ.. with this element for (int i = 0; i < n; i++) if (arr[i] != 0) // here count is incremented arr[count++] = arr[i]; // Now all non-zero elements have been shifted to // front and â..countâ.. is set as index of first 0. // Make all elements 0 from count to end. while (count < n) arr[count++] = 0; } // Driver function public static void Main () { int []arr = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}; int n = arr.Length; pushZerosToEnd(arr, n); Console.WriteLine(\"Array after pushing all zeros to the back: \"); for (int i = 0; i < n; i++) Console.Write(arr[i] +\" \"); }}/* This code is contributed by Anant Agrawal */",
"e": 32593,
"s": 31439,
"text": null
},
{
"code": "<?php// A PHP program to move all// zeroes at the end of array // Function which pushes all// zeros to end of an array.function pushZerosToEnd(&$arr, $n){ // Count of non-zero elements $count = 0; // Traverse the array. If // element encountered is // non-zero, then replace // the element at index // 'count' with this element for ($i = 0; $i < $n; $i++) if ($arr[$i] != 0) // here count is incremented $arr[$count++] = $arr[$i]; // Now all non-zero elements // have been shifted to front // and 'count' is set as index // of first 0. Make all elements // 0 from count to end. while ($count < $n) $arr[$count++] = 0;} // Driver Code$arr = array(1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9);$n = sizeof($arr);pushZerosToEnd($arr, $n);echo \"Array after pushing all \" . \"zeros to end of array :\\n\"; for ($i = 0; $i < $n; $i++)echo $arr[$i] . \" \"; // This code is contributed// by ChitraNayal?>",
"e": 33573,
"s": 32593,
"text": null
},
{
"code": "<script>// A JavaScript program to move all zeroes at the end of array // Function which pushes all zeros to end of an array.function pushZerosToEnd(arr, n){ let count = 0; // Count of non-zero elements // Traverse the array. If element encountered is non- // zero, then replace the element at index 'count' // with this element for (let i = 0; i < n; i++) if (arr[i] != 0) arr[count++] = arr[i]; // here count is // incremented // Now all non-zero elements have been shifted to // front and 'count' is set as index of first 0. // Make all elements 0 from count to end. while (count < n) arr[count++] = 0;} // Driver code let arr = [1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9]; let n = arr.length; pushZerosToEnd(arr, n); document.write(\"Array after pushing all zeros to end of array :<br>\"); for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); // This code is contributed by Surbhi Tyagi.</script>",
"e": 34578,
"s": 33573,
"text": null
},
{
"code": null,
"e": 34651,
"s": 34578,
"text": "Array after pushing all zeros to end of array :\n1 9 8 4 2 7 6 9 0 0 0 0 "
},
{
"code": null,
"e": 34661,
"s": 34651,
"text": "Output: "
},
{
"code": null,
"e": 34733,
"s": 34661,
"text": "Array after pushing all zeros to end of array :\n1 9 8 4 2 7 6 9 0 0 0 0"
},
{
"code": null,
"e": 34823,
"s": 34733,
"text": "Time Complexity: O(n) where n is number of elements in input array.Auxiliary Space: O(1) "
},
{
"code": null,
"e": 35653,
"s": 34823,
"text": "YouTubeGeeksforGeeks507K subscribersMove all zeroes to end of array | 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 / 6:23•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=0jXTju134Hw\" 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": 35827,
"s": 35653,
"text": "This article is contributed by Chandra Prakash. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 35833,
"s": 35827,
"text": "ukasp"
},
{
"code": null,
"e": 35847,
"s": 35833,
"text": "surbhityagi15"
},
{
"code": null,
"e": 35861,
"s": 35847,
"text": "adityakhosla0"
},
{
"code": null,
"e": 35873,
"s": 35861,
"text": "deadmarshal"
},
{
"code": null,
"e": 35880,
"s": 35873,
"text": "Amazon"
},
{
"code": null,
"e": 35890,
"s": 35880,
"text": "Bloomberg"
},
{
"code": null,
"e": 35899,
"s": 35890,
"text": "Linkedin"
},
{
"code": null,
"e": 35905,
"s": 35899,
"text": "Paytm"
},
{
"code": null,
"e": 35913,
"s": 35905,
"text": "Samsung"
},
{
"code": null,
"e": 35922,
"s": 35913,
"text": "SAP Labs"
},
{
"code": null,
"e": 35929,
"s": 35922,
"text": "Arrays"
},
{
"code": null,
"e": 35935,
"s": 35929,
"text": "Paytm"
},
{
"code": null,
"e": 35942,
"s": 35935,
"text": "Amazon"
},
{
"code": null,
"e": 35950,
"s": 35942,
"text": "Samsung"
},
{
"code": null,
"e": 35959,
"s": 35950,
"text": "SAP Labs"
},
{
"code": null,
"e": 35968,
"s": 35959,
"text": "Linkedin"
},
{
"code": null,
"e": 35978,
"s": 35968,
"text": "Bloomberg"
},
{
"code": null,
"e": 35985,
"s": 35978,
"text": "Arrays"
},
{
"code": null,
"e": 36083,
"s": 35985,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36106,
"s": 36083,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 36127,
"s": 36106,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 36172,
"s": 36127,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 36220,
"s": 36172,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 36274,
"s": 36220,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 36327,
"s": 36274,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 36351,
"s": 36327,
"text": "Find the Missing Number"
},
{
"code": null,
"e": 36378,
"s": 36351,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 36434,
"s": 36378,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
}
] |
Highway Billboard Problem - GeeksforGeeks
|
05 Aug, 2021
Consider a highway of M miles. The task is to place billboards on the highway such that revenue is maximized. The possible sites for billboards are given by number x1 < x2 < ..... < xn-1 < xn, specifying positions in miles measured from one end of the road. If we place a billboard at position xi, we receive a revenue of ri > 0. There is a restriction that no two billboards can be placed within t miles or less than it. Note : All possible sites from x1 to xn are in range from 0 to M as need to place billboards on a highway of M miles.Examples:
Input : M = 20
x[] = {6, 7, 12, 13, 14}
revenue[] = {5, 6, 5, 3, 1}
t = 5
Output: 10
By placing two billboards at 6 miles and 12
miles will produce the maximum revenue of 10.
Input : M = 15
x[] = {6, 9, 12, 14}
revenue[] = {5, 6, 3, 7}
t = 2
Output : 18
Let maxRev[i], 1 <= i <= M, be the maximum revenue generated from beginning to i miles on the highway. Now for each mile on the highway, we need to check whether this mile has the option for any billboard, if not then the maximum revenue generated till that mile would be same as maximum revenue generated till one mile before. But if that mile has the option for billboard then we have 2 options: 1. Either we will place the billboard, ignore the billboard in previous t miles, and add the revenue of the billboard placed. 2. Ignore this billboard. So maxRev[i] = max(maxRev[i-t-1] + revenue[i], maxRev[i-1])Below is implementation of this approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find maximum revenue by placing// billboard on the highway with given constraints.#include<bits/stdc++.h>using namespace std; int maxRevenue(int m, int x[], int revenue[], int n, int t){ // Array to store maximum revenue at each miles. int maxRev[m+1]; memset(maxRev, 0, sizeof(maxRev)); // actual minimum distance between 2 billboards. int nxtbb = 0; for (int i = 1; i <= m; i++) { // check if all billboards are already placed. if (nxtbb < n) { // check if we have billboard for that particular // mile. If not, copy the previous maximum revenue. if (x[nxtbb] != i) maxRev[i] = maxRev[i-1]; // we do have billboard for this mile. else { // We have 2 options, we either take current // or we ignore current billboard. // If current position is less than or equal to // t, then we can have only one billboard. if (i <= t) maxRev[i] = max(maxRev[i-1], revenue[nxtbb]); // Else we may have to remove previously placed // billboard else maxRev[i] = max(maxRev[i-t-1]+revenue[nxtbb], maxRev[i-1]); nxtbb++; } } else maxRev[i] = maxRev[i - 1]; } return maxRev[m];} // Driven Programint main(){ int m = 20; int x[] = {6, 7, 12, 13, 14}; int revenue[] = {5, 6, 5, 3, 1}; int n = sizeof(x)/sizeof(x[0]); int t = 5; cout << maxRevenue(m, x, revenue, n, t) << endl; return 0;}
// Java program to find maximum revenue// by placing billboard on the highway// with given constraints. class GFG{ static int maxRevenue(int m, int[] x, int[] revenue, int n, int t){ // Array to store maximum revenue // at each miles. int[] maxRev = new int[m + 1]; for(int i = 0; i < m + 1; i++) maxRev[i] = 0; // actual minimum distance between // 2 billboards. int nxtbb = 0; for (int i = 1; i <= m; i++) { // check if all billboards are // already placed. if (nxtbb < n) { // check if we have billboard for // that particular mile. If not, // copy the previous maximum revenue. if (x[nxtbb] != i) maxRev[i] = maxRev[i - 1]; // we do have billboard for this mile. else { // We have 2 options, we either take // current or we ignore current billboard. // If current position is less than or // equal to t, then we can have only // one billboard. if (i <= t) maxRev[i] = Math.max(maxRev[i - 1], revenue[nxtbb]); // Else we may have to remove // previously placed billboard else maxRev[i] = Math.max(maxRev[i - t - 1] + revenue[nxtbb], maxRev[i - 1]); nxtbb++; } } else maxRev[i] = maxRev[i - 1]; } return maxRev[m];} // Driver Codepublic static void main(String []args){ int m = 20; int[] x = new int[]{6, 7, 12, 13, 14}; int[] revenue = new int[]{5, 6, 5, 3, 1}; int n = x.length; int t = 5; System.out.println(maxRevenue(m, x, revenue, n, t));}} // This code is contributed by Ita_c.
# Python3 program to find maximum revenue# by placing billboard on the highway with# given constraints. def maxRevenue(m, x, revenue, n, t) : # Array to store maximum revenue # at each miles. maxRev = [0] * (m + 1) # actual minimum distance between # 2 billboards. nxtbb = 0; for i in range(1, m + 1) : # check if all billboards are # already placed. if (nxtbb < n) : # check if we have billboard for # that particular mile. If not, # copy the previous maximum revenue. if (x[nxtbb] != i) : maxRev[i] = maxRev[i - 1] # we do have billboard for this mile. else : # We have 2 options, we either take # current or we ignore current billboard. # If current position is less than or # equal to t, then we can have only # one billboard. if (i <= t) : maxRev[i] = max(maxRev[i - 1], revenue[nxtbb]) # Else we may have to remove # previously placed billboard else : maxRev[i] = max(maxRev[i - t - 1] + revenue[nxtbb], maxRev[i - 1]); nxtbb += 1 else : maxRev[i] = maxRev[i - 1] return maxRev[m] # Driver Codeif __name__ == "__main__" : m = 20 x = [6, 7, 12, 13, 14] revenue = [5, 6, 5, 3, 1] n = len(x) t = 5 print(maxRevenue(m, x, revenue, n, t)) # This code is contributed by Ryuga
// C# program to find maximum revenue// by placing billboard on the highway// with given constraints.using System; class GFG{static int maxRevenue(int m, int[] x, int[] revenue, int n, int t){ // Array to store maximum revenue // at each miles. int[] maxRev = new int[m + 1]; for(int i = 0; i < m + 1; i++) maxRev[i] = 0; // actual minimum distance between // 2 billboards. int nxtbb = 0; for (int i = 1; i <= m; i++) { // check if all billboards are // already placed. if (nxtbb < n) { // check if we have billboard for // that particular mile. If not, // copy the previous maximum revenue. if (x[nxtbb] != i) maxRev[i] = maxRev[i - 1]; // we do have billboard for this mile. else { // We have 2 options, we either take // current or we ignore current billboard. // If current position is less than or // equal to t, then we can have only // one billboard. if (i <= t) maxRev[i] = Math.Max(maxRev[i - 1], revenue[nxtbb]); // Else we may have to remove // previously placed billboard else maxRev[i] = Math.Max(maxRev[i - t - 1] + revenue[nxtbb], maxRev[i - 1]); nxtbb++; } } else maxRev[i] = maxRev[i - 1]; } return maxRev[m];} // Driver Codestatic void Main(){ int m = 20; int[] x = new int[]{6, 7, 12, 13, 14}; int[] revenue = new int[]{5, 6, 5, 3, 1}; int n = x.Length; int t = 5; Console.Write(maxRevenue(m, x, revenue, n, t));}} // This code is contributed by DrRoot_
<?php// PHP program to find// maximum revenue by// placing billboard on// the highway with given// constraints. function maxRevenue($m, $x, $revenue, $n, $t) { // Array to store maximum // revenue at each miles. $maxRev = array_fill(0, $m + 1, false); // actual minimum distance // between 2 billboards. $nxtbb = 0; for ($i = 1; $i <= $m; $i++) { // check if all billboards // are already placed. if ($nxtbb < $n) { // check if we have billboard // for that particular // mile. If not, copy the // previous maximum revenue. if ($x[$nxtbb] != $i) $maxRev[$i] = $maxRev[$i - 1]; // we do have billboard // for this mile. else { // We have 2 options, // we either take // current or we ignore // current billboard. // If current position is // less than or equal to // t, then we can have only // one billboard. if ($i <= $t) $maxRev[$i] = max($maxRev[$i - 1], $revenue[$nxtbb]); // Else we may have to // remove previously // placed billboard else $maxRev[$i] = max($maxRev[$i - $t - 1] + $revenue[$nxtbb], $maxRev[$i - 1]); $nxtbb++; } } else $maxRev[$i] = $maxRev[$i - 1]; } return $maxRev[$m];} // Driver Code$m = 20;$x = array(6, 7, 12, 13, 14);$revenue = array(5, 6, 5, 3, 1);$n = sizeof($x);$t = 5;echo maxRevenue($m, $x, $revenue, $n, $t); // This code is contributed by ajit?>
<script> // Javascript program to find maximum revenue// by placing billboard on the highway// with given constraints. function maxRevenue(m,x,revenue,n,t) { // Array to store maximum revenue // at each miles. let maxRev = new Array(m + 1); for(let i = 0; i < m + 1; i++) maxRev[i] = 0; // actual minimum distance between // 2 billboards. let nxtbb = 0; for (let i = 1; i <= m; i++) { // check if all billboards are // already placed. if (nxtbb < n) { // check if we have billboard for // that particular mile. If not, // copy the previous maximum revenue. if (x[nxtbb] != i) maxRev[i] = maxRev[i - 1]; // we do have billboard for this mile. else { // We have 2 options, we either take // current or we ignore current billboard. // If current position is less than or // equal to t, then we can have only // one billboard. if (i <= t) maxRev[i] = Math.max(maxRev[i - 1], revenue[nxtbb]); // Else we may have to remove // previously placed billboard else maxRev[i] = Math.max(maxRev[i - t - 1] + revenue[nxtbb], maxRev[i - 1]); nxtbb++; } } else maxRev[i] = maxRev[i - 1]; } return maxRev[m]; } // Driver Code let m = 20; let x=[6, 7, 12, 13, 14]; let revenue=[5, 6, 5, 3, 1]; let n = x.length; let t = 5; document.write(maxRevenue(m, x, revenue, n, t)); // This code is contributed by rag2127 </script>
Output:
10
Time Complexity: O(M), where M is distance of total Highway. Auxiliary Space: O(M).Source : https://courses.cs.washington.edu/courses/cse421/06au/slides/Lecture18/Lecture18.pdfThis article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
jit_t
ankthon
DrRoot_
ukasp
rag2127
sagar0719kumar
Dynamic Programming
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum size square sub-matrix with all 1s
Optimal Substructure Property in Dynamic Programming | DP-2
Optimal Binary Search Tree | DP-24
Min Cost Path | DP-6
Maximum Subarray Sum using Divide and Conquer algorithm
Greedy approach vs Dynamic programming
Maximum sum such that no two elements are adjacent
Word Break Problem | DP-32
3 Different ways to print Fibonacci series in Java
Top 50 Dynamic Programming Coding Problems for Interviews
|
[
{
"code": null,
"e": 25943,
"s": 25915,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 26494,
"s": 25943,
"text": "Consider a highway of M miles. The task is to place billboards on the highway such that revenue is maximized. The possible sites for billboards are given by number x1 < x2 < ..... < xn-1 < xn, specifying positions in miles measured from one end of the road. If we place a billboard at position xi, we receive a revenue of ri > 0. There is a restriction that no two billboards can be placed within t miles or less than it. Note : All possible sites from x1 to xn are in range from 0 to M as need to place billboards on a highway of M miles.Examples: "
},
{
"code": null,
"e": 26807,
"s": 26494,
"text": "Input : M = 20\n x[] = {6, 7, 12, 13, 14}\n revenue[] = {5, 6, 5, 3, 1}\n t = 5\nOutput: 10\nBy placing two billboards at 6 miles and 12\nmiles will produce the maximum revenue of 10.\n\nInput : M = 15\n x[] = {6, 9, 12, 14}\n revenue[] = {5, 6, 3, 7}\n t = 2\nOutput : 18 "
},
{
"code": null,
"e": 27461,
"s": 26809,
"text": "Let maxRev[i], 1 <= i <= M, be the maximum revenue generated from beginning to i miles on the highway. Now for each mile on the highway, we need to check whether this mile has the option for any billboard, if not then the maximum revenue generated till that mile would be same as maximum revenue generated till one mile before. But if that mile has the option for billboard then we have 2 options: 1. Either we will place the billboard, ignore the billboard in previous t miles, and add the revenue of the billboard placed. 2. Ignore this billboard. So maxRev[i] = max(maxRev[i-t-1] + revenue[i], maxRev[i-1])Below is implementation of this approach: "
},
{
"code": null,
"e": 27465,
"s": 27461,
"text": "C++"
},
{
"code": null,
"e": 27470,
"s": 27465,
"text": "Java"
},
{
"code": null,
"e": 27478,
"s": 27470,
"text": "Python3"
},
{
"code": null,
"e": 27481,
"s": 27478,
"text": "C#"
},
{
"code": null,
"e": 27485,
"s": 27481,
"text": "PHP"
},
{
"code": null,
"e": 27496,
"s": 27485,
"text": "Javascript"
},
{
"code": "// C++ program to find maximum revenue by placing// billboard on the highway with given constraints.#include<bits/stdc++.h>using namespace std; int maxRevenue(int m, int x[], int revenue[], int n, int t){ // Array to store maximum revenue at each miles. int maxRev[m+1]; memset(maxRev, 0, sizeof(maxRev)); // actual minimum distance between 2 billboards. int nxtbb = 0; for (int i = 1; i <= m; i++) { // check if all billboards are already placed. if (nxtbb < n) { // check if we have billboard for that particular // mile. If not, copy the previous maximum revenue. if (x[nxtbb] != i) maxRev[i] = maxRev[i-1]; // we do have billboard for this mile. else { // We have 2 options, we either take current // or we ignore current billboard. // If current position is less than or equal to // t, then we can have only one billboard. if (i <= t) maxRev[i] = max(maxRev[i-1], revenue[nxtbb]); // Else we may have to remove previously placed // billboard else maxRev[i] = max(maxRev[i-t-1]+revenue[nxtbb], maxRev[i-1]); nxtbb++; } } else maxRev[i] = maxRev[i - 1]; } return maxRev[m];} // Driven Programint main(){ int m = 20; int x[] = {6, 7, 12, 13, 14}; int revenue[] = {5, 6, 5, 3, 1}; int n = sizeof(x)/sizeof(x[0]); int t = 5; cout << maxRevenue(m, x, revenue, n, t) << endl; return 0;}",
"e": 29240,
"s": 27496,
"text": null
},
{
"code": "// Java program to find maximum revenue// by placing billboard on the highway// with given constraints. class GFG{ static int maxRevenue(int m, int[] x, int[] revenue, int n, int t){ // Array to store maximum revenue // at each miles. int[] maxRev = new int[m + 1]; for(int i = 0; i < m + 1; i++) maxRev[i] = 0; // actual minimum distance between // 2 billboards. int nxtbb = 0; for (int i = 1; i <= m; i++) { // check if all billboards are // already placed. if (nxtbb < n) { // check if we have billboard for // that particular mile. If not, // copy the previous maximum revenue. if (x[nxtbb] != i) maxRev[i] = maxRev[i - 1]; // we do have billboard for this mile. else { // We have 2 options, we either take // current or we ignore current billboard. // If current position is less than or // equal to t, then we can have only // one billboard. if (i <= t) maxRev[i] = Math.max(maxRev[i - 1], revenue[nxtbb]); // Else we may have to remove // previously placed billboard else maxRev[i] = Math.max(maxRev[i - t - 1] + revenue[nxtbb], maxRev[i - 1]); nxtbb++; } } else maxRev[i] = maxRev[i - 1]; } return maxRev[m];} // Driver Codepublic static void main(String []args){ int m = 20; int[] x = new int[]{6, 7, 12, 13, 14}; int[] revenue = new int[]{5, 6, 5, 3, 1}; int n = x.length; int t = 5; System.out.println(maxRevenue(m, x, revenue, n, t));}} // This code is contributed by Ita_c.",
"e": 31199,
"s": 29240,
"text": null
},
{
"code": "# Python3 program to find maximum revenue# by placing billboard on the highway with# given constraints. def maxRevenue(m, x, revenue, n, t) : # Array to store maximum revenue # at each miles. maxRev = [0] * (m + 1) # actual minimum distance between # 2 billboards. nxtbb = 0; for i in range(1, m + 1) : # check if all billboards are # already placed. if (nxtbb < n) : # check if we have billboard for # that particular mile. If not, # copy the previous maximum revenue. if (x[nxtbb] != i) : maxRev[i] = maxRev[i - 1] # we do have billboard for this mile. else : # We have 2 options, we either take # current or we ignore current billboard. # If current position is less than or # equal to t, then we can have only # one billboard. if (i <= t) : maxRev[i] = max(maxRev[i - 1], revenue[nxtbb]) # Else we may have to remove # previously placed billboard else : maxRev[i] = max(maxRev[i - t - 1] + revenue[nxtbb], maxRev[i - 1]); nxtbb += 1 else : maxRev[i] = maxRev[i - 1] return maxRev[m] # Driver Codeif __name__ == \"__main__\" : m = 20 x = [6, 7, 12, 13, 14] revenue = [5, 6, 5, 3, 1] n = len(x) t = 5 print(maxRevenue(m, x, revenue, n, t)) # This code is contributed by Ryuga",
"e": 32907,
"s": 31199,
"text": null
},
{
"code": "// C# program to find maximum revenue// by placing billboard on the highway// with given constraints.using System; class GFG{static int maxRevenue(int m, int[] x, int[] revenue, int n, int t){ // Array to store maximum revenue // at each miles. int[] maxRev = new int[m + 1]; for(int i = 0; i < m + 1; i++) maxRev[i] = 0; // actual minimum distance between // 2 billboards. int nxtbb = 0; for (int i = 1; i <= m; i++) { // check if all billboards are // already placed. if (nxtbb < n) { // check if we have billboard for // that particular mile. If not, // copy the previous maximum revenue. if (x[nxtbb] != i) maxRev[i] = maxRev[i - 1]; // we do have billboard for this mile. else { // We have 2 options, we either take // current or we ignore current billboard. // If current position is less than or // equal to t, then we can have only // one billboard. if (i <= t) maxRev[i] = Math.Max(maxRev[i - 1], revenue[nxtbb]); // Else we may have to remove // previously placed billboard else maxRev[i] = Math.Max(maxRev[i - t - 1] + revenue[nxtbb], maxRev[i - 1]); nxtbb++; } } else maxRev[i] = maxRev[i - 1]; } return maxRev[m];} // Driver Codestatic void Main(){ int m = 20; int[] x = new int[]{6, 7, 12, 13, 14}; int[] revenue = new int[]{5, 6, 5, 3, 1}; int n = x.Length; int t = 5; Console.Write(maxRevenue(m, x, revenue, n, t));}} // This code is contributed by DrRoot_",
"e": 34850,
"s": 32907,
"text": null
},
{
"code": "<?php// PHP program to find// maximum revenue by// placing billboard on// the highway with given// constraints. function maxRevenue($m, $x, $revenue, $n, $t) { // Array to store maximum // revenue at each miles. $maxRev = array_fill(0, $m + 1, false); // actual minimum distance // between 2 billboards. $nxtbb = 0; for ($i = 1; $i <= $m; $i++) { // check if all billboards // are already placed. if ($nxtbb < $n) { // check if we have billboard // for that particular // mile. If not, copy the // previous maximum revenue. if ($x[$nxtbb] != $i) $maxRev[$i] = $maxRev[$i - 1]; // we do have billboard // for this mile. else { // We have 2 options, // we either take // current or we ignore // current billboard. // If current position is // less than or equal to // t, then we can have only // one billboard. if ($i <= $t) $maxRev[$i] = max($maxRev[$i - 1], $revenue[$nxtbb]); // Else we may have to // remove previously // placed billboard else $maxRev[$i] = max($maxRev[$i - $t - 1] + $revenue[$nxtbb], $maxRev[$i - 1]); $nxtbb++; } } else $maxRev[$i] = $maxRev[$i - 1]; } return $maxRev[$m];} // Driver Code$m = 20;$x = array(6, 7, 12, 13, 14);$revenue = array(5, 6, 5, 3, 1);$n = sizeof($x);$t = 5;echo maxRevenue($m, $x, $revenue, $n, $t); // This code is contributed by ajit?>",
"e": 36833,
"s": 34850,
"text": null
},
{
"code": "<script> // Javascript program to find maximum revenue// by placing billboard on the highway// with given constraints. function maxRevenue(m,x,revenue,n,t) { // Array to store maximum revenue // at each miles. let maxRev = new Array(m + 1); for(let i = 0; i < m + 1; i++) maxRev[i] = 0; // actual minimum distance between // 2 billboards. let nxtbb = 0; for (let i = 1; i <= m; i++) { // check if all billboards are // already placed. if (nxtbb < n) { // check if we have billboard for // that particular mile. If not, // copy the previous maximum revenue. if (x[nxtbb] != i) maxRev[i] = maxRev[i - 1]; // we do have billboard for this mile. else { // We have 2 options, we either take // current or we ignore current billboard. // If current position is less than or // equal to t, then we can have only // one billboard. if (i <= t) maxRev[i] = Math.max(maxRev[i - 1], revenue[nxtbb]); // Else we may have to remove // previously placed billboard else maxRev[i] = Math.max(maxRev[i - t - 1] + revenue[nxtbb], maxRev[i - 1]); nxtbb++; } } else maxRev[i] = maxRev[i - 1]; } return maxRev[m]; } // Driver Code let m = 20; let x=[6, 7, 12, 13, 14]; let revenue=[5, 6, 5, 3, 1]; let n = x.length; let t = 5; document.write(maxRevenue(m, x, revenue, n, t)); // This code is contributed by rag2127 </script>",
"e": 38704,
"s": 36833,
"text": null
},
{
"code": null,
"e": 38713,
"s": 38704,
"text": "Output: "
},
{
"code": null,
"e": 38716,
"s": 38713,
"text": "10"
},
{
"code": null,
"e": 39313,
"s": 38716,
"text": "Time Complexity: O(M), where M is distance of total Highway. Auxiliary Space: O(M).Source : https://courses.cs.washington.edu/courses/cse421/06au/slides/Lecture18/Lecture18.pdfThis article is contributed by Anuj Chauhan. 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": 39319,
"s": 39313,
"text": "jit_t"
},
{
"code": null,
"e": 39327,
"s": 39319,
"text": "ankthon"
},
{
"code": null,
"e": 39335,
"s": 39327,
"text": "DrRoot_"
},
{
"code": null,
"e": 39341,
"s": 39335,
"text": "ukasp"
},
{
"code": null,
"e": 39349,
"s": 39341,
"text": "rag2127"
},
{
"code": null,
"e": 39364,
"s": 39349,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 39384,
"s": 39364,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 39404,
"s": 39384,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 39502,
"s": 39404,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39545,
"s": 39502,
"text": "Maximum size square sub-matrix with all 1s"
},
{
"code": null,
"e": 39605,
"s": 39545,
"text": "Optimal Substructure Property in Dynamic Programming | DP-2"
},
{
"code": null,
"e": 39640,
"s": 39605,
"text": "Optimal Binary Search Tree | DP-24"
},
{
"code": null,
"e": 39661,
"s": 39640,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 39717,
"s": 39661,
"text": "Maximum Subarray Sum using Divide and Conquer algorithm"
},
{
"code": null,
"e": 39756,
"s": 39717,
"text": "Greedy approach vs Dynamic programming"
},
{
"code": null,
"e": 39807,
"s": 39756,
"text": "Maximum sum such that no two elements are adjacent"
},
{
"code": null,
"e": 39834,
"s": 39807,
"text": "Word Break Problem | DP-32"
},
{
"code": null,
"e": 39885,
"s": 39834,
"text": "3 Different ways to print Fibonacci series in Java"
}
] |
Count number of ways to reach destination in a Maze - GeeksforGeeks
|
26 Oct, 2021
Given a maze with obstacles, count the number of paths to reach the rightmost-bottommost cell from the topmost-leftmost cell. A cell in the given maze has a value of -1 if it is a blockage or dead-end, else 0.From a given cell, we are allowed to move to cells (i+1, j) and (i, j+1) only.
Examples:
Input: maze[R][C] = {{0, 0, 0, 0},
{0, -1, 0, 0},
{-1, 0, 0, 0},
{0, 0, 0, 0}};
Output: 4
There are four possible paths as shown in
below diagram.
This problem is an extension of the below problem.
Backtracking | Set 2 (Rat in a Maze)In this post, a different solution is discussed that can be used to solve the above Rat in a Maze problem also.The idea is to modify the given grid[][] so that grid[i][j] contains count of paths to reach (i, j) from (0, 0) if (i, j) is not a blockage, else grid[i][j] remains -1.
We can recursively compute grid[i][j] using below
formula and finally return grid[R-1][C-1]
// If current cell is a blockage
if (maze[i][j] == -1)
maze[i][j] = -1; // Do not change
// If we can reach maze[i][j] from maze[i-1][j]
// then increment count.
else if (maze[i-1][j] > 0)
maze[i][j] = (maze[i][j] + maze[i-1][j]);
// If we can reach maze[i][j] from maze[i][j-1]
// then increment count.
else if (maze[i][j-1] > 0)
maze[i][j] = (maze[i][j] + maze[i][j-1]);
Below is the implementation of the above idea.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count number of paths in a maze// with obstacles.#include<bits/stdc++.h>using namespace std;#define R 4#define C 4 // Returns count of possible paths in a maze[R][C]// from (0,0) to (R-1,C-1)int countPaths(int maze[][C]){ // If the initial cell is blocked, there is no // way of moving anywhere if (maze[0][0]==-1) return 0; // Initializing the leftmost column for (int i=0; i<R; i++) { if (maze[i][0] == 0) maze[i][0] = 1; // If we encounter a blocked cell in leftmost // row, there is no way of visiting any cell // directly below it. else break; } // Similarly initialize the topmost row for (int i=1; i<C; i++) { if (maze[0][i] == 0) maze[0][i] = 1; // If we encounter a blocked cell in bottommost // row, there is no way of visiting any cell // directly below it. else break; } // The only difference is that if a cell is -1, // simply ignore it else recursively compute // count value maze[i][j] for (int i=1; i<R; i++) { for (int j=1; j<C; j++) { // If blockage is found, ignore this cell if (maze[i][j] == -1) continue; // If we can reach maze[i][j] from maze[i-1][j] // then increment count. if (maze[i-1][j] > 0) maze[i][j] = (maze[i][j] + maze[i-1][j]); // If we can reach maze[i][j] from maze[i][j-1] // then increment count. if (maze[i][j-1] > 0) maze[i][j] = (maze[i][j] + maze[i][j-1]); } } // If the final cell is blocked, output 0, otherwise // the answer return (maze[R-1][C-1] > 0)? maze[R-1][C-1] : 0;} // Driver codeint main(){ int maze[R][C] = {{0, 0, 0, 0}, {0, -1, 0, 0}, {-1, 0, 0, 0}, {0, 0, 0, 0}}; cout << countPaths(maze); return 0;}
// Java program to count number of paths in a maze// with obstacles.import java.io.*; class GFG{ static int R = 4; static int C = 4; // Returns count of possible paths in // a maze[R][C] from (0,0) to (R-1,C-1) static int countPaths(int maze[][]) { // If the initial cell is blocked, // there is no way of moving anywhere if (maze[0][0]==-1) return 0; // Initializing the leftmost column for (int i = 0; i < R; i++) { if (maze[i][0] == 0) maze[i][0] = 1; // If we encounter a blocked cell // in leftmost row, there is no way // of visiting any cell directly below it. else break; } // Similarly initialize the topmost row for (int i =1 ; i< C ; i++) { if (maze[0][i] == 0) maze[0][i] = 1; // If we encounter a blocked cell in // bottommost row, there is no way of // visiting any cell directly below it. else break; } // The only difference is that if a cell // is -1, simply ignore it else recursively // compute count value maze[i][j] for (int i = 1; i < R; i++) { for (int j = 1; j <C ; j++) { // If blockage is found, // ignore this cell if (maze[i][j] == -1) continue; // If we can reach maze[i][j] from // maze[i-1][j] then increment count. if (maze[i - 1][j] > 0) maze[i][j] = (maze[i][j] + maze[i - 1][j]); // If we can reach maze[i][j] from // maze[i][j-1] then increment count. if (maze[i][j - 1] > 0) maze[i][j] = (maze[i][j] + maze[i][j - 1]); } } // If the final cell is blocked, // output 0, otherwise the answer return (maze[R - 1][C - 1] > 0) ? maze[R - 1][C - 1] : 0; } // Driver code public static void main (String[] args) { int maze[][] = {{0, 0, 0, 0}, {0, -1, 0, 0}, {-1, 0, 0, 0}, {0, 0, 0, 0}}; System.out.println (countPaths(maze)); } } // This code is contributed by vt_m
# Python 3 program to count number of paths# in a maze with obstacles. R = 4C = 4 # Returns count of possible paths in a# maze[R][C] from (0,0) to (R-1,C-1)def countPaths(maze): # If the initial cell is blocked, # there is no way of moving anywhere if (maze[0][0] == -1): return 0 # Initializing the leftmost column for i in range(R): if (maze[i][0] == 0): maze[i][0] = 1 # If we encounter a blocked cell in # leftmost row, there is no way of # visiting any cell directly below it. else: break # Similarly initialize the topmost row for i in range(1, C, 1): if (maze[0][i] == 0): maze[0][i] = 1 # If we encounter a blocked cell in # bottommost row, there is no way of # visiting any cell directly below it. else: break # The only difference is that if a cell is -1, # simply ignore it else recursively compute # count value maze[i][j] for i in range(1, R, 1): for j in range(1, C, 1): # If blockage is found, ignore this cell if (maze[i][j] == -1): continue # If we can reach maze[i][j] from # maze[i-1][j] then increment count. if (maze[i - 1][j] > 0): maze[i][j] = (maze[i][j] + maze[i - 1][j]) # If we can reach maze[i][j] from # maze[i][j-1] then increment count. if (maze[i][j - 1] > 0): maze[i][j] = (maze[i][j] + maze[i][j - 1]) # If the final cell is blocked, # output 0, otherwise the answer if (maze[R - 1][C - 1] > 0): return maze[R - 1][C - 1] else: return 0 # Driver codeif __name__ == '__main__': maze = [[0, 0, 0, 0], [0, -1, 0, 0], [-1, 0, 0, 0], [0, 0, 0, 0 ]] print(countPaths(maze)) # This code is contributed by# Surendra_Gangwar
// C# program to count number of paths in a maze// with obstacles.using System; class GFG { static int R = 4; static int C = 4; // Returns count of possible paths in // a maze[R][C] from (0,0) to (R-1,C-1) static int countPaths(int [,]maze) { // If the initial cell is blocked, // there is no way of moving anywhere if (maze[0,0]==-1) return 0; // Initializing the leftmost column for (int i = 0; i < R; i++) { if (maze[i,0] == 0) maze[i,0] = 1; // If we encounter a blocked cell // in leftmost row, there is no way // of visiting any cell directly below it. else break; } // Similarly initialize the topmost row for (int i =1 ; i< C ; i++) { if (maze[0,i] == 0) maze[0,i] = 1; // If we encounter a blocked cell in // bottommost row, there is no way of // visiting any cell directly below it. else break; } // The only difference is that if a cell // is -1, simply ignore it else recursively // compute count value maze[i][j] for (int i = 1; i < R; i++) { for (int j = 1; j <C ; j++) { // If blockage is found, // ignore this cell if (maze[i,j] == -1) continue; // If we can reach maze[i][j] from // maze[i-1][j] then increment count. if (maze[i - 1,j] > 0) maze[i,j] = (maze[i,j] + maze[i - 1,j]); // If we can reach maze[i][j] from // maze[i][j-1] then increment count. if (maze[i,j - 1] > 0) maze[i,j] = (maze[i,j] + maze[i,j - 1]); } } // If the final cell is blocked, // output 0, otherwise the answer return (maze[R - 1,C - 1] > 0) ? maze[R - 1,C - 1] : 0; } // Driver code public static void Main () { int [,]maze = { {0, 0, 0, 0}, {0, -1, 0, 0}, {-1, 0, 0, 0}, {0, 0, 0, 0}}; Console.Write (countPaths(maze)); } } // This code is contributed by nitin mittal.
<?php// PHP program to count number// of paths in a maze with obstacles. $R = 4;$C = 4; // Returns count of possible// paths in a maze[R][C]// from (0,0) to (R-1,C-1)function countPaths( $maze){ global $R, $C; // If the initial cell is // blocked, there is no // way of moving anywhere if ($maze[0][0] == - 1) return 0; // Initializing the // leftmost column for ( $i = 0; $i < $R; $i++) { if ($maze[$i][0] == 0) $maze[$i][0] = 1; // If we encounter a blocked // cell in leftmost row, // there is no way of // visiting any cell // directly below it. else break; } // Similarly initialize // the topmost row for($i = 1; $i < $C; $i++) { if ($maze[0][$i] == 0) $maze[0][$i] = 1; // If we encounter a blocked // cell in bottommost row, // there is no way of // visiting any cell // directly below it. else break; } // The only difference is // that if a cell is -1, // simply ignore it else // recursively compute // count value maze[i][j] for($i = 1; $i < $R; $i++) { for($j = 1; $j < $C; $j++) { // If blockage is found, // ignore this cell if ($maze[$i][$j] == -1) continue; // If we can reach maze[i][j] // from maze[i-1][j] // then increment count. if ($maze[$i - 1][$j] > 0) $maze[$i][$j] = ($maze[$i][$j] + $maze[$i - 1][$j]); // If we can reach maze[i][j] // from maze[i][j-1] // then increment count. if ($maze[$i][$j - 1] > 0) $maze[$i][$j] = ($maze[$i][$j] + $maze[$i][$j - 1]); } } // If the final cell is // blocked, output 0, // otherwise the answer return ($maze[$R - 1][$C - 1] > 0) ? $maze[$R - 1][$C - 1] : 0;} // Driver Code $maze = array(array(0, 0, 0, 0), array(0, -1, 0, 0), array(-1, 0, 0, 0), array(0, 0, 0, 0)); echo countPaths($maze); // This code is contributed by anuj_67.?>
<script> // JavaScript program to count number// of paths in a maze with obstacles.let R = 4;let C = 4; // Returns count of possible paths in// a maze[R][C] from (0,0) to (R-1,C-1)function countPaths(maze){ // If the initial cell is blocked, // there is no way of moving anywhere if (maze[0][0] == -1) return 0; // Initializing the leftmost column for(let i = 0; i < R; i++) { if (maze[i][0] == 0) maze[i][0] = 1; // If we encounter a blocked cell // in leftmost row, there is no way // of visiting any cell directly below it. else break; } // Similarly initialize the topmost row for(let i = 1; i < C; i++) { if (maze[0][i] == 0) maze[0][i] = 1; // If we encounter a blocked cell in // bottommost row, there is no way of // visiting any cell directly below it. else break; } // The only difference is that if a cell // is -1, simply ignore it else recursively // compute count value maze[i][j] for(let i = 1; i < R; i++) { for(let j = 1; j < C; j++) { // If blockage is found, // ignore this cell if (maze[i][j] == -1) continue; // If we can reach maze[i][j] from // maze[i-1][j] then increment count. if (maze[i - 1][j] > 0) maze[i][j] = (maze[i][j] + maze[i - 1][j]); // If we can reach maze[i][j] from // maze[i][j-1] then increment count. if (maze[i][j - 1] > 0) maze[i][j] = (maze[i][j] + maze[i][j - 1]); } } // If the final cell is blocked, // output 0, otherwise the answer return (maze[R - 1][C - 1] > 0) ? maze[R - 1][C - 1] : 0;} // Driver Codelet maze = [ [ 0, 0, 0, 0 ], [ 0, -1, 0, 0 ], [ -1, 0, 0, 0 ], [ 0, 0, 0, 0 ] ]; document.write(countPaths(maze)); // This code is contributed by code_hunt </script>
Output:
4
Time Complexity: O(R x C)
This article is contributed by Roshni Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
vt_m
SURENDRA_GANGWAR
code_hunt
punamsingh628700
Amazon
Dynamic Programming
Matrix
Amazon
Dynamic Programming
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Floyd Warshall Algorithm | DP-16
Matrix Chain Multiplication | DP-8
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Edit Distance | DP-5
Overlapping Subproblems Property in Dynamic Programming | DP-1
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Print a given matrix in spiral form
Sudoku | Backtracking-7
Find the number of islands | Set 1 (Using DFS)
|
[
{
"code": null,
"e": 26245,
"s": 26217,
"text": "\n26 Oct, 2021"
},
{
"code": null,
"e": 26533,
"s": 26245,
"text": "Given a maze with obstacles, count the number of paths to reach the rightmost-bottommost cell from the topmost-leftmost cell. A cell in the given maze has a value of -1 if it is a blockage or dead-end, else 0.From a given cell, we are allowed to move to cells (i+1, j) and (i, j+1) only."
},
{
"code": null,
"e": 26544,
"s": 26533,
"text": "Examples: "
},
{
"code": null,
"e": 26760,
"s": 26544,
"text": "Input: maze[R][C] = {{0, 0, 0, 0},\n {0, -1, 0, 0},\n {-1, 0, 0, 0},\n {0, 0, 0, 0}};\nOutput: 4\nThere are four possible paths as shown in\nbelow diagram."
},
{
"code": null,
"e": 26811,
"s": 26760,
"text": "This problem is an extension of the below problem."
},
{
"code": null,
"e": 27128,
"s": 26811,
"text": "Backtracking | Set 2 (Rat in a Maze)In this post, a different solution is discussed that can be used to solve the above Rat in a Maze problem also.The idea is to modify the given grid[][] so that grid[i][j] contains count of paths to reach (i, j) from (0, 0) if (i, j) is not a blockage, else grid[i][j] remains -1. "
},
{
"code": null,
"e": 27632,
"s": 27128,
"text": "We can recursively compute grid[i][j] using below \nformula and finally return grid[R-1][C-1]\n\n // If current cell is a blockage\n if (maze[i][j] == -1)\n maze[i][j] = -1; // Do not change\n\n // If we can reach maze[i][j] from maze[i-1][j]\n // then increment count.\n else if (maze[i-1][j] > 0)\n maze[i][j] = (maze[i][j] + maze[i-1][j]);\n\n // If we can reach maze[i][j] from maze[i][j-1]\n // then increment count.\n else if (maze[i][j-1] > 0)\n maze[i][j] = (maze[i][j] + maze[i][j-1]);"
},
{
"code": null,
"e": 27680,
"s": 27632,
"text": "Below is the implementation of the above idea. "
},
{
"code": null,
"e": 27684,
"s": 27680,
"text": "C++"
},
{
"code": null,
"e": 27689,
"s": 27684,
"text": "Java"
},
{
"code": null,
"e": 27697,
"s": 27689,
"text": "Python3"
},
{
"code": null,
"e": 27700,
"s": 27697,
"text": "C#"
},
{
"code": null,
"e": 27704,
"s": 27700,
"text": "PHP"
},
{
"code": null,
"e": 27715,
"s": 27704,
"text": "Javascript"
},
{
"code": "// C++ program to count number of paths in a maze// with obstacles.#include<bits/stdc++.h>using namespace std;#define R 4#define C 4 // Returns count of possible paths in a maze[R][C]// from (0,0) to (R-1,C-1)int countPaths(int maze[][C]){ // If the initial cell is blocked, there is no // way of moving anywhere if (maze[0][0]==-1) return 0; // Initializing the leftmost column for (int i=0; i<R; i++) { if (maze[i][0] == 0) maze[i][0] = 1; // If we encounter a blocked cell in leftmost // row, there is no way of visiting any cell // directly below it. else break; } // Similarly initialize the topmost row for (int i=1; i<C; i++) { if (maze[0][i] == 0) maze[0][i] = 1; // If we encounter a blocked cell in bottommost // row, there is no way of visiting any cell // directly below it. else break; } // The only difference is that if a cell is -1, // simply ignore it else recursively compute // count value maze[i][j] for (int i=1; i<R; i++) { for (int j=1; j<C; j++) { // If blockage is found, ignore this cell if (maze[i][j] == -1) continue; // If we can reach maze[i][j] from maze[i-1][j] // then increment count. if (maze[i-1][j] > 0) maze[i][j] = (maze[i][j] + maze[i-1][j]); // If we can reach maze[i][j] from maze[i][j-1] // then increment count. if (maze[i][j-1] > 0) maze[i][j] = (maze[i][j] + maze[i][j-1]); } } // If the final cell is blocked, output 0, otherwise // the answer return (maze[R-1][C-1] > 0)? maze[R-1][C-1] : 0;} // Driver codeint main(){ int maze[R][C] = {{0, 0, 0, 0}, {0, -1, 0, 0}, {-1, 0, 0, 0}, {0, 0, 0, 0}}; cout << countPaths(maze); return 0;}",
"e": 29717,
"s": 27715,
"text": null
},
{
"code": "// Java program to count number of paths in a maze// with obstacles.import java.io.*; class GFG{ static int R = 4; static int C = 4; // Returns count of possible paths in // a maze[R][C] from (0,0) to (R-1,C-1) static int countPaths(int maze[][]) { // If the initial cell is blocked, // there is no way of moving anywhere if (maze[0][0]==-1) return 0; // Initializing the leftmost column for (int i = 0; i < R; i++) { if (maze[i][0] == 0) maze[i][0] = 1; // If we encounter a blocked cell // in leftmost row, there is no way // of visiting any cell directly below it. else break; } // Similarly initialize the topmost row for (int i =1 ; i< C ; i++) { if (maze[0][i] == 0) maze[0][i] = 1; // If we encounter a blocked cell in // bottommost row, there is no way of // visiting any cell directly below it. else break; } // The only difference is that if a cell // is -1, simply ignore it else recursively // compute count value maze[i][j] for (int i = 1; i < R; i++) { for (int j = 1; j <C ; j++) { // If blockage is found, // ignore this cell if (maze[i][j] == -1) continue; // If we can reach maze[i][j] from // maze[i-1][j] then increment count. if (maze[i - 1][j] > 0) maze[i][j] = (maze[i][j] + maze[i - 1][j]); // If we can reach maze[i][j] from // maze[i][j-1] then increment count. if (maze[i][j - 1] > 0) maze[i][j] = (maze[i][j] + maze[i][j - 1]); } } // If the final cell is blocked, // output 0, otherwise the answer return (maze[R - 1][C - 1] > 0) ? maze[R - 1][C - 1] : 0; } // Driver code public static void main (String[] args) { int maze[][] = {{0, 0, 0, 0}, {0, -1, 0, 0}, {-1, 0, 0, 0}, {0, 0, 0, 0}}; System.out.println (countPaths(maze)); } } // This code is contributed by vt_m",
"e": 32211,
"s": 29717,
"text": null
},
{
"code": "# Python 3 program to count number of paths# in a maze with obstacles. R = 4C = 4 # Returns count of possible paths in a# maze[R][C] from (0,0) to (R-1,C-1)def countPaths(maze): # If the initial cell is blocked, # there is no way of moving anywhere if (maze[0][0] == -1): return 0 # Initializing the leftmost column for i in range(R): if (maze[i][0] == 0): maze[i][0] = 1 # If we encounter a blocked cell in # leftmost row, there is no way of # visiting any cell directly below it. else: break # Similarly initialize the topmost row for i in range(1, C, 1): if (maze[0][i] == 0): maze[0][i] = 1 # If we encounter a blocked cell in # bottommost row, there is no way of # visiting any cell directly below it. else: break # The only difference is that if a cell is -1, # simply ignore it else recursively compute # count value maze[i][j] for i in range(1, R, 1): for j in range(1, C, 1): # If blockage is found, ignore this cell if (maze[i][j] == -1): continue # If we can reach maze[i][j] from # maze[i-1][j] then increment count. if (maze[i - 1][j] > 0): maze[i][j] = (maze[i][j] + maze[i - 1][j]) # If we can reach maze[i][j] from # maze[i][j-1] then increment count. if (maze[i][j - 1] > 0): maze[i][j] = (maze[i][j] + maze[i][j - 1]) # If the final cell is blocked, # output 0, otherwise the answer if (maze[R - 1][C - 1] > 0): return maze[R - 1][C - 1] else: return 0 # Driver codeif __name__ == '__main__': maze = [[0, 0, 0, 0], [0, -1, 0, 0], [-1, 0, 0, 0], [0, 0, 0, 0 ]] print(countPaths(maze)) # This code is contributed by# Surendra_Gangwar",
"e": 34204,
"s": 32211,
"text": null
},
{
"code": "// C# program to count number of paths in a maze// with obstacles.using System; class GFG { static int R = 4; static int C = 4; // Returns count of possible paths in // a maze[R][C] from (0,0) to (R-1,C-1) static int countPaths(int [,]maze) { // If the initial cell is blocked, // there is no way of moving anywhere if (maze[0,0]==-1) return 0; // Initializing the leftmost column for (int i = 0; i < R; i++) { if (maze[i,0] == 0) maze[i,0] = 1; // If we encounter a blocked cell // in leftmost row, there is no way // of visiting any cell directly below it. else break; } // Similarly initialize the topmost row for (int i =1 ; i< C ; i++) { if (maze[0,i] == 0) maze[0,i] = 1; // If we encounter a blocked cell in // bottommost row, there is no way of // visiting any cell directly below it. else break; } // The only difference is that if a cell // is -1, simply ignore it else recursively // compute count value maze[i][j] for (int i = 1; i < R; i++) { for (int j = 1; j <C ; j++) { // If blockage is found, // ignore this cell if (maze[i,j] == -1) continue; // If we can reach maze[i][j] from // maze[i-1][j] then increment count. if (maze[i - 1,j] > 0) maze[i,j] = (maze[i,j] + maze[i - 1,j]); // If we can reach maze[i][j] from // maze[i][j-1] then increment count. if (maze[i,j - 1] > 0) maze[i,j] = (maze[i,j] + maze[i,j - 1]); } } // If the final cell is blocked, // output 0, otherwise the answer return (maze[R - 1,C - 1] > 0) ? maze[R - 1,C - 1] : 0; } // Driver code public static void Main () { int [,]maze = { {0, 0, 0, 0}, {0, -1, 0, 0}, {-1, 0, 0, 0}, {0, 0, 0, 0}}; Console.Write (countPaths(maze)); } } // This code is contributed by nitin mittal.",
"e": 36699,
"s": 34204,
"text": null
},
{
"code": "<?php// PHP program to count number// of paths in a maze with obstacles. $R = 4;$C = 4; // Returns count of possible// paths in a maze[R][C]// from (0,0) to (R-1,C-1)function countPaths( $maze){ global $R, $C; // If the initial cell is // blocked, there is no // way of moving anywhere if ($maze[0][0] == - 1) return 0; // Initializing the // leftmost column for ( $i = 0; $i < $R; $i++) { if ($maze[$i][0] == 0) $maze[$i][0] = 1; // If we encounter a blocked // cell in leftmost row, // there is no way of // visiting any cell // directly below it. else break; } // Similarly initialize // the topmost row for($i = 1; $i < $C; $i++) { if ($maze[0][$i] == 0) $maze[0][$i] = 1; // If we encounter a blocked // cell in bottommost row, // there is no way of // visiting any cell // directly below it. else break; } // The only difference is // that if a cell is -1, // simply ignore it else // recursively compute // count value maze[i][j] for($i = 1; $i < $R; $i++) { for($j = 1; $j < $C; $j++) { // If blockage is found, // ignore this cell if ($maze[$i][$j] == -1) continue; // If we can reach maze[i][j] // from maze[i-1][j] // then increment count. if ($maze[$i - 1][$j] > 0) $maze[$i][$j] = ($maze[$i][$j] + $maze[$i - 1][$j]); // If we can reach maze[i][j] // from maze[i][j-1] // then increment count. if ($maze[$i][$j - 1] > 0) $maze[$i][$j] = ($maze[$i][$j] + $maze[$i][$j - 1]); } } // If the final cell is // blocked, output 0, // otherwise the answer return ($maze[$R - 1][$C - 1] > 0) ? $maze[$R - 1][$C - 1] : 0;} // Driver Code $maze = array(array(0, 0, 0, 0), array(0, -1, 0, 0), array(-1, 0, 0, 0), array(0, 0, 0, 0)); echo countPaths($maze); // This code is contributed by anuj_67.?>",
"e": 38968,
"s": 36699,
"text": null
},
{
"code": "<script> // JavaScript program to count number// of paths in a maze with obstacles.let R = 4;let C = 4; // Returns count of possible paths in// a maze[R][C] from (0,0) to (R-1,C-1)function countPaths(maze){ // If the initial cell is blocked, // there is no way of moving anywhere if (maze[0][0] == -1) return 0; // Initializing the leftmost column for(let i = 0; i < R; i++) { if (maze[i][0] == 0) maze[i][0] = 1; // If we encounter a blocked cell // in leftmost row, there is no way // of visiting any cell directly below it. else break; } // Similarly initialize the topmost row for(let i = 1; i < C; i++) { if (maze[0][i] == 0) maze[0][i] = 1; // If we encounter a blocked cell in // bottommost row, there is no way of // visiting any cell directly below it. else break; } // The only difference is that if a cell // is -1, simply ignore it else recursively // compute count value maze[i][j] for(let i = 1; i < R; i++) { for(let j = 1; j < C; j++) { // If blockage is found, // ignore this cell if (maze[i][j] == -1) continue; // If we can reach maze[i][j] from // maze[i-1][j] then increment count. if (maze[i - 1][j] > 0) maze[i][j] = (maze[i][j] + maze[i - 1][j]); // If we can reach maze[i][j] from // maze[i][j-1] then increment count. if (maze[i][j - 1] > 0) maze[i][j] = (maze[i][j] + maze[i][j - 1]); } } // If the final cell is blocked, // output 0, otherwise the answer return (maze[R - 1][C - 1] > 0) ? maze[R - 1][C - 1] : 0;} // Driver Codelet maze = [ [ 0, 0, 0, 0 ], [ 0, -1, 0, 0 ], [ -1, 0, 0, 0 ], [ 0, 0, 0, 0 ] ]; document.write(countPaths(maze)); // This code is contributed by code_hunt </script>",
"e": 41101,
"s": 38968,
"text": null
},
{
"code": null,
"e": 41109,
"s": 41101,
"text": "Output:"
},
{
"code": null,
"e": 41111,
"s": 41109,
"text": "4"
},
{
"code": null,
"e": 41137,
"s": 41111,
"text": "Time Complexity: O(R x C)"
},
{
"code": null,
"e": 41560,
"s": 41137,
"text": "This article is contributed by Roshni Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 41573,
"s": 41560,
"text": "nitin mittal"
},
{
"code": null,
"e": 41578,
"s": 41573,
"text": "vt_m"
},
{
"code": null,
"e": 41595,
"s": 41578,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 41605,
"s": 41595,
"text": "code_hunt"
},
{
"code": null,
"e": 41622,
"s": 41605,
"text": "punamsingh628700"
},
{
"code": null,
"e": 41629,
"s": 41622,
"text": "Amazon"
},
{
"code": null,
"e": 41649,
"s": 41629,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 41656,
"s": 41649,
"text": "Matrix"
},
{
"code": null,
"e": 41663,
"s": 41656,
"text": "Amazon"
},
{
"code": null,
"e": 41683,
"s": 41663,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 41690,
"s": 41683,
"text": "Matrix"
},
{
"code": null,
"e": 41788,
"s": 41690,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41821,
"s": 41788,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 41856,
"s": 41821,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 41924,
"s": 41856,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 41945,
"s": 41924,
"text": "Edit Distance | DP-5"
},
{
"code": null,
"e": 42008,
"s": 41945,
"text": "Overlapping Subproblems Property in Dynamic Programming | DP-1"
},
{
"code": null,
"e": 42043,
"s": 42008,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 42087,
"s": 42043,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 42123,
"s": 42087,
"text": "Print a given matrix in spiral form"
},
{
"code": null,
"e": 42147,
"s": 42123,
"text": "Sudoku | Backtracking-7"
}
] |
map::size() in C++ STL - GeeksforGeeks
|
27 Dec, 2018
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values.
map::size()In C++, size() function is used to return the total number of elements present in the map.
Syntax:
map_name.size()
Return Value: It returns the number of elements present in the map.
Examples:
Input : map1 = {
{1, "India"},
{2, "Nepal"},
{3, "Sri Lanka"},
{4, "Myanmar"}
}
map1.size();
Output: 4
Input : map2 = {};
map2.size();
Output: 0
// C++ program to illustrate// implementation of size() function#include <bits/stdc++.h>using namespace std; int main(){ // Take any two maps map<int, string> map1, map2; // Inserting values map1.insert(make_pair(1, "India")); map1.insert(make_pair(2, "Nepal")); map1.insert(make_pair(3, "Sri Lanka")); map1.insert(make_pair(4, "Myanmar")); // Printing the size cout << "map1 size: " << map1.size(); cout << endl; cout << "map2 size: " << map2.size(); return 0;}
Output:
map1 size: 4
map2 size: 0
Time complexity: Constant i.e. O(1)
vaibhavch9876
cpp-map
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Inline Functions in C++
Queue in C++ Standard Template Library (STL)
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
|
[
{
"code": null,
"e": 25368,
"s": 25340,
"text": "\n27 Dec, 2018"
},
{
"code": null,
"e": 25537,
"s": 25368,
"text": "Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values."
},
{
"code": null,
"e": 25639,
"s": 25537,
"text": "map::size()In C++, size() function is used to return the total number of elements present in the map."
},
{
"code": null,
"e": 25647,
"s": 25639,
"text": "Syntax:"
},
{
"code": null,
"e": 25664,
"s": 25647,
"text": "map_name.size()\n"
},
{
"code": null,
"e": 25732,
"s": 25664,
"text": "Return Value: It returns the number of elements present in the map."
},
{
"code": null,
"e": 25742,
"s": 25732,
"text": "Examples:"
},
{
"code": null,
"e": 25985,
"s": 25742,
"text": "Input : map1 = { \n {1, \"India\"},\n {2, \"Nepal\"},\n {3, \"Sri Lanka\"},\n {4, \"Myanmar\"}\n }\n map1.size();\nOutput: 4\n\nInput : map2 = {};\n map2.size();\nOutput: 0\n"
},
{
"code": "// C++ program to illustrate// implementation of size() function#include <bits/stdc++.h>using namespace std; int main(){ // Take any two maps map<int, string> map1, map2; // Inserting values map1.insert(make_pair(1, \"India\")); map1.insert(make_pair(2, \"Nepal\")); map1.insert(make_pair(3, \"Sri Lanka\")); map1.insert(make_pair(4, \"Myanmar\")); // Printing the size cout << \"map1 size: \" << map1.size(); cout << endl; cout << \"map2 size: \" << map2.size(); return 0;}",
"e": 26497,
"s": 25985,
"text": null
},
{
"code": null,
"e": 26505,
"s": 26497,
"text": "Output:"
},
{
"code": null,
"e": 26532,
"s": 26505,
"text": "map1 size: 4\nmap2 size: 0\n"
},
{
"code": null,
"e": 26568,
"s": 26532,
"text": "Time complexity: Constant i.e. O(1)"
},
{
"code": null,
"e": 26582,
"s": 26568,
"text": "vaibhavch9876"
},
{
"code": null,
"e": 26590,
"s": 26582,
"text": "cpp-map"
},
{
"code": null,
"e": 26594,
"s": 26590,
"text": "STL"
},
{
"code": null,
"e": 26598,
"s": 26594,
"text": "C++"
},
{
"code": null,
"e": 26602,
"s": 26598,
"text": "STL"
},
{
"code": null,
"e": 26606,
"s": 26602,
"text": "CPP"
},
{
"code": null,
"e": 26704,
"s": 26606,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26732,
"s": 26704,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26752,
"s": 26732,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 26785,
"s": 26752,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 26809,
"s": 26785,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 26834,
"s": 26809,
"text": "std::string class in C++"
},
{
"code": null,
"e": 26878,
"s": 26834,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26902,
"s": 26878,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 26947,
"s": 26902,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 27000,
"s": 26947,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
}
] |
numpy.lcm() in Python - GeeksforGeeks
|
29 Nov, 2018
numpy.lcm(arr1, arr2, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None) : This mathematical function helps user to calculate lcm value of |arr1| and |arr2| elements.
Parameters :arr1 / arr2 : [array_like]Input array.
Return : LCM of two or more numbers.
Code :
# Python program illustrating # lcm() method import numpy as np arr1 = [120, 24, 42, 10]arr2 = [2250, 12, 20, 50] print ("arr1 : ", arr1)print ("arr2 : ", arr2) print ("\nlcm of arr1 and arr2 : ", np.lcm(arr1, arr2))print ("\nlcm of arr1 and 10 : ", np.lcm(arr1, 10))
Output :
arr1 : [120, 24, 42, 10]
arr2 : [2250, 12, 20, 50]
lcm of arr1 and arr2 : [9000, 24, 420, 50]
lcm of arr1 and 10 : [120, 120, 210, 10]
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
|
[
{
"code": null,
"e": 26203,
"s": 26175,
"text": "\n29 Nov, 2018"
},
{
"code": null,
"e": 26395,
"s": 26203,
"text": "numpy.lcm(arr1, arr2, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None) : This mathematical function helps user to calculate lcm value of |arr1| and |arr2| elements."
},
{
"code": null,
"e": 26446,
"s": 26395,
"text": "Parameters :arr1 / arr2 : [array_like]Input array."
},
{
"code": null,
"e": 26483,
"s": 26446,
"text": "Return : LCM of two or more numbers."
},
{
"code": null,
"e": 26490,
"s": 26483,
"text": "Code :"
},
{
"code": "# Python program illustrating # lcm() method import numpy as np arr1 = [120, 24, 42, 10]arr2 = [2250, 12, 20, 50] print (\"arr1 : \", arr1)print (\"arr2 : \", arr2) print (\"\\nlcm of arr1 and arr2 : \", np.lcm(arr1, arr2))print (\"\\nlcm of arr1 and 10 : \", np.lcm(arr1, 10)) ",
"e": 26785,
"s": 26490,
"text": null
},
{
"code": null,
"e": 26794,
"s": 26785,
"text": "Output :"
},
{
"code": null,
"e": 26940,
"s": 26794,
"text": "arr1 : [120, 24, 42, 10]\narr2 : [2250, 12, 20, 50]\n\nlcm of arr1 and arr2 : [9000, 24, 420, 50]\n\nlcm of arr1 and 10 : [120, 120, 210, 10]\n"
},
{
"code": null,
"e": 26975,
"s": 26940,
"text": "Python numpy-Mathematical Function"
},
{
"code": null,
"e": 26988,
"s": 26975,
"text": "Python-numpy"
},
{
"code": null,
"e": 26995,
"s": 26988,
"text": "Python"
},
{
"code": null,
"e": 27093,
"s": 26995,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27111,
"s": 27093,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27143,
"s": 27111,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27165,
"s": 27143,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27207,
"s": 27165,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27233,
"s": 27207,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27262,
"s": 27233,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27306,
"s": 27262,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27343,
"s": 27306,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27379,
"s": 27343,
"text": "Convert integer to string in Python"
}
] |
Extended Knapsack Problem - GeeksforGeeks
|
30 Dec, 2021
Given N items, each item having a given weight Ci and a profit value Pi, the task is to maximize the profit by selecting a maximum of K items adding up to a maximum weight W.
Examples:
Input: N = 5, P[] = {2, 7, 1, 5, 3}, C[] = {2, 5, 2, 3, 4}, W = 8, K = 2. Output: 12 Explanation: Here, the maximum possible profit is when we take 2 items: item2 (P[1] = 7 and C[1] = 5) and item4 (P[3] = 5 and C[3] = 3). Hence, maximum profit = 7 + 5 = 12Input: N = 5, P[] = {2, 7, 1, 5, 3}, C[] = {2, 5, 2, 3, 4}, W = 1, K = 2 Output: 0 Explanation: All weights are greater than 1. Hence, no item can be picked.
Approach: The dynamic programming approach is preferred over the general recursion approach. Let us first verify that the conditions of DP are still satisfied.
Overlapping sub-problems: When the recursive solution is tried, 1 item is added first and the solution set is (1), (2), ...(n). In the second iteration we have (1, 2) and so on where (1) and (2) are recalculated. Hence there will be overlapping solutions.Optimal substructure: Overall, each item has only two choices, either it can be included in the solution or denied. For a particular subset of z elements, the solution for (z+1)th element can either have a solution corresponding to the z elements or the (z+1)th element can be added if it doesn’t exceed the knapsack constraints. Either way, the optimal substructure property is satisfied.
Overlapping sub-problems: When the recursive solution is tried, 1 item is added first and the solution set is (1), (2), ...(n). In the second iteration we have (1, 2) and so on where (1) and (2) are recalculated. Hence there will be overlapping solutions.
Optimal substructure: Overall, each item has only two choices, either it can be included in the solution or denied. For a particular subset of z elements, the solution for (z+1)th element can either have a solution corresponding to the z elements or the (z+1)th element can be added if it doesn’t exceed the knapsack constraints. Either way, the optimal substructure property is satisfied.
Let’s derive the recurrence. Let us consider a 3-dimensional table dp[N][W][K], where N is the number of elements, W is the maximum weight capacity and K is the maximum number of items allowed in the knapsack. Let’s define a state dp[i][j][k] where i denotes that we are considering the ith element, j denotes the current weight filled, and k denotes the number of items filled until now.For every state dp[i][j][k], the profit is either that of the previous state (when the current state is not included) or the profit of the current item added to that of the previous state (when the current item is selected). Hence, the recurrence relation is:
dp[i][j][k] = max( dp[i-1][j][k], dp[i-1][j-W[i-1]][k-1] + P[i])
Below is the implementation of the above approach:
C++
Java
Javascript
Python3
// C++ code for the extended// Knapsack Approach#include <bits/stdc++.h>using namespace std; // To store the dp valuesvector<vector<vector<int> > > dp; int maxProfit(int profit[], int weight[], int n, int max_W, int max_E){ // for each element given for (int i = 1; i <= n; i++) { // For each possible // weight value for (int j = 1; j <= max_W; j++) { // For each case where // the total elements are // less than the constraint for (int k = 1; k <= max_E; k++) { // To ensure that we dont // go out of the array if (j >= weight[i - 1]) { dp[i][j][k] = max( dp[i - 1][j][k], dp[i - 1][j - weight[i - 1]][k - 1] + profit[i - 1]); } else { dp[i][j][k] = dp[i - 1][j][k]; } } } } return dp[n][max_W][max_E];} // Driver Codeint main(){ int n = 5; int profit[] = { 2, 7, 1, 5, 3 }; int weight[] = { 2, 5, 2, 3, 4 }; int max_weight = 8; int max_element = 2; dp = vector<vector<vector<int> > >( n + 1, vector<vector<int> >( max_weight + 1, vector<int>(max_element + 1, 0))); cout << maxProfit(profit, weight, n, max_weight, max_element) << "\n"; return 0;}
// Java code for the extended// Knapsack Approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // To store the dp valuesstatic int[][][] dp = new int[100][100][100]; static int maxProfit(int profit[], int weight[], int n, int max_W, int max_E){ // for each element given for(int i = 1; i <= n; i++) { // For each possible // weight value for(int j = 1; j <= max_W; j++) { // For each case where // the total elements are // less than the constraint for(int k = 1; k <= max_E; k++) { // To ensure that we dont // go out of the array if (j >= weight[i - 1]) { dp[i][j][k] = Math.max(dp[i - 1][j][k], dp[i - 1][j - weight[i - 1]][k - 1] + profit[i - 1]); } else { dp[i][j][k] = dp[i - 1][j][k]; } } } } return dp[n][max_W][max_E];} // Driver codepublic static void main(String[] args){ int n = 5; int profit[] = { 2, 7, 1, 5, 3 }; int weight[] = { 2, 5, 2, 3, 4 }; int max_weight = 8; int max_element = 2; System.out.println(maxProfit(profit, weight, n, max_weight, max_element)); }} // This code is contributed by offbeat
<script> // Javascript code for the extended// Knapsack Approach // To store the dp valuesvar dp = Array.from(Array(100), ()=>Array(100));for(var i =0; i<100; i++) for(var j =0; j<100; j++) dp[i][j] = new Array(100).fill(0); function maxProfit(profit,weight, n, max_W, max_E){ // for each element given for (var i = 1; i <= n; i++) { // For each possible // weight value for (var j = 1; j <= max_W; j++) { // For each case where // the total elements are // less than the constraint for (var k = 1; k <= max_E; k++) { // To ensure that we dont // go out of the array if (j >= weight[i-1]) { dp[i][j][k] = Math.max(dp[i - 1][j][k], dp[i - 1][j - weight[i-1]][k - 1]+ profit[i-1]); } else { dp[i][j][k] = dp[i - 1][j][k]; } } } } return dp[n][max_W][max_E];} // Driver Codevar n = 5;var profit = [2, 7, 1, 5, 3 ];var weight = [2, 5, 2, 3, 4 ];var max_weight = 8;var max_element = 2;document.write( maxProfit(profit, weight, n, max_weight, max_element) + "<br>"); </script>
# Python3 code for the extended# Knapsack Approach # To store the dp valuesdp=[] def maxProfit(profit, weight, n, max_W, max_E): # for each element given for i in range(1,n+1) : # For each possible # weight value for j in range(1,max_W+1) : # For each case where # the total elements are # less than the constra for k in range(1, max_E+1) : # To ensure that we dont # go out of the array if (j >= weight[i - 1]) : dp[i][j][k] = max( dp[i - 1][j][k], dp[i - 1][j - weight[i - 1]][k - 1] + profit[i - 1]) else : dp[i][j][k] = dp[i - 1][j][k] return dp[n][max_W][max_E] # Driver Codeif __name__ == '__main__': n = 5 profit = [2, 7, 1, 5, 3 ] weight = [ 2, 5, 2, 3, 4 ] max_weight = 8 max_element = 2 dp = [[[0 for j in range(max_element + 1)]for i in range(max_weight + 1)] for k in range(n+1)] print(maxProfit(profit, weight, n, max_weight, max_element))
12
Time Complexity: O(N * W * K) Auxiliary Space: O(N * W * K)
nidhi_biet
manujk881
offbeat
famously
ashutoshsinghgeeksforgeeks
amartyaghoshgfg
knapsack
Algorithms
Dynamic Programming
Greedy
Dynamic Programming
Greedy
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SCAN (Elevator) Disk Scheduling Algorithms
Rail Fence Cipher - Encryption and Decryption
Program for SSTF disk scheduling algorithm
Quadratic Probing in Hashing
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Largest Sum Contiguous Subarray
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23
|
[
{
"code": null,
"e": 24702,
"s": 24674,
"text": "\n30 Dec, 2021"
},
{
"code": null,
"e": 24877,
"s": 24702,
"text": "Given N items, each item having a given weight Ci and a profit value Pi, the task is to maximize the profit by selecting a maximum of K items adding up to a maximum weight W."
},
{
"code": null,
"e": 24888,
"s": 24877,
"text": "Examples: "
},
{
"code": null,
"e": 25303,
"s": 24888,
"text": "Input: N = 5, P[] = {2, 7, 1, 5, 3}, C[] = {2, 5, 2, 3, 4}, W = 8, K = 2. Output: 12 Explanation: Here, the maximum possible profit is when we take 2 items: item2 (P[1] = 7 and C[1] = 5) and item4 (P[3] = 5 and C[3] = 3). Hence, maximum profit = 7 + 5 = 12Input: N = 5, P[] = {2, 7, 1, 5, 3}, C[] = {2, 5, 2, 3, 4}, W = 1, K = 2 Output: 0 Explanation: All weights are greater than 1. Hence, no item can be picked. "
},
{
"code": null,
"e": 25465,
"s": 25303,
"text": "Approach: The dynamic programming approach is preferred over the general recursion approach. Let us first verify that the conditions of DP are still satisfied. "
},
{
"code": null,
"e": 26110,
"s": 25465,
"text": "Overlapping sub-problems: When the recursive solution is tried, 1 item is added first and the solution set is (1), (2), ...(n). In the second iteration we have (1, 2) and so on where (1) and (2) are recalculated. Hence there will be overlapping solutions.Optimal substructure: Overall, each item has only two choices, either it can be included in the solution or denied. For a particular subset of z elements, the solution for (z+1)th element can either have a solution corresponding to the z elements or the (z+1)th element can be added if it doesn’t exceed the knapsack constraints. Either way, the optimal substructure property is satisfied."
},
{
"code": null,
"e": 26366,
"s": 26110,
"text": "Overlapping sub-problems: When the recursive solution is tried, 1 item is added first and the solution set is (1), (2), ...(n). In the second iteration we have (1, 2) and so on where (1) and (2) are recalculated. Hence there will be overlapping solutions."
},
{
"code": null,
"e": 26756,
"s": 26366,
"text": "Optimal substructure: Overall, each item has only two choices, either it can be included in the solution or denied. For a particular subset of z elements, the solution for (z+1)th element can either have a solution corresponding to the z elements or the (z+1)th element can be added if it doesn’t exceed the knapsack constraints. Either way, the optimal substructure property is satisfied."
},
{
"code": null,
"e": 27406,
"s": 26756,
"text": "Let’s derive the recurrence. Let us consider a 3-dimensional table dp[N][W][K], where N is the number of elements, W is the maximum weight capacity and K is the maximum number of items allowed in the knapsack. Let’s define a state dp[i][j][k] where i denotes that we are considering the ith element, j denotes the current weight filled, and k denotes the number of items filled until now.For every state dp[i][j][k], the profit is either that of the previous state (when the current state is not included) or the profit of the current item added to that of the previous state (when the current item is selected). Hence, the recurrence relation is: "
},
{
"code": null,
"e": 27473,
"s": 27406,
"text": "dp[i][j][k] = max( dp[i-1][j][k], dp[i-1][j-W[i-1]][k-1] + P[i]) "
},
{
"code": null,
"e": 27526,
"s": 27473,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27530,
"s": 27526,
"text": "C++"
},
{
"code": null,
"e": 27535,
"s": 27530,
"text": "Java"
},
{
"code": null,
"e": 27546,
"s": 27535,
"text": "Javascript"
},
{
"code": null,
"e": 27554,
"s": 27546,
"text": "Python3"
},
{
"code": "// C++ code for the extended// Knapsack Approach#include <bits/stdc++.h>using namespace std; // To store the dp valuesvector<vector<vector<int> > > dp; int maxProfit(int profit[], int weight[], int n, int max_W, int max_E){ // for each element given for (int i = 1; i <= n; i++) { // For each possible // weight value for (int j = 1; j <= max_W; j++) { // For each case where // the total elements are // less than the constraint for (int k = 1; k <= max_E; k++) { // To ensure that we dont // go out of the array if (j >= weight[i - 1]) { dp[i][j][k] = max( dp[i - 1][j][k], dp[i - 1][j - weight[i - 1]][k - 1] + profit[i - 1]); } else { dp[i][j][k] = dp[i - 1][j][k]; } } } } return dp[n][max_W][max_E];} // Driver Codeint main(){ int n = 5; int profit[] = { 2, 7, 1, 5, 3 }; int weight[] = { 2, 5, 2, 3, 4 }; int max_weight = 8; int max_element = 2; dp = vector<vector<vector<int> > >( n + 1, vector<vector<int> >( max_weight + 1, vector<int>(max_element + 1, 0))); cout << maxProfit(profit, weight, n, max_weight, max_element) << \"\\n\"; return 0;}",
"e": 29018,
"s": 27554,
"text": null
},
{
"code": "// Java code for the extended// Knapsack Approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // To store the dp valuesstatic int[][][] dp = new int[100][100][100]; static int maxProfit(int profit[], int weight[], int n, int max_W, int max_E){ // for each element given for(int i = 1; i <= n; i++) { // For each possible // weight value for(int j = 1; j <= max_W; j++) { // For each case where // the total elements are // less than the constraint for(int k = 1; k <= max_E; k++) { // To ensure that we dont // go out of the array if (j >= weight[i - 1]) { dp[i][j][k] = Math.max(dp[i - 1][j][k], dp[i - 1][j - weight[i - 1]][k - 1] + profit[i - 1]); } else { dp[i][j][k] = dp[i - 1][j][k]; } } } } return dp[n][max_W][max_E];} // Driver codepublic static void main(String[] args){ int n = 5; int profit[] = { 2, 7, 1, 5, 3 }; int weight[] = { 2, 5, 2, 3, 4 }; int max_weight = 8; int max_element = 2; System.out.println(maxProfit(profit, weight, n, max_weight, max_element)); }} // This code is contributed by offbeat",
"e": 30678,
"s": 29018,
"text": null
},
{
"code": "<script> // Javascript code for the extended// Knapsack Approach // To store the dp valuesvar dp = Array.from(Array(100), ()=>Array(100));for(var i =0; i<100; i++) for(var j =0; j<100; j++) dp[i][j] = new Array(100).fill(0); function maxProfit(profit,weight, n, max_W, max_E){ // for each element given for (var i = 1; i <= n; i++) { // For each possible // weight value for (var j = 1; j <= max_W; j++) { // For each case where // the total elements are // less than the constraint for (var k = 1; k <= max_E; k++) { // To ensure that we dont // go out of the array if (j >= weight[i-1]) { dp[i][j][k] = Math.max(dp[i - 1][j][k], dp[i - 1][j - weight[i-1]][k - 1]+ profit[i-1]); } else { dp[i][j][k] = dp[i - 1][j][k]; } } } } return dp[n][max_W][max_E];} // Driver Codevar n = 5;var profit = [2, 7, 1, 5, 3 ];var weight = [2, 5, 2, 3, 4 ];var max_weight = 8;var max_element = 2;document.write( maxProfit(profit, weight, n, max_weight, max_element) + \"<br>\"); </script>",
"e": 32126,
"s": 30678,
"text": null
},
{
"code": "# Python3 code for the extended# Knapsack Approach # To store the dp valuesdp=[] def maxProfit(profit, weight, n, max_W, max_E): # for each element given for i in range(1,n+1) : # For each possible # weight value for j in range(1,max_W+1) : # For each case where # the total elements are # less than the constra for k in range(1, max_E+1) : # To ensure that we dont # go out of the array if (j >= weight[i - 1]) : dp[i][j][k] = max( dp[i - 1][j][k], dp[i - 1][j - weight[i - 1]][k - 1] + profit[i - 1]) else : dp[i][j][k] = dp[i - 1][j][k] return dp[n][max_W][max_E] # Driver Codeif __name__ == '__main__': n = 5 profit = [2, 7, 1, 5, 3 ] weight = [ 2, 5, 2, 3, 4 ] max_weight = 8 max_element = 2 dp = [[[0 for j in range(max_element + 1)]for i in range(max_weight + 1)] for k in range(n+1)] print(maxProfit(profit, weight, n, max_weight, max_element))",
"e": 33348,
"s": 32126,
"text": null
},
{
"code": null,
"e": 33351,
"s": 33348,
"text": "12"
},
{
"code": null,
"e": 33413,
"s": 33353,
"text": "Time Complexity: O(N * W * K) Auxiliary Space: O(N * W * K)"
},
{
"code": null,
"e": 33424,
"s": 33413,
"text": "nidhi_biet"
},
{
"code": null,
"e": 33434,
"s": 33424,
"text": "manujk881"
},
{
"code": null,
"e": 33442,
"s": 33434,
"text": "offbeat"
},
{
"code": null,
"e": 33451,
"s": 33442,
"text": "famously"
},
{
"code": null,
"e": 33478,
"s": 33451,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 33494,
"s": 33478,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 33503,
"s": 33494,
"text": "knapsack"
},
{
"code": null,
"e": 33514,
"s": 33503,
"text": "Algorithms"
},
{
"code": null,
"e": 33534,
"s": 33514,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 33541,
"s": 33534,
"text": "Greedy"
},
{
"code": null,
"e": 33561,
"s": 33541,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 33568,
"s": 33561,
"text": "Greedy"
},
{
"code": null,
"e": 33579,
"s": 33568,
"text": "Algorithms"
},
{
"code": null,
"e": 33677,
"s": 33579,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33702,
"s": 33677,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 33745,
"s": 33702,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 33791,
"s": 33745,
"text": "Rail Fence Cipher - Encryption and Decryption"
},
{
"code": null,
"e": 33834,
"s": 33791,
"text": "Program for SSTF disk scheduling algorithm"
},
{
"code": null,
"e": 33863,
"s": 33834,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 33892,
"s": 33863,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 33922,
"s": 33892,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 33954,
"s": 33922,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 33988,
"s": 33954,
"text": "Longest Common Subsequence | DP-4"
}
] |
Count number of ways to divide a number in parts in C++
|
We are given a positive number N. The goal is to count the number of ways in which the number N can be divided into 3 parts. The parts may or may not be equal. N lies in range [1,5000].
We will do this by using three for loops for 3 parts of the number. Check at the innermost loop that the sum of all three is equal to N. If true, then increment the count of ways.
Let’s understand with examples.
Input − N=5
Output − Number of ways to divide N in 3 parts: 2
Explanation − 5 can be shown as sum of (1,1,3) and (1,2,2)
Input − N=9
Output − Number of ways to divide N in 3 parts: 7
Explanation − 9 can be shown as sum of : (1, 1, 7), (1, 2, 6), (1, 3, 5), (1, 4, 4), (2, 2, 5), (2, 3,4) and (3, 3, 3).
We take an integer N initialized with a value between 1 and 5000.
We take an integer N initialized with a value between 1 and 5000.
Function divideN(int n) takes n and returns the number of ways in which n can be divided into 3 parts.
Function divideN(int n) takes n and returns the number of ways in which n can be divided into 3 parts.
Take the initial variable count as 0 for the number of ways.
Take the initial variable count as 0 for the number of ways.
Traverse using three for loops for each part of the number.
Traverse using three for loops for each part of the number.
Outermost loop from 1<=i<n, inner loop i<=j<n , innermost j<=k<n.
Outermost loop from 1<=i<n, inner loop i<=j<n , innermost j<=k<n.
Check if the sum of i, j and k is equal to n . If true then increment count.
Check if the sum of i, j and k is equal to n . If true then increment count.
At the end of all loops count will have a total number of ways to divide n in three parts.
At the end of all loops count will have a total number of ways to divide n in three parts.
Return the count as result.
Return the count as result.
Live Demo
#include <bits/stdc++.h>
using namespace std;
int divideN(int n){
int count = 0;
for (int i = 1; i < n; i++){
for (int j = i ; j < n; j++){
for (int k = j; k < n; k++){
int sum=i+j+k;
if(sum==n)
{ count++; }
}
}
}
return count;
}
int main(){
int N=500;
cout <<endl<< "Number of ways to divide N in 3 parts : "<<divideN(N);
return 0;
}
If we run the above code it will generate the following output −
Number of ways to divide N in 3 parts: 20833
|
[
{
"code": null,
"e": 1248,
"s": 1062,
"text": "We are given a positive number N. The goal is to count the number of ways in which the number N can be divided into 3 parts. The parts may or may not be equal. N lies in range [1,5000]."
},
{
"code": null,
"e": 1428,
"s": 1248,
"text": "We will do this by using three for loops for 3 parts of the number. Check at the innermost loop that the sum of all three is equal to N. If true, then increment the count of ways."
},
{
"code": null,
"e": 1460,
"s": 1428,
"text": "Let’s understand with examples."
},
{
"code": null,
"e": 1472,
"s": 1460,
"text": "Input − N=5"
},
{
"code": null,
"e": 1522,
"s": 1472,
"text": "Output − Number of ways to divide N in 3 parts: 2"
},
{
"code": null,
"e": 1581,
"s": 1522,
"text": "Explanation − 5 can be shown as sum of (1,1,3) and (1,2,2)"
},
{
"code": null,
"e": 1593,
"s": 1581,
"text": "Input − N=9"
},
{
"code": null,
"e": 1643,
"s": 1593,
"text": "Output − Number of ways to divide N in 3 parts: 7"
},
{
"code": null,
"e": 1763,
"s": 1643,
"text": "Explanation − 9 can be shown as sum of : (1, 1, 7), (1, 2, 6), (1, 3, 5), (1, 4, 4), (2, 2, 5), (2, 3,4) and (3, 3, 3)."
},
{
"code": null,
"e": 1829,
"s": 1763,
"text": "We take an integer N initialized with a value between 1 and 5000."
},
{
"code": null,
"e": 1895,
"s": 1829,
"text": "We take an integer N initialized with a value between 1 and 5000."
},
{
"code": null,
"e": 1998,
"s": 1895,
"text": "Function divideN(int n) takes n and returns the number of ways in which n can be divided into 3 parts."
},
{
"code": null,
"e": 2101,
"s": 1998,
"text": "Function divideN(int n) takes n and returns the number of ways in which n can be divided into 3 parts."
},
{
"code": null,
"e": 2162,
"s": 2101,
"text": "Take the initial variable count as 0 for the number of ways."
},
{
"code": null,
"e": 2223,
"s": 2162,
"text": "Take the initial variable count as 0 for the number of ways."
},
{
"code": null,
"e": 2283,
"s": 2223,
"text": "Traverse using three for loops for each part of the number."
},
{
"code": null,
"e": 2343,
"s": 2283,
"text": "Traverse using three for loops for each part of the number."
},
{
"code": null,
"e": 2409,
"s": 2343,
"text": "Outermost loop from 1<=i<n, inner loop i<=j<n , innermost j<=k<n."
},
{
"code": null,
"e": 2475,
"s": 2409,
"text": "Outermost loop from 1<=i<n, inner loop i<=j<n , innermost j<=k<n."
},
{
"code": null,
"e": 2552,
"s": 2475,
"text": "Check if the sum of i, j and k is equal to n . If true then increment count."
},
{
"code": null,
"e": 2629,
"s": 2552,
"text": "Check if the sum of i, j and k is equal to n . If true then increment count."
},
{
"code": null,
"e": 2720,
"s": 2629,
"text": "At the end of all loops count will have a total number of ways to divide n in three parts."
},
{
"code": null,
"e": 2811,
"s": 2720,
"text": "At the end of all loops count will have a total number of ways to divide n in three parts."
},
{
"code": null,
"e": 2839,
"s": 2811,
"text": "Return the count as result."
},
{
"code": null,
"e": 2867,
"s": 2839,
"text": "Return the count as result."
},
{
"code": null,
"e": 2878,
"s": 2867,
"text": " Live Demo"
},
{
"code": null,
"e": 3303,
"s": 2878,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint divideN(int n){\n int count = 0;\n for (int i = 1; i < n; i++){\n for (int j = i ; j < n; j++){\n for (int k = j; k < n; k++){\n int sum=i+j+k;\n if(sum==n)\n { count++; }\n }\n }\n }\n return count;\n}\nint main(){\n int N=500;\n cout <<endl<< \"Number of ways to divide N in 3 parts : \"<<divideN(N);\n return 0;\n}"
},
{
"code": null,
"e": 3368,
"s": 3303,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 3413,
"s": 3368,
"text": "Number of ways to divide N in 3 parts: 20833"
}
] |
Check if a doubly linked list of characters is palindrome or not in C++
|
Here we will see how to check a string is a palindrome or not using a Doubly linked list. Here we will push each character of a string inside one doubly linked list. There will be two pointers, left and right. Then start scanning from both sides. If a left character is the same as right character, then move the left pointer to the next node, and move the right pointer to the previous node. Otherwise, return false. This process will be continued until the left and right are pointing at the same node, or the right pointer is pointing to the previous element of the left pointer.
Live Demo
#include <iostream>
using namespace std;
class Node {
public:
char data;
Node *next;
Node *prev;
};
void getNode(Node** start, char new_data) {
struct Node* newNode = new Node;
newNode->data = new_data;
newNode->next = (*start);
newNode->prev = NULL;
if ((*start) != NULL)
(*start)->prev = newNode ;
(*start) = newNode;
}
bool isPalindrome(Node *left) {
if (left == NULL)
return true;
Node *right = left;
while (right->next != NULL)
right = right->next;
while (left != right && right != left->prev) {
if (left->data != right->data)
return false;
left = left->next;
right = right->prev;
}
return true;
}
int main() {
Node* head = NULL;
string str = "madam";
for(int i = 0; i< str.length(); i++){
getNode(&head, str[i]);
}
if (isPalindrome(head))
cout << "This is Palindrome";
else
cout << "This is Not a Palindrome";
}
This is Palindrome
|
[
{
"code": null,
"e": 1645,
"s": 1062,
"text": "Here we will see how to check a string is a palindrome or not using a Doubly linked list. Here we will push each character of a string inside one doubly linked list. There will be two pointers, left and right. Then start scanning from both sides. If a left character is the same as right character, then move the left pointer to the next node, and move the right pointer to the previous node. Otherwise, return false. This process will be continued until the left and right are pointing at the same node, or the right pointer is pointing to the previous element of the left pointer."
},
{
"code": null,
"e": 1656,
"s": 1645,
"text": " Live Demo"
},
{
"code": null,
"e": 2603,
"s": 1656,
"text": "#include <iostream>\nusing namespace std;\nclass Node {\n public:\n char data;\n Node *next;\n Node *prev;\n};\nvoid getNode(Node** start, char new_data) {\n struct Node* newNode = new Node;\n newNode->data = new_data;\n newNode->next = (*start);\n newNode->prev = NULL;\n if ((*start) != NULL)\n (*start)->prev = newNode ;\n (*start) = newNode;\n}\nbool isPalindrome(Node *left) {\n if (left == NULL)\n return true;\n Node *right = left;\n while (right->next != NULL)\n right = right->next;\n while (left != right && right != left->prev) {\n if (left->data != right->data)\n return false;\n left = left->next;\n right = right->prev;\n }\nreturn true;\n}\nint main() {\n Node* head = NULL;\n string str = \"madam\";\n for(int i = 0; i< str.length(); i++){\n getNode(&head, str[i]);\n }\n if (isPalindrome(head))\n cout << \"This is Palindrome\";\n else\n cout << \"This is Not a Palindrome\";\n}"
},
{
"code": null,
"e": 2622,
"s": 2603,
"text": "This is Palindrome"
}
] |
Machine Learning in Production. Machine Learning Models beyond Jupyter... | by asjad anis | Towards Data Science
|
This article focuses on deploying machine learning models using mnist handwritten digit recognition as a base example implemented in tensorflow-2. In the end, we will be cooking up a small web app in React to test our model. If you are a machine learning enthusiast then you already know that mnist digit recognition is the hello world program of deep learning and by far you have already seen way too many articles about digit-recognition on medium and probably implemented that already which is exactly why I won’t be focusing too much on the problem itself and instead show you how you can deploy your models and consume them in production. To see the end result you can view the deployed-app here
Before jumping into deployments I will quickly give you a brief walkthrough of the model and show you how you can save your model and consume it in production later on. If you are tired of reading about handwritten-digit-recognition like me you can skip this portion and use the github-repo to get the model so you can follow the rest of the guide.
Libraries used.
Tensorflow 2
Matplotlip
Numpy
For pre-processing the data I am just normalizing the pixel values in 0–1 range by dividing with 255.
Once we have the data loaded and pre-processed I am using a convolutional-net with 2 conv-layers each followed by a max-pooling layer which is then flattened before it’s passed on to a dense layer with 128 units and finally our output layer has 10-units and its using softmax as the activation function which turns the end result to probabilities and distributes it over our classes.
For training the model I am using tensorboard, early-stopping, and model-checkpoint callbacks for gathering information during the training process. Tensorboard is a very handy tool in the tensorflow ecosystem, it lets you visualize your training process, model-graphs, and provides useful metrics that help you a lot in representing and sharing your findings and quickly experiment. Early-Stopping is also a very useful call-back that lets you monitor a very specific metric and stops training if that metric is not improving over time. This saves us from over-fitting our model.
Now that we have trained the model we will save our model in protobuf format which is the default-format in tensorflow-2. Note that we are saving the model in a sub-folder named 1. The reason is that tensorflow-serving uses this convention to load the model version you specify. By default, the server will serve the model with the largest version number.
The last part would be to convert our model to work with tensorflow-js in the browser and for that purpose, we will use tensorflow-converter which helps us convert our pre-trained tensorflow models in python to work in the browser using tensorflow-js. Install and run the tool using the below command and provide the path to your saved model directory when the wizard asks.
pip install tensorflowjs[wizard]tensorflowjs_wizard
If you have followed all the steps till here and have been successfully able to save a model congratulations you are halfway through the journey. Now you have a model that you can deploy in the cloud and use from various applications.
Before we begin with the deployments part lets quickly go through an alternative approach which is also widely used and implemented via a Flask app or an express-server or any other api-framework to serve the model which is not a very efficient way of serving your models in production, the reason being that those frameworks are primarily designed for HTTP requests/response and do not account for your machine’s hardware capability when making inferences. Similarly, it could be hard to standardize the way you load and serve your model via a rest end-point and when you have multiple models/projects being worked on. One of the biggest advantage of using tensorflow-serving over Flask is that it is primarily built for serving flexible and scalable ML models in production and has been battle-tested. Plus it has support for model versioning and serving many models with many versions and it scales really well. However, Flask or any other API-framework that you use can come in very handy if they are used as a middle layer between the client and tensorflow-serving, handling the routing for different tf-servers and preprocessing the data before sending it over to the model for prediction. You can visit this article for a much better understanding of this.
Now we can get on with the deployment part, I will be using Google Cloud to deploy the models and go step by step into the various cloud services that are available to you. Google cloud and tensorflow integrate quite well, we will be looking in particular at these three options that are available to us.
Tensorflow-Serving.
AI-Platform-Predictions
Cloud-Functions
In the first part of this series, we will be using tensorflow-serving, followed by AI-Platform and cloud functions in the next two parts.
Tensorflow serving is a part of the tensorflow extended ecosystem, one of the key benefits of tensorflow serving is that it’s highly scalable and has low latency. Tensorflow serving has the capability to serve multiple models and versions which is a potential use-case when you are going in production you might need to update your models and serve multiple versions.
We will be using tensorflow-serving with docker which is very easy and quick to get started with. Before following the next steps head over to the docker-website and install the docker-desktop app for your OS.
// from terminal pull the tensorflow-serving docker image docker pull tensorflow/serving
The tensorflow serving image has port 8500 exposed for gRPC whereas port 8501 is exposed for REST-API. Now to serve with docker we need
A saved-model that we want to serve. (We have already saved our model)
We need to open up a port on our host on which we will be serving the model.
A name for our model which the client applications will use to refer to the model.
Next in the terminal run the below com
docker run -p 8501:8501 --mount type=bind,source=<path-to-your-model>,target=/models/mnist-digit-model -e MODEL_NAME=mnist-digit-recog -t tensorflow/serving
Please note the path would be to the root folder of your model and not the sub-folder which specifies the model-version. With the above command, we have basically started a docker container and binded the rest-api port with the host port 8501. Next, we are bounding our saved model path to the default model path i.e models/mnist-digit-recog. After which we have specified the environment variable name and set it to mnist-digit-recog and that is it, if you have followed the steps till here properly you should have a docker image running with tensorflow-serving and your model being served on port 8501.
Note if you want to expose the gRPC port too you can run the below command.
docker run -p 8501:8501 -p 8500:8500 --mount type=bind,source=<path-to-your-model>,target=/models/mnist-digit-model -e MODEL_NAME=mnist-digit-recog -t tensorflow/serving
If everything ran successfully you should have similar output on your terminal as below.
If you want to explore tensorflow-serving with docker I suggest you look into the official docs.
Now that we have tensorflow serving our model, let’s quickly test this by making a post request, and verify that everything is working correctly.
The REST url structure is given below:
HOST = localhostPORT = 8501MODEL_NAME = mnist-digit-recogMODEL_VERSION = 1// Defaulthttp://{HOST}:{PORT}/v1/models/{MODEL_NAME}:predict// Specific Model-Versionhttp://{HOST}:{PORT}/v1/models/{MODEL_NAME}/versions/{MODEL_VERSION}:predict
We can use the below piece of code to quickly test that the model is being served properly. Load up the notebook from the attached github-repo above and in a new cell paste the code below and run it to see the results.
Similarly, you can now call this end-point from any client-side application and voila you should have the predicted digit. For instance, if you are a JS fan you can use the below code snippet.
Awesome now if we want to create our own docker-image that has our model built-in we can do that by first running the serving image as a daemon and then copy our saved model to the containers model folder. For that quickly follow the steps from the official tensorflow-serving guide here. You can name your container whatever you want, I have called mine mnist-digit-container and now we don’t have to bind our model path or do any extra config. We can just run the below command to get our model served.
docker run -p 8501:8501 <your-container-name>
And that’s it we have a container with our model built-in. Before we move on to the next step please give this link a visit which discusses how you can specify the model configuration and versioning which could be very handy.
Now we will deploy the docker image on Google Cloud using Kubernetes. Before we move on with the setup let’s first have a quick glance at Kubernetes. In short, Kubernetes helps automate the process of deploying, scaling, and managing containerized applications. In a production environment, it is needed to manage the containers and make sure that they are always up and available and there is no downtime, this is where Kubernetes comes into play and help scale your containarized apps. It can offer load-balancing, self-healing, resource utilization in the best possible way. Do give the official Kubernetes docs a visit to get a deeper understanding of how it works.
When you deploy Kubernetes you get a cluster and every cluster will have at least one worker node.
A few terminologies to keep in mind when using Kubernetes.
Node — A node is basically a worker machine that runs a containerized app.
POD — The worker nodes host POD’s and a POD is a group of one or more containers, where each POD has a unique IP-address and a namespace.
YAML — A file for configuring Kubernetes.
Deployment — Specify the number of replicas of a POD you want to run. Deployment ensures then that the replicas are up and running in the cluster.
Service — An abstraction to define a policy on how to access the POD’s, which is connected to the deployment.
For this, you first need to set up an account on Google Cloud. Once you have an account set up, install the google-sdk from this link. Next head over to Google Cloud Console and create a new project I have called mine tensorflow-training.
Now head over to the terminal and run gcloud init this will ask you a couple of straight-forward questions and once you are done with this you will be authenticated with your google cloud account.
Next, run gcloud config set project [your-project-id] to set the project you just created above. To get the project id you can go to the gcp console and from the dropdown next to the search bar you can select the project-id.
Now we are all ready and set-up to create a Kubernetes Engine for the service deployment. For this follow the below steps.
Enable the Kubernetes Engine Api in cloud console by going into API & Services -> Enable API -> Kubernetes Engine Api
gcloud container clusters create mnist-digit-cluster — num-nodes 2 --zone <specify-the-zone>
Next we will set the default cluster for gcloud container command by running gcloud config set container/cluster mnist-digit-cluster
Now we will pass cluster credentials to kubectl gcloud container clusters get-credentials mnist-digit-cluster —- zone <specify-the-zone>
After this, we will upload our docker image to the Google Container Registry so that we are able to run it on the GCP.
First we will tag our image using Container Registry format and our project name by running docker tag <container-name> gcr.io/<project-id>/<image-name>
Note the image-name above can be different from the image name on the local-machine.
Next we configure docker to use gcloud as credential-helper by running gcloud auth configure-docker
Now we are all set to push our docker image to the registry. docker push gcr.io/<project-id>/<image-name
We are almost there, now we need to create a yaml config file for creating a deployment, so head into your favorite text editor and paste the following content in a file and save on your local-disk with .yaml extension. Please update the yaml file with your project-id and image-name and I also suggest that you look into the available options for configuring.
apiVersion: apps/v1kind: Deploymentmetadata: name: mnist-deploymentspec: replicas: 3 selector: matchLabels: app: mnist-server template: metadata: labels: app: mnist-server spec: containers: - name: <image-name> image: gcr.io/<project-id>/<image-name> ports: - containerPort: 8501---apiVersion: v1kind: Servicemetadata: labels: run: mnist-service name: mnist-servicespec: ports: - port: 8501 targetPort: 8501 selector: app: mnist-server type: LoadBalancer
Now you can run kubectl create -f <path-to-yaml-file> and if everything goes well you should be notified that both deployment and service were created. You can verify this by running the below commands in terminal
kubectl get deployments
kubectl get services
And now finally we can describe our service using kubectl describe service mnist-service note down the external ip-address listed next to LoadBalancer Ingress. This is the IP we can now use to query our deployed model from client applications.
The URL structure will be the same as above you just have to replace localhost with the above ip-address and that’s it. To quickly verify you can use the above python or js code-snippet to predict or just go to the below URL in the browser to make sure it all went well.
url = http://{ip}:8501/v1/models/<your-model-name>/versions/1
Now it’s time to host our converted tensorflow model in a cloud-storage bucket and load it in React-App using Tensorflow-JS. For this quickly head over to your google cloud console and navigate to storage. Create a bucket choose a name, and specify the location. Once the bucket is created you can either upload your tf-js model from the UI or from the command line by running the below command in the terminal.
Make sure that you have the converted model.json file and the companion group1-shard.bin file.
gsutil cp -r <path-to-tf-js-model-dir> gs://<bucket-name>/
Now that we have uploaded the model json file in the bucket we need to make the files public to be accessible for the client-apps and enable cors on the created bucket. For cors please read here for a detailed explanation.
Make the files public by navigating to the files in the bucket and click Edit Permissions where you can add an entry for Public. Do this for both model.json & group1-shard1of1.bin file. Once marked public, copy the public-url for model.json file which will be needed for loading the model.
For enabling cors on the bucket head over to google console and active Google Cloud Shell.
Once you are in the shell type
//Allowing every domain to access your bucket.echo '[{"origin": ["*"],"responseHeader": ["Content-Type"],"method": ["GET", "HEAD"],"maxAgeSeconds": 3600}]' > cors-config.jsongsutil cors set cors-config.json gs://<bucket-name>
Now we are all set to load the model in our client-app using tensorflow-js.
To explore the source-code head over to the github-repo.
github.com
Here’s our deployed model in action.
|
[
{
"code": null,
"e": 873,
"s": 172,
"text": "This article focuses on deploying machine learning models using mnist handwritten digit recognition as a base example implemented in tensorflow-2. In the end, we will be cooking up a small web app in React to test our model. If you are a machine learning enthusiast then you already know that mnist digit recognition is the hello world program of deep learning and by far you have already seen way too many articles about digit-recognition on medium and probably implemented that already which is exactly why I won’t be focusing too much on the problem itself and instead show you how you can deploy your models and consume them in production. To see the end result you can view the deployed-app here"
},
{
"code": null,
"e": 1222,
"s": 873,
"text": "Before jumping into deployments I will quickly give you a brief walkthrough of the model and show you how you can save your model and consume it in production later on. If you are tired of reading about handwritten-digit-recognition like me you can skip this portion and use the github-repo to get the model so you can follow the rest of the guide."
},
{
"code": null,
"e": 1238,
"s": 1222,
"text": "Libraries used."
},
{
"code": null,
"e": 1251,
"s": 1238,
"text": "Tensorflow 2"
},
{
"code": null,
"e": 1262,
"s": 1251,
"text": "Matplotlip"
},
{
"code": null,
"e": 1268,
"s": 1262,
"text": "Numpy"
},
{
"code": null,
"e": 1370,
"s": 1268,
"text": "For pre-processing the data I am just normalizing the pixel values in 0–1 range by dividing with 255."
},
{
"code": null,
"e": 1754,
"s": 1370,
"text": "Once we have the data loaded and pre-processed I am using a convolutional-net with 2 conv-layers each followed by a max-pooling layer which is then flattened before it’s passed on to a dense layer with 128 units and finally our output layer has 10-units and its using softmax as the activation function which turns the end result to probabilities and distributes it over our classes."
},
{
"code": null,
"e": 2335,
"s": 1754,
"text": "For training the model I am using tensorboard, early-stopping, and model-checkpoint callbacks for gathering information during the training process. Tensorboard is a very handy tool in the tensorflow ecosystem, it lets you visualize your training process, model-graphs, and provides useful metrics that help you a lot in representing and sharing your findings and quickly experiment. Early-Stopping is also a very useful call-back that lets you monitor a very specific metric and stops training if that metric is not improving over time. This saves us from over-fitting our model."
},
{
"code": null,
"e": 2691,
"s": 2335,
"text": "Now that we have trained the model we will save our model in protobuf format which is the default-format in tensorflow-2. Note that we are saving the model in a sub-folder named 1. The reason is that tensorflow-serving uses this convention to load the model version you specify. By default, the server will serve the model with the largest version number."
},
{
"code": null,
"e": 3065,
"s": 2691,
"text": "The last part would be to convert our model to work with tensorflow-js in the browser and for that purpose, we will use tensorflow-converter which helps us convert our pre-trained tensorflow models in python to work in the browser using tensorflow-js. Install and run the tool using the below command and provide the path to your saved model directory when the wizard asks."
},
{
"code": null,
"e": 3117,
"s": 3065,
"text": "pip install tensorflowjs[wizard]tensorflowjs_wizard"
},
{
"code": null,
"e": 3352,
"s": 3117,
"text": "If you have followed all the steps till here and have been successfully able to save a model congratulations you are halfway through the journey. Now you have a model that you can deploy in the cloud and use from various applications."
},
{
"code": null,
"e": 4616,
"s": 3352,
"text": "Before we begin with the deployments part lets quickly go through an alternative approach which is also widely used and implemented via a Flask app or an express-server or any other api-framework to serve the model which is not a very efficient way of serving your models in production, the reason being that those frameworks are primarily designed for HTTP requests/response and do not account for your machine’s hardware capability when making inferences. Similarly, it could be hard to standardize the way you load and serve your model via a rest end-point and when you have multiple models/projects being worked on. One of the biggest advantage of using tensorflow-serving over Flask is that it is primarily built for serving flexible and scalable ML models in production and has been battle-tested. Plus it has support for model versioning and serving many models with many versions and it scales really well. However, Flask or any other API-framework that you use can come in very handy if they are used as a middle layer between the client and tensorflow-serving, handling the routing for different tf-servers and preprocessing the data before sending it over to the model for prediction. You can visit this article for a much better understanding of this."
},
{
"code": null,
"e": 4921,
"s": 4616,
"text": "Now we can get on with the deployment part, I will be using Google Cloud to deploy the models and go step by step into the various cloud services that are available to you. Google cloud and tensorflow integrate quite well, we will be looking in particular at these three options that are available to us."
},
{
"code": null,
"e": 4941,
"s": 4921,
"text": "Tensorflow-Serving."
},
{
"code": null,
"e": 4965,
"s": 4941,
"text": "AI-Platform-Predictions"
},
{
"code": null,
"e": 4981,
"s": 4965,
"text": "Cloud-Functions"
},
{
"code": null,
"e": 5119,
"s": 4981,
"text": "In the first part of this series, we will be using tensorflow-serving, followed by AI-Platform and cloud functions in the next two parts."
},
{
"code": null,
"e": 5487,
"s": 5119,
"text": "Tensorflow serving is a part of the tensorflow extended ecosystem, one of the key benefits of tensorflow serving is that it’s highly scalable and has low latency. Tensorflow serving has the capability to serve multiple models and versions which is a potential use-case when you are going in production you might need to update your models and serve multiple versions."
},
{
"code": null,
"e": 5697,
"s": 5487,
"text": "We will be using tensorflow-serving with docker which is very easy and quick to get started with. Before following the next steps head over to the docker-website and install the docker-desktop app for your OS."
},
{
"code": null,
"e": 5808,
"s": 5697,
"text": "// from terminal pull the tensorflow-serving docker image docker pull tensorflow/serving"
},
{
"code": null,
"e": 5944,
"s": 5808,
"text": "The tensorflow serving image has port 8500 exposed for gRPC whereas port 8501 is exposed for REST-API. Now to serve with docker we need"
},
{
"code": null,
"e": 6015,
"s": 5944,
"text": "A saved-model that we want to serve. (We have already saved our model)"
},
{
"code": null,
"e": 6092,
"s": 6015,
"text": "We need to open up a port on our host on which we will be serving the model."
},
{
"code": null,
"e": 6175,
"s": 6092,
"text": "A name for our model which the client applications will use to refer to the model."
},
{
"code": null,
"e": 6214,
"s": 6175,
"text": "Next in the terminal run the below com"
},
{
"code": null,
"e": 6371,
"s": 6214,
"text": "docker run -p 8501:8501 --mount type=bind,source=<path-to-your-model>,target=/models/mnist-digit-model -e MODEL_NAME=mnist-digit-recog -t tensorflow/serving"
},
{
"code": null,
"e": 6977,
"s": 6371,
"text": "Please note the path would be to the root folder of your model and not the sub-folder which specifies the model-version. With the above command, we have basically started a docker container and binded the rest-api port with the host port 8501. Next, we are bounding our saved model path to the default model path i.e models/mnist-digit-recog. After which we have specified the environment variable name and set it to mnist-digit-recog and that is it, if you have followed the steps till here properly you should have a docker image running with tensorflow-serving and your model being served on port 8501."
},
{
"code": null,
"e": 7053,
"s": 6977,
"text": "Note if you want to expose the gRPC port too you can run the below command."
},
{
"code": null,
"e": 7223,
"s": 7053,
"text": "docker run -p 8501:8501 -p 8500:8500 --mount type=bind,source=<path-to-your-model>,target=/models/mnist-digit-model -e MODEL_NAME=mnist-digit-recog -t tensorflow/serving"
},
{
"code": null,
"e": 7312,
"s": 7223,
"text": "If everything ran successfully you should have similar output on your terminal as below."
},
{
"code": null,
"e": 7409,
"s": 7312,
"text": "If you want to explore tensorflow-serving with docker I suggest you look into the official docs."
},
{
"code": null,
"e": 7555,
"s": 7409,
"text": "Now that we have tensorflow serving our model, let’s quickly test this by making a post request, and verify that everything is working correctly."
},
{
"code": null,
"e": 7594,
"s": 7555,
"text": "The REST url structure is given below:"
},
{
"code": null,
"e": 7831,
"s": 7594,
"text": "HOST = localhostPORT = 8501MODEL_NAME = mnist-digit-recogMODEL_VERSION = 1// Defaulthttp://{HOST}:{PORT}/v1/models/{MODEL_NAME}:predict// Specific Model-Versionhttp://{HOST}:{PORT}/v1/models/{MODEL_NAME}/versions/{MODEL_VERSION}:predict"
},
{
"code": null,
"e": 8050,
"s": 7831,
"text": "We can use the below piece of code to quickly test that the model is being served properly. Load up the notebook from the attached github-repo above and in a new cell paste the code below and run it to see the results."
},
{
"code": null,
"e": 8243,
"s": 8050,
"text": "Similarly, you can now call this end-point from any client-side application and voila you should have the predicted digit. For instance, if you are a JS fan you can use the below code snippet."
},
{
"code": null,
"e": 8748,
"s": 8243,
"text": "Awesome now if we want to create our own docker-image that has our model built-in we can do that by first running the serving image as a daemon and then copy our saved model to the containers model folder. For that quickly follow the steps from the official tensorflow-serving guide here. You can name your container whatever you want, I have called mine mnist-digit-container and now we don’t have to bind our model path or do any extra config. We can just run the below command to get our model served."
},
{
"code": null,
"e": 8794,
"s": 8748,
"text": "docker run -p 8501:8501 <your-container-name>"
},
{
"code": null,
"e": 9020,
"s": 8794,
"text": "And that’s it we have a container with our model built-in. Before we move on to the next step please give this link a visit which discusses how you can specify the model configuration and versioning which could be very handy."
},
{
"code": null,
"e": 9690,
"s": 9020,
"text": "Now we will deploy the docker image on Google Cloud using Kubernetes. Before we move on with the setup let’s first have a quick glance at Kubernetes. In short, Kubernetes helps automate the process of deploying, scaling, and managing containerized applications. In a production environment, it is needed to manage the containers and make sure that they are always up and available and there is no downtime, this is where Kubernetes comes into play and help scale your containarized apps. It can offer load-balancing, self-healing, resource utilization in the best possible way. Do give the official Kubernetes docs a visit to get a deeper understanding of how it works."
},
{
"code": null,
"e": 9789,
"s": 9690,
"text": "When you deploy Kubernetes you get a cluster and every cluster will have at least one worker node."
},
{
"code": null,
"e": 9848,
"s": 9789,
"text": "A few terminologies to keep in mind when using Kubernetes."
},
{
"code": null,
"e": 9923,
"s": 9848,
"text": "Node — A node is basically a worker machine that runs a containerized app."
},
{
"code": null,
"e": 10061,
"s": 9923,
"text": "POD — The worker nodes host POD’s and a POD is a group of one or more containers, where each POD has a unique IP-address and a namespace."
},
{
"code": null,
"e": 10103,
"s": 10061,
"text": "YAML — A file for configuring Kubernetes."
},
{
"code": null,
"e": 10250,
"s": 10103,
"text": "Deployment — Specify the number of replicas of a POD you want to run. Deployment ensures then that the replicas are up and running in the cluster."
},
{
"code": null,
"e": 10360,
"s": 10250,
"text": "Service — An abstraction to define a policy on how to access the POD’s, which is connected to the deployment."
},
{
"code": null,
"e": 10599,
"s": 10360,
"text": "For this, you first need to set up an account on Google Cloud. Once you have an account set up, install the google-sdk from this link. Next head over to Google Cloud Console and create a new project I have called mine tensorflow-training."
},
{
"code": null,
"e": 10796,
"s": 10599,
"text": "Now head over to the terminal and run gcloud init this will ask you a couple of straight-forward questions and once you are done with this you will be authenticated with your google cloud account."
},
{
"code": null,
"e": 11021,
"s": 10796,
"text": "Next, run gcloud config set project [your-project-id] to set the project you just created above. To get the project id you can go to the gcp console and from the dropdown next to the search bar you can select the project-id."
},
{
"code": null,
"e": 11144,
"s": 11021,
"text": "Now we are all ready and set-up to create a Kubernetes Engine for the service deployment. For this follow the below steps."
},
{
"code": null,
"e": 11262,
"s": 11144,
"text": "Enable the Kubernetes Engine Api in cloud console by going into API & Services -> Enable API -> Kubernetes Engine Api"
},
{
"code": null,
"e": 11355,
"s": 11262,
"text": "gcloud container clusters create mnist-digit-cluster — num-nodes 2 --zone <specify-the-zone>"
},
{
"code": null,
"e": 11488,
"s": 11355,
"text": "Next we will set the default cluster for gcloud container command by running gcloud config set container/cluster mnist-digit-cluster"
},
{
"code": null,
"e": 11625,
"s": 11488,
"text": "Now we will pass cluster credentials to kubectl gcloud container clusters get-credentials mnist-digit-cluster —- zone <specify-the-zone>"
},
{
"code": null,
"e": 11744,
"s": 11625,
"text": "After this, we will upload our docker image to the Google Container Registry so that we are able to run it on the GCP."
},
{
"code": null,
"e": 11897,
"s": 11744,
"text": "First we will tag our image using Container Registry format and our project name by running docker tag <container-name> gcr.io/<project-id>/<image-name>"
},
{
"code": null,
"e": 11982,
"s": 11897,
"text": "Note the image-name above can be different from the image name on the local-machine."
},
{
"code": null,
"e": 12082,
"s": 11982,
"text": "Next we configure docker to use gcloud as credential-helper by running gcloud auth configure-docker"
},
{
"code": null,
"e": 12187,
"s": 12082,
"text": "Now we are all set to push our docker image to the registry. docker push gcr.io/<project-id>/<image-name"
},
{
"code": null,
"e": 12548,
"s": 12187,
"text": "We are almost there, now we need to create a yaml config file for creating a deployment, so head into your favorite text editor and paste the following content in a file and save on your local-disk with .yaml extension. Please update the yaml file with your project-id and image-name and I also suggest that you look into the available options for configuring."
},
{
"code": null,
"e": 13079,
"s": 12548,
"text": "apiVersion: apps/v1kind: Deploymentmetadata: name: mnist-deploymentspec: replicas: 3 selector: matchLabels: app: mnist-server template: metadata: labels: app: mnist-server spec: containers: - name: <image-name> image: gcr.io/<project-id>/<image-name> ports: - containerPort: 8501---apiVersion: v1kind: Servicemetadata: labels: run: mnist-service name: mnist-servicespec: ports: - port: 8501 targetPort: 8501 selector: app: mnist-server type: LoadBalancer"
},
{
"code": null,
"e": 13293,
"s": 13079,
"text": "Now you can run kubectl create -f <path-to-yaml-file> and if everything goes well you should be notified that both deployment and service were created. You can verify this by running the below commands in terminal"
},
{
"code": null,
"e": 13317,
"s": 13293,
"text": "kubectl get deployments"
},
{
"code": null,
"e": 13338,
"s": 13317,
"text": "kubectl get services"
},
{
"code": null,
"e": 13582,
"s": 13338,
"text": "And now finally we can describe our service using kubectl describe service mnist-service note down the external ip-address listed next to LoadBalancer Ingress. This is the IP we can now use to query our deployed model from client applications."
},
{
"code": null,
"e": 13853,
"s": 13582,
"text": "The URL structure will be the same as above you just have to replace localhost with the above ip-address and that’s it. To quickly verify you can use the above python or js code-snippet to predict or just go to the below URL in the browser to make sure it all went well."
},
{
"code": null,
"e": 13915,
"s": 13853,
"text": "url = http://{ip}:8501/v1/models/<your-model-name>/versions/1"
},
{
"code": null,
"e": 14327,
"s": 13915,
"text": "Now it’s time to host our converted tensorflow model in a cloud-storage bucket and load it in React-App using Tensorflow-JS. For this quickly head over to your google cloud console and navigate to storage. Create a bucket choose a name, and specify the location. Once the bucket is created you can either upload your tf-js model from the UI or from the command line by running the below command in the terminal."
},
{
"code": null,
"e": 14422,
"s": 14327,
"text": "Make sure that you have the converted model.json file and the companion group1-shard.bin file."
},
{
"code": null,
"e": 14481,
"s": 14422,
"text": "gsutil cp -r <path-to-tf-js-model-dir> gs://<bucket-name>/"
},
{
"code": null,
"e": 14704,
"s": 14481,
"text": "Now that we have uploaded the model json file in the bucket we need to make the files public to be accessible for the client-apps and enable cors on the created bucket. For cors please read here for a detailed explanation."
},
{
"code": null,
"e": 14994,
"s": 14704,
"text": "Make the files public by navigating to the files in the bucket and click Edit Permissions where you can add an entry for Public. Do this for both model.json & group1-shard1of1.bin file. Once marked public, copy the public-url for model.json file which will be needed for loading the model."
},
{
"code": null,
"e": 15085,
"s": 14994,
"text": "For enabling cors on the bucket head over to google console and active Google Cloud Shell."
},
{
"code": null,
"e": 15116,
"s": 15085,
"text": "Once you are in the shell type"
},
{
"code": null,
"e": 15342,
"s": 15116,
"text": "//Allowing every domain to access your bucket.echo '[{\"origin\": [\"*\"],\"responseHeader\": [\"Content-Type\"],\"method\": [\"GET\", \"HEAD\"],\"maxAgeSeconds\": 3600}]' > cors-config.jsongsutil cors set cors-config.json gs://<bucket-name>"
},
{
"code": null,
"e": 15418,
"s": 15342,
"text": "Now we are all set to load the model in our client-app using tensorflow-js."
},
{
"code": null,
"e": 15475,
"s": 15418,
"text": "To explore the source-code head over to the github-repo."
},
{
"code": null,
"e": 15486,
"s": 15475,
"text": "github.com"
}
] |
jQuery - load() Method
|
The load( url, data, callback ) method loads data from the server and places the returned HTML into the matched element.
Here is the simple syntax to use this method −
[selector].load( url, [data], [callback] )
Here is the description of all the parameters used by this method −
url − A string containing the URL to which the request is sent.
url − A string containing the URL to which the request is sent.
data − This optional parameter represents a map of data that is sent with the request.
data − This optional parameter represents a map of data that is sent with the request.
callback − This optional parameter represents a function that is executed if the request succeeds
callback − This optional parameter represents a function that is executed if the request succeeds
Assuming we have following HTML content in result.html file −
<h1>THIS IS RESULT...</h1>
Following is a simple example a simple showing the usage of this method.
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#driver").click(function(event){
$('#stage').load('result.html');
});
});
</script>
</head>
<body>
<p>Click on the button to load result.html file:</p>
<div id = "stage" style = "background-color:cc0;">
STAGE
</div>
<input type = "button" id = "driver" value = "Load Data" />
</body>
</html>
This should produce following result −
Click on the button to load result.html file −
27 Lectures
1 hours
Mahesh Kumar
27 Lectures
1.5 hours
Pratik Singh
72 Lectures
4.5 hours
Frahaan Hussain
60 Lectures
9 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Sandip Bhattacharya
12 Lectures
53 mins
Laurence Svekis
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2443,
"s": 2322,
"text": "The load( url, data, callback ) method loads data from the server and places the returned HTML into the matched element."
},
{
"code": null,
"e": 2490,
"s": 2443,
"text": "Here is the simple syntax to use this method −"
},
{
"code": null,
"e": 2534,
"s": 2490,
"text": "[selector].load( url, [data], [callback] )\n"
},
{
"code": null,
"e": 2602,
"s": 2534,
"text": "Here is the description of all the parameters used by this method −"
},
{
"code": null,
"e": 2666,
"s": 2602,
"text": "url − A string containing the URL to which the request is sent."
},
{
"code": null,
"e": 2730,
"s": 2666,
"text": "url − A string containing the URL to which the request is sent."
},
{
"code": null,
"e": 2817,
"s": 2730,
"text": "data − This optional parameter represents a map of data that is sent with the request."
},
{
"code": null,
"e": 2904,
"s": 2817,
"text": "data − This optional parameter represents a map of data that is sent with the request."
},
{
"code": null,
"e": 3002,
"s": 2904,
"text": "callback − This optional parameter represents a function that is executed if the request succeeds"
},
{
"code": null,
"e": 3100,
"s": 3002,
"text": "callback − This optional parameter represents a function that is executed if the request succeeds"
},
{
"code": null,
"e": 3162,
"s": 3100,
"text": "Assuming we have following HTML content in result.html file −"
},
{
"code": null,
"e": 3190,
"s": 3162,
"text": "<h1>THIS IS RESULT...</h1>\n"
},
{
"code": null,
"e": 3263,
"s": 3190,
"text": "Following is a simple example a simple showing the usage of this method."
},
{
"code": null,
"e": 3965,
"s": 3263,
"text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"#driver\").click(function(event){\n $('#stage').load('result.html');\n });\n });\n </script>\n </head>\n\t\n <body>\n <p>Click on the button to load result.html file:</p>\n\t\t\n <div id = \"stage\" style = \"background-color:cc0;\">\n STAGE\n </div>\n\t\t\n <input type = \"button\" id = \"driver\" value = \"Load Data\" />\n </body>\n</html>"
},
{
"code": null,
"e": 4004,
"s": 3965,
"text": "This should produce following result −"
},
{
"code": null,
"e": 4051,
"s": 4004,
"text": "Click on the button to load result.html file −"
},
{
"code": null,
"e": 4084,
"s": 4051,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4098,
"s": 4084,
"text": " Mahesh Kumar"
},
{
"code": null,
"e": 4133,
"s": 4098,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4147,
"s": 4133,
"text": " Pratik Singh"
},
{
"code": null,
"e": 4182,
"s": 4147,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4199,
"s": 4182,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4232,
"s": 4199,
"text": "\n 60 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 4260,
"s": 4232,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4293,
"s": 4260,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4314,
"s": 4293,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 4346,
"s": 4314,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 4363,
"s": 4346,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 4370,
"s": 4363,
"text": " Print"
},
{
"code": null,
"e": 4381,
"s": 4370,
"text": " Add Notes"
}
] |
Open Specific Settings Using Android Application - GeeksforGeeks
|
05 Nov, 2020
In android development, the phase comes where the app needs specific settings to be modified manually by the user. So at that time developer directs the user to open specific settings and modify them. So in this article, it has been discussed how to open specific settings and make the user change them easily.
Step 1: Create a new Empty Activity android project
While creating a new android studio project give the name of the project as “Open specific settings”.
You may refer: Android | How to Create/Start a New Project in Android Studio?
Select Kotlin as the language, and layout name as activity_main.xml.
Step 2: You may change the color combination of the application
You may change the color combination of the base theme of the application. To change it open app -> src -> main -> res -> values -> colors.xml.
Invoke the following code in colors.xml.
XML
<?xml version="1.0" encoding="utf-8"?><resources> <color name="colorPrimary">#0f9d58</color> <color name="colorPrimaryDark">#006d2d</color> <color name="colorAccent">#55cf86</color></resources>
You may refer to the following image to get the colors.xml file.
Step 3: Working with the activity_main.xml
Here, Buttons are used to open each of the specific settings. There are many different settings in android out of all of the seven that are most commonly used. So seven buttons are added to the activity layout.
Invoke the following code inside activity_main.xml:
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--Make sure to give appropriate IDs to all buttons so that can be easily handled--> <!--Button to open wireless settings--> <Button android:id="@+id/wireless_settings" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:backgroundTint="@color/colorPrimary" android:text="Open Wireless Settings" android:textColor="@android:color/white" /> <!--Button to open wifi settings--> <Button android:id="@+id/wifi_settings" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:backgroundTint="@color/colorPrimary" android:text="Open Wi-Fi Settings" android:textColor="@android:color/white" /> <!--Button to open bluetooth settings--> <Button android:id="@+id/bluetooth_settings" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:backgroundTint="@color/colorPrimary" android:text="Open Bluetooth Settings" android:textColor="@android:color/white" /> <!--Button to open date settings--> <Button android:id="@+id/date_settings" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:backgroundTint="@color/colorPrimary" android:text="Open Date Settings" android:textColor="@android:color/white" /> <!--Button to open input method settings--> <Button android:id="@+id/input_method_settings" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:backgroundTint="@color/colorPrimary" android:text="Open Input Method Settings" android:textColor="@android:color/white" /> <!--Button to open display settings--> <Button android:id="@+id/display_settings" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:backgroundTint="@color/colorPrimary" android:text="Open Display Settings" android:textColor="@android:color/white" /> <!--Button to open Location settings--> <Button android:id="@+id/location_settings" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:backgroundTint="@color/colorPrimary" android:text="Open Location Settings" android:textColor="@android:color/white" /> </LinearLayout>
The following output UI is produced:
Step 4: Working with the MainActivity.kt file
You may refer: Buttons in Kotlin to know how to handle the button clicks through setOnClickListener using Kotlin.
In this case, implicit intents are used you may refer: Android | Implicit and Explicit Intents with Examples for implicit intents.
Invoke the following code to handle all the buttons.
Kotlin
import android.content.Intentimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.provider.Settings.*import android.view.Viewimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Handle wireless settings button wireless_settings?.setOnClickListener(View.OnClickListener{ val i = Intent(ACTION_WIRELESS_SETTINGS) startActivity(i) }) // Handle wifi settings button wifi_settings?.setOnClickListener(View.OnClickListener{ val i = Intent(ACTION_WIFI_SETTINGS) startActivity(i) }) // Handle bluetooth settings button bluetooth_settings?.setOnClickListener(View.OnClickListener{ val i = Intent(ACTION_BLUETOOTH_SETTINGS) startActivity(i) }) // Handle date settings button date_settings?.setOnClickListener(View.OnClickListener{ val i = Intent(ACTION_DATE_SETTINGS) startActivity(i) }) // Handle input method settings button input_method_settings?.setOnClickListener(View.OnClickListener{ val i = Intent(ACTION_INPUT_METHOD_SETTINGS) startActivity(i) }) // Handle display settings button display_settings?.setOnClickListener(View.OnClickListener{ val i = Intent(ACTION_DISPLAY_SETTINGS) startActivity(i) }) // Handle location settings button location_settings?.setOnClickListener(View.OnClickListener{ val i = Intent(ACTION_LOCATION_SOURCE_SETTINGS) startActivity(i) }) }}
Note: Make sure to import the android.provider.Settings package to import all the settings class in the project:
import android.provider.Settings.*
adityamshidlyali
android
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Android Listview in Java with Example
Retrofit with Kotlin Coroutine in Android
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
|
[
{
"code": null,
"e": 24725,
"s": 24697,
"text": "\n05 Nov, 2020"
},
{
"code": null,
"e": 25036,
"s": 24725,
"text": "In android development, the phase comes where the app needs specific settings to be modified manually by the user. So at that time developer directs the user to open specific settings and modify them. So in this article, it has been discussed how to open specific settings and make the user change them easily."
},
{
"code": null,
"e": 25088,
"s": 25036,
"text": "Step 1: Create a new Empty Activity android project"
},
{
"code": null,
"e": 25190,
"s": 25088,
"text": "While creating a new android studio project give the name of the project as “Open specific settings”."
},
{
"code": null,
"e": 25268,
"s": 25190,
"text": "You may refer: Android | How to Create/Start a New Project in Android Studio?"
},
{
"code": null,
"e": 25337,
"s": 25268,
"text": "Select Kotlin as the language, and layout name as activity_main.xml."
},
{
"code": null,
"e": 25401,
"s": 25337,
"text": "Step 2: You may change the color combination of the application"
},
{
"code": null,
"e": 25545,
"s": 25401,
"text": "You may change the color combination of the base theme of the application. To change it open app -> src -> main -> res -> values -> colors.xml."
},
{
"code": null,
"e": 25586,
"s": 25545,
"text": "Invoke the following code in colors.xml."
},
{
"code": null,
"e": 25590,
"s": 25586,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"colorPrimary\">#0f9d58</color> <color name=\"colorPrimaryDark\">#006d2d</color> <color name=\"colorAccent\">#55cf86</color></resources>",
"e": 25793,
"s": 25590,
"text": null
},
{
"code": null,
"e": 25858,
"s": 25793,
"text": "You may refer to the following image to get the colors.xml file."
},
{
"code": null,
"e": 25902,
"s": 25858,
"text": "Step 3: Working with the activity_main.xml "
},
{
"code": null,
"e": 26113,
"s": 25902,
"text": "Here, Buttons are used to open each of the specific settings. There are many different settings in android out of all of the seven that are most commonly used. So seven buttons are added to the activity layout."
},
{
"code": null,
"e": 26165,
"s": 26113,
"text": "Invoke the following code inside activity_main.xml:"
},
{
"code": null,
"e": 26169,
"s": 26165,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <!--Make sure to give appropriate IDs to all buttons so that can be easily handled--> <!--Button to open wireless settings--> <Button android:id=\"@+id/wireless_settings\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"8dp\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"Open Wireless Settings\" android:textColor=\"@android:color/white\" /> <!--Button to open wifi settings--> <Button android:id=\"@+id/wifi_settings\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"8dp\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"Open Wi-Fi Settings\" android:textColor=\"@android:color/white\" /> <!--Button to open bluetooth settings--> <Button android:id=\"@+id/bluetooth_settings\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"8dp\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"Open Bluetooth Settings\" android:textColor=\"@android:color/white\" /> <!--Button to open date settings--> <Button android:id=\"@+id/date_settings\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"8dp\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"Open Date Settings\" android:textColor=\"@android:color/white\" /> <!--Button to open input method settings--> <Button android:id=\"@+id/input_method_settings\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"8dp\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"Open Input Method Settings\" android:textColor=\"@android:color/white\" /> <!--Button to open display settings--> <Button android:id=\"@+id/display_settings\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"8dp\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"Open Display Settings\" android:textColor=\"@android:color/white\" /> <!--Button to open Location settings--> <Button android:id=\"@+id/location_settings\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"8dp\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"Open Location Settings\" android:textColor=\"@android:color/white\" /> </LinearLayout>",
"e": 29190,
"s": 26169,
"text": null
},
{
"code": null,
"e": 29228,
"s": 29190,
"text": "The following output UI is produced: "
},
{
"code": null,
"e": 29275,
"s": 29228,
"text": "Step 4: Working with the MainActivity.kt file "
},
{
"code": null,
"e": 29389,
"s": 29275,
"text": "You may refer: Buttons in Kotlin to know how to handle the button clicks through setOnClickListener using Kotlin."
},
{
"code": null,
"e": 29520,
"s": 29389,
"text": "In this case, implicit intents are used you may refer: Android | Implicit and Explicit Intents with Examples for implicit intents."
},
{
"code": null,
"e": 29573,
"s": 29520,
"text": "Invoke the following code to handle all the buttons."
},
{
"code": null,
"e": 29580,
"s": 29573,
"text": "Kotlin"
},
{
"code": "import android.content.Intentimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.provider.Settings.*import android.view.Viewimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Handle wireless settings button wireless_settings?.setOnClickListener(View.OnClickListener{ val i = Intent(ACTION_WIRELESS_SETTINGS) startActivity(i) }) // Handle wifi settings button wifi_settings?.setOnClickListener(View.OnClickListener{ val i = Intent(ACTION_WIFI_SETTINGS) startActivity(i) }) // Handle bluetooth settings button bluetooth_settings?.setOnClickListener(View.OnClickListener{ val i = Intent(ACTION_BLUETOOTH_SETTINGS) startActivity(i) }) // Handle date settings button date_settings?.setOnClickListener(View.OnClickListener{ val i = Intent(ACTION_DATE_SETTINGS) startActivity(i) }) // Handle input method settings button input_method_settings?.setOnClickListener(View.OnClickListener{ val i = Intent(ACTION_INPUT_METHOD_SETTINGS) startActivity(i) }) // Handle display settings button display_settings?.setOnClickListener(View.OnClickListener{ val i = Intent(ACTION_DISPLAY_SETTINGS) startActivity(i) }) // Handle location settings button location_settings?.setOnClickListener(View.OnClickListener{ val i = Intent(ACTION_LOCATION_SOURCE_SETTINGS) startActivity(i) }) }}",
"e": 31521,
"s": 29580,
"text": null
},
{
"code": null,
"e": 31635,
"s": 31521,
"text": "Note: Make sure to import the android.provider.Settings package to import all the settings class in the project: "
},
{
"code": null,
"e": 31670,
"s": 31635,
"text": "import android.provider.Settings.*"
},
{
"code": null,
"e": 31687,
"s": 31670,
"text": "adityamshidlyali"
},
{
"code": null,
"e": 31695,
"s": 31687,
"text": "android"
},
{
"code": null,
"e": 31703,
"s": 31695,
"text": "Android"
},
{
"code": null,
"e": 31708,
"s": 31703,
"text": "Java"
},
{
"code": null,
"e": 31713,
"s": 31708,
"text": "Java"
},
{
"code": null,
"e": 31721,
"s": 31713,
"text": "Android"
},
{
"code": null,
"e": 31819,
"s": 31721,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31828,
"s": 31819,
"text": "Comments"
},
{
"code": null,
"e": 31841,
"s": 31828,
"text": "Old Comments"
},
{
"code": null,
"e": 31880,
"s": 31841,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 31930,
"s": 31880,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 31981,
"s": 31930,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 32019,
"s": 31981,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 32061,
"s": 32019,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 32076,
"s": 32061,
"text": "Arrays in Java"
},
{
"code": null,
"e": 32120,
"s": 32076,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 32142,
"s": 32120,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 32167,
"s": 32142,
"text": "Reverse a string in Java"
}
] |
bitset::flip() in C++ STL - GeeksforGeeks
|
06 Jun, 2020
bitset::flip() is a built-in STL in C++ which flips the bits. If no parameter is passed in the function, then it flips all the bit values converting zeros to ones and ones to zeros. If a parameter position is passed, it flips the bit at the position only.
Syntax:
bitset_name.flip(int pos)
Parameter: The function accepts a parameter pos which is not mandatory. If a parameter pos is passed, it flips the bit at the index pos only(the index pos is calculated starting from the right). In case no parameter is passed, it flips all the bit values converting zeros to ones and ones to zeros.
Return Value: The function flips all the bit values according to the parameter passed or not and returns the new binary representation of the number.
Below programs illustrates the bitset::flip() function.
Program 1:
// CPP program to illustrate the// bitset::flip() function// when no parameter is passed#include <bits/stdc++.h>using namespace std; int main(){ // Initialization of bitset bitset<4> b1(string("1100")); bitset<6> b2(string("010010")); // Printing the bitset after flipping the bits cout << b1 << " after applying flip() function returns "; cout << b1.flip() << endl; cout << b2 << " after applying flip() function returns "; cout << b2.flip(); return 0;}
0011 after applying flip() function returns 1100
101101 after applying flip() function returns 010010
Program 2:
// CPP program to illustrate the// bitset::flip() function// when parameter is passed #include <bits/stdc++.h>using namespace std; int main(){ // Initialization of bitset bitset<4> b1(string("1100")); bitset<7> b2(string("0100100")); // Printing the bitset after flipping the bits cout << b1 << " after applying flip(3) function returns "; cout << b1.flip(3) << endl; cout << b2 << " after applying flip(6) function returns "; cout << b2.flip(6); return 0;}
0100 after applying flip(3) function returns 1100
1100100 after applying flip(6) function returns 0100100
koen1
CPP-bitset
CPP-Functions
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Convert string to char array in C++
List in C++ Standard Template Library (STL)
Iterators in C++ STL
std::string class in C++
Inline Functions in C++
|
[
{
"code": null,
"e": 24098,
"s": 24070,
"text": "\n06 Jun, 2020"
},
{
"code": null,
"e": 24354,
"s": 24098,
"text": "bitset::flip() is a built-in STL in C++ which flips the bits. If no parameter is passed in the function, then it flips all the bit values converting zeros to ones and ones to zeros. If a parameter position is passed, it flips the bit at the position only."
},
{
"code": null,
"e": 24362,
"s": 24354,
"text": "Syntax:"
},
{
"code": null,
"e": 24389,
"s": 24362,
"text": "bitset_name.flip(int pos)\n"
},
{
"code": null,
"e": 24688,
"s": 24389,
"text": "Parameter: The function accepts a parameter pos which is not mandatory. If a parameter pos is passed, it flips the bit at the index pos only(the index pos is calculated starting from the right). In case no parameter is passed, it flips all the bit values converting zeros to ones and ones to zeros."
},
{
"code": null,
"e": 24838,
"s": 24688,
"text": "Return Value: The function flips all the bit values according to the parameter passed or not and returns the new binary representation of the number."
},
{
"code": null,
"e": 24894,
"s": 24838,
"text": "Below programs illustrates the bitset::flip() function."
},
{
"code": null,
"e": 24905,
"s": 24894,
"text": "Program 1:"
},
{
"code": "// CPP program to illustrate the// bitset::flip() function// when no parameter is passed#include <bits/stdc++.h>using namespace std; int main(){ // Initialization of bitset bitset<4> b1(string(\"1100\")); bitset<6> b2(string(\"010010\")); // Printing the bitset after flipping the bits cout << b1 << \" after applying flip() function returns \"; cout << b1.flip() << endl; cout << b2 << \" after applying flip() function returns \"; cout << b2.flip(); return 0;}",
"e": 25394,
"s": 24905,
"text": null
},
{
"code": null,
"e": 25497,
"s": 25394,
"text": "0011 after applying flip() function returns 1100\n101101 after applying flip() function returns 010010\n"
},
{
"code": null,
"e": 25508,
"s": 25497,
"text": "Program 2:"
},
{
"code": "// CPP program to illustrate the// bitset::flip() function// when parameter is passed #include <bits/stdc++.h>using namespace std; int main(){ // Initialization of bitset bitset<4> b1(string(\"1100\")); bitset<7> b2(string(\"0100100\")); // Printing the bitset after flipping the bits cout << b1 << \" after applying flip(3) function returns \"; cout << b1.flip(3) << endl; cout << b2 << \" after applying flip(6) function returns \"; cout << b2.flip(6); return 0;}",
"e": 26003,
"s": 25508,
"text": null
},
{
"code": null,
"e": 26110,
"s": 26003,
"text": "0100 after applying flip(3) function returns 1100\n1100100 after applying flip(6) function returns 0100100\n"
},
{
"code": null,
"e": 26116,
"s": 26110,
"text": "koen1"
},
{
"code": null,
"e": 26127,
"s": 26116,
"text": "CPP-bitset"
},
{
"code": null,
"e": 26141,
"s": 26127,
"text": "CPP-Functions"
},
{
"code": null,
"e": 26145,
"s": 26141,
"text": "STL"
},
{
"code": null,
"e": 26149,
"s": 26145,
"text": "C++"
},
{
"code": null,
"e": 26153,
"s": 26149,
"text": "STL"
},
{
"code": null,
"e": 26157,
"s": 26153,
"text": "CPP"
},
{
"code": null,
"e": 26255,
"s": 26157,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26283,
"s": 26255,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26303,
"s": 26283,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 26327,
"s": 26303,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 26360,
"s": 26327,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 26404,
"s": 26360,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26440,
"s": 26404,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 26484,
"s": 26440,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26505,
"s": 26484,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 26530,
"s": 26505,
"text": "std::string class in C++"
}
] |
Neural Machine Translation (NMT) with Attention Mechanism | by Harshil Patel | Towards Data Science
|
It is an undeniable truth that in this era of globalization, language translation plays a vital role in communication among the denizens of different nation’s. Moreover, in a country like India - which a multilingual nation, language difference could be observed in its states itself! Hence, considering the importance of Language Translation, it becomes necessary to develop a system that could easily translate an unknown language to a known language.
In accordance with this, in this story, we will make a Deep Learning model that will translate English sentences to Marathi sentences. I have chosen Marathi language as it is easy for me to recognize. You can use any other language that is comfortable for you, as the model nearly remains the same. Moreover, I will try to briefly explain a major concept in language processing called Attention Mechanism here!
Working of Long Short Time Memory(LSTM) cellsWorking of TensorFlow, Keras and some other mandatory python libraries.
Working of Long Short Time Memory(LSTM) cells
Working of TensorFlow, Keras and some other mandatory python libraries.
The major drawback of encoder-decoder model in sequence to sequence recurrent neural network is that it can only work on short sequences. It is difficult for the encoder model to memorize long sequences and convert it into a fixed-length vector. Moreover, the decoder receives only one information that is the last encoder hidden state. Hence it's difficult for the decoder to summarize large input sequence at once. So, how do we overcome this problem?
How about if we give a vector representation from every encoder step to the decoder model!
Now, this is where the concept of ‘Attention Mechanism’ comes. The major intuition about this is that it predicts the next word by concentrating on a few relevant parts of the sequence rather than looking on the entire sequence.
In layman terms it can be described as an interference between encoder and decoder which extracts useful information from encoder and transmits it back to the decoder.
Refer here for detailed understanding about Attention Mechanism.
There are mainly two types of attention mechanism:
Global Attention
Local Attention
Global Attention are those attention in which all the hidden state vectors of the encoder are passed to get the context vector.
Local Attention are those attention in which only a few hidden state vectors of encoder are considered for the generation of context vector.
We will be using global attention in this story. Let’s now make use of attention mechanism and develop a language translator that will convert English sentence to Marathi sentence.
Open Jupyter Notebook and import some required libraries:
import pandas as pdfrom sklearn.model_selection import train_test_splitimport stringfrom string import digitsimport refrom sklearn.utils import shufflefrom tensorflow.keras.preprocessing.sequence import pad_sequencesfrom tensorflow.keras.layers import LSTM, Input, Dense,Embedding, Concatenate, TimeDistributedfrom tensorflow.keras.models import Model,load_model, model_from_jsonfrom tensorflow.keras.utils import plot_modelfrom tensorflow.keras.preprocessing.text import one_hot, Tokenizerfrom tensorflow.keras.callbacks import EarlyStoppingimport pickle as pklimport numpy as np
We will be working on a language dataset available here.
This site contains a dataset of numerous languages and its translation to English. You can download any language dataset as per your preference and comfort. However, remember to choose a dataset which is quite huge, so that we can get better results after training the model. Here, I will be downloading Marathi-English dataset which comprises of 38696 sentences.
After downloading load dataset, import the data as mentioned below:
with open('mar.txt','r') as f: data = f.read()
Data Transformation
As you can see that it is a raw text file and hence it is necessary to clean and transform it as per our preference. We will separate Marathi and English sentences and form a list of it, continuing it by storing it into a dataframe so that it's easy for us to reuse it again easily.
uncleaned_data_list = data.split('\n')len(uncleaned_data_list)uncleaned_data_list = uncleaned_data_list[:38695]len(uncleaned_data_list)english_word = []marathi_word = []cleaned_data_list = []for word in uncleaned_data_list: english_word.append(word.split('\t')[:-1][0]) marathi_word.append(word.split('\t')[:-1][1])language_data = pd.DataFrame(columns=['English','Marathi'])language_data['English'] = english_wordlanguage_data['Marathi'] = marathi_wordlanguage_data.to_csv('language_data.csv', index=False)
language_data.head()
english_text = language_data['English'].valuesmarathi_text = language_data['Marathi'].valueslen(english_text), len(marathi_text)
Data Cleaning
Now let’s clean the data and make it suitable for our model. In the cleaning process, we will convert into lower case, remove all punctuation and other unnecessary letters and digits too.
#to lower caseenglish_text_ = [x.lower() for x in english_text]marathi_text_ = [x.lower() for x in marathi_text]#removing inverted commasenglish_text_ = [re.sub("'",'',x) for x in english_text_]marathi_text_ = [re.sub("'",'',x) for x in marathi_text_]def remove_punc(text_list): table = str.maketrans('', '', string.punctuation) removed_punc_text = [] for sent in text_list: sentance = [w.translate(table) for w in sent.split(' ')] removed_punc_text.append(' '.join(sentance)) return removed_punc_textenglish_text_ = remove_punc(english_text_)marathi_text_ = remove_punc(marathi_text_)remove_digits = str.maketrans('', '', digits)removed_digits_text = []for sent in english_text_: sentance = [w.translate(remove_digits) for w in sent.split(' ')] removed_digits_text.append(' '.join(sentance))english_text_ = removed_digits_text# removing the digits from the marathi sentancesmarathi_text_ = [re.sub("[२३०८१५७९४६]","",x) for x in marathi_text_]marathi_text_ = [re.sub("[\u200d]","",x) for x in marathi_text_]# removing the stating and ending whitespacesenglish_text_ = [x.strip() for x in english_text_]marathi_text_ = [x.strip() for x in marathi_text_]
Adding ‘start’ and ‘end’ tag to marathi sentence. This will help the decoder to know from where to start decoding and when to end.
# Putting the start and end words in the marathi sentancesmarathi_text_ = ["start " + x + " end" for x in marathi_text_]# manipulated_marathi_text_marathi_text_[0], english_text_[0]
(‘start जा end’, ‘go’)
We will split our dataset with a ratio of 0.1 so that our trained model can give precise results. X_train and y_train will be our training set while X_test and y_test will be our testing/validation set.
X = english_text_Y = marathi_text_X_train, X_test, y_train, y_test=train_test_split(X,Y,test_size=0.1)
Let’s determine the maximum length of our sentences in both English and Marathi:
def Max_length(data): max_length_ = max([len(x.split(' ')) for x in data]) return max_length_#Training datamax_length_english = Max_length(X_train)max_length_marathi = Max_length(y_train)#Test datamax_length_english_test = Max_length(X_test)max_length_marathi_test = Max_length(y_test)max_length_marathi, max_length_english
(26, 32)
Tokenization:
As a neural network requires numerical data to process, it becomes necessary to convert our string input to a numerical list. One way of doing this is to use Tokenizer provided by keras-preprocessing library.
Also, remember it is mandatory to have an equal length of all input sequences in sequence-to-sequence models. So, we will pad extra ‘0s’ to make the sequence of the same length. This would be done by pad_sequence.
englishTokenizer = Tokenizer()englishTokenizer.fit_on_texts(X_train)Eword2index = englishTokenizer.word_indexvocab_size_source = len(Eword2index) + 1X_train = englishTokenizer.texts_to_sequences(X_train)X_train = pad_sequences(X_train, maxlen=max_length_english, padding='post')X_test = englishTokenizer.texts_to_sequences(X_test)X_test = pad_sequences(X_test, maxlen = max_length_english, padding='post')marathiTokenizer = Tokenizer()marathiTokenizer.fit_on_texts(y_train)Mword2index = marathiTokenizer.word_indexvocab_size_target = len(Mword2index) + 1y_train = marathiTokenizer.texts_to_sequences(y_train)y_train = pad_sequences(y_train, maxlen=max_length_marathi, padding='post')y_test = marathiTokenizer.texts_to_sequences(y_test)y_test = pad_sequences(y_test, maxlen = max_length_marathi, padding='post')vocab_size_source, vocab_size_target
(5413, 12789)
X_train[0], y_train[0]
(array([ 1, 157, 5, 134, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int32), array([ 1, 6, 22, 61, 253, 29, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int32))
To save our preprocessing time whenever we reuse it again in future, we will save our important attributes. So, let’s do it first with the help of pickle library.
with open('NMT_data.pkl','wb') as f: pkl.dump([X_train, y_train, X_test, y_test],f)with open('NMT_Etokenizer.pkl','wb') as f: pkl.dump([vocab_size_source, Eword2index, englishTokenizer], f)with open('NMT_Mtokenizer.pkl', 'wb') as f: pkl.dump([vocab_size_target, Mword2index, marathiTokenizer], f)X_train = np.array(X_train)y_train = np.array(y_train)X_test = np.array(X_test)y_test = np.array(y_test)
Instead of a simple encoder-decoder architecture, we will be using Attention Mechanism as discussed earlier in this blog.
Keras does not officially support attention layer. So, we can either implement our own attention layer or use a third-party implementation. For now, we will be using a third party attention mechanism. You can download the attention layer from here and copy it in a different file called attention.py. This attention is an implementation of ‘Bahdanau Attention’ .
Let’s define the structure of our model:
from attention import AttentionLayerfrom keras import backend as K K.clear_session() latent_dim = 500# Encoder encoder_inputs = Input(shape=(max_length_english,)) enc_emb = Embedding(vocab_size_source, latent_dim,trainable=True)(encoder_inputs)#LSTM 1 encoder_lstm1 = LSTM(latent_dim,return_sequences=True,return_state=True) encoder_output1, state_h1, state_c1 = encoder_lstm1(enc_emb)#LSTM 2 encoder_lstm2 = LSTM(latent_dim,return_sequences=True,return_state=True) encoder_output2, state_h2, state_c2 = encoder_lstm2(encoder_output1)#LSTM 3 encoder_lstm3=LSTM(latent_dim, return_state=True, return_sequences=True) encoder_outputs, state_h, state_c= encoder_lstm3(encoder_output2)# Set up the decoder. decoder_inputs = Input(shape=(None,)) dec_emb_layer = Embedding(vocab_size_target, latent_dim,trainable=True) dec_emb = dec_emb_layer(decoder_inputs)#LSTM using encoder_states as initial statedecoder_lstm = LSTM(latent_dim, return_sequences=True, return_state=True) decoder_outputs,decoder_fwd_state, decoder_back_state = decoder_lstm(dec_emb,initial_state=[state_h, state_c])#Attention Layerattn_layer = AttentionLayer(name='attention_layer') attn_out, attn_states = attn_layer([encoder_outputs, decoder_outputs])# Concat attention output and decoder LSTM output decoder_concat_input = Concatenate(axis=-1, name='concat_layer')([decoder_outputs, attn_out])#Dense layerdecoder_dense = TimeDistributed(Dense(vocab_size_target, activation='softmax')) decoder_outputs = decoder_dense(decoder_concat_input)# Define the modelmodel = Model([encoder_inputs, decoder_inputs], decoder_outputs) plot_model(model, to_file='train_model.png', show_shapes=True)
You can modify this model as per your choice and requirement to get better results. You can change number of layers, number of units or some regularization techniques too. For the time being, let’s move forward and see what our model looks like!
model.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
We will first define some callbacks so that it would be easy for model visualization and evaluation in future.
es = EarlyStopping(monitor='val_loss', mode='min', verbose=1)
We are using ‘Teacher Forcing’ technique for faster training of our model. In the teacher forcing method, we also pass the target data as the input to the decoder. For example, if we are going to predict ‘hello’, then we will pass ‘hello’ itself as an input to the decoder. Due to this it makes the learning process faster.
Let's train our Model:
history = model.fit([X_train, y_train[:,:-1]], y_train.reshape(y_train.shape[0], y_train.shape[1],1)[:,1:], epochs=50, callbacks=[es], batch_size=512, validation_data = ([X_test, y_test[:,:-1]], y_test.reshape(y_test.shape[0], y_test.shape[1], 1)[:,1:]))
The execution time was around 39 seconds per epoch on 12GB NVIDIA Tesla K80 GPU. EarlyStopping was achieved at 18th epoch.
We can visualize the loss difference in both training and validation phase as:
from matplotlib import pyplot pyplot.plot(history.history['loss'], label='train') pyplot.plot(history.history['val_loss'], label='test') pyplot.legend() pyplot.show()
We are getting some pretty good results from our model with around 90% validation accuracy and a validation loss of 0.5303.
Let’s save our trained model with proper weights. Do remember to save the model like I have done as we have to load weights too for the inference model.
model_json = model.to_json()with open("NMT_model.json", "w") as json_file: json_file.write(model_json)# serialize weights to HDF5model.save_weights("NMT_model_weight.h5")print("Saved model to disk")
Load model:
# loading the model architecture and asigning the weightsjson_file = open('NMT_model.json', 'r')loaded_model_json = json_file.read()json_file.close()model_loaded = model_from_json(loaded_model_json, custom_objects={'AttentionLayer': AttentionLayer})# load weights into new modelmodel_loaded.load_weights("NMT_model_weight.h5")
In machine learning we use inference model to predict our output sequences by considering weights from a pre-trained model. In other terms, it can be said that its a model that deduces properties that are learned in training phase and are now used for predicting new sequences.
Let’s code our inference model:
latent_dim=500# encoder inferenceencoder_inputs = model_loaded.input[0] #loading encoder_inputsencoder_outputs, state_h, state_c = model_loaded.layers[6].output #loading encoder_outputs#print(encoder_outputs.shape)encoder_model = Model(inputs=encoder_inputs,outputs=[encoder_outputs, state_h, state_c])# decoder inference# Below tensors will hold the states of the previous time stepdecoder_state_input_h = Input(shape=(latent_dim,))decoder_state_input_c = Input(shape=(latent_dim,))decoder_hidden_state_input = Input(shape=(32,latent_dim))# Get the embeddings of the decoder sequencedecoder_inputs = model_loaded.layers[3].output#print(decoder_inputs.shape)dec_emb_layer = model_loaded.layers[5]dec_emb2= dec_emb_layer(decoder_inputs)# To predict the next word in the sequence, set the initial states to the states from the previous time stepdecoder_lstm = model_loaded.layers[7]decoder_outputs2, state_h2, state_c2 = decoder_lstm(dec_emb2, initial_state=[decoder_state_input_h, decoder_state_input_c])#attention inferenceattn_layer = model_loaded.layers[8]attn_out_inf, attn_states_inf = attn_layer([decoder_hidden_state_input, decoder_outputs2])concate = model_loaded.layers[9]decoder_inf_concat = concate([decoder_outputs2, attn_out_inf])# A dense softmax layer to generate prob dist. over the target vocabularydecoder_dense = model_loaded.layers[10]decoder_outputs2 = decoder_dense(decoder_inf_concat)# Final decoder modeldecoder_model = Model([decoder_inputs] + [decoder_hidden_state_input,decoder_state_input_h, decoder_state_input_c],[decoder_outputs2] + [state_h2, state_c2])
Now we have trained the sequence to sequence model and created the inference model using the trained model for making a prediction. Let’s predict some Marathi sentences from the English sentences.
def decode_sequence(input_seq): # Encode the input as state vectors. e_out, e_h, e_c = encoder_model.predict(input_seq)# Generate empty target sequence of length 1. target_seq = np.zeros((1,1))# Chose the 'start' word as the first word of the target sequence target_seq[0, 0] = Mword2index['start']stop_condition = False decoded_sentence = '' while not stop_condition: output_tokens, h, c = decoder_model.predict([target_seq] + [e_out, e_h, e_c])# Sample a token sampled_token_index = np.argmax(output_tokens[0, -1, :]) if sampled_token_index == 0: break else: sampled_token = Mindex2word[sampled_token_index]if(sampled_token!='end'): decoded_sentence += ' '+sampled_token# Exit condition: either hit max length or find stop word. if (sampled_token == 'end' or len(decoded_sentence.split()) >= (26-1)): stop_condition = True# Update the target sequence (of length 1). target_seq = np.zeros((1,1)) target_seq[0, 0] = sampled_token_index# Update internal states e_h, e_c = h, creturn decoded_sentence
Forming a reverse vocabulary:
Eindex2word = englishTokenizer.index_wordMindex2word = marathiTokenizer.index_word
Some transformation before giving a string to the function:
def seq2summary(input_seq): newString='' for i in input_seq: if((i!=0 and i!=Mword2index['start']) and i!=Mword2index['end']): newString=newString+Mindex2word[i]+' ' return newStringdef seq2text(input_seq): newString='' for i in input_seq: if(i!=0): newString=newString+Eindex2word[i]+' ' return newString
Call the necessary functions and let’s test our translation model:
for i in range(10): print("Review:",seq2text(X_test[i])) print("Original summary:",seq2summary(y_test[i])) print("Predicted summary:",decode_sequence(X_test[i].reshape(1,32))) print("\n")
Review: no one will tell you Original summary: तुला कोणीही सांगणार नाही Predicted summary: कोणीही तुला सांगणार नाही
Review: look ahead Original summary: समोर बघा Predicted summary: तिथे बघ
Review: im going to return this to tom Original summary: मी हे टॉमला परत करायला जातोय Predicted summary: मी ते स्वतःहून करणार आहे
Review: an eagle is flying in the sky Original summary: आकाशात एक गरुड आहे Predicted summary: न्यूयॉर्क अतिरेकी तो दुसर्याचा
Review: he speaks arabic Original summary: तो अरबी बोलतो Predicted summary: तो अरबी बोलतो
Review: clean up this mess Original summary: हा पसारा साफ करून टाका Predicted summary: हा पसारा साफ कर
Review: dont speak french in the class Original summary: वर्गात फ्रेंचमध्ये बोलू नका Predicted summary: वर्गात जास्त कठीण राहू नकोस
Review: i turned the lights out Original summary: मी दिवे Predicted summary: मी दोन हात वर केला
Review: how many rackets do you have Original summary: तुझ्याकडे किती रॅकेट आहेत Predicted summary: तुमच्याकडे किती बहिणी आहेत
Review: i gave tom marys phone number Original summary: मी टॉमला मेरीचा फोन नंबर दिला Predicted summary: मी टॉमला मेरीचा फोन क्रमांक दिला
Hurrah!!
Our model makes some good translations of English sentences to Marathi sentences.
I have deployed my model through Django and have hosted it on heroku. You can look at it here.
hurdlenet.herokuapp.com
In this story, we learned about the functionality of Attention Mechanism and implemented a Language Translation task. This task could have multiple use cases in daily lifestyles. For example, we can use this technique to build a multi-language translator that can translate various languages from a single language. Also, if we can integrate this with an Optical Character Recognition system, we can translate texts directly from images.
If you have any other use case or technique to work with translation data and also, if you find a more improved model for NMT, do share in the response block below!
The entire code for this article is available here. If you have any feedback, feel free to reach out to me on LinkedIn.
|
[
{
"code": null,
"e": 625,
"s": 171,
"text": "It is an undeniable truth that in this era of globalization, language translation plays a vital role in communication among the denizens of different nation’s. Moreover, in a country like India - which a multilingual nation, language difference could be observed in its states itself! Hence, considering the importance of Language Translation, it becomes necessary to develop a system that could easily translate an unknown language to a known language."
},
{
"code": null,
"e": 1036,
"s": 625,
"text": "In accordance with this, in this story, we will make a Deep Learning model that will translate English sentences to Marathi sentences. I have chosen Marathi language as it is easy for me to recognize. You can use any other language that is comfortable for you, as the model nearly remains the same. Moreover, I will try to briefly explain a major concept in language processing called Attention Mechanism here!"
},
{
"code": null,
"e": 1153,
"s": 1036,
"text": "Working of Long Short Time Memory(LSTM) cellsWorking of TensorFlow, Keras and some other mandatory python libraries."
},
{
"code": null,
"e": 1199,
"s": 1153,
"text": "Working of Long Short Time Memory(LSTM) cells"
},
{
"code": null,
"e": 1271,
"s": 1199,
"text": "Working of TensorFlow, Keras and some other mandatory python libraries."
},
{
"code": null,
"e": 1725,
"s": 1271,
"text": "The major drawback of encoder-decoder model in sequence to sequence recurrent neural network is that it can only work on short sequences. It is difficult for the encoder model to memorize long sequences and convert it into a fixed-length vector. Moreover, the decoder receives only one information that is the last encoder hidden state. Hence it's difficult for the decoder to summarize large input sequence at once. So, how do we overcome this problem?"
},
{
"code": null,
"e": 1816,
"s": 1725,
"text": "How about if we give a vector representation from every encoder step to the decoder model!"
},
{
"code": null,
"e": 2045,
"s": 1816,
"text": "Now, this is where the concept of ‘Attention Mechanism’ comes. The major intuition about this is that it predicts the next word by concentrating on a few relevant parts of the sequence rather than looking on the entire sequence."
},
{
"code": null,
"e": 2213,
"s": 2045,
"text": "In layman terms it can be described as an interference between encoder and decoder which extracts useful information from encoder and transmits it back to the decoder."
},
{
"code": null,
"e": 2278,
"s": 2213,
"text": "Refer here for detailed understanding about Attention Mechanism."
},
{
"code": null,
"e": 2329,
"s": 2278,
"text": "There are mainly two types of attention mechanism:"
},
{
"code": null,
"e": 2346,
"s": 2329,
"text": "Global Attention"
},
{
"code": null,
"e": 2362,
"s": 2346,
"text": "Local Attention"
},
{
"code": null,
"e": 2490,
"s": 2362,
"text": "Global Attention are those attention in which all the hidden state vectors of the encoder are passed to get the context vector."
},
{
"code": null,
"e": 2631,
"s": 2490,
"text": "Local Attention are those attention in which only a few hidden state vectors of encoder are considered for the generation of context vector."
},
{
"code": null,
"e": 2812,
"s": 2631,
"text": "We will be using global attention in this story. Let’s now make use of attention mechanism and develop a language translator that will convert English sentence to Marathi sentence."
},
{
"code": null,
"e": 2870,
"s": 2812,
"text": "Open Jupyter Notebook and import some required libraries:"
},
{
"code": null,
"e": 3451,
"s": 2870,
"text": "import pandas as pdfrom sklearn.model_selection import train_test_splitimport stringfrom string import digitsimport refrom sklearn.utils import shufflefrom tensorflow.keras.preprocessing.sequence import pad_sequencesfrom tensorflow.keras.layers import LSTM, Input, Dense,Embedding, Concatenate, TimeDistributedfrom tensorflow.keras.models import Model,load_model, model_from_jsonfrom tensorflow.keras.utils import plot_modelfrom tensorflow.keras.preprocessing.text import one_hot, Tokenizerfrom tensorflow.keras.callbacks import EarlyStoppingimport pickle as pklimport numpy as np"
},
{
"code": null,
"e": 3508,
"s": 3451,
"text": "We will be working on a language dataset available here."
},
{
"code": null,
"e": 3872,
"s": 3508,
"text": "This site contains a dataset of numerous languages and its translation to English. You can download any language dataset as per your preference and comfort. However, remember to choose a dataset which is quite huge, so that we can get better results after training the model. Here, I will be downloading Marathi-English dataset which comprises of 38696 sentences."
},
{
"code": null,
"e": 3940,
"s": 3872,
"text": "After downloading load dataset, import the data as mentioned below:"
},
{
"code": null,
"e": 3988,
"s": 3940,
"text": "with open('mar.txt','r') as f: data = f.read()"
},
{
"code": null,
"e": 4008,
"s": 3988,
"text": "Data Transformation"
},
{
"code": null,
"e": 4291,
"s": 4008,
"text": "As you can see that it is a raw text file and hence it is necessary to clean and transform it as per our preference. We will separate Marathi and English sentences and form a list of it, continuing it by storing it into a dataframe so that it's easy for us to reuse it again easily."
},
{
"code": null,
"e": 4800,
"s": 4291,
"text": "uncleaned_data_list = data.split('\\n')len(uncleaned_data_list)uncleaned_data_list = uncleaned_data_list[:38695]len(uncleaned_data_list)english_word = []marathi_word = []cleaned_data_list = []for word in uncleaned_data_list: english_word.append(word.split('\\t')[:-1][0]) marathi_word.append(word.split('\\t')[:-1][1])language_data = pd.DataFrame(columns=['English','Marathi'])language_data['English'] = english_wordlanguage_data['Marathi'] = marathi_wordlanguage_data.to_csv('language_data.csv', index=False)"
},
{
"code": null,
"e": 4821,
"s": 4800,
"text": "language_data.head()"
},
{
"code": null,
"e": 4950,
"s": 4821,
"text": "english_text = language_data['English'].valuesmarathi_text = language_data['Marathi'].valueslen(english_text), len(marathi_text)"
},
{
"code": null,
"e": 4964,
"s": 4950,
"text": "Data Cleaning"
},
{
"code": null,
"e": 5152,
"s": 4964,
"text": "Now let’s clean the data and make it suitable for our model. In the cleaning process, we will convert into lower case, remove all punctuation and other unnecessary letters and digits too."
},
{
"code": null,
"e": 6317,
"s": 5152,
"text": "#to lower caseenglish_text_ = [x.lower() for x in english_text]marathi_text_ = [x.lower() for x in marathi_text]#removing inverted commasenglish_text_ = [re.sub(\"'\",'',x) for x in english_text_]marathi_text_ = [re.sub(\"'\",'',x) for x in marathi_text_]def remove_punc(text_list): table = str.maketrans('', '', string.punctuation) removed_punc_text = [] for sent in text_list: sentance = [w.translate(table) for w in sent.split(' ')] removed_punc_text.append(' '.join(sentance)) return removed_punc_textenglish_text_ = remove_punc(english_text_)marathi_text_ = remove_punc(marathi_text_)remove_digits = str.maketrans('', '', digits)removed_digits_text = []for sent in english_text_: sentance = [w.translate(remove_digits) for w in sent.split(' ')] removed_digits_text.append(' '.join(sentance))english_text_ = removed_digits_text# removing the digits from the marathi sentancesmarathi_text_ = [re.sub(\"[२३०८१५७९४६]\",\"\",x) for x in marathi_text_]marathi_text_ = [re.sub(\"[\\u200d]\",\"\",x) for x in marathi_text_]# removing the stating and ending whitespacesenglish_text_ = [x.strip() for x in english_text_]marathi_text_ = [x.strip() for x in marathi_text_]"
},
{
"code": null,
"e": 6448,
"s": 6317,
"text": "Adding ‘start’ and ‘end’ tag to marathi sentence. This will help the decoder to know from where to start decoding and when to end."
},
{
"code": null,
"e": 6630,
"s": 6448,
"text": "# Putting the start and end words in the marathi sentancesmarathi_text_ = [\"start \" + x + \" end\" for x in marathi_text_]# manipulated_marathi_text_marathi_text_[0], english_text_[0]"
},
{
"code": null,
"e": 6653,
"s": 6630,
"text": "(‘start जा end’, ‘go’)"
},
{
"code": null,
"e": 6856,
"s": 6653,
"text": "We will split our dataset with a ratio of 0.1 so that our trained model can give precise results. X_train and y_train will be our training set while X_test and y_test will be our testing/validation set."
},
{
"code": null,
"e": 6959,
"s": 6856,
"text": "X = english_text_Y = marathi_text_X_train, X_test, y_train, y_test=train_test_split(X,Y,test_size=0.1)"
},
{
"code": null,
"e": 7040,
"s": 6959,
"text": "Let’s determine the maximum length of our sentences in both English and Marathi:"
},
{
"code": null,
"e": 7366,
"s": 7040,
"text": "def Max_length(data): max_length_ = max([len(x.split(' ')) for x in data]) return max_length_#Training datamax_length_english = Max_length(X_train)max_length_marathi = Max_length(y_train)#Test datamax_length_english_test = Max_length(X_test)max_length_marathi_test = Max_length(y_test)max_length_marathi, max_length_english"
},
{
"code": null,
"e": 7375,
"s": 7366,
"text": "(26, 32)"
},
{
"code": null,
"e": 7389,
"s": 7375,
"text": "Tokenization:"
},
{
"code": null,
"e": 7598,
"s": 7389,
"text": "As a neural network requires numerical data to process, it becomes necessary to convert our string input to a numerical list. One way of doing this is to use Tokenizer provided by keras-preprocessing library."
},
{
"code": null,
"e": 7812,
"s": 7598,
"text": "Also, remember it is mandatory to have an equal length of all input sequences in sequence-to-sequence models. So, we will pad extra ‘0s’ to make the sequence of the same length. This would be done by pad_sequence."
},
{
"code": null,
"e": 8659,
"s": 7812,
"text": "englishTokenizer = Tokenizer()englishTokenizer.fit_on_texts(X_train)Eword2index = englishTokenizer.word_indexvocab_size_source = len(Eword2index) + 1X_train = englishTokenizer.texts_to_sequences(X_train)X_train = pad_sequences(X_train, maxlen=max_length_english, padding='post')X_test = englishTokenizer.texts_to_sequences(X_test)X_test = pad_sequences(X_test, maxlen = max_length_english, padding='post')marathiTokenizer = Tokenizer()marathiTokenizer.fit_on_texts(y_train)Mword2index = marathiTokenizer.word_indexvocab_size_target = len(Mword2index) + 1y_train = marathiTokenizer.texts_to_sequences(y_train)y_train = pad_sequences(y_train, maxlen=max_length_marathi, padding='post')y_test = marathiTokenizer.texts_to_sequences(y_test)y_test = pad_sequences(y_test, maxlen = max_length_marathi, padding='post')vocab_size_source, vocab_size_target"
},
{
"code": null,
"e": 8673,
"s": 8659,
"text": "(5413, 12789)"
},
{
"code": null,
"e": 8696,
"s": 8673,
"text": "X_train[0], y_train[0]"
},
{
"code": null,
"e": 8926,
"s": 8696,
"text": "(array([ 1, 157, 5, 134, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int32), array([ 1, 6, 22, 61, 253, 29, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int32))"
},
{
"code": null,
"e": 9089,
"s": 8926,
"text": "To save our preprocessing time whenever we reuse it again in future, we will save our important attributes. So, let’s do it first with the help of pickle library."
},
{
"code": null,
"e": 9493,
"s": 9089,
"text": "with open('NMT_data.pkl','wb') as f: pkl.dump([X_train, y_train, X_test, y_test],f)with open('NMT_Etokenizer.pkl','wb') as f: pkl.dump([vocab_size_source, Eword2index, englishTokenizer], f)with open('NMT_Mtokenizer.pkl', 'wb') as f: pkl.dump([vocab_size_target, Mword2index, marathiTokenizer], f)X_train = np.array(X_train)y_train = np.array(y_train)X_test = np.array(X_test)y_test = np.array(y_test)"
},
{
"code": null,
"e": 9615,
"s": 9493,
"text": "Instead of a simple encoder-decoder architecture, we will be using Attention Mechanism as discussed earlier in this blog."
},
{
"code": null,
"e": 9978,
"s": 9615,
"text": "Keras does not officially support attention layer. So, we can either implement our own attention layer or use a third-party implementation. For now, we will be using a third party attention mechanism. You can download the attention layer from here and copy it in a different file called attention.py. This attention is an implementation of ‘Bahdanau Attention’ ."
},
{
"code": null,
"e": 10019,
"s": 9978,
"text": "Let’s define the structure of our model:"
},
{
"code": null,
"e": 11669,
"s": 10019,
"text": "from attention import AttentionLayerfrom keras import backend as K K.clear_session() latent_dim = 500# Encoder encoder_inputs = Input(shape=(max_length_english,)) enc_emb = Embedding(vocab_size_source, latent_dim,trainable=True)(encoder_inputs)#LSTM 1 encoder_lstm1 = LSTM(latent_dim,return_sequences=True,return_state=True) encoder_output1, state_h1, state_c1 = encoder_lstm1(enc_emb)#LSTM 2 encoder_lstm2 = LSTM(latent_dim,return_sequences=True,return_state=True) encoder_output2, state_h2, state_c2 = encoder_lstm2(encoder_output1)#LSTM 3 encoder_lstm3=LSTM(latent_dim, return_state=True, return_sequences=True) encoder_outputs, state_h, state_c= encoder_lstm3(encoder_output2)# Set up the decoder. decoder_inputs = Input(shape=(None,)) dec_emb_layer = Embedding(vocab_size_target, latent_dim,trainable=True) dec_emb = dec_emb_layer(decoder_inputs)#LSTM using encoder_states as initial statedecoder_lstm = LSTM(latent_dim, return_sequences=True, return_state=True) decoder_outputs,decoder_fwd_state, decoder_back_state = decoder_lstm(dec_emb,initial_state=[state_h, state_c])#Attention Layerattn_layer = AttentionLayer(name='attention_layer') attn_out, attn_states = attn_layer([encoder_outputs, decoder_outputs])# Concat attention output and decoder LSTM output decoder_concat_input = Concatenate(axis=-1, name='concat_layer')([decoder_outputs, attn_out])#Dense layerdecoder_dense = TimeDistributed(Dense(vocab_size_target, activation='softmax')) decoder_outputs = decoder_dense(decoder_concat_input)# Define the modelmodel = Model([encoder_inputs, decoder_inputs], decoder_outputs) plot_model(model, to_file='train_model.png', show_shapes=True)"
},
{
"code": null,
"e": 11915,
"s": 11669,
"text": "You can modify this model as per your choice and requirement to get better results. You can change number of layers, number of units or some regularization techniques too. For the time being, let’s move forward and see what our model looks like!"
},
{
"code": null,
"e": 12039,
"s": 11915,
"text": "model.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy', metrics=['accuracy'])"
},
{
"code": null,
"e": 12150,
"s": 12039,
"text": "We will first define some callbacks so that it would be easy for model visualization and evaluation in future."
},
{
"code": null,
"e": 12212,
"s": 12150,
"text": "es = EarlyStopping(monitor='val_loss', mode='min', verbose=1)"
},
{
"code": null,
"e": 12536,
"s": 12212,
"text": "We are using ‘Teacher Forcing’ technique for faster training of our model. In the teacher forcing method, we also pass the target data as the input to the decoder. For example, if we are going to predict ‘hello’, then we will pass ‘hello’ itself as an input to the decoder. Due to this it makes the learning process faster."
},
{
"code": null,
"e": 12559,
"s": 12536,
"text": "Let's train our Model:"
},
{
"code": null,
"e": 12902,
"s": 12559,
"text": "history = model.fit([X_train, y_train[:,:-1]], y_train.reshape(y_train.shape[0], y_train.shape[1],1)[:,1:], epochs=50, callbacks=[es], batch_size=512, validation_data = ([X_test, y_test[:,:-1]], y_test.reshape(y_test.shape[0], y_test.shape[1], 1)[:,1:]))"
},
{
"code": null,
"e": 13025,
"s": 12902,
"text": "The execution time was around 39 seconds per epoch on 12GB NVIDIA Tesla K80 GPU. EarlyStopping was achieved at 18th epoch."
},
{
"code": null,
"e": 13104,
"s": 13025,
"text": "We can visualize the loss difference in both training and validation phase as:"
},
{
"code": null,
"e": 13271,
"s": 13104,
"text": "from matplotlib import pyplot pyplot.plot(history.history['loss'], label='train') pyplot.plot(history.history['val_loss'], label='test') pyplot.legend() pyplot.show()"
},
{
"code": null,
"e": 13395,
"s": 13271,
"text": "We are getting some pretty good results from our model with around 90% validation accuracy and a validation loss of 0.5303."
},
{
"code": null,
"e": 13548,
"s": 13395,
"text": "Let’s save our trained model with proper weights. Do remember to save the model like I have done as we have to load weights too for the inference model."
},
{
"code": null,
"e": 13750,
"s": 13548,
"text": "model_json = model.to_json()with open(\"NMT_model.json\", \"w\") as json_file: json_file.write(model_json)# serialize weights to HDF5model.save_weights(\"NMT_model_weight.h5\")print(\"Saved model to disk\")"
},
{
"code": null,
"e": 13762,
"s": 13750,
"text": "Load model:"
},
{
"code": null,
"e": 14089,
"s": 13762,
"text": "# loading the model architecture and asigning the weightsjson_file = open('NMT_model.json', 'r')loaded_model_json = json_file.read()json_file.close()model_loaded = model_from_json(loaded_model_json, custom_objects={'AttentionLayer': AttentionLayer})# load weights into new modelmodel_loaded.load_weights(\"NMT_model_weight.h5\")"
},
{
"code": null,
"e": 14367,
"s": 14089,
"text": "In machine learning we use inference model to predict our output sequences by considering weights from a pre-trained model. In other terms, it can be said that its a model that deduces properties that are learned in training phase and are now used for predicting new sequences."
},
{
"code": null,
"e": 14399,
"s": 14367,
"text": "Let’s code our inference model:"
},
{
"code": null,
"e": 15985,
"s": 14399,
"text": "latent_dim=500# encoder inferenceencoder_inputs = model_loaded.input[0] #loading encoder_inputsencoder_outputs, state_h, state_c = model_loaded.layers[6].output #loading encoder_outputs#print(encoder_outputs.shape)encoder_model = Model(inputs=encoder_inputs,outputs=[encoder_outputs, state_h, state_c])# decoder inference# Below tensors will hold the states of the previous time stepdecoder_state_input_h = Input(shape=(latent_dim,))decoder_state_input_c = Input(shape=(latent_dim,))decoder_hidden_state_input = Input(shape=(32,latent_dim))# Get the embeddings of the decoder sequencedecoder_inputs = model_loaded.layers[3].output#print(decoder_inputs.shape)dec_emb_layer = model_loaded.layers[5]dec_emb2= dec_emb_layer(decoder_inputs)# To predict the next word in the sequence, set the initial states to the states from the previous time stepdecoder_lstm = model_loaded.layers[7]decoder_outputs2, state_h2, state_c2 = decoder_lstm(dec_emb2, initial_state=[decoder_state_input_h, decoder_state_input_c])#attention inferenceattn_layer = model_loaded.layers[8]attn_out_inf, attn_states_inf = attn_layer([decoder_hidden_state_input, decoder_outputs2])concate = model_loaded.layers[9]decoder_inf_concat = concate([decoder_outputs2, attn_out_inf])# A dense softmax layer to generate prob dist. over the target vocabularydecoder_dense = model_loaded.layers[10]decoder_outputs2 = decoder_dense(decoder_inf_concat)# Final decoder modeldecoder_model = Model([decoder_inputs] + [decoder_hidden_state_input,decoder_state_input_h, decoder_state_input_c],[decoder_outputs2] + [state_h2, state_c2])"
},
{
"code": null,
"e": 16182,
"s": 15985,
"text": "Now we have trained the sequence to sequence model and created the inference model using the trained model for making a prediction. Let’s predict some Marathi sentences from the English sentences."
},
{
"code": null,
"e": 17315,
"s": 16182,
"text": "def decode_sequence(input_seq): # Encode the input as state vectors. e_out, e_h, e_c = encoder_model.predict(input_seq)# Generate empty target sequence of length 1. target_seq = np.zeros((1,1))# Chose the 'start' word as the first word of the target sequence target_seq[0, 0] = Mword2index['start']stop_condition = False decoded_sentence = '' while not stop_condition: output_tokens, h, c = decoder_model.predict([target_seq] + [e_out, e_h, e_c])# Sample a token sampled_token_index = np.argmax(output_tokens[0, -1, :]) if sampled_token_index == 0: break else: sampled_token = Mindex2word[sampled_token_index]if(sampled_token!='end'): decoded_sentence += ' '+sampled_token# Exit condition: either hit max length or find stop word. if (sampled_token == 'end' or len(decoded_sentence.split()) >= (26-1)): stop_condition = True# Update the target sequence (of length 1). target_seq = np.zeros((1,1)) target_seq[0, 0] = sampled_token_index# Update internal states e_h, e_c = h, creturn decoded_sentence"
},
{
"code": null,
"e": 17345,
"s": 17315,
"text": "Forming a reverse vocabulary:"
},
{
"code": null,
"e": 17428,
"s": 17345,
"text": "Eindex2word = englishTokenizer.index_wordMindex2word = marathiTokenizer.index_word"
},
{
"code": null,
"e": 17488,
"s": 17428,
"text": "Some transformation before giving a string to the function:"
},
{
"code": null,
"e": 17836,
"s": 17488,
"text": "def seq2summary(input_seq): newString='' for i in input_seq: if((i!=0 and i!=Mword2index['start']) and i!=Mword2index['end']): newString=newString+Mindex2word[i]+' ' return newStringdef seq2text(input_seq): newString='' for i in input_seq: if(i!=0): newString=newString+Eindex2word[i]+' ' return newString"
},
{
"code": null,
"e": 17903,
"s": 17836,
"text": "Call the necessary functions and let’s test our translation model:"
},
{
"code": null,
"e": 18097,
"s": 17903,
"text": "for i in range(10): print(\"Review:\",seq2text(X_test[i])) print(\"Original summary:\",seq2summary(y_test[i])) print(\"Predicted summary:\",decode_sequence(X_test[i].reshape(1,32))) print(\"\\n\")"
},
{
"code": null,
"e": 18213,
"s": 18097,
"text": "Review: no one will tell you Original summary: तुला कोणीही सांगणार नाही Predicted summary: कोणीही तुला सांगणार नाही"
},
{
"code": null,
"e": 18286,
"s": 18213,
"text": "Review: look ahead Original summary: समोर बघा Predicted summary: तिथे बघ"
},
{
"code": null,
"e": 18416,
"s": 18286,
"text": "Review: im going to return this to tom Original summary: मी हे टॉमला परत करायला जातोय Predicted summary: मी ते स्वतःहून करणार आहे"
},
{
"code": null,
"e": 18541,
"s": 18416,
"text": "Review: an eagle is flying in the sky Original summary: आकाशात एक गरुड आहे Predicted summary: न्यूयॉर्क अतिरेकी तो दुसर्याचा"
},
{
"code": null,
"e": 18631,
"s": 18541,
"text": "Review: he speaks arabic Original summary: तो अरबी बोलतो Predicted summary: तो अरबी बोलतो"
},
{
"code": null,
"e": 18734,
"s": 18631,
"text": "Review: clean up this mess Original summary: हा पसारा साफ करून टाका Predicted summary: हा पसारा साफ कर"
},
{
"code": null,
"e": 18866,
"s": 18734,
"text": "Review: dont speak french in the class Original summary: वर्गात फ्रेंचमध्ये बोलू नका Predicted summary: वर्गात जास्त कठीण राहू नकोस"
},
{
"code": null,
"e": 18962,
"s": 18866,
"text": "Review: i turned the lights out Original summary: मी दिवे Predicted summary: मी दोन हात वर केला"
},
{
"code": null,
"e": 19089,
"s": 18962,
"text": "Review: how many rackets do you have Original summary: तुझ्याकडे किती रॅकेट आहेत Predicted summary: तुमच्याकडे किती बहिणी आहेत"
},
{
"code": null,
"e": 19227,
"s": 19089,
"text": "Review: i gave tom marys phone number Original summary: मी टॉमला मेरीचा फोन नंबर दिला Predicted summary: मी टॉमला मेरीचा फोन क्रमांक दिला"
},
{
"code": null,
"e": 19236,
"s": 19227,
"text": "Hurrah!!"
},
{
"code": null,
"e": 19318,
"s": 19236,
"text": "Our model makes some good translations of English sentences to Marathi sentences."
},
{
"code": null,
"e": 19413,
"s": 19318,
"text": "I have deployed my model through Django and have hosted it on heroku. You can look at it here."
},
{
"code": null,
"e": 19437,
"s": 19413,
"text": "hurdlenet.herokuapp.com"
},
{
"code": null,
"e": 19875,
"s": 19437,
"text": "In this story, we learned about the functionality of Attention Mechanism and implemented a Language Translation task. This task could have multiple use cases in daily lifestyles. For example, we can use this technique to build a multi-language translator that can translate various languages from a single language. Also, if we can integrate this with an Optical Character Recognition system, we can translate texts directly from images."
},
{
"code": null,
"e": 20040,
"s": 19875,
"text": "If you have any other use case or technique to work with translation data and also, if you find a more improved model for NMT, do share in the response block below!"
}
] |
Struts 2 - The Set Tag
|
The property tag is used to get the property of a value, which will default to the top of the stack if none is specified. This example shows you the usage of three simple data tags - namely set, push and property.
For this exercise, let us reuse examples given in "Data Type Conversion" chapter but with little modifications. So let us start with creating classes. Consider the following POJO class Environment.java.
package com.tutorialspoint.struts2;
public class Environment {
private String name;
public Environment(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Let us have following action class −
package com.tutorialspoint.struts2;
import com.opensymphony.xwork2.ActionSupport;
public class SystemDetails extends ActionSupport {
private Environment environment = new Environment("Development");
private String operatingSystem = "Windows XP SP3";
public String execute() {
return SUCCESS;
}
public Environment getEnvironment() {
return environment;
}
public void setEnvironment(Environment environment) {
this.environment = environment;
}
public String getOperatingSystem() {
return operatingSystem;
}
public void setOperatingSystem(String operatingSystem) {
this.operatingSystem = operatingSystem;
}
}
Let us have System.jsp with the following content −
<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>System Details</title>
</head>
<body>
<p>The environment name property can be accessed in three ways:</p>
(Method 1) Environment Name:
<s:property value = "environment.name"/><br/>
(Method 2) Environment Name:
<s:push value = "environment">
<s:property value = "name"/><br/>
</s:push>
(Method 3) Environment Name:
<s:set name = "myenv" value = "environment.name"/>
<s:property value = "myenv"/>
</body>
</html>
Let us now go through the three options one by one −
In the first method, we use the property tag to get the value of the environment's name. Since the environment variable is in the action class, it is automatically available in the value stack. We can directly refer to it using the propertyenvironment.name. Method 1 works fine, when you have limited number of properties in a class. Imagine if you have 20 properties in the Environment class. Every time you need to refer to these variables you need to add "environment." as the prefix. This is where the push tag comes in handy.
In the first method, we use the property tag to get the value of the environment's name. Since the environment variable is in the action class, it is automatically available in the value stack. We can directly refer to it using the propertyenvironment.name. Method 1 works fine, when you have limited number of properties in a class. Imagine if you have 20 properties in the Environment class. Every time you need to refer to these variables you need to add "environment." as the prefix. This is where the push tag comes in handy.
In the second method, we push the "environment" property to the stack. Therefore now within the body of the push tag, the environment property is available at the root of the stack. So you now refer to the property quite easily as shown in the example.
In the second method, we push the "environment" property to the stack. Therefore now within the body of the push tag, the environment property is available at the root of the stack. So you now refer to the property quite easily as shown in the example.
In the final method, we use the set tag to create a new variable called myenv. This variable's value is set to environment.name. So, now we can use this variable wherever we refer to the environment's name.
In the final method, we use the set tag to create a new variable called myenv. This variable's value is set to environment.name. So, now we can use this variable wherever we refer to the environment's name.
Your struts.xml should look like −
<?xml version = "1.0" Encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name = "struts.devMode" value = "true" />
<package name = "helloworld" extends = "struts-default">
<action name = "system"
class = "com.tutorialspoint.struts2.SystemDetails"
method = "execute">
<result name = "success">/System.jsp</result>
</action>
</package>
</struts>
Your web.xml should look like −
<?xml version = "1.0" Encoding = "UTF-8"?>
<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns = "http://java.sun.com/xml/ns/javaee"
xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id = "WebApp_ID" version = "3.0">
<display-name>Struts 2</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/system.action. This will produce the following screen −
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2460,
"s": 2246,
"text": "The property tag is used to get the property of a value, which will default to the top of the stack if none is specified. This example shows you the usage of three simple data tags - namely set, push and property."
},
{
"code": null,
"e": 2663,
"s": 2460,
"text": "For this exercise, let us reuse examples given in \"Data Type Conversion\" chapter but with little modifications. So let us start with creating classes. Consider the following POJO class Environment.java."
},
{
"code": null,
"e": 2948,
"s": 2663,
"text": "package com.tutorialspoint.struts2;\n\npublic class Environment {\n private String name;\n public Environment(String name) {\n this.name = name;\n }\n \n public String getName() {\n return name;\n }\n \n public void setName(String name) {\n this.name = name;\n }\n}"
},
{
"code": null,
"e": 2985,
"s": 2948,
"text": "Let us have following action class −"
},
{
"code": null,
"e": 3675,
"s": 2985,
"text": "package com.tutorialspoint.struts2;\nimport com.opensymphony.xwork2.ActionSupport;\n\npublic class SystemDetails extends ActionSupport {\n private Environment environment = new Environment(\"Development\");\n private String operatingSystem = \"Windows XP SP3\";\n\n public String execute() {\n return SUCCESS;\n }\n \n public Environment getEnvironment() {\n return environment;\n }\n \n public void setEnvironment(Environment environment) {\n this.environment = environment;\n }\n \n public String getOperatingSystem() {\n return operatingSystem;\n }\n \n public void setOperatingSystem(String operatingSystem) {\n this.operatingSystem = operatingSystem;\n }\n}"
},
{
"code": null,
"e": 3728,
"s": 3675,
"text": "Let us have System.jsp with the following content −"
},
{
"code": null,
"e": 4521,
"s": 3728,
"text": "<%@ page language = \"java\" contentType = \"text/html; charset = ISO-8859-1\"\n\tpageEncoding = \"ISO-8859-1\"%>\n<%@ taglib prefix = \"s\" uri = \"/struts-tags\"%>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \n\"http://www.w3.org/TR/html4/loose.dtd\">\n\n<html>\n <head>\n <title>System Details</title>\n </head>\n \n <body> \n <p>The environment name property can be accessed in three ways:</p>\n\n (Method 1) Environment Name: \n <s:property value = \"environment.name\"/><br/>\n\n (Method 2) Environment Name: \n <s:push value = \"environment\">\n <s:property value = \"name\"/><br/>\n </s:push>\n\n (Method 3) Environment Name:\n <s:set name = \"myenv\" value = \"environment.name\"/>\n <s:property value = \"myenv\"/>\n \n </body>\n</html>"
},
{
"code": null,
"e": 4574,
"s": 4521,
"text": "Let us now go through the three options one by one −"
},
{
"code": null,
"e": 5105,
"s": 4574,
"text": "In the first method, we use the property tag to get the value of the environment's name. Since the environment variable is in the action class, it is automatically available in the value stack. We can directly refer to it using the propertyenvironment.name. Method 1 works fine, when you have limited number of properties in a class. Imagine if you have 20 properties in the Environment class. Every time you need to refer to these variables you need to add \"environment.\" as the prefix. This is where the push tag comes in handy."
},
{
"code": null,
"e": 5636,
"s": 5105,
"text": "In the first method, we use the property tag to get the value of the environment's name. Since the environment variable is in the action class, it is automatically available in the value stack. We can directly refer to it using the propertyenvironment.name. Method 1 works fine, when you have limited number of properties in a class. Imagine if you have 20 properties in the Environment class. Every time you need to refer to these variables you need to add \"environment.\" as the prefix. This is where the push tag comes in handy."
},
{
"code": null,
"e": 5889,
"s": 5636,
"text": "In the second method, we push the \"environment\" property to the stack. Therefore now within the body of the push tag, the environment property is available at the root of the stack. So you now refer to the property quite easily as shown in the example."
},
{
"code": null,
"e": 6142,
"s": 5889,
"text": "In the second method, we push the \"environment\" property to the stack. Therefore now within the body of the push tag, the environment property is available at the root of the stack. So you now refer to the property quite easily as shown in the example."
},
{
"code": null,
"e": 6349,
"s": 6142,
"text": "In the final method, we use the set tag to create a new variable called myenv. This variable's value is set to environment.name. So, now we can use this variable wherever we refer to the environment's name."
},
{
"code": null,
"e": 6556,
"s": 6349,
"text": "In the final method, we use the set tag to create a new variable called myenv. This variable's value is set to environment.name. So, now we can use this variable wherever we refer to the environment's name."
},
{
"code": null,
"e": 6591,
"s": 6556,
"text": "Your struts.xml should look like −"
},
{
"code": null,
"e": 7119,
"s": 6591,
"text": "<?xml version = \"1.0\" Encoding = \"UTF-8\"?>\n<!DOCTYPE struts PUBLIC\n \"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN\"\n \"http://struts.apache.org/dtds/struts-2.0.dtd\">\n\n<struts>\n <constant name = \"struts.devMode\" value = \"true\" />\n <package name = \"helloworld\" extends = \"struts-default\">\n <action name = \"system\" \n class = \"com.tutorialspoint.struts2.SystemDetails\" \n method = \"execute\">\n <result name = \"success\">/System.jsp</result>\n </action>\n </package>\n</struts>"
},
{
"code": null,
"e": 7151,
"s": 7119,
"text": "Your web.xml should look like −"
},
{
"code": null,
"e": 7965,
"s": 7151,
"text": "<?xml version = \"1.0\" Encoding = \"UTF-8\"?>\n<web-app xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns = \"http://java.sun.com/xml/ns/javaee\" \n xmlns:web = \"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n xsi:schemaLocation = \"http://java.sun.com/xml/ns/javaee \n http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\"\n id = \"WebApp_ID\" version = \"3.0\">\n \n <display-name>Struts 2</display-name>\n \n <welcome-file-list>\n <welcome-file>index.jsp</welcome-file>\n </welcome-file-list>\n \n <filter>\n <filter-name>struts2</filter-name>\n <filter-class>\n org.apache.struts2.dispatcher.FilterDispatcher\n </filter-class>\n </filter>\n\n <filter-mapping>\n <filter-name>struts2</filter-name>\n <url-pattern>/*</url-pattern>\n </filter-mapping>\n</web-app>"
},
{
"code": null,
"e": 8251,
"s": 7965,
"text": "Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/system.action. This will produce the following screen −"
},
{
"code": null,
"e": 8258,
"s": 8251,
"text": " Print"
},
{
"code": null,
"e": 8269,
"s": 8258,
"text": " Add Notes"
}
] |
Remove K Digits | Practice | GeeksforGeeks
|
Given a non-negative integer S represented as a string, remove K digits from the number so that the new number is the smallest possible.
Note : The given num does not contain any leading zero.
Example 1:
Input:
S = "149811", K = 3
Output: 111
Explanation: Remove the three digits
4, 9, and 8 to form the new number 111
which is smallest.
Example 2:
Input:
S = "1002991", K = 3
Output: 21
Explanation: Remove the three digits 1(leading
one), 9, and 9 to form the new number 21(Note
that the output must not contain leading
zeroes) which is the smallest.
Your Task:
You don't need to read input or print anything. Your task is to complete the function removeKdigits() which takes the string S and an integer K as input and returns the new number which is the smallest possible.
Expected Time Complexity: O(|S|).
Expected Auxiliary Space: O(|S|).
Constraints:
1<=|S|<=10002
1<=K<=|S|
0
emmanueluluabuike1 month ago
Simple java solution
public String removeKdigits(String s, int k) {
// code here
Stack<Character> stack = new Stack<>();
StringBuilder sb = new StringBuilder();
String newWord;
for (int i = 0; i < s.length(); i++) {
char num = s.charAt(i);
while (k > 0 && !stack.isEmpty() && stack.peek() > num){
stack.pop();
k--;
}
if(stack.isEmpty() && num == '0')
continue;
stack.push(num);
}
while(!stack.isEmpty() && k > 0){
stack.pop();
k--;
}
if(stack.isEmpty())
return "0";
while(!stack.isEmpty()){
sb.append(stack.peek());
stack.pop();
}
newWord = sb.reverse().toString();
return newWord;
}
0
hanumanmanyam8371 month ago
class Solution {
public String removeKdigits(String S, int K) {
// code here
StringBuilder sb = new StringBuilder();
Stack<Integer>st=new Stack<>();
for(int i=0;i<S.length();i++)
{
while(!st.isEmpty() && st.peek()>(S.charAt(i)-'0') && K>0)
{
st.pop();
K--;
}
if(!st.isEmpty() || S.charAt(i)!='0')
{
st.push(S.charAt(i)-'0');
}
}
while(!st.isEmpty()&&K>0)
{
st.pop();
K--;
}
if(st.isEmpty())
{
return "0";
}
while(!st.isEmpty())
{
sb.append(st.pop());
}
String str = sb.reverse().toString();
return str;
}
}
0
shuklaps11191 month ago
//java Solution 0.8/1.9
class Solution { public String removeKdigits(String S, int K) { StringBuilder sb = new StringBuilder(); if(S.length()<=K){ return "0"; } if(K==0){ return S; } Stack<Character> st = new Stack<>(); for(int i=0;i<S.length();i++){ char c = S.charAt(i); while(!st.isEmpty() && K>0 && st.peek() > c){ st.pop(); K--; } if(!st.isEmpty() || c!='0'){ st.push(c); } } while(!st.isEmpty()&&K>0){ st.pop(); K--; } if(st.isEmpty()) return "0"; while(!st.isEmpty()){ sb.append(st.pop()); } String str = sb.reverse().toString(); return str; }}
0
prasadkandekar5552 months ago
C++ O(S) time and space solution :)
class Solution {
public:
string removeKdigits(string num, int k) {
// treat ans as a stack in below for loop
string ans = "";
for (char c : num) {
// make sure digits in ans are in ascending order remove one char
while (ans.length() && ans.back() > c && k) {
ans.pop_back();
k--;
}
// can't have leading '0'
if (ans.length() || c != '0') {
ans.push_back(c);
}
}
// make sure remove k digits in total
while (ans.length() && k--) {
ans.pop_back();
}
return ans.empty() ? "0" : ans;
}
};
-1
gulshan992 months ago
string removeKdigits(string S, int k) {
string ans="";
for(char c:S){
while(ans.length() and ans.back()>c and k)
{
ans.pop_back();
k--;
}
if(ans.length() || c!='0'){
ans.push_back(c);
}
}
while(ans.length() and k--){
ans.pop_back();
}
return ans.empty()?"0":ans;
}
-1
chessnoobdj3 months ago
C++
string removeKdigits(string S, int k) {
int i = 0;
stack <char> s;
while(S[i]!='\0'){
while(!s.empty() && s.top()>S[i] && k){
s.pop();
k--;
}
if(!s.empty() || S[i] != '0')
s.push(S[i]);
i++;
}
while(!s.empty() && k--)
s.pop();
string str = "";
while(!s.empty()){
str += s.top();
s.pop();
}
reverse(str.begin(), str.end());
if(str.empty())
str += "0";
return str;
}
-1
thanoschild4 months ago
Time complexity = O(N), Space complexity = O(N)
string removeKdigits(string S, int K) { stack<int> st; for(int i=0; i<S.size(); i++) { while(!st.empty() && st.top() > S[i] && K>0) { st.pop(); K--; } if(!st.empty() || S[i] != '0') st.push(S[i]); } while(!st.empty() && K--) { st.pop(); } if(st.empty()) return "0"; string ans; while(!st.empty()) { ans += st.top(); st.pop(); } reverse(ans.begin(), ans.end()); return ans; }
-1
shivambhadani1236 months ago
O(N) time and O(N) space using stack
class Solution {
public:
string removeKdigits(string S, int K) {
stack<char> st;
for(int i=0; i<S.size(); i++) {
while(!st.empty() && st.top()>S[i] && K>0) {
st.pop();
K--;
}
if(!st.empty() || S[i]!='0') st.push(S[i]);
}
while(!st.empty() && K--) {;
st.pop();
}
if(st.empty()) return "0";
string ans;
while(!st.empty()) {
ans = st.top() + ans;
st.pop();
}
return ans;
}
};
0
shady418 months ago
shady41
Need to remove greater nos. from significant positions...
string removeKdigits(string str, int k) { deque<char>dq; for(char i: str){ if(dq.empty()) dq.push_back(i); else{ while(k && !dq.empty() && dq.back()-'0'>i-'0'){ dq.pop_back(); k--; } dq.push_back(i); } } while(k && !dq.empty()){ dq.pop_back(); k--; } while(!dq.empty() && dq.front()=='0'){ dq.pop_front(); } string ans=""; while(!dq.empty()){ ans.push_back(dq.front()); dq.pop_front(); } return (ans.empty())?"0":ans; }
-1
wallflower10 months ago
wallflower
Hint : Use the next greater element concept of stack to pop elements that are greater than the current element. Then for the remaining k, remove elements from top of stack. And return the string obtained.
https://ide.geeksforgeeks.o...
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": 431,
"s": 238,
"text": "Given a non-negative integer S represented as a string, remove K digits from the number so that the new number is the smallest possible.\nNote : The given num does not contain any leading zero."
},
{
"code": null,
"e": 442,
"s": 431,
"text": "Example 1:"
},
{
"code": null,
"e": 578,
"s": 442,
"text": "Input:\nS = \"149811\", K = 3\nOutput: 111\nExplanation: Remove the three digits \n4, 9, and 8 to form the new number 111\nwhich is smallest.\n"
},
{
"code": null,
"e": 589,
"s": 578,
"text": "Example 2:"
},
{
"code": null,
"e": 793,
"s": 589,
"text": "Input:\nS = \"1002991\", K = 3\nOutput: 21\nExplanation: Remove the three digits 1(leading\none), 9, and 9 to form the new number 21(Note\nthat the output must not contain leading\nzeroes) which is the smallest."
},
{
"code": null,
"e": 1017,
"s": 793,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function removeKdigits() which takes the string S and an integer K as input and returns the new number which is the smallest possible."
},
{
"code": null,
"e": 1086,
"s": 1017,
"text": "\nExpected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(|S|)."
},
{
"code": null,
"e": 1124,
"s": 1086,
"text": "\nConstraints:\n1<=|S|<=10002\n1<=K<=|S|"
},
{
"code": null,
"e": 1126,
"s": 1124,
"text": "0"
},
{
"code": null,
"e": 1155,
"s": 1126,
"text": "emmanueluluabuike1 month ago"
},
{
"code": null,
"e": 1176,
"s": 1155,
"text": "Simple java solution"
},
{
"code": null,
"e": 2038,
"s": 1178,
"text": "public String removeKdigits(String s, int k) {\n // code here\n Stack<Character> stack = new Stack<>();\n StringBuilder sb = new StringBuilder();\n String newWord;\n\n for (int i = 0; i < s.length(); i++) {\n char num = s.charAt(i);\n while (k > 0 && !stack.isEmpty() && stack.peek() > num){\n stack.pop();\n k--;\n }\n if(stack.isEmpty() && num == '0')\n continue;\n stack.push(num);\n }\n\n while(!stack.isEmpty() && k > 0){\n stack.pop();\n k--;\n }\n \n if(stack.isEmpty())\n return \"0\";\n \n while(!stack.isEmpty()){\n sb.append(stack.peek());\n stack.pop();\n }\n\n newWord = sb.reverse().toString();\n return newWord;\n }"
},
{
"code": null,
"e": 2040,
"s": 2038,
"text": "0"
},
{
"code": null,
"e": 2068,
"s": 2040,
"text": "hanumanmanyam8371 month ago"
},
{
"code": null,
"e": 2901,
"s": 2068,
"text": "class Solution {\n public String removeKdigits(String S, int K) {\n // code here\n StringBuilder sb = new StringBuilder();\n Stack<Integer>st=new Stack<>();\n for(int i=0;i<S.length();i++)\n {\n while(!st.isEmpty() && st.peek()>(S.charAt(i)-'0') && K>0)\n {\n st.pop();\n K--;\n }\n if(!st.isEmpty() || S.charAt(i)!='0')\n {\n st.push(S.charAt(i)-'0');\n }\n \n }\n while(!st.isEmpty()&&K>0)\n {\n st.pop();\n K--;\n }\n if(st.isEmpty())\n {\n return \"0\";\n }\n while(!st.isEmpty())\n {\n sb.append(st.pop());\n }\n String str = sb.reverse().toString();\n return str;\n }\n}"
},
{
"code": null,
"e": 2903,
"s": 2901,
"text": "0"
},
{
"code": null,
"e": 2927,
"s": 2903,
"text": "shuklaps11191 month ago"
},
{
"code": null,
"e": 2951,
"s": 2927,
"text": "//java Solution 0.8/1.9"
},
{
"code": null,
"e": 3794,
"s": 2953,
"text": "class Solution { public String removeKdigits(String S, int K) { StringBuilder sb = new StringBuilder(); if(S.length()<=K){ return \"0\"; } if(K==0){ return S; } Stack<Character> st = new Stack<>(); for(int i=0;i<S.length();i++){ char c = S.charAt(i); while(!st.isEmpty() && K>0 && st.peek() > c){ st.pop(); K--; } if(!st.isEmpty() || c!='0'){ st.push(c); } } while(!st.isEmpty()&&K>0){ st.pop(); K--; } if(st.isEmpty()) return \"0\"; while(!st.isEmpty()){ sb.append(st.pop()); } String str = sb.reverse().toString(); return str; }}"
},
{
"code": null,
"e": 3796,
"s": 3794,
"text": "0"
},
{
"code": null,
"e": 3826,
"s": 3796,
"text": "prasadkandekar5552 months ago"
},
{
"code": null,
"e": 3862,
"s": 3826,
"text": "C++ O(S) time and space solution :)"
},
{
"code": null,
"e": 4655,
"s": 3862,
"text": "class Solution {\n public:\n string removeKdigits(string num, int k) {\n // treat ans as a stack in below for loop\n string ans = \"\"; \n \n for (char c : num) {\n \n // make sure digits in ans are in ascending order remove one char\n while (ans.length() && ans.back() > c && k) {\n ans.pop_back(); \n k--; \n }\n \n // can't have leading '0'\n if (ans.length() || c != '0') {\n ans.push_back(c); \n } \n }\n \n // make sure remove k digits in total\n while (ans.length() && k--) {\n ans.pop_back(); \n } \n \n return ans.empty() ? \"0\" : ans;\n \n }\n};"
},
{
"code": null,
"e": 4660,
"s": 4657,
"text": "-1"
},
{
"code": null,
"e": 4682,
"s": 4660,
"text": "gulshan992 months ago"
},
{
"code": null,
"e": 5119,
"s": 4682,
"text": "string removeKdigits(string S, int k) {\n string ans=\"\";\n for(char c:S){\n while(ans.length() and ans.back()>c and k)\n {\n ans.pop_back();\n k--;\n }\n if(ans.length() || c!='0'){\n ans.push_back(c);\n }\n }\n while(ans.length() and k--){\n ans.pop_back();\n }\n return ans.empty()?\"0\":ans;\n }"
},
{
"code": null,
"e": 5122,
"s": 5119,
"text": "-1"
},
{
"code": null,
"e": 5146,
"s": 5122,
"text": "chessnoobdj3 months ago"
},
{
"code": null,
"e": 5150,
"s": 5146,
"text": "C++"
},
{
"code": null,
"e": 5751,
"s": 5150,
"text": "string removeKdigits(string S, int k) {\n int i = 0;\n stack <char> s;\n while(S[i]!='\\0'){\n while(!s.empty() && s.top()>S[i] && k){\n s.pop();\n k--;\n }\n if(!s.empty() || S[i] != '0')\n s.push(S[i]);\n i++;\n }\n while(!s.empty() && k--)\n s.pop();\n string str = \"\";\n while(!s.empty()){\n str += s.top();\n s.pop();\n }\n reverse(str.begin(), str.end());\n if(str.empty())\n str += \"0\";\n return str;\n }"
},
{
"code": null,
"e": 5754,
"s": 5751,
"text": "-1"
},
{
"code": null,
"e": 5778,
"s": 5754,
"text": "thanoschild4 months ago"
},
{
"code": null,
"e": 5830,
"s": 5778,
"text": "Time complexity = O(N), Space complexity = O(N) "
},
{
"code": null,
"e": 6412,
"s": 5830,
"text": "string removeKdigits(string S, int K) { stack<int> st; for(int i=0; i<S.size(); i++) { while(!st.empty() && st.top() > S[i] && K>0) { st.pop(); K--; } if(!st.empty() || S[i] != '0') st.push(S[i]); } while(!st.empty() && K--) { st.pop(); } if(st.empty()) return \"0\"; string ans; while(!st.empty()) { ans += st.top(); st.pop(); } reverse(ans.begin(), ans.end()); return ans; }"
},
{
"code": null,
"e": 6415,
"s": 6412,
"text": "-1"
},
{
"code": null,
"e": 6444,
"s": 6415,
"text": "shivambhadani1236 months ago"
},
{
"code": null,
"e": 6481,
"s": 6444,
"text": "O(N) time and O(N) space using stack"
},
{
"code": null,
"e": 7066,
"s": 6481,
"text": "class Solution {\n public:\n string removeKdigits(string S, int K) {\n stack<char> st;\n for(int i=0; i<S.size(); i++) {\n while(!st.empty() && st.top()>S[i] && K>0) {\n st.pop();\n K--;\n }\n if(!st.empty() || S[i]!='0') st.push(S[i]);\n }\n while(!st.empty() && K--) {;\n st.pop();\n }\n if(st.empty()) return \"0\";\n \n string ans;\n \n while(!st.empty()) {\n ans = st.top() + ans;\n st.pop();\n }\n return ans;\n }\n};"
},
{
"code": null,
"e": 7068,
"s": 7066,
"text": "0"
},
{
"code": null,
"e": 7088,
"s": 7068,
"text": "shady418 months ago"
},
{
"code": null,
"e": 7096,
"s": 7088,
"text": "shady41"
},
{
"code": null,
"e": 7154,
"s": 7096,
"text": "Need to remove greater nos. from significant positions..."
},
{
"code": null,
"e": 7825,
"s": 7154,
"text": "string removeKdigits(string str, int k) { deque<char>dq; for(char i: str){ if(dq.empty()) dq.push_back(i); else{ while(k && !dq.empty() && dq.back()-'0'>i-'0'){ dq.pop_back(); k--; } dq.push_back(i); } } while(k && !dq.empty()){ dq.pop_back(); k--; } while(!dq.empty() && dq.front()=='0'){ dq.pop_front(); } string ans=\"\"; while(!dq.empty()){ ans.push_back(dq.front()); dq.pop_front(); } return (ans.empty())?\"0\":ans; }"
},
{
"code": null,
"e": 7828,
"s": 7825,
"text": "-1"
},
{
"code": null,
"e": 7852,
"s": 7828,
"text": "wallflower10 months ago"
},
{
"code": null,
"e": 7863,
"s": 7852,
"text": "wallflower"
},
{
"code": null,
"e": 8069,
"s": 7863,
"text": "Hint : Use the next greater element concept of stack to pop elements that are greater than the current element. Then for the remaining k, remove elements from top of stack. And return the string obtained."
},
{
"code": null,
"e": 8100,
"s": 8069,
"text": "https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 8246,
"s": 8100,
"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": 8282,
"s": 8246,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 8292,
"s": 8282,
"text": "\nProblem\n"
},
{
"code": null,
"e": 8302,
"s": 8292,
"text": "\nContest\n"
},
{
"code": null,
"e": 8365,
"s": 8302,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8513,
"s": 8365,
"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": 8721,
"s": 8513,
"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": 8827,
"s": 8721,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Bootstrap page-header class
|
Page header is used to add appropriate spacing around the headings on a page.
To use a page header, wrap your heading in a <div> with a class of .page-header −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "page-header">
<h1>
Header
<small>Subtext for header</small>
</h1>
</div>
<p>Demo text! Demo text! Demo text! Demo text! Demo text!
Demo text! Demo text! Demo text! Demo text!
</p>
</body>
</html>
|
[
{
"code": null,
"e": 1140,
"s": 1062,
"text": "Page header is used to add appropriate spacing around the headings on a page."
},
{
"code": null,
"e": 1222,
"s": 1140,
"text": "To use a page header, wrap your heading in a <div> with a class of .page-header −"
},
{
"code": null,
"e": 1232,
"s": 1222,
"text": "Live Demo"
},
{
"code": null,
"e": 1805,
"s": 1232,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"page-header\">\n <h1>\n Header\n <small>Subtext for header</small>\n </h1>\n </div>\n <p>Demo text! Demo text! Demo text! Demo text! Demo text!\n Demo text! Demo text! Demo text! Demo text!\n </p>\n </body>\n</html>"
}
] |
DecisionTreeRegressor — Stop Using For Future Projections! | by Kaushik Choudhury | Towards Data Science
|
Scikit-learn is one of the most famous machine learning library in Python. It offers several classification, regression and clustering algorithms and its key strength, in my opinion, is seamless integration with Numpy, Pandas and Scipy.
Scikit-learn is so well written by the developers, that with a couple of lines of code we can check the model predictions by many different algorithms. I feel sometimes, this strength of Scikit-learn inadvertently works to its disadvantage. Machine learning developers esp. with relatively lesser experience implements an inappropriate algorithm for prediction without grasping particular algorithms salient feature and limitations.
In this article, I will discuss the reason we should not use the decision tree regression algorithm in making a prediction involving extrapolating the data.
Objective
We have the iron, calcium and protein content of peas since the time it is picked from the farm until 1142 days. Let us assume that it is easier and economical to measure the iron and calcium content compare to protein content.
We will use this data to train the DecisionTreeRegressor algorithm and then predict the protein content based on new data points related to iron content, calcium, and days passed.
Sample Data File
I think that the data file is pretty much self-explanatory. The rows show the iron, calcium and protein content of peas with days since harvesting.
Step 1- We will import the packages pandas, matplotlib, and DecisionTreeRegressor and NumPy which we are going to use for our analysis.
from sklearn.tree import DecisionTreeRegressorimport pandas as pdimport matplotlib.pyplot as pltimport numpy as np
Step 2- Read the full data sample data excel file into the PandasDataframe called “data”.
data= pd.read_excel("Peas Nutrient.xlsx")
I will not focus on preliminary data quality checks like blank values, outliers, etc. and respective correction approach in this article, and assuming that there are no data series related to the discrepancy.
Step 3- We will split the full data set into two parts viz. training and testing set. As the name suggests, we will be using the training dataset to train the decision tree regressor algorithm and compare the protein predictions with actual content based on data in the testing set.
In the below code, data records from day 1 to day 900 are sliced as training data and data records from day 901 to 1142 as testing data.
Training_data= data[:900]Test_data=data.loc[901:1142]
Step 4- “Days passed”, “iron content” and “calcium content” are independent variables used for prediction.”Protein content” predicted is the dependent variable. Generally, the independent variable is denoted with “X “and the dependent variable with “y”.
In the code below, “Protein content” data column is dropped from the DataFrame and remaining, data i.e independent variables datapoints is declared as X_train. Similarly, all the data columns except “Protein content” is dropped and declared as y_train.
X_train=Training_data.drop(["Protein Content "], axis=1)y_train=Training_data.drop(["Days Passed", "Iron Content " ,"Calcium Content "], axis=1)
The same process is repeated in the below code for the testing data set i.e. values from day 901 to day 1142,
X_test=Test_data.drop(["Protein Content "], axis=1)y_test=Test_data.drop(["Days Passed", "Iron Content " ,"Calcium Content "], axis=1)
Step 5- DecisionTreeRegressor model is trained with the training dataset. Further, the score is checked to understand how well the algorithm is trained on this data.
tree_reg = DecisionTreeRegressor().fit(X_train, y_train)print("The model training score is" , tree_reg.score(X_train, y_train))
A perfect score of 1.0 itself indicates the overfitting of the model.
Step 5- To address the overfitting due to unconstrained depth of tree during training the model, we will put a constraint of the max depth of 4.
tree_reg = DecisionTreeRegressor(max_depth=6).fit(X_train, y_train)print("The model training score is" , tree_reg.score(X_train, y_train))
This solves the overfitting of the model on training data, and the model is ready to predict the protein content based on test data points.
Step 6- In the below code, “protein content” of test data set i.e. from days 901 to 1142 is predicted based on respective “days passed”, “iron content” and “calcium content” data.
y_pred_tree = tree_reg.predict(X_test)
Step 7- We will plot the predicted protein content by the decision tree regression model and compare with actual protein content in the test dataset from day 901 to 1142.
plt.plot(X_test["Days Passed"],y_test, label="Actual Data")plt.plot(X_test["Days Passed"],np.rint(y_pred_tree), label="Predicted Data")plt.ylabel("Days Passed")plt.xlabel('Protin Content (in Grams)')plt.legend(loc='best')plt.show()
We can see that the decision tree regressor model, which is trained quite well in training dataset with 0.93 score fails miserably to predict the protein content on test data. The model predicts the same protein content of ~ 51.34 for all days.
We should not use the Decision Tree Regression model for prediction involving extrapolating the data. This is just an example, and the main takeaway for us machine learning practitioners are to consider the data, prediction objective, algorithms strengths and limitations before starting modelling.
We can make similar mistakes while selecting the independent variables for Machine Learning Supervised Algorithms. In the article, “How to identify the right independent variables for Machine Learning Supervised Algorithms? ” I have discussed a structured approach to identify the appropriate independent variables to make accurate predictions.
|
[
{
"code": null,
"e": 408,
"s": 171,
"text": "Scikit-learn is one of the most famous machine learning library in Python. It offers several classification, regression and clustering algorithms and its key strength, in my opinion, is seamless integration with Numpy, Pandas and Scipy."
},
{
"code": null,
"e": 841,
"s": 408,
"text": "Scikit-learn is so well written by the developers, that with a couple of lines of code we can check the model predictions by many different algorithms. I feel sometimes, this strength of Scikit-learn inadvertently works to its disadvantage. Machine learning developers esp. with relatively lesser experience implements an inappropriate algorithm for prediction without grasping particular algorithms salient feature and limitations."
},
{
"code": null,
"e": 998,
"s": 841,
"text": "In this article, I will discuss the reason we should not use the decision tree regression algorithm in making a prediction involving extrapolating the data."
},
{
"code": null,
"e": 1008,
"s": 998,
"text": "Objective"
},
{
"code": null,
"e": 1236,
"s": 1008,
"text": "We have the iron, calcium and protein content of peas since the time it is picked from the farm until 1142 days. Let us assume that it is easier and economical to measure the iron and calcium content compare to protein content."
},
{
"code": null,
"e": 1416,
"s": 1236,
"text": "We will use this data to train the DecisionTreeRegressor algorithm and then predict the protein content based on new data points related to iron content, calcium, and days passed."
},
{
"code": null,
"e": 1433,
"s": 1416,
"text": "Sample Data File"
},
{
"code": null,
"e": 1581,
"s": 1433,
"text": "I think that the data file is pretty much self-explanatory. The rows show the iron, calcium and protein content of peas with days since harvesting."
},
{
"code": null,
"e": 1717,
"s": 1581,
"text": "Step 1- We will import the packages pandas, matplotlib, and DecisionTreeRegressor and NumPy which we are going to use for our analysis."
},
{
"code": null,
"e": 1832,
"s": 1717,
"text": "from sklearn.tree import DecisionTreeRegressorimport pandas as pdimport matplotlib.pyplot as pltimport numpy as np"
},
{
"code": null,
"e": 1922,
"s": 1832,
"text": "Step 2- Read the full data sample data excel file into the PandasDataframe called “data”."
},
{
"code": null,
"e": 1964,
"s": 1922,
"text": "data= pd.read_excel(\"Peas Nutrient.xlsx\")"
},
{
"code": null,
"e": 2173,
"s": 1964,
"text": "I will not focus on preliminary data quality checks like blank values, outliers, etc. and respective correction approach in this article, and assuming that there are no data series related to the discrepancy."
},
{
"code": null,
"e": 2456,
"s": 2173,
"text": "Step 3- We will split the full data set into two parts viz. training and testing set. As the name suggests, we will be using the training dataset to train the decision tree regressor algorithm and compare the protein predictions with actual content based on data in the testing set."
},
{
"code": null,
"e": 2593,
"s": 2456,
"text": "In the below code, data records from day 1 to day 900 are sliced as training data and data records from day 901 to 1142 as testing data."
},
{
"code": null,
"e": 2647,
"s": 2593,
"text": "Training_data= data[:900]Test_data=data.loc[901:1142]"
},
{
"code": null,
"e": 2901,
"s": 2647,
"text": "Step 4- “Days passed”, “iron content” and “calcium content” are independent variables used for prediction.”Protein content” predicted is the dependent variable. Generally, the independent variable is denoted with “X “and the dependent variable with “y”."
},
{
"code": null,
"e": 3154,
"s": 2901,
"text": "In the code below, “Protein content” data column is dropped from the DataFrame and remaining, data i.e independent variables datapoints is declared as X_train. Similarly, all the data columns except “Protein content” is dropped and declared as y_train."
},
{
"code": null,
"e": 3299,
"s": 3154,
"text": "X_train=Training_data.drop([\"Protein Content \"], axis=1)y_train=Training_data.drop([\"Days Passed\", \"Iron Content \" ,\"Calcium Content \"], axis=1)"
},
{
"code": null,
"e": 3409,
"s": 3299,
"text": "The same process is repeated in the below code for the testing data set i.e. values from day 901 to day 1142,"
},
{
"code": null,
"e": 3544,
"s": 3409,
"text": "X_test=Test_data.drop([\"Protein Content \"], axis=1)y_test=Test_data.drop([\"Days Passed\", \"Iron Content \" ,\"Calcium Content \"], axis=1)"
},
{
"code": null,
"e": 3710,
"s": 3544,
"text": "Step 5- DecisionTreeRegressor model is trained with the training dataset. Further, the score is checked to understand how well the algorithm is trained on this data."
},
{
"code": null,
"e": 3838,
"s": 3710,
"text": "tree_reg = DecisionTreeRegressor().fit(X_train, y_train)print(\"The model training score is\" , tree_reg.score(X_train, y_train))"
},
{
"code": null,
"e": 3908,
"s": 3838,
"text": "A perfect score of 1.0 itself indicates the overfitting of the model."
},
{
"code": null,
"e": 4053,
"s": 3908,
"text": "Step 5- To address the overfitting due to unconstrained depth of tree during training the model, we will put a constraint of the max depth of 4."
},
{
"code": null,
"e": 4192,
"s": 4053,
"text": "tree_reg = DecisionTreeRegressor(max_depth=6).fit(X_train, y_train)print(\"The model training score is\" , tree_reg.score(X_train, y_train))"
},
{
"code": null,
"e": 4332,
"s": 4192,
"text": "This solves the overfitting of the model on training data, and the model is ready to predict the protein content based on test data points."
},
{
"code": null,
"e": 4512,
"s": 4332,
"text": "Step 6- In the below code, “protein content” of test data set i.e. from days 901 to 1142 is predicted based on respective “days passed”, “iron content” and “calcium content” data."
},
{
"code": null,
"e": 4551,
"s": 4512,
"text": "y_pred_tree = tree_reg.predict(X_test)"
},
{
"code": null,
"e": 4722,
"s": 4551,
"text": "Step 7- We will plot the predicted protein content by the decision tree regression model and compare with actual protein content in the test dataset from day 901 to 1142."
},
{
"code": null,
"e": 4954,
"s": 4722,
"text": "plt.plot(X_test[\"Days Passed\"],y_test, label=\"Actual Data\")plt.plot(X_test[\"Days Passed\"],np.rint(y_pred_tree), label=\"Predicted Data\")plt.ylabel(\"Days Passed\")plt.xlabel('Protin Content (in Grams)')plt.legend(loc='best')plt.show()"
},
{
"code": null,
"e": 5199,
"s": 4954,
"text": "We can see that the decision tree regressor model, which is trained quite well in training dataset with 0.93 score fails miserably to predict the protein content on test data. The model predicts the same protein content of ~ 51.34 for all days."
},
{
"code": null,
"e": 5498,
"s": 5199,
"text": "We should not use the Decision Tree Regression model for prediction involving extrapolating the data. This is just an example, and the main takeaway for us machine learning practitioners are to consider the data, prediction objective, algorithms strengths and limitations before starting modelling."
}
] |
Miscellaneous Problems of Time Complexity - GeeksforGeeks
|
16 Feb, 2022
Prerequisite : Asymptotic Notations
Time Complexity :Time complexity is the time needed by an algorithm expressed as a function of the size of a problem. It can also be defined as the amount of computer time it needs to run a program to completion. When we solve a problem of time complexity then this definition help the most – “It is the number of operations an algorithm performs to complete its task with respect to the input size.”
There are following some miscellaneous problems of time complexity which are always frequently asking in different types of quizzes.
1. What is the time complexity of the following code –
C++
C
Java
Python3
C#
Javascript
void function(int n){ int i = 1, s = 1; while (s < n) { s = s + i; i++; }} // This code is contributed by Shubham Singh
void function(int n){ int i = 1, s = 1; while (s < n) { s = s + i; i++; }}
public static void function(int n){ int i = 1, s = 1; while (s < n) { s = s + i; i++; }} // This code is contributed by Shubham Singh
def function(n): i = 1 s = 1 while (s < n): s = s + i i+=1 # This code is contributed by Shubham Singh
public static void function(int n){ int i = 1, s = 1; while (s < n) { s = s + i; i++; }} // This code is contributed by Shubham Singh
<script>function functionn(int n){ var i = 1; var s = 1; while (s < n) { s = s + i; i++; }} // This code is contributed by Shubham Singh</script>
Solution – Time complexity = O(√n).
Explanation – We can define the ‘S’ terms according to the relation Si = Si-1 + i. Let k is the total number of iterations taken by the program
When S>=n , then loop will stop at kth iterations,⇒ S>=n ⇒ S=n⇒ 2 + 2 + 3 + 4 + ......+ k = n⇒ 1 + (k * (k + 1))/2 = n⇒ k2 = n k = √nHence, the time complexity is O(√n).
2. What is the time complexity of the following code :
C++
C
Java
Python3
C#
Javascript
void fun(int n){ if (n < 5) cout << "GeeksforGeeks"; else { for (int i = 0; i < n; i++) { cout << i; } }} // This code is contributed by Shubham Singh
void fun(int n){ if (n < 5) printf("GeeksforGeeks"); else { for (int i = 0; i < n; i++) { printf("%d", i); } }}
public static void fun(int n){ if (n < 5) System.out.print("GeeksforGeeks"); else { for (int i = 0; i < n; i++) { System.out.print(i + " "); } }} // This code is contributed by Shubham Singh
def fun(n): if (n < 5): print("GeeksforGeeks", end ="") else: for i in range(n): print(i, end= " ") # This code is contributed by Shubham Singh
public static void fun(int n){ if (n < 5) Console.Write("GeeksforGeeks"); else { for (int i = 0; i < n; i++) { Console.Write(i + " "); } }} // This code is contributed by Shubham Singh
<script>function fun(n){ if (n < 5) document.write("GeeksforGeeks"); else { for (var i = 0; i < n; i++) { document.write(i + " "); } }} //This code is contributed by Shubham Singh</script>
Solution – Time complexity = O(1) in best case and O(n) in worst case.
Explanation –This program contains if and else condition. Hence, there are 2 possibilities of time complexity. If the value of n is less than 5, then we get only GeeksforGeeks as output and its time complexity will be O(1). But, if n>=5, then for loop will execute and time complexity becomes O(n), it is considered as worst case because it takes more time.
3. What is the time complexity of the following code :
C++
C
Java
Python3
C#
void fun(int a, int b){ while (a != b) { if (a > b) a = a - b; else b = b - a; }} // This code is contributed by Shubham Singh
void fun(int a, int b){ while (a != b) { if (a > b) a = a - b; else b = b - a; }}
public static void fun(int a, int b){ while (a != b) { if (a > b) a = a - b; else b = b - a; }} // This code is contributed by Shubham Singh
def fun(a, b): while (a != b): if (a > b): a = a - b else: b = b - a # This code is contributed by Shubham Singh
public static void fun(int a, int b){ while (a != b) { if (a > b) a = a - b; else b = b - a; }} // This code is contributed by Shubham Singh
Solution –Time complexity = O(1) in best case and O(max(a, b)) worst case.
Explanation –If the value of a and b are the same, then while loop will not be executed. Hence, time complexity will be O(1). But if a!=b, then the while loop will be executed. Let a=16 and b=5;
For this case, while loop executed 8 times (a/2⇒16/2⇒8). If a=5 and b=16, then also the loop will be executed 8 times. So we can say that time complexity is O(max(a/2,b/2))⇒O(max(a, b)), it is considered as worst case because it takes more time.
4. What is the time complexity of the following code :
C++
C
void fun(int n){ for(int i=0;i*i<n;i++) cout<<"GeeksforGeeks";} // This code is contributed by Shubham Singh
void fun(int n){ for(int i=0;i*i<n;i++) printf("%s","GeeksforGeeks");}
Solution – Time complexity = O(√n).
Explanation –Let k be the no. of iteration of the loop.
⇒ The loop will stop when i * i >=n i.e., i*i=n⇒ i*i=n ⇒ k2 = n⇒k =√nHence, the time complexity is O(√n).
5. What is the time complexity of the following code :
C++
C
void fun(int n, int x){ for (int i = 1; i < n; i = i * x) //or for(int i = n; i >=1; i = i / x) cout << "GeeksforGeeks";} //This code is contributed by Shubham Singh
void fun(int n, int x){ for (int i = 1; i < n; i = i * x) //or for(int i = n; i >=1; i = i / x) print("GeeksforGeeks");}
Solution – Time complexity = O(logxn).
Explanation – Let k be the no. of iteration of the loop.
⇒ The loop will stop when i>=n ⇒ xk = n⇒ xk=n (Take log both sides)⇒ k=logxn⇒Hence, time complexity is O(logxn).
6. What is the time complexity of the following code :
C
void fun(int n){ for (int i = 0; i < n / 2; i++) for (int j = 1; j + n / 2 <= n; j++) for (int k = 1; k <= n; k = k * 2) cout << "GeeksforGeeks";}
Solution –Time complexity = O(n2log2n).
Explanation – Time complexity of 1st for loop = O(n/2) ⇒ O(n).Time complexity of 2nd for loop = O(n/2) ⇒ O(n).Time complexity of 3rd for loop = O(log2n). (refer question number – 5)Hence, the time complexity of function will become O(n2log2n).
7. What is the time complexity of the following code :
C
void fun(int n){ for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j = j + i) cout << "GeeksforGeeks";}
Solution – Time complexity = O(nlogn).
Explanation – Time complexity of 1st for loop = O(n). 2nd loop executes n/i times for each value of i. Its time complexity is O(∑ni=1 n/i) ⇒ O(logn).Hence, time complexity of function = O(nlogn).
8. What is the time complexity of the following code :
C
void fun(int n){ for (int i = 0; i <= n / 3; i++) for (int j = 1; j <= n; j = j + 4) cout << "GeeksforGeeks";}
Solution – Time complexity = O(n2).
Explanation – Time complexity of 1st for loop = O(n/3) ⇒ O(n).Time complexity of 2nd for loop = O(n/4) ⇒ O(n).Hence, the time complexity of function will become O(n2).
9. What is the time complexity of the following code :
C++
C
void fun(int n){ int i = 1; while (i < n) { int j = n; while (j > 0) { j = j / 2; } i = i * 2; }} //This code is contributed by Shubham Singh
void fun(int n){ int i = 1; while (i < n) { int j = n; while (j > 0) { j = j / 2; } i = i * 2; }}
Solution – Time complexity = O(log2n).
Explanation – In each iteration , i become twice (T.C=O(logn)) and j become half (T.C=O(logn)). So, time complexity will become O(log2n).We can convert this while loop into for loop. for( int i = 1; i < n; i = i * 2) for( int j=n ; j > 0; j = j / 2).
Time complexity of above for loop is also O(log2n).
10. Consider the following C-code, what is the number of comparisons made in the execution of the loop ?
C
void fun(int n){ int j = 1; while (j <= n) { j = j * 2; }}
Solution – ceil(log2n)+1.
Explanation –Let k be the no. of iteration of the loop. After the kth step, the value of j is 2k. Hence, k=log2n. Here, we use ceil of log2n, because log2n may be in decimal. Since we are doing one more comparison for exiting from the loop.So, the answer is ceil(log2n)+1.
anuragkumar8
SHUBHAMSINGH10
surinderdawra388
time complexity
Analysis
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
3-coloring is NP Complete
Proof that Dominant Set of a Graph is NP-Complete
Difference between Deterministic and Non-deterministic Algorithms
Set partition is NP complete
Pseudo-polynomial Algorithms
Complexity analysis of various operations of Binary Min Heap
Proof that Independent Set in Graph theory is NP Complete
Applications of Hashing
Time Complexity Analysis | Tower Of Hanoi (Recursion)
|
[
{
"code": null,
"e": 24655,
"s": 24627,
"text": "\n16 Feb, 2022"
},
{
"code": null,
"e": 24691,
"s": 24655,
"text": "Prerequisite : Asymptotic Notations"
},
{
"code": null,
"e": 25092,
"s": 24691,
"text": "Time Complexity :Time complexity is the time needed by an algorithm expressed as a function of the size of a problem. It can also be defined as the amount of computer time it needs to run a program to completion. When we solve a problem of time complexity then this definition help the most – “It is the number of operations an algorithm performs to complete its task with respect to the input size.”"
},
{
"code": null,
"e": 25225,
"s": 25092,
"text": "There are following some miscellaneous problems of time complexity which are always frequently asking in different types of quizzes."
},
{
"code": null,
"e": 25280,
"s": 25225,
"text": "1. What is the time complexity of the following code –"
},
{
"code": null,
"e": 25284,
"s": 25280,
"text": "C++"
},
{
"code": null,
"e": 25286,
"s": 25284,
"text": "C"
},
{
"code": null,
"e": 25291,
"s": 25286,
"text": "Java"
},
{
"code": null,
"e": 25299,
"s": 25291,
"text": "Python3"
},
{
"code": null,
"e": 25302,
"s": 25299,
"text": "C#"
},
{
"code": null,
"e": 25313,
"s": 25302,
"text": "Javascript"
},
{
"code": "void function(int n){ int i = 1, s = 1; while (s < n) { s = s + i; i++; }} // This code is contributed by Shubham Singh",
"e": 25456,
"s": 25313,
"text": null
},
{
"code": "void function(int n){ int i = 1, s = 1; while (s < n) { s = s + i; i++; }}",
"e": 25554,
"s": 25456,
"text": null
},
{
"code": "public static void function(int n){ int i = 1, s = 1; while (s < n) { s = s + i; i++; }} // This code is contributed by Shubham Singh",
"e": 25711,
"s": 25554,
"text": null
},
{
"code": "def function(n): i = 1 s = 1 while (s < n): s = s + i i+=1 # This code is contributed by Shubham Singh",
"e": 25841,
"s": 25711,
"text": null
},
{
"code": "public static void function(int n){ int i = 1, s = 1; while (s < n) { s = s + i; i++; }} // This code is contributed by Shubham Singh",
"e": 25998,
"s": 25841,
"text": null
},
{
"code": "<script>function functionn(int n){ var i = 1; var s = 1; while (s < n) { s = s + i; i++; }} // This code is contributed by Shubham Singh</script>",
"e": 26170,
"s": 25998,
"text": null
},
{
"code": null,
"e": 26210,
"s": 26173,
"text": "Solution – Time complexity = O(√n)."
},
{
"code": null,
"e": 26357,
"s": 26212,
"text": "Explanation – We can define the ‘S’ terms according to the relation Si = Si-1 + i. Let k is the total number of iterations taken by the program "
},
{
"code": null,
"e": 26534,
"s": 26361,
"text": " When S>=n , then loop will stop at kth iterations,⇒ S>=n ⇒ S=n⇒ 2 + 2 + 3 + 4 + ......+ k = n⇒ 1 + (k * (k + 1))/2 = n⇒ k2 = n k = √nHence, the time complexity is O(√n)."
},
{
"code": null,
"e": 26592,
"s": 26536,
"text": "2. What is the time complexity of the following code : "
},
{
"code": null,
"e": 26598,
"s": 26594,
"text": "C++"
},
{
"code": null,
"e": 26600,
"s": 26598,
"text": "C"
},
{
"code": null,
"e": 26605,
"s": 26600,
"text": "Java"
},
{
"code": null,
"e": 26613,
"s": 26605,
"text": "Python3"
},
{
"code": null,
"e": 26616,
"s": 26613,
"text": "C#"
},
{
"code": null,
"e": 26627,
"s": 26616,
"text": "Javascript"
},
{
"code": "void fun(int n){ if (n < 5) cout << \"GeeksforGeeks\"; else { for (int i = 0; i < n; i++) { cout << i; } }} // This code is contributed by Shubham Singh",
"e": 26819,
"s": 26627,
"text": null
},
{
"code": "void fun(int n){ if (n < 5) printf(\"GeeksforGeeks\"); else { for (int i = 0; i < n; i++) { printf(\"%d\", i); } }}",
"e": 26972,
"s": 26819,
"text": null
},
{
"code": "public static void fun(int n){ if (n < 5) System.out.print(\"GeeksforGeeks\"); else { for (int i = 0; i < n; i++) { System.out.print(i + \" \"); } }} // This code is contributed by Shubham Singh",
"e": 27204,
"s": 26972,
"text": null
},
{
"code": "def fun(n): if (n < 5): print(\"GeeksforGeeks\", end =\"\") else: for i in range(n): print(i, end= \" \") # This code is contributed by Shubham Singh",
"e": 27391,
"s": 27204,
"text": null
},
{
"code": "public static void fun(int n){ if (n < 5) Console.Write(\"GeeksforGeeks\"); else { for (int i = 0; i < n; i++) { Console.Write(i + \" \"); } }} // This code is contributed by Shubham Singh",
"e": 27617,
"s": 27391,
"text": null
},
{
"code": "<script>function fun(n){ if (n < 5) document.write(\"GeeksforGeeks\"); else { for (var i = 0; i < n; i++) { document.write(i + \" \"); } }} //This code is contributed by Shubham Singh</script>",
"e": 27847,
"s": 27617,
"text": null
},
{
"code": null,
"e": 27918,
"s": 27847,
"text": "Solution – Time complexity = O(1) in best case and O(n) in worst case."
},
{
"code": null,
"e": 28276,
"s": 27918,
"text": "Explanation –This program contains if and else condition. Hence, there are 2 possibilities of time complexity. If the value of n is less than 5, then we get only GeeksforGeeks as output and its time complexity will be O(1). But, if n>=5, then for loop will execute and time complexity becomes O(n), it is considered as worst case because it takes more time."
},
{
"code": null,
"e": 28332,
"s": 28276,
"text": "3. What is the time complexity of the following code : "
},
{
"code": null,
"e": 28336,
"s": 28332,
"text": "C++"
},
{
"code": null,
"e": 28338,
"s": 28336,
"text": "C"
},
{
"code": null,
"e": 28343,
"s": 28338,
"text": "Java"
},
{
"code": null,
"e": 28351,
"s": 28343,
"text": "Python3"
},
{
"code": null,
"e": 28354,
"s": 28351,
"text": "C#"
},
{
"code": "void fun(int a, int b){ while (a != b) { if (a > b) a = a - b; else b = b - a; }} // This code is contributed by Shubham Singh",
"e": 28523,
"s": 28354,
"text": null
},
{
"code": "void fun(int a, int b){ while (a != b) { if (a > b) a = a - b; else b = b - a; }}",
"e": 28647,
"s": 28523,
"text": null
},
{
"code": "public static void fun(int a, int b){ while (a != b) { if (a > b) a = a - b; else b = b - a; }} // This code is contributed by Shubham Singh",
"e": 28830,
"s": 28647,
"text": null
},
{
"code": "def fun(a, b): while (a != b): if (a > b): a = a - b else: b = b - a # This code is contributed by Shubham Singh",
"e": 28999,
"s": 28830,
"text": null
},
{
"code": "public static void fun(int a, int b){ while (a != b) { if (a > b) a = a - b; else b = b - a; }} // This code is contributed by Shubham Singh",
"e": 29182,
"s": 28999,
"text": null
},
{
"code": null,
"e": 29260,
"s": 29185,
"text": "Solution –Time complexity = O(1) in best case and O(max(a, b)) worst case."
},
{
"code": null,
"e": 29457,
"s": 29262,
"text": "Explanation –If the value of a and b are the same, then while loop will not be executed. Hence, time complexity will be O(1). But if a!=b, then the while loop will be executed. Let a=16 and b=5;"
},
{
"code": null,
"e": 29707,
"s": 29461,
"text": "For this case, while loop executed 8 times (a/2⇒16/2⇒8). If a=5 and b=16, then also the loop will be executed 8 times. So we can say that time complexity is O(max(a/2,b/2))⇒O(max(a, b)), it is considered as worst case because it takes more time."
},
{
"code": null,
"e": 29765,
"s": 29709,
"text": "4. What is the time complexity of the following code : "
},
{
"code": null,
"e": 29771,
"s": 29767,
"text": "C++"
},
{
"code": null,
"e": 29773,
"s": 29771,
"text": "C"
},
{
"code": "void fun(int n){ for(int i=0;i*i<n;i++) cout<<\"GeeksforGeeks\";} // This code is contributed by Shubham Singh",
"e": 29886,
"s": 29773,
"text": null
},
{
"code": "void fun(int n){ for(int i=0;i*i<n;i++) printf(\"%s\",\"GeeksforGeeks\");}",
"e": 29961,
"s": 29886,
"text": null
},
{
"code": null,
"e": 29997,
"s": 29961,
"text": "Solution – Time complexity = O(√n)."
},
{
"code": null,
"e": 30053,
"s": 29997,
"text": "Explanation –Let k be the no. of iteration of the loop."
},
{
"code": null,
"e": 30166,
"s": 30053,
"text": "⇒ The loop will stop when i * i >=n i.e., i*i=n⇒ i*i=n ⇒ k2 = n⇒k =√nHence, the time complexity is O(√n)."
},
{
"code": null,
"e": 30222,
"s": 30166,
"text": "5. What is the time complexity of the following code : "
},
{
"code": null,
"e": 30226,
"s": 30222,
"text": "C++"
},
{
"code": null,
"e": 30228,
"s": 30226,
"text": "C"
},
{
"code": "void fun(int n, int x){ for (int i = 1; i < n; i = i * x) //or for(int i = n; i >=1; i = i / x) cout << \"GeeksforGeeks\";} //This code is contributed by Shubham Singh",
"e": 30404,
"s": 30228,
"text": null
},
{
"code": "void fun(int n, int x){ for (int i = 1; i < n; i = i * x) //or for(int i = n; i >=1; i = i / x) print(\"GeeksforGeeks\");}",
"e": 30535,
"s": 30404,
"text": null
},
{
"code": null,
"e": 30577,
"s": 30538,
"text": "Solution – Time complexity = O(logxn)."
},
{
"code": null,
"e": 30636,
"s": 30579,
"text": "Explanation – Let k be the no. of iteration of the loop."
},
{
"code": null,
"e": 30776,
"s": 30640,
"text": "⇒ The loop will stop when i>=n ⇒ xk = n⇒ xk=n (Take log both sides)⇒ k=logxn⇒Hence, time complexity is O(logxn)."
},
{
"code": null,
"e": 30834,
"s": 30778,
"text": "6. What is the time complexity of the following code : "
},
{
"code": null,
"e": 30838,
"s": 30836,
"text": "C"
},
{
"code": "void fun(int n){ for (int i = 0; i < n / 2; i++) for (int j = 1; j + n / 2 <= n; j++) for (int k = 1; k <= n; k = k * 2) cout << \"GeeksforGeeks\";}",
"e": 31021,
"s": 30838,
"text": null
},
{
"code": null,
"e": 31065,
"s": 31024,
"text": "Solution –Time complexity = O(n2log2n)."
},
{
"code": null,
"e": 31347,
"s": 31067,
"text": "Explanation – Time complexity of 1st for loop = O(n/2) ⇒ O(n).Time complexity of 2nd for loop = O(n/2) ⇒ O(n).Time complexity of 3rd for loop = O(log2n). (refer question number – 5)Hence, the time complexity of function will become O(n2log2n)."
},
{
"code": null,
"e": 31405,
"s": 31349,
"text": "7. What is the time complexity of the following code : "
},
{
"code": null,
"e": 31409,
"s": 31407,
"text": "C"
},
{
"code": "void fun(int n){ for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j = j + i) cout << \"GeeksforGeeks\";}",
"e": 31537,
"s": 31409,
"text": null
},
{
"code": null,
"e": 31579,
"s": 31540,
"text": "Solution – Time complexity = O(nlogn)."
},
{
"code": null,
"e": 31777,
"s": 31581,
"text": "Explanation – Time complexity of 1st for loop = O(n). 2nd loop executes n/i times for each value of i. Its time complexity is O(∑ni=1 n/i) ⇒ O(logn).Hence, time complexity of function = O(nlogn)."
},
{
"code": null,
"e": 31843,
"s": 31779,
"text": " 8. What is the time complexity of the following code : "
},
{
"code": null,
"e": 31847,
"s": 31845,
"text": "C"
},
{
"code": "void fun(int n){ for (int i = 0; i <= n / 3; i++) for (int j = 1; j <= n; j = j + 4) cout << \"GeeksforGeeks\";}",
"e": 31979,
"s": 31847,
"text": null
},
{
"code": null,
"e": 32016,
"s": 31979,
"text": "Solution – Time complexity = O(n2)."
},
{
"code": null,
"e": 32184,
"s": 32016,
"text": "Explanation – Time complexity of 1st for loop = O(n/3) ⇒ O(n).Time complexity of 2nd for loop = O(n/4) ⇒ O(n).Hence, the time complexity of function will become O(n2)."
},
{
"code": null,
"e": 32242,
"s": 32184,
"text": "9. What is the time complexity of the following code : "
},
{
"code": null,
"e": 32246,
"s": 32242,
"text": "C++"
},
{
"code": null,
"e": 32248,
"s": 32246,
"text": "C"
},
{
"code": "void fun(int n){ int i = 1; while (i < n) { int j = n; while (j > 0) { j = j / 2; } i = i * 2; }} //This code is contributed by Shubham Singh",
"e": 32438,
"s": 32248,
"text": null
},
{
"code": "void fun(int n){ int i = 1; while (i < n) { int j = n; while (j > 0) { j = j / 2; } i = i * 2; }}",
"e": 32584,
"s": 32438,
"text": null
},
{
"code": null,
"e": 32624,
"s": 32584,
"text": "Solution – Time complexity = O(log2n)."
},
{
"code": null,
"e": 32881,
"s": 32624,
"text": "Explanation – In each iteration , i become twice (T.C=O(logn)) and j become half (T.C=O(logn)). So, time complexity will become O(log2n).We can convert this while loop into for loop. for( int i = 1; i < n; i = i * 2) for( int j=n ; j > 0; j = j / 2)."
},
{
"code": null,
"e": 32933,
"s": 32881,
"text": "Time complexity of above for loop is also O(log2n)."
},
{
"code": null,
"e": 33038,
"s": 32933,
"text": "10. Consider the following C-code, what is the number of comparisons made in the execution of the loop ?"
},
{
"code": null,
"e": 33040,
"s": 33038,
"text": "C"
},
{
"code": "void fun(int n){ int j = 1; while (j <= n) { j = j * 2; }}",
"e": 33115,
"s": 33040,
"text": null
},
{
"code": null,
"e": 33141,
"s": 33115,
"text": "Solution – ceil(log2n)+1."
},
{
"code": null,
"e": 33414,
"s": 33141,
"text": "Explanation –Let k be the no. of iteration of the loop. After the kth step, the value of j is 2k. Hence, k=log2n. Here, we use ceil of log2n, because log2n may be in decimal. Since we are doing one more comparison for exiting from the loop.So, the answer is ceil(log2n)+1."
},
{
"code": null,
"e": 33427,
"s": 33414,
"text": "anuragkumar8"
},
{
"code": null,
"e": 33442,
"s": 33427,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 33459,
"s": 33442,
"text": "surinderdawra388"
},
{
"code": null,
"e": 33475,
"s": 33459,
"text": "time complexity"
},
{
"code": null,
"e": 33484,
"s": 33475,
"text": "Analysis"
},
{
"code": null,
"e": 33582,
"s": 33484,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33591,
"s": 33582,
"text": "Comments"
},
{
"code": null,
"e": 33604,
"s": 33591,
"text": "Old Comments"
},
{
"code": null,
"e": 33671,
"s": 33604,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 33697,
"s": 33671,
"text": "3-coloring is NP Complete"
},
{
"code": null,
"e": 33747,
"s": 33697,
"text": "Proof that Dominant Set of a Graph is NP-Complete"
},
{
"code": null,
"e": 33813,
"s": 33747,
"text": "Difference between Deterministic and Non-deterministic Algorithms"
},
{
"code": null,
"e": 33842,
"s": 33813,
"text": "Set partition is NP complete"
},
{
"code": null,
"e": 33871,
"s": 33842,
"text": "Pseudo-polynomial Algorithms"
},
{
"code": null,
"e": 33932,
"s": 33871,
"text": "Complexity analysis of various operations of Binary Min Heap"
},
{
"code": null,
"e": 33990,
"s": 33932,
"text": "Proof that Independent Set in Graph theory is NP Complete"
},
{
"code": null,
"e": 34014,
"s": 33990,
"text": "Applications of Hashing"
}
] |
How to embed Lua codes in Java?
|
Lua is probably the most commonly used embedding language that can be integrated or embedded into different major programming languages. There are different projects that does this work of embedding for us, Lua has been embedded into C, C# and Java also.
In this article, we will explore how the embedding of Lua in Java works, and we will also explore the most commonly used project that does this for us.
Embedding Lua with Java simply means the fact we should be able to run the code inside the Lua file with the help of the java commands. Just like how we run a normal Java file with the following command
javac HelloWorld.java
java HelloWorld
or
java HelloWorld
We should be able to replace the .java file with the .lua one.
The most commonly used project for embedding Lua in Java is luaj. The source code is present on this link.
You can clone the repository on your local machine with the help of the following command −
git clone https://github.com/luaj/luaj.git
After cloning, you will be able to find several examples present inside the examples/ directory.
Inside that directory a folder named lua is present and we will use one example from that which is the hello.lua one.
Just type the following command in the terminal −
java -cp luaj-jse-3.0.2.jar lua examples/lua/hello.lua
hello, world
This is how easy it is to embed Lua in Java.
|
[
{
"code": null,
"e": 1317,
"s": 1062,
"text": "Lua is probably the most commonly used embedding language that can be integrated or embedded into different major programming languages. There are different projects that does this work of embedding for us, Lua has been embedded into C, C# and Java also."
},
{
"code": null,
"e": 1469,
"s": 1317,
"text": "In this article, we will explore how the embedding of Lua in Java works, and we will also explore the most commonly used project that does this for us."
},
{
"code": null,
"e": 1672,
"s": 1469,
"text": "Embedding Lua with Java simply means the fact we should be able to run the code inside the Lua file with the help of the java commands. Just like how we run a normal Java file with the following command"
},
{
"code": null,
"e": 1729,
"s": 1672,
"text": "javac HelloWorld.java\njava HelloWorld\nor\njava HelloWorld"
},
{
"code": null,
"e": 1792,
"s": 1729,
"text": "We should be able to replace the .java file with the .lua one."
},
{
"code": null,
"e": 1899,
"s": 1792,
"text": "The most commonly used project for embedding Lua in Java is luaj. The source code is present on this link."
},
{
"code": null,
"e": 1991,
"s": 1899,
"text": "You can clone the repository on your local machine with the help of the following command −"
},
{
"code": null,
"e": 2034,
"s": 1991,
"text": "git clone https://github.com/luaj/luaj.git"
},
{
"code": null,
"e": 2131,
"s": 2034,
"text": "After cloning, you will be able to find several examples present inside the examples/ directory."
},
{
"code": null,
"e": 2249,
"s": 2131,
"text": "Inside that directory a folder named lua is present and we will use one example from that which is the hello.lua one."
},
{
"code": null,
"e": 2299,
"s": 2249,
"text": "Just type the following command in the terminal −"
},
{
"code": null,
"e": 2354,
"s": 2299,
"text": "java -cp luaj-jse-3.0.2.jar lua examples/lua/hello.lua"
},
{
"code": null,
"e": 2368,
"s": 2354,
"text": "hello, world\n"
},
{
"code": null,
"e": 2413,
"s": 2368,
"text": "This is how easy it is to embed Lua in Java."
}
] |
How does the repetition operator work on a tuple in Python?
|
We are accustomed to using the * symbol to represent multiplication, but when the operand on the left side of the * is a tuple, it becomes the repetition operator. The repetition operator makes multiple copies of a tuple and joins them all together. Tuples can be created using the repetition operator, *.
numbers = (0,) * 5 # we use the comma to denote that this is a single valued tuple and not an #expression
print numbers
This will give the output −
(0, 0, 0, 0, 0)
[0] is a tuple with one element, 0. The repetition operator makes 5 copies of this tuple and joins them all together into a single tuple. Another example using multiple elements in the tuple.
numbers = (0, 1, 2) * 3
print numbers
This will give the output −
(0, 1, 2, 0, 1, 2, 0, 1, 2)
|
[
{
"code": null,
"e": 1369,
"s": 1062,
"text": "We are accustomed to using the * symbol to represent multiplication, but when the operand on the left side of the * is a tuple, it becomes the repetition operator. The repetition operator makes multiple copies of a tuple and joins them all together. Tuples can be created using the repetition operator, *. "
},
{
"code": null,
"e": 1490,
"s": 1369,
"text": "numbers = (0,) * 5 # we use the comma to denote that this is a single valued tuple and not an #expression\nprint numbers"
},
{
"code": null,
"e": 1518,
"s": 1490,
"text": "This will give the output −"
},
{
"code": null,
"e": 1534,
"s": 1518,
"text": "(0, 0, 0, 0, 0)"
},
{
"code": null,
"e": 1727,
"s": 1534,
"text": "[0] is a tuple with one element, 0. The repetition operator makes 5 copies of this tuple and joins them all together into a single tuple. Another example using multiple elements in the tuple."
},
{
"code": null,
"e": 1765,
"s": 1727,
"text": "numbers = (0, 1, 2) * 3\nprint numbers"
},
{
"code": null,
"e": 1793,
"s": 1765,
"text": "This will give the output −"
},
{
"code": null,
"e": 1821,
"s": 1793,
"text": "(0, 1, 2, 0, 1, 2, 0, 1, 2)"
}
] |
What is ROW_NUMBER() in MySQL?
|
Row_NUMBER() included from MySQL version 8.0. It is a type of window function. This can be
used to assign a sequence number for rows. To understand, create a table with the help of CREATE pcommand −
mysql> CREATE table rowNumberDemo
-> (
-> FirstName varchar(100)
-> );
Query OK, 0 rows affected (0.92 sec)
mysql> INSERT into rowNumberDemo values('john');
Query OK, 1 row affected (0.17 sec)
mysql> INSERT into rowNumberDemo values('john');
Query OK, 1 row affected (0.29 sec)
mysql> INSERT into rowNumberDemo values('Bob');
Query OK, 1 row affected (0.13 sec)
mysql> INSERT into rowNumberDemo values('Smith');
Query OK, 1 row affected (0.17 sec)
We can display all the records with the help of SELECT statement −
mysql> SELECT * from rowNumberDemo;
The following is the output −
+-----------+
| FirstName |
+-----------+
| john |
| john |
| Bob |
| Smith |
+-----------+
4 rows in set (0.00 sec)
Now, we can use the row_number() to assign a incrementing value for every record −
mysql> SELECT row_number() over ( order by firstName) RowNumberSqeuence,FirstName from rowNumberDemo
-> order by FirstName;
The following is the output −
+-------------------+-----------+
| RowNumberSqeuence | FirstName |
+-------------------+-----------+
| 1 | Bob |
| 2 | john |
| 3 | john |
| 4 | Smith |
+-------------------+-----------+
4 rows in set (0.00 sec)
Look at the output, we have assigned a number to every record with the help of row_number().
|
[
{
"code": null,
"e": 1261,
"s": 1062,
"text": "Row_NUMBER() included from MySQL version 8.0. It is a type of window function. This can be\nused to assign a sequence number for rows. To understand, create a table with the help of CREATE pcommand −"
},
{
"code": null,
"e": 1369,
"s": 1261,
"text": "mysql> CREATE table rowNumberDemo\n-> (\n-> FirstName varchar(100)\n-> );\nQuery OK, 0 rows affected (0.92 sec)"
},
{
"code": null,
"e": 1712,
"s": 1369,
"text": "mysql> INSERT into rowNumberDemo values('john');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> INSERT into rowNumberDemo values('john');\nQuery OK, 1 row affected (0.29 sec)\n\nmysql> INSERT into rowNumberDemo values('Bob');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> INSERT into rowNumberDemo values('Smith');\nQuery OK, 1 row affected (0.17 sec)"
},
{
"code": null,
"e": 1779,
"s": 1712,
"text": "We can display all the records with the help of SELECT statement −"
},
{
"code": null,
"e": 1816,
"s": 1779,
"text": "mysql> SELECT * from rowNumberDemo;\n"
},
{
"code": null,
"e": 1846,
"s": 1816,
"text": "The following is the output −"
},
{
"code": null,
"e": 1983,
"s": 1846,
"text": "+-----------+\n| FirstName |\n+-----------+\n| john |\n| john |\n| Bob |\n| Smith |\n+-----------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2066,
"s": 1983,
"text": "Now, we can use the row_number() to assign a incrementing value for every record −"
},
{
"code": null,
"e": 2190,
"s": 2066,
"text": "mysql> SELECT row_number() over ( order by firstName) RowNumberSqeuence,FirstName from rowNumberDemo\n-> order by FirstName;"
},
{
"code": null,
"e": 2220,
"s": 2190,
"text": "The following is the output −"
},
{
"code": null,
"e": 2517,
"s": 2220,
"text": "+-------------------+-----------+\n| RowNumberSqeuence | FirstName |\n+-------------------+-----------+\n| 1 | Bob |\n| 2 | john |\n| 3 | john |\n| 4 | Smith |\n+-------------------+-----------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2610,
"s": 2517,
"text": "Look at the output, we have assigned a number to every record with the help of row_number()."
}
] |
Is there a difference between copy initialization and direct initialization in C++?
|
The Copy initialization can be done using the concept of copy constructor. As we know that the constructors are used to initialize the objects. We can create our copy constructor to make a copy of some other object, or in other words, initialize current object with the value of another object. On the other hand, the direct initialization can be done using assignment operation.
The main difference between these two types of initialization is that the copy initialization creates a separate memory block for the new object. But the direct initialization does not make new memory space. It uses reference variable to point to the previous memory block.
classname (const classname &obj) {
// body of constructor
}
classname Ob1, Ob2;
Ob2 = Ob1;
Let us see the detailed differences between Copy initialization and Direct initialization.
|
[
{
"code": null,
"e": 1442,
"s": 1062,
"text": "The Copy initialization can be done using the concept of copy constructor. As we know that the constructors are used to initialize the objects. We can create our copy constructor to make a copy of some other object, or in other words, initialize current object with the value of another object. On the other hand, the direct initialization can be done using assignment operation."
},
{
"code": null,
"e": 1716,
"s": 1442,
"text": "The main difference between these two types of initialization is that the copy initialization creates a separate memory block for the new object. But the direct initialization does not make new memory space. It uses reference variable to point to the previous memory block."
},
{
"code": null,
"e": 1779,
"s": 1716,
"text": "classname (const classname &obj) {\n // body of constructor\n}"
},
{
"code": null,
"e": 1810,
"s": 1779,
"text": "classname Ob1, Ob2;\nOb2 = Ob1;"
},
{
"code": null,
"e": 1901,
"s": 1810,
"text": "Let us see the detailed differences between Copy initialization and Direct initialization."
}
] |
Write a program to calculate pow(x,n) in C++
|
In this problem, we are given two integers x and n. Our task is to write a program to calculate the pow(x,n).
Let’s take an example to understand the problem,
x = 5 , n = 3
125
Program to calculate the pow(x,n),
Live Demo
#include <iostream>
using namespace std;
float myPow(float x, int y) {
if(y == 0)
return 1;
float temp = myPow(x, y / 2);
if (y % 2 == 0)
return temp*temp;
else {
if(y > 0)
return x*temp*temp;
else
return (temp*temp)/x;
}
}
int main() {
float x = 5;
int n = 7;
cout<<x<<" raised to the power "<<n<<" is "<<myPow(x, n);
return 0;
}
5 raised to the power 7 is 78125
The program shows an efficient approach by dividing the power into half and then multipling the two half and also considers the negative cases.
|
[
{
"code": null,
"e": 1172,
"s": 1062,
"text": "In this problem, we are given two integers x and n. Our task is to write a program to calculate the pow(x,n)."
},
{
"code": null,
"e": 1221,
"s": 1172,
"text": "Let’s take an example to understand the problem,"
},
{
"code": null,
"e": 1235,
"s": 1221,
"text": "x = 5 , n = 3"
},
{
"code": null,
"e": 1239,
"s": 1235,
"text": "125"
},
{
"code": null,
"e": 1274,
"s": 1239,
"text": "Program to calculate the pow(x,n),"
},
{
"code": null,
"e": 1285,
"s": 1274,
"text": " Live Demo"
},
{
"code": null,
"e": 1685,
"s": 1285,
"text": "#include <iostream>\nusing namespace std;\nfloat myPow(float x, int y) {\n if(y == 0)\n return 1;\n float temp = myPow(x, y / 2);\n if (y % 2 == 0)\n return temp*temp;\n else {\n if(y > 0)\n return x*temp*temp;\n else\n return (temp*temp)/x;\n }\n}\nint main() {\n float x = 5;\n int n = 7;\n cout<<x<<\" raised to the power \"<<n<<\" is \"<<myPow(x, n);\n return 0;\n}"
},
{
"code": null,
"e": 1718,
"s": 1685,
"text": "5 raised to the power 7 is 78125"
},
{
"code": null,
"e": 1862,
"s": 1718,
"text": "The program shows an efficient approach by dividing the power into half and then multipling the two half and also considers the negative cases."
}
] |
Count the number of digits of palindrome numbers in an array - GeeksforGeeks
|
10 May, 2021
Given an array arr[] with N integers. The task is to count all the digits of all palindrome numbers present in the array.Examples:
Input: arr[] = {121, 56, 434} Output: 6 Only 121 and 434 are palindromes and digitCount(121) + digitCount(434) = 3 + 3 = 6Input: arr[] = {56, 455, 546, 234} Output: 0
Approach: For every element of the array, if it is a one digit number then add 1 to the answer for its digit else check if the number is a palindrome. If yes then find the count of its digits and add it to the answer.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to return the reverse of nint reverse(int n){ int rev = 0; while (n > 0) { int d = n % 10; rev = rev * 10 + d; n = n / 10; } return rev;} // Function that returns true// if n is a palindromebool isPalin(int n){ return (n == reverse(n));} // Function to return the// count of digits of nint countDigits(int n){ int c = 0; while (n > 0) { n = n / 10; c++; } return c;} // Function to return the count of digits// in all the palindromic numbers of arr[]int countPalinDigits(int arr[], int n){ int s = 0; for (int i = 0; i < n; i++) { // If arr[i] is a one digit number // or it is a palindrome if (arr[i] < 10 || isPalin(arr[i])) { s += countDigits(arr[i]); } } return s;} // Driver codeint main(){ int arr[] = { 121, 56, 434 }; int n = sizeof(arr) / sizeof(arr[0]); cout << (countPalinDigits(arr, n)); return 0;} // This code is contributed by mits
// Java implementation of the approachclass GFG { // Function to return the reverse of n static int reverse(int n) { int rev = 0; while (n > 0) { int d = n % 10; rev = rev * 10 + d; n = n / 10; } return rev; } // Function that returns true // if n is a palindrome static boolean isPalin(int n) { return (n == reverse(n)); } // Function to return the // count of digits of n static int countDigits(int n) { int c = 0; while (n > 0) { n = n / 10; c++; } return c; } // Function to return the count of digits // in all the palindromic numbers of arr[] static int countPalinDigits(int[] arr, int n) { int s = 0; for (int i = 0; i < n; i++) { // If arr[i] is a one digit number // or it is a palindrome if (arr[i] < 10 || isPalin(arr[i])) { s += countDigits(arr[i]); } } return s; } // Driver code public static void main(String[] args) { int[] arr = { 121, 56, 434 }; int n = arr.length; System.out.println(countPalinDigits(arr, n)); }}
# Python3 implementation of the approach # Function to return the reverse of ndef reverse(n): rev = 0; while (n > 0): d = n % 10; rev = rev * 10 + d; n = n // 10; return rev; # Function that returns true# if n is a palindromedef isPalin(n): return (n == reverse(n)); # Function to return the# count of digits of ndef countDigits(n): c = 0; while (n > 0): n = n // 10; c += 1; return c; # Function to return the count of digits# in all the palindromic numbers of arr[]def countPalinDigits(arr, n): s = 0; for i in range(n): # If arr[i] is a one digit number # or it is a palindrome if (arr[i] < 10 or isPalin(arr[i])): s += countDigits(arr[i]); return s; # Driver codearr = [ 121, 56, 434 ];n = len(arr);print(countPalinDigits(arr, n)); # This code contributed by Rajput-Ji
// C# implementation of the approachusing System; class GFG{ // Function to return the reverse of n static int reverse(int n) { int rev = 0; while (n > 0) { int d = n % 10; rev = rev * 10 + d; n = n / 10; } return rev; } // Function that returns true // if n is a palindrome static bool isPalin(int n) { return (n == reverse(n)); } // Function to return the // count of digits of n static int countDigits(int n) { int c = 0; while (n > 0) { n = n / 10; c++; } return c; } // Function to return the count of digits // in all the palindromic numbers of arr[] static int countPalinDigits(int[] arr, int n) { int s = 0; for (int i = 0; i < n; i++) { // If arr[i] is a one digit number // or it is a palindrome if (arr[i] < 10 || isPalin(arr[i])) { s += countDigits(arr[i]); } } return s; } // Driver code public static void Main() { int[] arr = { 121, 56, 434 }; int n = arr.Length; Console.WriteLine(countPalinDigits(arr, n)); }} /* This code contributed by PrinciRaj1992 */
<script> // Javascript implementation of the approach // Function to return the reverse of nfunction reverse(n){ let rev = 0; while (n > 0) { let d = n % 10; rev = rev * 10 + d; n = parseInt(n / 10); } return rev;} // Function that returns true// if n is a palindromefunction isPalin(n){ return (n == reverse(n));} // Function to return the// count of digits of nfunction countDigits(n){ let c = 0; while (n > 0) { n = parseInt(n / 10); c++; } return c;} // Function to return the count of digits// in all the palindromic numbers of arr[]function countPalinDigits(arr, n){ let s = 0; for (let i = 0; i < n; i++) { // If arr[i] is a one digit number // or it is a palindrome if (arr[i] < 10 || isPalin(arr[i])) { s += countDigits(arr[i]); } } return s;} // Driver code let arr = [ 121, 56, 434 ]; let n = arr.length; document.write(countPalinDigits(arr, n)); </script>
6
Shorter Python Implementation
Python3
# Function to return the count of digits# in all the palindromic numbers of arr[]def countPalinDigits(arr): sum = 0 for n in arr: n_str = str(n) l = len(n_str) if n_str[l::-1] == n_str: # if palindrome sum += l return sum # Driver codearr = [ 121, 56, 434 ];print(countPalinDigits(arr));
6
princiraj1992
Mithun Kumar
Rajput-Ji
mailprakashindia
subhammahato348
number-digits
palindrome
Arrays
Mathematical
Arrays
Mathematical
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Move all negative numbers to beginning and positive to end with constant extra space
Program to find sum of elements in a given array
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 24796,
"s": 24768,
"text": "\n10 May, 2021"
},
{
"code": null,
"e": 24929,
"s": 24796,
"text": "Given an array arr[] with N integers. The task is to count all the digits of all palindrome numbers present in the array.Examples: "
},
{
"code": null,
"e": 25098,
"s": 24929,
"text": "Input: arr[] = {121, 56, 434} Output: 6 Only 121 and 434 are palindromes and digitCount(121) + digitCount(434) = 3 + 3 = 6Input: arr[] = {56, 455, 546, 234} Output: 0 "
},
{
"code": null,
"e": 25370,
"s": 25100,
"text": "Approach: For every element of the array, if it is a one digit number then add 1 to the answer for its digit else check if the number is a palindrome. If yes then find the count of its digits and add it to the answer.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25374,
"s": 25370,
"text": "C++"
},
{
"code": null,
"e": 25379,
"s": 25374,
"text": "Java"
},
{
"code": null,
"e": 25387,
"s": 25379,
"text": "Python3"
},
{
"code": null,
"e": 25390,
"s": 25387,
"text": "C#"
},
{
"code": null,
"e": 25401,
"s": 25390,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to return the reverse of nint reverse(int n){ int rev = 0; while (n > 0) { int d = n % 10; rev = rev * 10 + d; n = n / 10; } return rev;} // Function that returns true// if n is a palindromebool isPalin(int n){ return (n == reverse(n));} // Function to return the// count of digits of nint countDigits(int n){ int c = 0; while (n > 0) { n = n / 10; c++; } return c;} // Function to return the count of digits// in all the palindromic numbers of arr[]int countPalinDigits(int arr[], int n){ int s = 0; for (int i = 0; i < n; i++) { // If arr[i] is a one digit number // or it is a palindrome if (arr[i] < 10 || isPalin(arr[i])) { s += countDigits(arr[i]); } } return s;} // Driver codeint main(){ int arr[] = { 121, 56, 434 }; int n = sizeof(arr) / sizeof(arr[0]); cout << (countPalinDigits(arr, n)); return 0;} // This code is contributed by mits",
"e": 26483,
"s": 25401,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { // Function to return the reverse of n static int reverse(int n) { int rev = 0; while (n > 0) { int d = n % 10; rev = rev * 10 + d; n = n / 10; } return rev; } // Function that returns true // if n is a palindrome static boolean isPalin(int n) { return (n == reverse(n)); } // Function to return the // count of digits of n static int countDigits(int n) { int c = 0; while (n > 0) { n = n / 10; c++; } return c; } // Function to return the count of digits // in all the palindromic numbers of arr[] static int countPalinDigits(int[] arr, int n) { int s = 0; for (int i = 0; i < n; i++) { // If arr[i] is a one digit number // or it is a palindrome if (arr[i] < 10 || isPalin(arr[i])) { s += countDigits(arr[i]); } } return s; } // Driver code public static void main(String[] args) { int[] arr = { 121, 56, 434 }; int n = arr.length; System.out.println(countPalinDigits(arr, n)); }}",
"e": 27717,
"s": 26483,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the reverse of ndef reverse(n): rev = 0; while (n > 0): d = n % 10; rev = rev * 10 + d; n = n // 10; return rev; # Function that returns true# if n is a palindromedef isPalin(n): return (n == reverse(n)); # Function to return the# count of digits of ndef countDigits(n): c = 0; while (n > 0): n = n // 10; c += 1; return c; # Function to return the count of digits# in all the palindromic numbers of arr[]def countPalinDigits(arr, n): s = 0; for i in range(n): # If arr[i] is a one digit number # or it is a palindrome if (arr[i] < 10 or isPalin(arr[i])): s += countDigits(arr[i]); return s; # Driver codearr = [ 121, 56, 434 ];n = len(arr);print(countPalinDigits(arr, n)); # This code contributed by Rajput-Ji",
"e": 28591,
"s": 27717,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the reverse of n static int reverse(int n) { int rev = 0; while (n > 0) { int d = n % 10; rev = rev * 10 + d; n = n / 10; } return rev; } // Function that returns true // if n is a palindrome static bool isPalin(int n) { return (n == reverse(n)); } // Function to return the // count of digits of n static int countDigits(int n) { int c = 0; while (n > 0) { n = n / 10; c++; } return c; } // Function to return the count of digits // in all the palindromic numbers of arr[] static int countPalinDigits(int[] arr, int n) { int s = 0; for (int i = 0; i < n; i++) { // If arr[i] is a one digit number // or it is a palindrome if (arr[i] < 10 || isPalin(arr[i])) { s += countDigits(arr[i]); } } return s; } // Driver code public static void Main() { int[] arr = { 121, 56, 434 }; int n = arr.Length; Console.WriteLine(countPalinDigits(arr, n)); }} /* This code contributed by PrinciRaj1992 */",
"e": 29900,
"s": 28591,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the reverse of nfunction reverse(n){ let rev = 0; while (n > 0) { let d = n % 10; rev = rev * 10 + d; n = parseInt(n / 10); } return rev;} // Function that returns true// if n is a palindromefunction isPalin(n){ return (n == reverse(n));} // Function to return the// count of digits of nfunction countDigits(n){ let c = 0; while (n > 0) { n = parseInt(n / 10); c++; } return c;} // Function to return the count of digits// in all the palindromic numbers of arr[]function countPalinDigits(arr, n){ let s = 0; for (let i = 0; i < n; i++) { // If arr[i] is a one digit number // or it is a palindrome if (arr[i] < 10 || isPalin(arr[i])) { s += countDigits(arr[i]); } } return s;} // Driver code let arr = [ 121, 56, 434 ]; let n = arr.length; document.write(countPalinDigits(arr, n)); </script>",
"e": 30907,
"s": 29900,
"text": null
},
{
"code": null,
"e": 30909,
"s": 30907,
"text": "6"
},
{
"code": null,
"e": 30942,
"s": 30911,
"text": "Shorter Python Implementation "
},
{
"code": null,
"e": 30950,
"s": 30942,
"text": "Python3"
},
{
"code": "# Function to return the count of digits# in all the palindromic numbers of arr[]def countPalinDigits(arr): sum = 0 for n in arr: n_str = str(n) l = len(n_str) if n_str[l::-1] == n_str: # if palindrome sum += l return sum # Driver codearr = [ 121, 56, 434 ];print(countPalinDigits(arr));",
"e": 31269,
"s": 30950,
"text": null
},
{
"code": null,
"e": 31271,
"s": 31269,
"text": "6"
},
{
"code": null,
"e": 31287,
"s": 31273,
"text": "princiraj1992"
},
{
"code": null,
"e": 31300,
"s": 31287,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 31310,
"s": 31300,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 31327,
"s": 31310,
"text": "mailprakashindia"
},
{
"code": null,
"e": 31343,
"s": 31327,
"text": "subhammahato348"
},
{
"code": null,
"e": 31357,
"s": 31343,
"text": "number-digits"
},
{
"code": null,
"e": 31368,
"s": 31357,
"text": "palindrome"
},
{
"code": null,
"e": 31375,
"s": 31368,
"text": "Arrays"
},
{
"code": null,
"e": 31388,
"s": 31375,
"text": "Mathematical"
},
{
"code": null,
"e": 31395,
"s": 31388,
"text": "Arrays"
},
{
"code": null,
"e": 31408,
"s": 31395,
"text": "Mathematical"
},
{
"code": null,
"e": 31419,
"s": 31408,
"text": "palindrome"
},
{
"code": null,
"e": 31517,
"s": 31419,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31542,
"s": 31517,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 31562,
"s": 31542,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 31600,
"s": 31562,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 31685,
"s": 31600,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 31734,
"s": 31685,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 31764,
"s": 31734,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 31824,
"s": 31764,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 31839,
"s": 31824,
"text": "C++ Data Types"
},
{
"code": null,
"e": 31882,
"s": 31839,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Creating start Menu in Pygame - GeeksforGeeks
|
05 Sep, 2020
Pygame is a Python library that can be used specifically to design and build games. Pygame supports only 2d games that are built using different shapes or sprites. Pygame doesn’t have an in-built layout design or any in-built UI system this means there is no easy way to make UI or levels for a game. The only way to make levels or different menus in pygame is by using functions.
Functions in Pygame are a way to contain different menus or levels by defining an event type in each function, then calling the functions from their respective container function.
For example, the game function will be called if the player hits the play button on the start menu. So, the start menu function becomes container functions for the game function. The important thing to note is that the start function can’t be called directly from game function. If the game contains different unlockable levels, then the previous level becomes the container function for the next level.
Sample Code For A Game Containing Start Menu
Python program to demonstrate Menus And Levels
Python
import pygame import sys # initializing the constructor pygame.init() # screen resolution res = (720,720) # opens up a window screen = pygame.display.set_mode(res) # white color color = (255,255,255) # light shade of the button color_light = (170,170,170) # dark shade of the button color_dark = (100,100,100) # stores the width of the # screen into a variable width = screen.get_width() # stores the height of the # screen into a variable height = screen.get_height() # defining a font smallfont = pygame.font.SysFont('Corbel',35) # rendering a text written in # this font text = smallfont.render('quit' , True , color) while True: for ev in pygame.event.get(): if ev.type == pygame.QUIT: pygame.quit() #checks if a mouse is clicked if ev.type == pygame.MOUSEBUTTONDOWN: #if the mouse is clicked on the # button the game is terminated if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40: pygame.quit() # fills the screen with a color screen.fill((60,25,60)) # stores the (x,y) coordinates into # the variable as a tuple mouse = pygame.mouse.get_pos() # if mouse is hovered on a button it # changes to lighter shade if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40: pygame.draw.rect(screen,color_light,[width/2,height/2,140,40]) else: pygame.draw.rect(screen,color_dark,[width/2,height/2,140,40]) # superimposing the text onto our button screen.blit(text , (width/2+50,height/2)) # updates the frames of the game pygame.display.update()
Output:
Python-PyGame
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
|
[
{
"code": null,
"e": 24031,
"s": 24003,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 24412,
"s": 24031,
"text": "Pygame is a Python library that can be used specifically to design and build games. Pygame supports only 2d games that are built using different shapes or sprites. Pygame doesn’t have an in-built layout design or any in-built UI system this means there is no easy way to make UI or levels for a game. The only way to make levels or different menus in pygame is by using functions."
},
{
"code": null,
"e": 24593,
"s": 24412,
"text": "Functions in Pygame are a way to contain different menus or levels by defining an event type in each function, then calling the functions from their respective container function. "
},
{
"code": null,
"e": 24997,
"s": 24593,
"text": "For example, the game function will be called if the player hits the play button on the start menu. So, the start menu function becomes container functions for the game function. The important thing to note is that the start function can’t be called directly from game function. If the game contains different unlockable levels, then the previous level becomes the container function for the next level."
},
{
"code": null,
"e": 25042,
"s": 24997,
"text": "Sample Code For A Game Containing Start Menu"
},
{
"code": null,
"e": 25089,
"s": 25042,
"text": "Python program to demonstrate Menus And Levels"
},
{
"code": null,
"e": 25096,
"s": 25089,
"text": "Python"
},
{
"code": "import pygame import sys # initializing the constructor pygame.init() # screen resolution res = (720,720) # opens up a window screen = pygame.display.set_mode(res) # white color color = (255,255,255) # light shade of the button color_light = (170,170,170) # dark shade of the button color_dark = (100,100,100) # stores the width of the # screen into a variable width = screen.get_width() # stores the height of the # screen into a variable height = screen.get_height() # defining a font smallfont = pygame.font.SysFont('Corbel',35) # rendering a text written in # this font text = smallfont.render('quit' , True , color) while True: for ev in pygame.event.get(): if ev.type == pygame.QUIT: pygame.quit() #checks if a mouse is clicked if ev.type == pygame.MOUSEBUTTONDOWN: #if the mouse is clicked on the # button the game is terminated if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40: pygame.quit() # fills the screen with a color screen.fill((60,25,60)) # stores the (x,y) coordinates into # the variable as a tuple mouse = pygame.mouse.get_pos() # if mouse is hovered on a button it # changes to lighter shade if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40: pygame.draw.rect(screen,color_light,[width/2,height/2,140,40]) else: pygame.draw.rect(screen,color_dark,[width/2,height/2,140,40]) # superimposing the text onto our button screen.blit(text , (width/2+50,height/2)) # updates the frames of the game pygame.display.update() ",
"e": 26869,
"s": 25096,
"text": null
},
{
"code": null,
"e": 26877,
"s": 26869,
"text": "Output:"
},
{
"code": null,
"e": 26891,
"s": 26877,
"text": "Python-PyGame"
},
{
"code": null,
"e": 26898,
"s": 26891,
"text": "Python"
},
{
"code": null,
"e": 26996,
"s": 26898,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27005,
"s": 26996,
"text": "Comments"
},
{
"code": null,
"e": 27018,
"s": 27005,
"text": "Old Comments"
},
{
"code": null,
"e": 27036,
"s": 27018,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27071,
"s": 27036,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27093,
"s": 27071,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27125,
"s": 27093,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27155,
"s": 27125,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27197,
"s": 27155,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27223,
"s": 27197,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27266,
"s": 27223,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27310,
"s": 27266,
"text": "Reading and Writing to text files in Python"
}
] |
Build and Analyze Knowledge Graphs with Diffbot | by Khuyen Tran | Towards Data Science
|
What do you often do when you want to learn more about a person? You might decide to read about a person using websites such as Wikipedia.
However, the text can be lengthy, and it might take you a while to get the pieces of information that you need.
Since we are better at absorbing information in form of images than text, wouldn’t it be nice if you can get a graph like below when searching for Steve Jobs?
That is when Diffbot comes in handy. In this article, you will learn how to build and analyze knowledge graphs using Diffbot.
A knowledge graph represents a collection of entities, which are objects, events, abstract concepts, and illustrates the relationship between them. Knowledge graphs are used by Google to enhance its search engine’s results.
Diffbot is the world’s largest knowledge graph that allows you to access a trillion connected facts across the web.
To start with Diffbot, sign up for a 14-day free trial. This free trial will allow you to search Diffbot’s Knowledge Graph.
After logging in, click the Search option to search the Diffbot Knowledge Graph.
Have you ever wondered:
which school Apple’s employees went to,
what their majors were,
and what the most popular roles at Apple are?
We can answer these questions using Diffbot’s Search. Start with searching for the Diffbot ID of Apple Inc. by:
selecting “Organization”
filtering by “name” that “contains” “apple”
clicking “Search”
You will see 61,820 results that are related to apple. Since we are only interested in Apple Inc., click “Apple Inc.”
You will be directed to the website that shows specific information about Apple Inc. Copy the ID in the website’s URL. The ID found in the URL below is “EHb0_0NEcMwyY8b083taTTw”.
To search for all employees in Apple Inc, click the Query tab then pass:
type:Person employments.employer.id:”EHb0_0NEcMwyY8b083taTTw”
... to the search box.
After clicking “Search”, Diffbot will return over 200k results.
Click the graph icon in the top right corner to view the knowledge graph of the results.
And you should see the knowledge graph like below! This graph shows the relationship between Apple Inc. and other entities. The relationships with these entities can be “city”, “employer”, “metro area”, “institution”, etc
Note that this graph only shows the top 25 results. To get the knowledge graph of the next 25 most important results, click the “More” button at the top of the graph.
To get a better view of a certain node, you can move it to another location.
To view the information of each entity, click that entity. You should see its information like below:
To get the results in JSON format, click the JSON tab in the top right corner.
What are the skills of Apple’s employees? We can find that out by looking at the skills section in the JSON file.
One employee can have many skills and different employees have different skills. Is there a way that we can summarize these skills? That could be easily be done by adding facet:skills.name to the previous query:
type:Person employments.employer.id:"EHb0_0NEcMwyY8b083taTTw" facet:skills.name
facet will display summary data about the values of the specified field
skills.name tells Diffbot to access the name field within the skills field in the JSON file.
Top 50 skills of employees at Apple:
What were the majors of Apple’s employees in college? We can find that out by adding facet:educations.major.name to the query:
type:Person employments.employer.id:"EHb0_0NEcMwyY8b083taTTw" facet:educations.major.name
The top 25 majors of employees at Apple are:
From the graph above, we can see that the top majors are related to computer science, engineer, and business administration. The results are not surprising since Apple is a technology company that specializes in consumer electronics, computer software, and online services.
What are the top schools that Apple’s employees went to? That could be found by adding facet:educations.institution.name to the query:
type:Person employments.employer.id:"EHb0_0NEcMwyY8b083taTTw" facet:educations.institution.name
The top 5 schools that Apple’s employees went to are:
Standford University
University of California Berkley
SJSU
Harvard University
University of Phoenix
We can see that a lot of these universities are the country’s top universities and are located in California. This doesn’t mean that you need to go to these top universities to get accepted in Apple. It does mean that if you go to these universities, you might have a higher chance of being accepted to Apple.
Have you ever wondered:
what artificial intelligence companies’ revenues are,
which countries these companies are located at,
and how many employees are working in these companies?
Let’s answer these questions using Diffbot. Start with selecting “Organization”, then filter the search by industries. Click the dropdown box and scroll down until you see the “Artificial Intelligence Companies” option.
The knowledge graph of the first 25 companies showing up in the search results:
What are the top 50 descriptors of these artificial intelligence companies? Let’s find that out by adding facet: descriptors to the previous query:
type:Organization industries:"Artificial Intelligence Companies" facet: descriptors
What are the revenues of these companies?
type:Organization industries:"Artificial Intelligence Companies" facet: revenue.value
The majority of these companies have revenues ranging from $100k-1 million.
To get companies whose revenues are in a certain range, you can add the following to your query:
type:Organization industries:"Artificial Intelligence Companies" revenue.value>=100000 revenue.value<500000
Another interesting thing to find out is which countries have the highest number of AI companies.
type:Organization industries:"Artificial Intelligence Companies" facet: location.country.name
Locations of the top 25 countries:
Names of the top 5 countries with the highest number of AI companies:
What are the average numbers of employees in these companies?
type:Organization industries:"Artificial Intelligence Companies" facet: nbEmployees
The majority of companies have a number of employees ranging from 5 to 100 employees. There are only 4 companies with more than 100k employees. What are they?
Let’s find that out by clicking the number in the table below the graph:
There are only 4 companies in the world with more than 100k employees and they are all Japanese companies! This could be because many Japanese workers are loyal to their companies.
These results are cool. But what if you want to export the data from Diffbot for further analysis? That can be done using Python or command-line.
To use the Knowledge Graph API, make an HTTP GET request to the following endpoint:
https://kg.diffbot.com/kg/dql_endpoint?token=...&type=query&query=...
We can also create a function that returns the endpoint. This function takes:
Diffbot’s API token
the URL of the JSON file we want to download
The token can be found in the top right corner of your Dashboard.
The URL of the JSON file can be found by clicking the JSON tab in the top right corner.
Use the URL of the page you are directed to as the second parameter of the function get_diffbot_json .
And you will get a downloadable URL:
https://kg.diffbot.com/kg/dql_endpoint?token=your-token&type=query&query=type%3APerson+id%3A%22EyauXV2QZOW2fEP8Cb_Hoxg%22&from=0&size=25&output_format=
To download the data in the URL returned by the get_diffbot_json , use the requests library:
And the JSON file will be saved in your local machine!
You can also download the JSON file on your terminal using wget :
wget https://kg.diffbot.com/kg/dql_endpoint?token=your-tokenc&type=query&query=type%3APerson+id%3A%22EyauXV2QZOW2fEP8Cb_Hoxg%22&from=0&size=25&output_format=
Congratulations! You have just learned how to build a knowledge graph and summarize essential facts using Diffbot. I hope this article will give you the motivation to explore other topics that you are interested in.
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": 311,
"s": 172,
"text": "What do you often do when you want to learn more about a person? You might decide to read about a person using websites such as Wikipedia."
},
{
"code": null,
"e": 423,
"s": 311,
"text": "However, the text can be lengthy, and it might take you a while to get the pieces of information that you need."
},
{
"code": null,
"e": 582,
"s": 423,
"text": "Since we are better at absorbing information in form of images than text, wouldn’t it be nice if you can get a graph like below when searching for Steve Jobs?"
},
{
"code": null,
"e": 708,
"s": 582,
"text": "That is when Diffbot comes in handy. In this article, you will learn how to build and analyze knowledge graphs using Diffbot."
},
{
"code": null,
"e": 932,
"s": 708,
"text": "A knowledge graph represents a collection of entities, which are objects, events, abstract concepts, and illustrates the relationship between them. Knowledge graphs are used by Google to enhance its search engine’s results."
},
{
"code": null,
"e": 1048,
"s": 932,
"text": "Diffbot is the world’s largest knowledge graph that allows you to access a trillion connected facts across the web."
},
{
"code": null,
"e": 1172,
"s": 1048,
"text": "To start with Diffbot, sign up for a 14-day free trial. This free trial will allow you to search Diffbot’s Knowledge Graph."
},
{
"code": null,
"e": 1253,
"s": 1172,
"text": "After logging in, click the Search option to search the Diffbot Knowledge Graph."
},
{
"code": null,
"e": 1277,
"s": 1253,
"text": "Have you ever wondered:"
},
{
"code": null,
"e": 1317,
"s": 1277,
"text": "which school Apple’s employees went to,"
},
{
"code": null,
"e": 1341,
"s": 1317,
"text": "what their majors were,"
},
{
"code": null,
"e": 1387,
"s": 1341,
"text": "and what the most popular roles at Apple are?"
},
{
"code": null,
"e": 1499,
"s": 1387,
"text": "We can answer these questions using Diffbot’s Search. Start with searching for the Diffbot ID of Apple Inc. by:"
},
{
"code": null,
"e": 1524,
"s": 1499,
"text": "selecting “Organization”"
},
{
"code": null,
"e": 1568,
"s": 1524,
"text": "filtering by “name” that “contains” “apple”"
},
{
"code": null,
"e": 1586,
"s": 1568,
"text": "clicking “Search”"
},
{
"code": null,
"e": 1704,
"s": 1586,
"text": "You will see 61,820 results that are related to apple. Since we are only interested in Apple Inc., click “Apple Inc.”"
},
{
"code": null,
"e": 1883,
"s": 1704,
"text": "You will be directed to the website that shows specific information about Apple Inc. Copy the ID in the website’s URL. The ID found in the URL below is “EHb0_0NEcMwyY8b083taTTw”."
},
{
"code": null,
"e": 1956,
"s": 1883,
"text": "To search for all employees in Apple Inc, click the Query tab then pass:"
},
{
"code": null,
"e": 2018,
"s": 1956,
"text": "type:Person employments.employer.id:”EHb0_0NEcMwyY8b083taTTw”"
},
{
"code": null,
"e": 2041,
"s": 2018,
"text": "... to the search box."
},
{
"code": null,
"e": 2105,
"s": 2041,
"text": "After clicking “Search”, Diffbot will return over 200k results."
},
{
"code": null,
"e": 2194,
"s": 2105,
"text": "Click the graph icon in the top right corner to view the knowledge graph of the results."
},
{
"code": null,
"e": 2416,
"s": 2194,
"text": "And you should see the knowledge graph like below! This graph shows the relationship between Apple Inc. and other entities. The relationships with these entities can be “city”, “employer”, “metro area”, “institution”, etc"
},
{
"code": null,
"e": 2583,
"s": 2416,
"text": "Note that this graph only shows the top 25 results. To get the knowledge graph of the next 25 most important results, click the “More” button at the top of the graph."
},
{
"code": null,
"e": 2660,
"s": 2583,
"text": "To get a better view of a certain node, you can move it to another location."
},
{
"code": null,
"e": 2762,
"s": 2660,
"text": "To view the information of each entity, click that entity. You should see its information like below:"
},
{
"code": null,
"e": 2841,
"s": 2762,
"text": "To get the results in JSON format, click the JSON tab in the top right corner."
},
{
"code": null,
"e": 2955,
"s": 2841,
"text": "What are the skills of Apple’s employees? We can find that out by looking at the skills section in the JSON file."
},
{
"code": null,
"e": 3167,
"s": 2955,
"text": "One employee can have many skills and different employees have different skills. Is there a way that we can summarize these skills? That could be easily be done by adding facet:skills.name to the previous query:"
},
{
"code": null,
"e": 3247,
"s": 3167,
"text": "type:Person employments.employer.id:\"EHb0_0NEcMwyY8b083taTTw\" facet:skills.name"
},
{
"code": null,
"e": 3319,
"s": 3247,
"text": "facet will display summary data about the values of the specified field"
},
{
"code": null,
"e": 3412,
"s": 3319,
"text": "skills.name tells Diffbot to access the name field within the skills field in the JSON file."
},
{
"code": null,
"e": 3449,
"s": 3412,
"text": "Top 50 skills of employees at Apple:"
},
{
"code": null,
"e": 3576,
"s": 3449,
"text": "What were the majors of Apple’s employees in college? We can find that out by adding facet:educations.major.name to the query:"
},
{
"code": null,
"e": 3666,
"s": 3576,
"text": "type:Person employments.employer.id:\"EHb0_0NEcMwyY8b083taTTw\" facet:educations.major.name"
},
{
"code": null,
"e": 3711,
"s": 3666,
"text": "The top 25 majors of employees at Apple are:"
},
{
"code": null,
"e": 3985,
"s": 3711,
"text": "From the graph above, we can see that the top majors are related to computer science, engineer, and business administration. The results are not surprising since Apple is a technology company that specializes in consumer electronics, computer software, and online services."
},
{
"code": null,
"e": 4120,
"s": 3985,
"text": "What are the top schools that Apple’s employees went to? That could be found by adding facet:educations.institution.name to the query:"
},
{
"code": null,
"e": 4216,
"s": 4120,
"text": "type:Person employments.employer.id:\"EHb0_0NEcMwyY8b083taTTw\" facet:educations.institution.name"
},
{
"code": null,
"e": 4270,
"s": 4216,
"text": "The top 5 schools that Apple’s employees went to are:"
},
{
"code": null,
"e": 4291,
"s": 4270,
"text": "Standford University"
},
{
"code": null,
"e": 4324,
"s": 4291,
"text": "University of California Berkley"
},
{
"code": null,
"e": 4329,
"s": 4324,
"text": "SJSU"
},
{
"code": null,
"e": 4348,
"s": 4329,
"text": "Harvard University"
},
{
"code": null,
"e": 4370,
"s": 4348,
"text": "University of Phoenix"
},
{
"code": null,
"e": 4680,
"s": 4370,
"text": "We can see that a lot of these universities are the country’s top universities and are located in California. This doesn’t mean that you need to go to these top universities to get accepted in Apple. It does mean that if you go to these universities, you might have a higher chance of being accepted to Apple."
},
{
"code": null,
"e": 4704,
"s": 4680,
"text": "Have you ever wondered:"
},
{
"code": null,
"e": 4758,
"s": 4704,
"text": "what artificial intelligence companies’ revenues are,"
},
{
"code": null,
"e": 4806,
"s": 4758,
"text": "which countries these companies are located at,"
},
{
"code": null,
"e": 4861,
"s": 4806,
"text": "and how many employees are working in these companies?"
},
{
"code": null,
"e": 5081,
"s": 4861,
"text": "Let’s answer these questions using Diffbot. Start with selecting “Organization”, then filter the search by industries. Click the dropdown box and scroll down until you see the “Artificial Intelligence Companies” option."
},
{
"code": null,
"e": 5161,
"s": 5081,
"text": "The knowledge graph of the first 25 companies showing up in the search results:"
},
{
"code": null,
"e": 5309,
"s": 5161,
"text": "What are the top 50 descriptors of these artificial intelligence companies? Let’s find that out by adding facet: descriptors to the previous query:"
},
{
"code": null,
"e": 5393,
"s": 5309,
"text": "type:Organization industries:\"Artificial Intelligence Companies\" facet: descriptors"
},
{
"code": null,
"e": 5435,
"s": 5393,
"text": "What are the revenues of these companies?"
},
{
"code": null,
"e": 5521,
"s": 5435,
"text": "type:Organization industries:\"Artificial Intelligence Companies\" facet: revenue.value"
},
{
"code": null,
"e": 5597,
"s": 5521,
"text": "The majority of these companies have revenues ranging from $100k-1 million."
},
{
"code": null,
"e": 5694,
"s": 5597,
"text": "To get companies whose revenues are in a certain range, you can add the following to your query:"
},
{
"code": null,
"e": 5802,
"s": 5694,
"text": "type:Organization industries:\"Artificial Intelligence Companies\" revenue.value>=100000 revenue.value<500000"
},
{
"code": null,
"e": 5900,
"s": 5802,
"text": "Another interesting thing to find out is which countries have the highest number of AI companies."
},
{
"code": null,
"e": 5994,
"s": 5900,
"text": "type:Organization industries:\"Artificial Intelligence Companies\" facet: location.country.name"
},
{
"code": null,
"e": 6029,
"s": 5994,
"text": "Locations of the top 25 countries:"
},
{
"code": null,
"e": 6099,
"s": 6029,
"text": "Names of the top 5 countries with the highest number of AI companies:"
},
{
"code": null,
"e": 6161,
"s": 6099,
"text": "What are the average numbers of employees in these companies?"
},
{
"code": null,
"e": 6245,
"s": 6161,
"text": "type:Organization industries:\"Artificial Intelligence Companies\" facet: nbEmployees"
},
{
"code": null,
"e": 6404,
"s": 6245,
"text": "The majority of companies have a number of employees ranging from 5 to 100 employees. There are only 4 companies with more than 100k employees. What are they?"
},
{
"code": null,
"e": 6477,
"s": 6404,
"text": "Let’s find that out by clicking the number in the table below the graph:"
},
{
"code": null,
"e": 6658,
"s": 6477,
"text": "There are only 4 companies in the world with more than 100k employees and they are all Japanese companies! This could be because many Japanese workers are loyal to their companies."
},
{
"code": null,
"e": 6804,
"s": 6658,
"text": "These results are cool. But what if you want to export the data from Diffbot for further analysis? That can be done using Python or command-line."
},
{
"code": null,
"e": 6888,
"s": 6804,
"text": "To use the Knowledge Graph API, make an HTTP GET request to the following endpoint:"
},
{
"code": null,
"e": 6958,
"s": 6888,
"text": "https://kg.diffbot.com/kg/dql_endpoint?token=...&type=query&query=..."
},
{
"code": null,
"e": 7036,
"s": 6958,
"text": "We can also create a function that returns the endpoint. This function takes:"
},
{
"code": null,
"e": 7056,
"s": 7036,
"text": "Diffbot’s API token"
},
{
"code": null,
"e": 7101,
"s": 7056,
"text": "the URL of the JSON file we want to download"
},
{
"code": null,
"e": 7167,
"s": 7101,
"text": "The token can be found in the top right corner of your Dashboard."
},
{
"code": null,
"e": 7255,
"s": 7167,
"text": "The URL of the JSON file can be found by clicking the JSON tab in the top right corner."
},
{
"code": null,
"e": 7358,
"s": 7255,
"text": "Use the URL of the page you are directed to as the second parameter of the function get_diffbot_json ."
},
{
"code": null,
"e": 7395,
"s": 7358,
"text": "And you will get a downloadable URL:"
},
{
"code": null,
"e": 7547,
"s": 7395,
"text": "https://kg.diffbot.com/kg/dql_endpoint?token=your-token&type=query&query=type%3APerson+id%3A%22EyauXV2QZOW2fEP8Cb_Hoxg%22&from=0&size=25&output_format="
},
{
"code": null,
"e": 7640,
"s": 7547,
"text": "To download the data in the URL returned by the get_diffbot_json , use the requests library:"
},
{
"code": null,
"e": 7695,
"s": 7640,
"text": "And the JSON file will be saved in your local machine!"
},
{
"code": null,
"e": 7761,
"s": 7695,
"text": "You can also download the JSON file on your terminal using wget :"
},
{
"code": null,
"e": 7919,
"s": 7761,
"text": "wget https://kg.diffbot.com/kg/dql_endpoint?token=your-tokenc&type=query&query=type%3APerson+id%3A%22EyauXV2QZOW2fEP8Cb_Hoxg%22&from=0&size=25&output_format="
},
{
"code": null,
"e": 8135,
"s": 7919,
"text": "Congratulations! You have just learned how to build a knowledge graph and summarize essential facts using Diffbot. I hope this article will give you the motivation to explore other topics that you are interested in."
},
{
"code": null,
"e": 8295,
"s": 8135,
"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."
}
] |
How to add a PHP page to WordPress? - GeeksforGeeks
|
05 Aug, 2020
WordPress is one of the best blogging platforms. This is the scenario, we have a custom PHP page which we want to integrate with the WordPress blog. Our PHP file which we are getting to integrate might not use any of the WordPress APIs. Integrating PHP files with WordPress is very important for the back-end development of web design.
Step 1: Login to Microsoft Web Matrix The following screen appears. Open or create your WordPress template.
Step 2: Create WordPress Template Page We can start with a sample file and copy page.php, rename it on your choice and put it inside the theme folder ../wp-content/themes/mytheme/
<?php/*Template Name: GFG*/ /* Rest PHP code here */?>
This new file should start with the following content and then followed by the custom PHP content. This is the WordPress template. Remember to upload this to the theme folder. Now the WordPress template is ready.
Step 3: Create WordPress PageClick the “Pages” link from the WordPress Dashboard. The template we created can be used to create this new page. We can give the Page name and choose the “Template” from the drop-down from the “Page Attributes” section. There the PHP-page we uploaded will come with the “GeeksfoGeeks” listed in the dropdown. Now publish. Here we go, we have created a WordPress PHP page using our custom code. Whenever this page is linked, our custom PHP code will get executed. Various types of templates can be created through it.
Example: In functions, you need to implement it as follows:
function simple_function_1() { return "Hello World!";} add_shortcode( 'own_shortcode1', 'simple_function_1' );
In post/page:
[own_shortcode1]
Output:
Hello World!
A real-time scenario is we will construct a sitemap page using this WordPress template option.
PHP-Misc
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
Different ways for passing data to view in Laravel
How to generate PDF file using PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24972,
"s": 24944,
"text": "\n05 Aug, 2020"
},
{
"code": null,
"e": 25308,
"s": 24972,
"text": "WordPress is one of the best blogging platforms. This is the scenario, we have a custom PHP page which we want to integrate with the WordPress blog. Our PHP file which we are getting to integrate might not use any of the WordPress APIs. Integrating PHP files with WordPress is very important for the back-end development of web design."
},
{
"code": null,
"e": 25416,
"s": 25308,
"text": "Step 1: Login to Microsoft Web Matrix The following screen appears. Open or create your WordPress template."
},
{
"code": null,
"e": 25596,
"s": 25416,
"text": "Step 2: Create WordPress Template Page We can start with a sample file and copy page.php, rename it on your choice and put it inside the theme folder ../wp-content/themes/mytheme/"
},
{
"code": "<?php/*Template Name: GFG*/ /* Rest PHP code here */?>",
"e": 25652,
"s": 25596,
"text": null
},
{
"code": null,
"e": 25865,
"s": 25652,
"text": "This new file should start with the following content and then followed by the custom PHP content. This is the WordPress template. Remember to upload this to the theme folder. Now the WordPress template is ready."
},
{
"code": null,
"e": 26412,
"s": 25865,
"text": "Step 3: Create WordPress PageClick the “Pages” link from the WordPress Dashboard. The template we created can be used to create this new page. We can give the Page name and choose the “Template” from the drop-down from the “Page Attributes” section. There the PHP-page we uploaded will come with the “GeeksfoGeeks” listed in the dropdown. Now publish. Here we go, we have created a WordPress PHP page using our custom code. Whenever this page is linked, our custom PHP code will get executed. Various types of templates can be created through it."
},
{
"code": null,
"e": 26472,
"s": 26412,
"text": "Example: In functions, you need to implement it as follows:"
},
{
"code": "function simple_function_1() { return \"Hello World!\";} add_shortcode( 'own_shortcode1', 'simple_function_1' );",
"e": 26587,
"s": 26472,
"text": null
},
{
"code": null,
"e": 26601,
"s": 26587,
"text": "In post/page:"
},
{
"code": null,
"e": 26618,
"s": 26601,
"text": "[own_shortcode1]"
},
{
"code": null,
"e": 26626,
"s": 26618,
"text": "Output:"
},
{
"code": null,
"e": 26639,
"s": 26626,
"text": "Hello World!"
},
{
"code": null,
"e": 26734,
"s": 26639,
"text": "A real-time scenario is we will construct a sitemap page using this WordPress template option."
},
{
"code": null,
"e": 26743,
"s": 26734,
"text": "PHP-Misc"
},
{
"code": null,
"e": 26750,
"s": 26743,
"text": "Picked"
},
{
"code": null,
"e": 26754,
"s": 26750,
"text": "PHP"
},
{
"code": null,
"e": 26771,
"s": 26754,
"text": "Web Technologies"
},
{
"code": null,
"e": 26775,
"s": 26771,
"text": "PHP"
},
{
"code": null,
"e": 26873,
"s": 26775,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26882,
"s": 26873,
"text": "Comments"
},
{
"code": null,
"e": 26895,
"s": 26882,
"text": "Old Comments"
},
{
"code": null,
"e": 26977,
"s": 26895,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 27019,
"s": 26977,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 27070,
"s": 27019,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 27107,
"s": 27070,
"text": "How to generate PDF file using PHP ?"
},
{
"code": null,
"e": 27181,
"s": 27107,
"text": "Create a drop-down list that options fetched from a MySQL database in PHP"
},
{
"code": null,
"e": 27223,
"s": 27181,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27256,
"s": 27223,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27299,
"s": 27256,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27361,
"s": 27299,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Date getTimezoneOffset() Method
|
Javascript date getTimezoneOffset() method returns the time-zone offset in minutes for the current locale. The time-zone offset is the minutes in difference, the Greenwich Mean Time (GMT) is relative to your local time.
For example, if your time zone is GMT+10, -600 will be returned. Daylight savings time prevents this value from being a constant.
Its syntax is as follows −
Date.getTimezoneOffset()
Returns the time-zone offset in minutes for the current locale.
Try the following example.
<html>
<head>
<title>JavaScript getTimezoneOffset Method</title>
</head>
<body>
<script type = "text/javascript">
var dt = new Date();
var tz = dt.getTimezoneOffset();
document.write("getTimezoneOffset() : " + tz );
</script>
</body>
</html>
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2686,
"s": 2466,
"text": "Javascript date getTimezoneOffset() method returns the time-zone offset in minutes for the current locale. The time-zone offset is the minutes in difference, the Greenwich Mean Time (GMT) is relative to your local time."
},
{
"code": null,
"e": 2816,
"s": 2686,
"text": "For example, if your time zone is GMT+10, -600 will be returned. Daylight savings time prevents this value from being a constant."
},
{
"code": null,
"e": 2843,
"s": 2816,
"text": "Its syntax is as follows −"
},
{
"code": null,
"e": 2869,
"s": 2843,
"text": "Date.getTimezoneOffset()\n"
},
{
"code": null,
"e": 2933,
"s": 2869,
"text": "Returns the time-zone offset in minutes for the current locale."
},
{
"code": null,
"e": 2960,
"s": 2933,
"text": "Try the following example."
},
{
"code": null,
"e": 3274,
"s": 2960,
"text": "<html>\n <head>\n <title>JavaScript getTimezoneOffset Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var dt = new Date();\n var tz = dt.getTimezoneOffset(); \n document.write(\"getTimezoneOffset() : \" + tz ); \n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 3309,
"s": 3274,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3323,
"s": 3309,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3357,
"s": 3323,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3371,
"s": 3357,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3406,
"s": 3371,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3423,
"s": 3406,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3458,
"s": 3423,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3475,
"s": 3458,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3508,
"s": 3475,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3536,
"s": 3508,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3570,
"s": 3536,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 3598,
"s": 3570,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3605,
"s": 3598,
"text": " Print"
},
{
"code": null,
"e": 3616,
"s": 3605,
"text": " Add Notes"
}
] |
Mathematics | Probability - GeeksforGeeks
|
26 Mar, 2022
Probability refers to the extent of occurrence of events. When an event occurs like throwing a ball, picking a card from deck, etc., then the must be some probability associated with that event. In terms of mathematics, probability refers to the ratio of wanted outcomes to the total number of possible outcomes. There are three approaches to the theory of probability, namely:
Empirical ApproachClassical ApproachAxiomatic Approach
Empirical Approach
Classical Approach
Axiomatic Approach
In this article, we are going to study about Axiomatic Approach. In this approach, we represent the probability in terms of sample space(S) and other terms. Basic Terminologies:
Random Event :- If the repetition of an experiment occurs several times under similar conditions, if it does not produce the same outcome everytime but the outcome in a trial is one of the several possible outcomes, then such an experiment is called random event or a probabilistic event.
Elementary Event – The elementary event refers to the outcome of each random event performed. Whenever the random event is performed, each associated outcome is known as elementary event.
Sample Space – Sample Space refers to the set of all possible outcomes of a random event.Example, when a coin is tossed, the possible outcomes are head and tail.
Event – An event refers to the subset of the sample space associated with a random event.
Occurrence of an Event – An event associated with a random event is said to occur if any one of the elementary event belonging to it is an outcome.
Sure Event – An event associated with a random event is said to be sure event if it always occurs whenever the random event is performed.
Impossible Event – An event associated with a random event is said to be impossible event if it never occurs whenever the random event is performed.
Compound Event – An event associated with a random event is said to be compound event if it is the disjoint union of two or more elementary events.
Mutually Exclusive Events – Two or more events associated with a random event are said to be mutually exclusive events if any one of the event occurs, it prevents the occurrence of all other events.This means that no two or more events can occur simultaneously at the same time.
Exhaustive Events – Two or more events associated with a random event are said to be exhaustive events if their union is the sample space.
Probability of an Event – If there are total p possible outcomes associated with a random experiment and q of them are favourable outcomes to the event A, then the probability of event A is denoted by P(A) and is given by
P(A) = q/p
The probability of non-occurrence of event A, i.e, P(A’) = 1 – P(A) Note –
If the value of P(A) = 1, then event A is called sure event .
If the value of P(A) = 0, then event A is called impossible event.
Also, P(A) + P(A’) = 1
Theorems:
General – Let A, B, C are the events associated with a random experiment, thenP(A∪B) = P(A) + P(B) – P(A∩B)P(A∪B) = P(A) + P(B) if A and B are mutually exclusiveP(A∪B∪C) = P(A) + P(B) + P(C) – P(A∩B) – P(B∩C)- P(C∩A) + P(A∩B∩C)P(A∩B’) = P(A) – P(A∩B)P(A’∩B) = P(B) – P(A∩B)
P(A∪B) = P(A) + P(B) – P(A∩B)P(A∪B) = P(A) + P(B) if A and B are mutually exclusiveP(A∪B∪C) = P(A) + P(B) + P(C) – P(A∩B) – P(B∩C)- P(C∩A) + P(A∩B∩C)P(A∩B’) = P(A) – P(A∩B)P(A’∩B) = P(B) – P(A∩B)
P(A∪B) = P(A) + P(B) – P(A∩B)
P(A∪B) = P(A) + P(B) if A and B are mutually exclusive
P(A∪B∪C) = P(A) + P(B) + P(C) – P(A∩B) – P(B∩C)- P(C∩A) + P(A∩B∩C)
P(A∩B’) = P(A) – P(A∩B)
P(A’∩B) = P(B) – P(A∩B)
Extension of Multiplication Theorem – Let A1, A2, ....., An are n events associated with a random experiment, then P(A1∩A2∩A3 ..... An) = P(A1)P(A2/A1)P(A3/A2∩A1) ..... P(An/A1∩A2∩A3∩ ..... ∩An-1)
Example-1: A bag contains 10 oranges and 20 apples out of which 5 apples and 3 oranges are defective. If a person takes out two at random, what is the probability that either both are good or both are apples? Solution – Out of 30 items, two can selected in 30C2 ways . Thus, Total elementary events = 30C2 . Consider the events : A = Getting two apples B = Getting two good items Required Probability is : P(A∪B) = P(A) + P(B) – P(A∩B) ...(i) There are 20 apples, out of which 2 can drawn in 20C2 ways . P(A) = 20C2/30C2 There are 8 defective items and 22 are good, Out of 22 good items, two can be can drawn in 22C2 ways . P(B) = 22C2/30C2 Since there are 15 items which are good apples, out of which 2 can be selected in 15C2 ways . P(A∩B) = 15C2/30C2 Substituting the values of P(A), P(B) and P(A∩B) in (i) Required probability is = (20C2/30C2) + (22C2/30C2) – (15C2/30C2) = 316/435 Example-2: The probability that a person will get an electric contract is 2/5 and probability that he will not get plumbing contract is 4/7. If the probability of getting at least one contact is 2/3, what is the probability of getting both? Solution: Consider the two events: A = Person gets electric contract B = Person gets plumbing contract We have, P(A) = 2/5 P(B’) = 4/7 P(A∪B) = 2/3 Now, P(A∩B) = P(A) + P(B) – P(A∪B) = (2/5) + (1 – 4/7) – (2/3) = 17/105 Total Law of Probability – Let S be the sample space associated with a random experiment and E1, E2, ..., En be n mutually exclusive and exhaustive events associated with the random experiment. If A is any event which occurs with E1 or E2 or ... or En, then
P(A) = P(E1)P(A/E1) + P(E2)P(A/E2) + ... + P(En)P(A/En)
Example-1: A bag contains 3 black balls and 4 red balls .A second bag contains 4 black balls and 2 red balls. One bag is selected at random. From the selected bag, one ball is drawn. Find the probability that the ball drawn is red. Solution: A red ball can be drawn in two ways:
Selecting bag I and then drawing a red ball from it.Selecting bag II and then drawing a red ball from it.
Selecting bag I and then drawing a red ball from it.
Selecting bag II and then drawing a red ball from it.
Let E1, E2 and A be the defined events as follows : E1 = Selecting bag I E2 = Selecting bag II A = Drawing red ball Since selecting one of the two bags at random . P(E1) = 1/2 P(E2) = 1/2 Now, probability of drawing red ball when first bag has been chosen P(A/E1) = 4/7 and, probability of drawing red ball when second bag has been chosen P(A/E2) = 2/6 Using total law of probability, we have P(A) = P(E1)P(A/E1) + P(E2)P(A/E2) = (1/2)(4/7) + (1/2)(2/6) = 19/42 Hence, the probability of drawing a red ball is 19/42 Example-2: In a bulb factory, three machines namely A, B, C produces 25%, 35% and 40% of the total bulbs respectively. Of their output, 5, 4 and 2 percent are defective bulbs respectively. A bulb is drawn at random from products. What is the probability that bulb drawn is defective? Solution: Let E1, E2, E3 and A be the defined events as follows : E1 = The bulb is manufactured by machine A E2 = The bulb is manufactured by machine B E3 = The bulb is manufactured by machine C A = The bulb is defective According to given conditions ; P(E1) = 25/100 P(E2) = 35/100 P(E3) = 40/100 Now, probability that the bulb is defective given that is produced by Machine A P(A/E1) = 5/100 and, probability that the bulb is defective given that is produced by Machine B P(A/E2) = 4/100 and, probability that the bulb is defective given that is produced by Machine C P(A/E3) = 2/100 Using total law of probability, we have P(A) = P(E1)P(A/E1) + P(E2)P(A/E2) + P(E3)P(A/E3) = (25/100)(5/100) + (35/100)(4/100) + (40/100)(2/100) = 0.0345 Hence, the probability that the bulb is defective is 0.0345
Astha Tyagi
hl2kerg
SuhailNaik
shreyashagrawal
chhabradhanvi
bharghavsaip
rkbhola5
Engineering Mathematics
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inequalities in LaTeX
Newton's Divided Difference Interpolation Formula
Arrow Symbols in LaTeX
Set Notations in LaTeX
Univariate, Bivariate and Multivariate data and its analysis
Layers of OSI Model
ACID Properties in DBMS
Normal Forms in DBMS
Types of Operating Systems
|
[
{
"code": null,
"e": 29952,
"s": 29924,
"text": "\n26 Mar, 2022"
},
{
"code": null,
"e": 30330,
"s": 29952,
"text": "Probability refers to the extent of occurrence of events. When an event occurs like throwing a ball, picking a card from deck, etc., then the must be some probability associated with that event. In terms of mathematics, probability refers to the ratio of wanted outcomes to the total number of possible outcomes. There are three approaches to the theory of probability, namely:"
},
{
"code": null,
"e": 30385,
"s": 30330,
"text": "Empirical ApproachClassical ApproachAxiomatic Approach"
},
{
"code": null,
"e": 30404,
"s": 30385,
"text": "Empirical Approach"
},
{
"code": null,
"e": 30423,
"s": 30404,
"text": "Classical Approach"
},
{
"code": null,
"e": 30442,
"s": 30423,
"text": "Axiomatic Approach"
},
{
"code": null,
"e": 30620,
"s": 30442,
"text": "In this article, we are going to study about Axiomatic Approach. In this approach, we represent the probability in terms of sample space(S) and other terms. Basic Terminologies:"
},
{
"code": null,
"e": 30909,
"s": 30620,
"text": "Random Event :- If the repetition of an experiment occurs several times under similar conditions, if it does not produce the same outcome everytime but the outcome in a trial is one of the several possible outcomes, then such an experiment is called random event or a probabilistic event."
},
{
"code": null,
"e": 31097,
"s": 30909,
"text": "Elementary Event – The elementary event refers to the outcome of each random event performed. Whenever the random event is performed, each associated outcome is known as elementary event."
},
{
"code": null,
"e": 31259,
"s": 31097,
"text": "Sample Space – Sample Space refers to the set of all possible outcomes of a random event.Example, when a coin is tossed, the possible outcomes are head and tail."
},
{
"code": null,
"e": 31349,
"s": 31259,
"text": "Event – An event refers to the subset of the sample space associated with a random event."
},
{
"code": null,
"e": 31497,
"s": 31349,
"text": "Occurrence of an Event – An event associated with a random event is said to occur if any one of the elementary event belonging to it is an outcome."
},
{
"code": null,
"e": 31635,
"s": 31497,
"text": "Sure Event – An event associated with a random event is said to be sure event if it always occurs whenever the random event is performed."
},
{
"code": null,
"e": 31784,
"s": 31635,
"text": "Impossible Event – An event associated with a random event is said to be impossible event if it never occurs whenever the random event is performed."
},
{
"code": null,
"e": 31932,
"s": 31784,
"text": "Compound Event – An event associated with a random event is said to be compound event if it is the disjoint union of two or more elementary events."
},
{
"code": null,
"e": 32211,
"s": 31932,
"text": "Mutually Exclusive Events – Two or more events associated with a random event are said to be mutually exclusive events if any one of the event occurs, it prevents the occurrence of all other events.This means that no two or more events can occur simultaneously at the same time."
},
{
"code": null,
"e": 32350,
"s": 32211,
"text": "Exhaustive Events – Two or more events associated with a random event are said to be exhaustive events if their union is the sample space."
},
{
"code": null,
"e": 32572,
"s": 32350,
"text": "Probability of an Event – If there are total p possible outcomes associated with a random experiment and q of them are favourable outcomes to the event A, then the probability of event A is denoted by P(A) and is given by"
},
{
"code": null,
"e": 32585,
"s": 32572,
"text": " P(A) = q/p "
},
{
"code": null,
"e": 32660,
"s": 32585,
"text": "The probability of non-occurrence of event A, i.e, P(A’) = 1 – P(A) Note –"
},
{
"code": null,
"e": 32722,
"s": 32660,
"text": "If the value of P(A) = 1, then event A is called sure event ."
},
{
"code": null,
"e": 32789,
"s": 32722,
"text": "If the value of P(A) = 0, then event A is called impossible event."
},
{
"code": null,
"e": 32812,
"s": 32789,
"text": "Also, P(A) + P(A’) = 1"
},
{
"code": null,
"e": 32822,
"s": 32812,
"text": "Theorems:"
},
{
"code": null,
"e": 33096,
"s": 32822,
"text": "General – Let A, B, C are the events associated with a random experiment, thenP(A∪B) = P(A) + P(B) – P(A∩B)P(A∪B) = P(A) + P(B) if A and B are mutually exclusiveP(A∪B∪C) = P(A) + P(B) + P(C) – P(A∩B) – P(B∩C)- P(C∩A) + P(A∩B∩C)P(A∩B’) = P(A) – P(A∩B)P(A’∩B) = P(B) – P(A∩B)"
},
{
"code": null,
"e": 33292,
"s": 33096,
"text": "P(A∪B) = P(A) + P(B) – P(A∩B)P(A∪B) = P(A) + P(B) if A and B are mutually exclusiveP(A∪B∪C) = P(A) + P(B) + P(C) – P(A∩B) – P(B∩C)- P(C∩A) + P(A∩B∩C)P(A∩B’) = P(A) – P(A∩B)P(A’∩B) = P(B) – P(A∩B)"
},
{
"code": null,
"e": 33322,
"s": 33292,
"text": "P(A∪B) = P(A) + P(B) – P(A∩B)"
},
{
"code": null,
"e": 33377,
"s": 33322,
"text": "P(A∪B) = P(A) + P(B) if A and B are mutually exclusive"
},
{
"code": null,
"e": 33444,
"s": 33377,
"text": "P(A∪B∪C) = P(A) + P(B) + P(C) – P(A∩B) – P(B∩C)- P(C∩A) + P(A∩B∩C)"
},
{
"code": null,
"e": 33468,
"s": 33444,
"text": "P(A∩B’) = P(A) – P(A∩B)"
},
{
"code": null,
"e": 33492,
"s": 33468,
"text": "P(A’∩B) = P(B) – P(A∩B)"
},
{
"code": null,
"e": 33689,
"s": 33492,
"text": "Extension of Multiplication Theorem – Let A1, A2, ....., An are n events associated with a random experiment, then P(A1∩A2∩A3 ..... An) = P(A1)P(A2/A1)P(A3/A2∩A1) ..... P(An/A1∩A2∩A3∩ ..... ∩An-1)"
},
{
"code": null,
"e": 35294,
"s": 33689,
"text": "Example-1: A bag contains 10 oranges and 20 apples out of which 5 apples and 3 oranges are defective. If a person takes out two at random, what is the probability that either both are good or both are apples? Solution – Out of 30 items, two can selected in 30C2 ways . Thus, Total elementary events = 30C2 . Consider the events : A = Getting two apples B = Getting two good items Required Probability is : P(A∪B) = P(A) + P(B) – P(A∩B) ...(i) There are 20 apples, out of which 2 can drawn in 20C2 ways . P(A) = 20C2/30C2 There are 8 defective items and 22 are good, Out of 22 good items, two can be can drawn in 22C2 ways . P(B) = 22C2/30C2 Since there are 15 items which are good apples, out of which 2 can be selected in 15C2 ways . P(A∩B) = 15C2/30C2 Substituting the values of P(A), P(B) and P(A∩B) in (i) Required probability is = (20C2/30C2) + (22C2/30C2) – (15C2/30C2) = 316/435 Example-2: The probability that a person will get an electric contract is 2/5 and probability that he will not get plumbing contract is 4/7. If the probability of getting at least one contact is 2/3, what is the probability of getting both? Solution: Consider the two events: A = Person gets electric contract B = Person gets plumbing contract We have, P(A) = 2/5 P(B’) = 4/7 P(A∪B) = 2/3 Now, P(A∩B) = P(A) + P(B) – P(A∪B) = (2/5) + (1 – 4/7) – (2/3) = 17/105 Total Law of Probability – Let S be the sample space associated with a random experiment and E1, E2, ..., En be n mutually exclusive and exhaustive events associated with the random experiment. If A is any event which occurs with E1 or E2 or ... or En, then"
},
{
"code": null,
"e": 35351,
"s": 35294,
"text": "P(A) = P(E1)P(A/E1) + P(E2)P(A/E2) + ... + P(En)P(A/En)"
},
{
"code": null,
"e": 35630,
"s": 35351,
"text": "Example-1: A bag contains 3 black balls and 4 red balls .A second bag contains 4 black balls and 2 red balls. One bag is selected at random. From the selected bag, one ball is drawn. Find the probability that the ball drawn is red. Solution: A red ball can be drawn in two ways:"
},
{
"code": null,
"e": 35736,
"s": 35630,
"text": "Selecting bag I and then drawing a red ball from it.Selecting bag II and then drawing a red ball from it."
},
{
"code": null,
"e": 35789,
"s": 35736,
"text": "Selecting bag I and then drawing a red ball from it."
},
{
"code": null,
"e": 35843,
"s": 35789,
"text": "Selecting bag II and then drawing a red ball from it."
},
{
"code": null,
"e": 37442,
"s": 35843,
"text": "Let E1, E2 and A be the defined events as follows : E1 = Selecting bag I E2 = Selecting bag II A = Drawing red ball Since selecting one of the two bags at random . P(E1) = 1/2 P(E2) = 1/2 Now, probability of drawing red ball when first bag has been chosen P(A/E1) = 4/7 and, probability of drawing red ball when second bag has been chosen P(A/E2) = 2/6 Using total law of probability, we have P(A) = P(E1)P(A/E1) + P(E2)P(A/E2) = (1/2)(4/7) + (1/2)(2/6) = 19/42 Hence, the probability of drawing a red ball is 19/42 Example-2: In a bulb factory, three machines namely A, B, C produces 25%, 35% and 40% of the total bulbs respectively. Of their output, 5, 4 and 2 percent are defective bulbs respectively. A bulb is drawn at random from products. What is the probability that bulb drawn is defective? Solution: Let E1, E2, E3 and A be the defined events as follows : E1 = The bulb is manufactured by machine A E2 = The bulb is manufactured by machine B E3 = The bulb is manufactured by machine C A = The bulb is defective According to given conditions ; P(E1) = 25/100 P(E2) = 35/100 P(E3) = 40/100 Now, probability that the bulb is defective given that is produced by Machine A P(A/E1) = 5/100 and, probability that the bulb is defective given that is produced by Machine B P(A/E2) = 4/100 and, probability that the bulb is defective given that is produced by Machine C P(A/E3) = 2/100 Using total law of probability, we have P(A) = P(E1)P(A/E1) + P(E2)P(A/E2) + P(E3)P(A/E3) = (25/100)(5/100) + (35/100)(4/100) + (40/100)(2/100) = 0.0345 Hence, the probability that the bulb is defective is 0.0345"
},
{
"code": null,
"e": 37454,
"s": 37442,
"text": "Astha Tyagi"
},
{
"code": null,
"e": 37462,
"s": 37454,
"text": "hl2kerg"
},
{
"code": null,
"e": 37473,
"s": 37462,
"text": "SuhailNaik"
},
{
"code": null,
"e": 37489,
"s": 37473,
"text": "shreyashagrawal"
},
{
"code": null,
"e": 37503,
"s": 37489,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 37516,
"s": 37503,
"text": "bharghavsaip"
},
{
"code": null,
"e": 37525,
"s": 37516,
"text": "rkbhola5"
},
{
"code": null,
"e": 37549,
"s": 37525,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 37557,
"s": 37549,
"text": "GATE CS"
},
{
"code": null,
"e": 37655,
"s": 37557,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37664,
"s": 37655,
"text": "Comments"
},
{
"code": null,
"e": 37677,
"s": 37664,
"text": "Old Comments"
},
{
"code": null,
"e": 37699,
"s": 37677,
"text": "Inequalities in LaTeX"
},
{
"code": null,
"e": 37749,
"s": 37699,
"text": "Newton's Divided Difference Interpolation Formula"
},
{
"code": null,
"e": 37772,
"s": 37749,
"text": "Arrow Symbols in LaTeX"
},
{
"code": null,
"e": 37795,
"s": 37772,
"text": "Set Notations in LaTeX"
},
{
"code": null,
"e": 37856,
"s": 37795,
"text": "Univariate, Bivariate and Multivariate data and its analysis"
},
{
"code": null,
"e": 37876,
"s": 37856,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 37900,
"s": 37876,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 37921,
"s": 37900,
"text": "Normal Forms in DBMS"
}
] |
DAX Filter - RELATEDTABLE function
|
Evaluates a table expression in a context modified by the given filters.
RELATEDTABLE (<tableName>)
tableName
The name of an existing table.
It cannot be an expression.
A table of values.
DAX RELATEDTETABLE function changes the context in which the data is filtered, and evaluates the expression in the new context that you specify.
DAX RELATEDTABLE function is equivalent to DAX CALCULATETABLE function with no logical expression.
= SUMX (RELATEDTABLE (East_Sales),East_Sales[Sales Amount])
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2074,
"s": 2001,
"text": "Evaluates a table expression in a context modified by the given filters."
},
{
"code": null,
"e": 2103,
"s": 2074,
"text": "RELATEDTABLE (<tableName>) \n"
},
{
"code": null,
"e": 2113,
"s": 2103,
"text": "tableName"
},
{
"code": null,
"e": 2144,
"s": 2113,
"text": "The name of an existing table."
},
{
"code": null,
"e": 2172,
"s": 2144,
"text": "It cannot be an expression."
},
{
"code": null,
"e": 2191,
"s": 2172,
"text": "A table of values."
},
{
"code": null,
"e": 2336,
"s": 2191,
"text": "DAX RELATEDTETABLE function changes the context in which the data is filtered, and evaluates the expression in the new context that you specify."
},
{
"code": null,
"e": 2435,
"s": 2336,
"text": "DAX RELATEDTABLE function is equivalent to DAX CALCULATETABLE function with no logical expression."
},
{
"code": null,
"e": 2496,
"s": 2435,
"text": "= SUMX (RELATEDTABLE (East_Sales),East_Sales[Sales Amount]) "
},
{
"code": null,
"e": 2531,
"s": 2496,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 2545,
"s": 2531,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 2578,
"s": 2545,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2592,
"s": 2578,
"text": " Randy Minder"
},
{
"code": null,
"e": 2627,
"s": 2592,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 2641,
"s": 2627,
"text": " Randy Minder"
},
{
"code": null,
"e": 2648,
"s": 2641,
"text": " Print"
},
{
"code": null,
"e": 2659,
"s": 2648,
"text": " Add Notes"
}
] |
C# - Enums
|
An enumeration is a set of named integer constants. An enumerated type is declared using the enum keyword.
C# enumerations are value data type. In other words, enumeration contains its own values and cannot inherit or cannot pass inheritance.
The general syntax for declaring an enumeration is −
enum <enum_name> {
enumeration list
};
Where,
The enum_name specifies the enumeration type name.
The enum_name specifies the enumeration type name.
The enumeration list is a comma-separated list of identifiers.
The enumeration list is a comma-separated list of identifiers.
Each of the symbols in the enumeration list stands for an integer value, one greater than the symbol that precedes it. By default, the value of the first enumeration symbol is 0. For example −
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
The following example demonstrates use of enum variable −
using System;
namespace EnumApplication {
class EnumProgram {
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
static void Main(string[] args) {
int WeekdayStart = (int)Days.Mon;
int WeekdayEnd = (int)Days.Fri;
Console.WriteLine("Monday: {0}", WeekdayStart);
Console.WriteLine("Friday: {0}", WeekdayEnd);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
Monday: 1
Friday: 5
119 Lectures
23.5 hours
Raja Biswas
37 Lectures
13 hours
Trevoir Williams
16 Lectures
1 hours
Peter Jepson
159 Lectures
21.5 hours
Ebenezer Ogbu
193 Lectures
17 hours
Arnold Higuit
24 Lectures
2.5 hours
Eric Frick
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2377,
"s": 2270,
"text": "An enumeration is a set of named integer constants. An enumerated type is declared using the enum keyword."
},
{
"code": null,
"e": 2513,
"s": 2377,
"text": "C# enumerations are value data type. In other words, enumeration contains its own values and cannot inherit or cannot pass inheritance."
},
{
"code": null,
"e": 2566,
"s": 2513,
"text": "The general syntax for declaring an enumeration is −"
},
{
"code": null,
"e": 2610,
"s": 2566,
"text": "enum <enum_name> {\n enumeration list \n};\n"
},
{
"code": null,
"e": 2617,
"s": 2610,
"text": "Where,"
},
{
"code": null,
"e": 2668,
"s": 2617,
"text": "The enum_name specifies the enumeration type name."
},
{
"code": null,
"e": 2719,
"s": 2668,
"text": "The enum_name specifies the enumeration type name."
},
{
"code": null,
"e": 2782,
"s": 2719,
"text": "The enumeration list is a comma-separated list of identifiers."
},
{
"code": null,
"e": 2845,
"s": 2782,
"text": "The enumeration list is a comma-separated list of identifiers."
},
{
"code": null,
"e": 3038,
"s": 2845,
"text": "Each of the symbols in the enumeration list stands for an integer value, one greater than the symbol that precedes it. By default, the value of the first enumeration symbol is 0. For example −"
},
{
"code": null,
"e": 3088,
"s": 3038,
"text": "enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };\n"
},
{
"code": null,
"e": 3146,
"s": 3088,
"text": "The following example demonstrates use of enum variable −"
},
{
"code": null,
"e": 3557,
"s": 3146,
"text": "using System;\n\nnamespace EnumApplication {\n class EnumProgram {\n enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };\n\n static void Main(string[] args) {\n int WeekdayStart = (int)Days.Mon;\n int WeekdayEnd = (int)Days.Fri;\n \n Console.WriteLine(\"Monday: {0}\", WeekdayStart);\n Console.WriteLine(\"Friday: {0}\", WeekdayEnd);\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 3638,
"s": 3557,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3659,
"s": 3638,
"text": "Monday: 1\nFriday: 5\n"
},
{
"code": null,
"e": 3696,
"s": 3659,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 3709,
"s": 3696,
"text": " Raja Biswas"
},
{
"code": null,
"e": 3743,
"s": 3709,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3761,
"s": 3743,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 3794,
"s": 3761,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3808,
"s": 3794,
"text": " Peter Jepson"
},
{
"code": null,
"e": 3845,
"s": 3808,
"text": "\n 159 Lectures \n 21.5 hours \n"
},
{
"code": null,
"e": 3860,
"s": 3845,
"text": " Ebenezer Ogbu"
},
{
"code": null,
"e": 3895,
"s": 3860,
"text": "\n 193 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 3910,
"s": 3895,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 3945,
"s": 3910,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3957,
"s": 3945,
"text": " Eric Frick"
},
{
"code": null,
"e": 3964,
"s": 3957,
"text": " Print"
},
{
"code": null,
"e": 3975,
"s": 3964,
"text": " Add Notes"
}
] |
Web Scraping with Selenium. This is the third part of a 4 part... | by Karthikeyan P | Towards Data Science
|
Selenium is a portable framework for testing web applications. It is open-source software released under the Apache License 2.0 that runs on Windows, Linux and macOS. Despite serving its major purpose, Selenium is also used as a web scraping tool. Without delving into the components of Selenium, we shall focus on a single component that is useful for web scraping, WebDriver. Selenium WebDriver provides us with an ability to control a web browser through a programming interface to create and execute test cases.
In our case, we shall be using it for scraping data from websites. Selenium comes in handy when websites display content dynamically i.e. use JavaScripts to render content. Even though Scrapy is a powerful web scraping framework, it becomes useless with these dynamic websites. My goal for this tutorial is to make you familiarize with Selenium and carry out some basic web scraping using it.
Let us start by installing selenium and a webdriver. WebDrivers support 7 Programming Languages: Python, Java, C#, Ruby, PHP, .Net and Perl. The examples in this manual are with Python language. There are tutorials available on the internet with other languages.
This is the third part of a 4 part tutorial series on web scraping using Scrapy and Selenium. The other parts can be found at
Part 1: Web scraping with Scrapy: Theoretical Understanding
Part 2: Web scraping with Scrapy: Practical Understanding
Part 4: Web scraping with Selenium & Scrapy
Installing Selenium on any Linux OS is easy. Just execute the following command in a terminal and Selenium would be installed automatically.
pip install selenium
Selenium officially has WebDrivers for 5 Web Browsers. Here, we shall see the installation of WebDriver for two of the most widely used browsers: Chrome and Firefox.
First, we need to download the latest stable version of chromedriver from Chrome’s official site. It would be a zip file. All we need to do is extract it and put it in the executable path.
wget https://chromedriver.storage.googleapis.com/83.0.4103.39/chromedriver_linux64.zipunzip chromedriver_linux64.zipsudo mv chromedriver /usr/local/bin/
Installing geckodriver for Firefox is even simpler since it is maintained by Firefox itself. All we need to do is execute the following line in a terminal and you are ready to play around with selenium and geckodriver.
sudo apt install firefox-geckodriver
There are two examples with increasing levels of complexity. First one would be a simpler webpage opening and typing into textboxes and pressing key(s). This example is to showcase how a webpage can be controlled through Selenium using a program. The second one would be a more complex web scraping example involving mouse scrolling, mouse button clicks and navigating to other pages. The goal here is to make you feel confident to start web scraping with Selenium.
Let us try out a simple automation task using Selenium and chromedriver as our training wheel exercise. For this, we would try to log into a Facebook account and we are not performing any kind of data scraping. I am assuming that you have some knowledge of identifying HTML tags used in a webpage using the browser’s developer tools. The following is a piece of python code that opens up a new Chrome browser, opens the Facebook main page, enters a username, password and clicks Login button.
from selenium import webdriverfrom selenium.webdriver.common.keys import Keysuser_name = "Your E-mail"password = "Your Password"# Creating a chromedriver instancedriver = webdriver.Chrome() # For Chrome# driver = webdriver.Firefox() # For Firefox# Opening facebook homepagedriver.get("https://www.facebook.com")# Identifying email and password textboxesemail = driver.find_element_by_id("email")passwd = driver.find_element_by_id("pass")# Sending user_name and password to corresponding textboxesemail.send_keys(user_name)passwd.send_keys(password)# Sending a signal that RETURN key has been pressedpasswd.send_keys(Keys.RETURN)# driver.quit()
After executing this python code, your Facebook homepage would open in a new Chrome browser window. Let us examine how this became possible.
It all starts with the creation of a webdriver instance for your browser. As I am using Chrome, I have used driver = webdriver.Chrome().Then we open the Facebook webpage using driver.get("https://www.facebook.com"). When python encounters driver.get(URL), it opens a new browser window and opens the webpage specified by the URL.Once the homepage is loaded, we identify the textboxes to type e-mail and password using their HTML tag’s id attribute. This is done using driver.find_element_by_id().We send the username and password values for logging into Facebook using send_keys().We then simulate the user’s action of pressing RETURN/ENTER key by sending its corresponding signal using send_keys(Keys.RETURN).
It all starts with the creation of a webdriver instance for your browser. As I am using Chrome, I have used driver = webdriver.Chrome().
Then we open the Facebook webpage using driver.get("https://www.facebook.com"). When python encounters driver.get(URL), it opens a new browser window and opens the webpage specified by the URL.
Once the homepage is loaded, we identify the textboxes to type e-mail and password using their HTML tag’s id attribute. This is done using driver.find_element_by_id().
We send the username and password values for logging into Facebook using send_keys().
We then simulate the user’s action of pressing RETURN/ENTER key by sending its corresponding signal using send_keys(Keys.RETURN).
IMPORTANT NOTE:Any instance created in a program should be closed at the end of the program or after its purpose is served. So, whenever we are creating a webdriver instance, it has to be terminated using driver.quit(). If we do not terminate the opened instances, it starts to use up RAM, which may impact the machine's performance and slow it down. In the above example, this termination process has been commented out to show the output in a browser window. And, if terminated, the browser window would also be closed and the reader would not be able to see the output.
This is a more complex example. OpenAQ is a non-profit organization that collects and shares air quality data that are open and can be accessed in many ways. This is evident from the site’s robots.txt.
User-agent: * Disallow:
Our goal here is to collect data on PM2.5 readings from all the countries listed on http://openaq.org. PM2.5 are the particulate matter (PM) that have a diameter lesser than 2.5 micrometres, which is way smaller than the diameter of a human hair. If the reader is interested in knowing more about PM2.5, please follow this link.
The reason for choosing Selenium over Scrapy is that http://openaq.org uses React JS to render data. If it were static webpages, Scrapy would scrape the data efficiently. To scrape data, we first need to analyze the website, manually navigate the pages and note down the user interaction steps required to extract data.
It is always better to scrape with as few webpage navigations as possible. The website has a webpage https://openaq.org/#/locations which could be used as a starting point for scraping.
The filter locations option on the left-side panel is used to filter out PM2.5 data for each country. The Results on the right-side panel show cards that open a new page when clicked to display PM2.5 and other data.
A sample page containing PM2.5 data is shown below. From this page, we can extract PM2.5 values, location, city, country, date and time of recording PM2.5 value using XPATH or CSS.
Similarly, the left-side panel can be used to filter out and collect URLs of all the locations that contain PM2.5 data. The following are the actions that we performed manually to collect the data.
Open https://openaq.org/#/locationsFrom the left-side panel, select/click checkbox of a country. Let us go through the countries alphabetically.Also, from the left-side panel, select/click checkbox PM2.5.Wait for the cards to load in the right-side panel. Each card would then open a new webpage when clicked to display PM2.5 and other data.
Open https://openaq.org/#/locations
From the left-side panel, select/click checkbox of a country. Let us go through the countries alphabetically.
Also, from the left-side panel, select/click checkbox PM2.5.
Wait for the cards to load in the right-side panel. Each card would then open a new webpage when clicked to display PM2.5 and other data.
Based on the manual steps performed, data collection from http://openaq.org is broken down to 3 steps.
Collecting country names as displayed on OpenAQ countries webpage. This would be used in selecting appropriate checkboxes while filtering.Collecting URLs that contain PM2.5 data from each country. Some countries contain more than 20 PM2.5 readings collected from various locations. It would require further manipulation of the webpage, which is explained in the code section.Opening up webpages of the individual URL and extracting PM2.5 data.
Collecting country names as displayed on OpenAQ countries webpage. This would be used in selecting appropriate checkboxes while filtering.
Collecting URLs that contain PM2.5 data from each country. Some countries contain more than 20 PM2.5 readings collected from various locations. It would require further manipulation of the webpage, which is explained in the code section.
Opening up webpages of the individual URL and extracting PM2.5 data.
Now that we have the steps needed, let us start to code. The example is divided into 3 functions, each performing the task corresponding to the aforementioned 3 steps. The python code for this example can be found in my GitHub repository.
Instead of using OpenAQ locations webpage, there is https://openaq.org/#/countries webpage, which displays all the countries at once. It is easier to extract country names from this page.
from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECimport jsondef get_countries():countries_list = []# driver = webdriver.Chrome() # To open a new browser window and navigate it# Use the headless option to avoid opening a new browser window options = webdriver.ChromeOptions() options.add_argument("headless") desired_capabilities = options.to_capabilities() driver = webdriver.Chrome(desired_capabilities=desired_capabilities)# Getting webpage with the list of countriesdriver.get("https://openaq.org/#/countries")# Implicit wait driver.implicitly_wait(10)# Explicit wait wait = WebDriverWait(driver, 5) wait.until(EC.presence_of_element_located((By.CLASS_NAME, "card__title"))) countries = driver.find_elements_by_class_name("card__title") for country in countries: countries_list.append(country.text)driver.quit()# Write countries_list to json file with open("countries_list.json", "w") as f: json.dump(countries_list, f)
Let us understand how the code works. As always, the first step is to instantiate the webdriver. Here, instead of opening a new browser window, the webdriver is instantiated as a headless one. This way, a new browser window will not be opened and the burden on RAM would be reduced. The second step is to open the webpage containing the list of countries. The concept of wait is used in the above code.
Implicit Wait: When created, is alive until the WebDriver object dies. And is common for all operations. It instructs the webdriver to wait for a certain amount of time before elements load on the webpage.
Explicit Wait: Intelligent waits that are confined to a particular web element, in this case, tag with class name “card__title”. It is generally used along with ExpectedConditions.
The third step is to extract the country names using the tag with class name “card__title”. Finally, the country names are written to a JSON file for persistence. Below is a glimpse of the JSON file.
countries_list.json["Afghanistan", "Algeria", "Andorra", "Antigua and Barbuda", ... ]
The next step after getting the list of countries is to get the URLs of every location that records PM2.5 data. To do this, we need to open the OpenAQ locations webpage and make use of the left-side panel to filter out countries and PM2.5 data. Once it is filtered, the right-side panel would be populated with cards to individual locations that record PM2.5 data. We extract the URLs corresponding to each of these cards and eventually write them to a file that would be used in the next step of extracting PM2.5 data. Some countries have more than 20 locations that record PM2.5 data. For example, Australia has 162 locations, Belgium has 69 locations, China has 1602 locations. For these countries, the right-side panel on locations webpage is subdivided into pages. It is highly imperative that we navigate through these pages and collect URLs of all the locations. The code below has a while TRUE: loop that performs this exact task of page navigation.
from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.common.action_chains import ActionChainsfrom logzero import loggerimport selenium.common.exceptions as exceptionimport timeimport jsondef get_urls():# Load the countries list written by get_countries() with open("countries_list.json", "r") as f: countries_list = json.load(f) # driver = webdriver.Chrome() # Use headless option to not open a new browser window options = webdriver.ChromeOptions() options.add_argument("headless") desired_capabilities = options.to_capabilities() driver = webdriver.Chrome(desired_capabilities=desired_capabilities)urls_final = [] for country in countries_list:# Opening locations webpage driver.get("https://openaq.org/#/locations") driver.implicitly_wait(5) urls = []# Scrolling down the country filter till the country is visible action = ActionChains(driver) action.move_to_element(driver.find_element_by_xpath("//span[contains(text()," + '"' + country + '"' + ")]")) action.perform()# Identifying country and PM2.5 checkboxes country_button = driver.find_element_by_xpath("//label[contains(@for," + '"' + country + '"' + ")]") values_button = driver.find_element_by_xpath("//span[contains(text(),'PM2.5')]") # Clicking the checkboxes country_button.click() time.sleep(2) values_button.click() time.sleep(2)while True: # Navigating subpages where there are more PM2.5 data. For example, Australia has 162 PM2.5 readings from 162 different locations that are spread across 11 subpages.locations = driver.find_elements_by_xpath("//h1[@class='card__title']/a")for loc in locations: link = loc.get_attribute("href") urls.append(link)try: next_button = driver.find_element_by_xpath("//li[@class='next']") next_button.click() except exception.NoSuchElementException: logger.debug(f"Last page reached for {country}") breaklogger.info(f"{country} has {len(urls)} PM2.5 URLs") urls_final.extend(urls)logger.info(f"Total PM2.5 URLs: {len(urls_final)}") driver.quit()# Write the URLs to a file with open("urls.json", "w") as f: json.dump(urls_final, f)
It is always a good practice to log the output of programs that tend to run longer than 5 minutes. For this purpose, the above code makes use of logzero. The output JSON file containing the URLs looks like this.
urls.json[ "https://openaq.org/#/location/US%20Diplomatic%20Post%3A%20Kabul", "https://openaq.org/#/location/Kabul", "https://openaq.org/#/location/US%20Diplomatic%20Post%3A%20Algiers", ...]
The process of getting PM2.5 data from the individual location is a straight forward web scraping task of identifying the HTML tag containing the data and extracting it with text processing. The same happens in the code provided below. The code extracts the country, city, location, PM2.5 value, URL of the location, date and time of recording PM2.5 value. Since there are over 5000 URLs to be opened, there would be a problem with RAM usage unless the RAM installed is over 64GB. To make this program to run on machines with minimum 8GB of RAM, the webdriver is terminated and re-instantiated every 200 URLs.
from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.common.action_chains import ActionChainsfrom logzero import loggerimport selenium.common.exceptions as exceptionimport timeimport jsondef get_pm_data():# Load the URLs list written by get_urls() with open("urls.json", "r") as f: urls = json.load(f)# Use headless option to not open a new browser window options = webdriver.ChromeOptions() options.add_argument("headless") desired_capabilities = options.to_capabilities() driver = webdriver.Chrome(desired_capabilities=desired_capabilities)list_data_dict = [] count = 0for i, url in enumerate(urls): data_dict = {}# Open the webpage corresponding to each URL driver.get(url) driver.implicitly_wait(10) time.sleep(2)try: # Extract Location and City loc = driver.find_element_by_xpath("//h1[@class='inpage__title']").text.split("\n") logger.info(f"loc: {loc}") location = loc[0] city_country = loc[1].replace("in ", "", 1).split(",") city = city_country[0] country = city_country[1] data_dict["country"] = country data_dict["city"] = city data_dict["location"] = locationpm = driver.find_element_by_xpath("//dt[text()='PM2.5']/following-sibling::dd[1]").textif pm is not None: # Extract PM2.5 value, Date and Time of recording split = pm.split("μg/m3") pm = split[0] date_time = split[1].replace("at ", "").split(" ") date_pm = date_time[1] time_pm = date_time[2] data_dict["pm25"] = pm data_dict["url"] = url data_dict["date"] = date_pm data_dict["time"] = time_pmlist_data_dict.append(data_dict) count += 1except exception.NoSuchElementException: # Logging the info of locations that do not have PM2.5 data for manual checking logger.error(f"{location} in {city},{country} does not have PM2.5")# Terminating and re-instantiating webdriver every 200 URL to reduce the load on RAM if (i != 0) and (i % 200 == 0): driver.quit() driver = webdriver.Chrome(desired_capabilities=desired_capabilities) logger.info("Chromedriver restarted")# Write the extracted data into a JSON file with open("openaq_data.json", "w") as f: json.dump(list_data_dict, f)logger.info(f"Scraped {count} PM2.5 readings.") driver.quit()
The outcome of the program looks as shown below. The program has extracted PM2.5 values from 4114 individual locations. Imagine opening these individual webpages and manually extracting the data. It is times like this makes us appreciate the use of web scraping programs or bots, in general.
openaq_data.json[ { "country": " Afghanistan", "city": "Kabul", "location": "US Diplomatic Post: Kabul", "pm25": "33", "url": "https://openaq.org/#/location/US%20Diplomatic%20Post%3A%20Kabul", "date": "2020/07/31", "time": "11:00" }, { "country": " Algeria", "city": "Algiers", "location": "US Diplomatic Post: Algiers", "pm25": "31", "url": "https://openaq.org/#/location/US%20Diplomatic%20Post%3A%20Algiers", "date": "2020/07/31", "time": "08:30" }, { "country": " Australia", "city": "Adelaide", "location": "CBD", "pm25": "9", "url": "https://openaq.org/#/location/CBD", "date": "2020/07/31", "time": "11:00" }, ...]
I hope this tutorial has given you the confidence to start web scraping with Selenium. The complete code of the example is available in my GitHub repository. In the next tutorial, I shall show you how to integrate Selenium with Scrapy.
Till then, Good Luck. Stay safe and happy learning.!
|
[
{
"code": null,
"e": 687,
"s": 171,
"text": "Selenium is a portable framework for testing web applications. It is open-source software released under the Apache License 2.0 that runs on Windows, Linux and macOS. Despite serving its major purpose, Selenium is also used as a web scraping tool. Without delving into the components of Selenium, we shall focus on a single component that is useful for web scraping, WebDriver. Selenium WebDriver provides us with an ability to control a web browser through a programming interface to create and execute test cases."
},
{
"code": null,
"e": 1080,
"s": 687,
"text": "In our case, we shall be using it for scraping data from websites. Selenium comes in handy when websites display content dynamically i.e. use JavaScripts to render content. Even though Scrapy is a powerful web scraping framework, it becomes useless with these dynamic websites. My goal for this tutorial is to make you familiarize with Selenium and carry out some basic web scraping using it."
},
{
"code": null,
"e": 1343,
"s": 1080,
"text": "Let us start by installing selenium and a webdriver. WebDrivers support 7 Programming Languages: Python, Java, C#, Ruby, PHP, .Net and Perl. The examples in this manual are with Python language. There are tutorials available on the internet with other languages."
},
{
"code": null,
"e": 1469,
"s": 1343,
"text": "This is the third part of a 4 part tutorial series on web scraping using Scrapy and Selenium. The other parts can be found at"
},
{
"code": null,
"e": 1529,
"s": 1469,
"text": "Part 1: Web scraping with Scrapy: Theoretical Understanding"
},
{
"code": null,
"e": 1587,
"s": 1529,
"text": "Part 2: Web scraping with Scrapy: Practical Understanding"
},
{
"code": null,
"e": 1631,
"s": 1587,
"text": "Part 4: Web scraping with Selenium & Scrapy"
},
{
"code": null,
"e": 1772,
"s": 1631,
"text": "Installing Selenium on any Linux OS is easy. Just execute the following command in a terminal and Selenium would be installed automatically."
},
{
"code": null,
"e": 1793,
"s": 1772,
"text": "pip install selenium"
},
{
"code": null,
"e": 1959,
"s": 1793,
"text": "Selenium officially has WebDrivers for 5 Web Browsers. Here, we shall see the installation of WebDriver for two of the most widely used browsers: Chrome and Firefox."
},
{
"code": null,
"e": 2148,
"s": 1959,
"text": "First, we need to download the latest stable version of chromedriver from Chrome’s official site. It would be a zip file. All we need to do is extract it and put it in the executable path."
},
{
"code": null,
"e": 2301,
"s": 2148,
"text": "wget https://chromedriver.storage.googleapis.com/83.0.4103.39/chromedriver_linux64.zipunzip chromedriver_linux64.zipsudo mv chromedriver /usr/local/bin/"
},
{
"code": null,
"e": 2520,
"s": 2301,
"text": "Installing geckodriver for Firefox is even simpler since it is maintained by Firefox itself. All we need to do is execute the following line in a terminal and you are ready to play around with selenium and geckodriver."
},
{
"code": null,
"e": 2557,
"s": 2520,
"text": "sudo apt install firefox-geckodriver"
},
{
"code": null,
"e": 3023,
"s": 2557,
"text": "There are two examples with increasing levels of complexity. First one would be a simpler webpage opening and typing into textboxes and pressing key(s). This example is to showcase how a webpage can be controlled through Selenium using a program. The second one would be a more complex web scraping example involving mouse scrolling, mouse button clicks and navigating to other pages. The goal here is to make you feel confident to start web scraping with Selenium."
},
{
"code": null,
"e": 3516,
"s": 3023,
"text": "Let us try out a simple automation task using Selenium and chromedriver as our training wheel exercise. For this, we would try to log into a Facebook account and we are not performing any kind of data scraping. I am assuming that you have some knowledge of identifying HTML tags used in a webpage using the browser’s developer tools. The following is a piece of python code that opens up a new Chrome browser, opens the Facebook main page, enters a username, password and clicks Login button."
},
{
"code": null,
"e": 4161,
"s": 3516,
"text": "from selenium import webdriverfrom selenium.webdriver.common.keys import Keysuser_name = \"Your E-mail\"password = \"Your Password\"# Creating a chromedriver instancedriver = webdriver.Chrome() # For Chrome# driver = webdriver.Firefox() # For Firefox# Opening facebook homepagedriver.get(\"https://www.facebook.com\")# Identifying email and password textboxesemail = driver.find_element_by_id(\"email\")passwd = driver.find_element_by_id(\"pass\")# Sending user_name and password to corresponding textboxesemail.send_keys(user_name)passwd.send_keys(password)# Sending a signal that RETURN key has been pressedpasswd.send_keys(Keys.RETURN)# driver.quit()"
},
{
"code": null,
"e": 4302,
"s": 4161,
"text": "After executing this python code, your Facebook homepage would open in a new Chrome browser window. Let us examine how this became possible."
},
{
"code": null,
"e": 5013,
"s": 4302,
"text": "It all starts with the creation of a webdriver instance for your browser. As I am using Chrome, I have used driver = webdriver.Chrome().Then we open the Facebook webpage using driver.get(\"https://www.facebook.com\"). When python encounters driver.get(URL), it opens a new browser window and opens the webpage specified by the URL.Once the homepage is loaded, we identify the textboxes to type e-mail and password using their HTML tag’s id attribute. This is done using driver.find_element_by_id().We send the username and password values for logging into Facebook using send_keys().We then simulate the user’s action of pressing RETURN/ENTER key by sending its corresponding signal using send_keys(Keys.RETURN)."
},
{
"code": null,
"e": 5150,
"s": 5013,
"text": "It all starts with the creation of a webdriver instance for your browser. As I am using Chrome, I have used driver = webdriver.Chrome()."
},
{
"code": null,
"e": 5344,
"s": 5150,
"text": "Then we open the Facebook webpage using driver.get(\"https://www.facebook.com\"). When python encounters driver.get(URL), it opens a new browser window and opens the webpage specified by the URL."
},
{
"code": null,
"e": 5512,
"s": 5344,
"text": "Once the homepage is loaded, we identify the textboxes to type e-mail and password using their HTML tag’s id attribute. This is done using driver.find_element_by_id()."
},
{
"code": null,
"e": 5598,
"s": 5512,
"text": "We send the username and password values for logging into Facebook using send_keys()."
},
{
"code": null,
"e": 5728,
"s": 5598,
"text": "We then simulate the user’s action of pressing RETURN/ENTER key by sending its corresponding signal using send_keys(Keys.RETURN)."
},
{
"code": null,
"e": 6301,
"s": 5728,
"text": "IMPORTANT NOTE:Any instance created in a program should be closed at the end of the program or after its purpose is served. So, whenever we are creating a webdriver instance, it has to be terminated using driver.quit(). If we do not terminate the opened instances, it starts to use up RAM, which may impact the machine's performance and slow it down. In the above example, this termination process has been commented out to show the output in a browser window. And, if terminated, the browser window would also be closed and the reader would not be able to see the output."
},
{
"code": null,
"e": 6503,
"s": 6301,
"text": "This is a more complex example. OpenAQ is a non-profit organization that collects and shares air quality data that are open and can be accessed in many ways. This is evident from the site’s robots.txt."
},
{
"code": null,
"e": 6527,
"s": 6503,
"text": "User-agent: * Disallow:"
},
{
"code": null,
"e": 6856,
"s": 6527,
"text": "Our goal here is to collect data on PM2.5 readings from all the countries listed on http://openaq.org. PM2.5 are the particulate matter (PM) that have a diameter lesser than 2.5 micrometres, which is way smaller than the diameter of a human hair. If the reader is interested in knowing more about PM2.5, please follow this link."
},
{
"code": null,
"e": 7176,
"s": 6856,
"text": "The reason for choosing Selenium over Scrapy is that http://openaq.org uses React JS to render data. If it were static webpages, Scrapy would scrape the data efficiently. To scrape data, we first need to analyze the website, manually navigate the pages and note down the user interaction steps required to extract data."
},
{
"code": null,
"e": 7362,
"s": 7176,
"text": "It is always better to scrape with as few webpage navigations as possible. The website has a webpage https://openaq.org/#/locations which could be used as a starting point for scraping."
},
{
"code": null,
"e": 7578,
"s": 7362,
"text": "The filter locations option on the left-side panel is used to filter out PM2.5 data for each country. The Results on the right-side panel show cards that open a new page when clicked to display PM2.5 and other data."
},
{
"code": null,
"e": 7759,
"s": 7578,
"text": "A sample page containing PM2.5 data is shown below. From this page, we can extract PM2.5 values, location, city, country, date and time of recording PM2.5 value using XPATH or CSS."
},
{
"code": null,
"e": 7957,
"s": 7759,
"text": "Similarly, the left-side panel can be used to filter out and collect URLs of all the locations that contain PM2.5 data. The following are the actions that we performed manually to collect the data."
},
{
"code": null,
"e": 8299,
"s": 7957,
"text": "Open https://openaq.org/#/locationsFrom the left-side panel, select/click checkbox of a country. Let us go through the countries alphabetically.Also, from the left-side panel, select/click checkbox PM2.5.Wait for the cards to load in the right-side panel. Each card would then open a new webpage when clicked to display PM2.5 and other data."
},
{
"code": null,
"e": 8335,
"s": 8299,
"text": "Open https://openaq.org/#/locations"
},
{
"code": null,
"e": 8445,
"s": 8335,
"text": "From the left-side panel, select/click checkbox of a country. Let us go through the countries alphabetically."
},
{
"code": null,
"e": 8506,
"s": 8445,
"text": "Also, from the left-side panel, select/click checkbox PM2.5."
},
{
"code": null,
"e": 8644,
"s": 8506,
"text": "Wait for the cards to load in the right-side panel. Each card would then open a new webpage when clicked to display PM2.5 and other data."
},
{
"code": null,
"e": 8747,
"s": 8644,
"text": "Based on the manual steps performed, data collection from http://openaq.org is broken down to 3 steps."
},
{
"code": null,
"e": 9191,
"s": 8747,
"text": "Collecting country names as displayed on OpenAQ countries webpage. This would be used in selecting appropriate checkboxes while filtering.Collecting URLs that contain PM2.5 data from each country. Some countries contain more than 20 PM2.5 readings collected from various locations. It would require further manipulation of the webpage, which is explained in the code section.Opening up webpages of the individual URL and extracting PM2.5 data."
},
{
"code": null,
"e": 9330,
"s": 9191,
"text": "Collecting country names as displayed on OpenAQ countries webpage. This would be used in selecting appropriate checkboxes while filtering."
},
{
"code": null,
"e": 9568,
"s": 9330,
"text": "Collecting URLs that contain PM2.5 data from each country. Some countries contain more than 20 PM2.5 readings collected from various locations. It would require further manipulation of the webpage, which is explained in the code section."
},
{
"code": null,
"e": 9637,
"s": 9568,
"text": "Opening up webpages of the individual URL and extracting PM2.5 data."
},
{
"code": null,
"e": 9876,
"s": 9637,
"text": "Now that we have the steps needed, let us start to code. The example is divided into 3 functions, each performing the task corresponding to the aforementioned 3 steps. The python code for this example can be found in my GitHub repository."
},
{
"code": null,
"e": 10064,
"s": 9876,
"text": "Instead of using OpenAQ locations webpage, there is https://openaq.org/#/countries webpage, which displays all the countries at once. It is easier to extract country names from this page."
},
{
"code": null,
"e": 11178,
"s": 10064,
"text": "from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECimport jsondef get_countries():countries_list = []# driver = webdriver.Chrome() # To open a new browser window and navigate it# Use the headless option to avoid opening a new browser window options = webdriver.ChromeOptions() options.add_argument(\"headless\") desired_capabilities = options.to_capabilities() driver = webdriver.Chrome(desired_capabilities=desired_capabilities)# Getting webpage with the list of countriesdriver.get(\"https://openaq.org/#/countries\")# Implicit wait driver.implicitly_wait(10)# Explicit wait wait = WebDriverWait(driver, 5) wait.until(EC.presence_of_element_located((By.CLASS_NAME, \"card__title\"))) countries = driver.find_elements_by_class_name(\"card__title\") for country in countries: countries_list.append(country.text)driver.quit()# Write countries_list to json file with open(\"countries_list.json\", \"w\") as f: json.dump(countries_list, f)"
},
{
"code": null,
"e": 11581,
"s": 11178,
"text": "Let us understand how the code works. As always, the first step is to instantiate the webdriver. Here, instead of opening a new browser window, the webdriver is instantiated as a headless one. This way, a new browser window will not be opened and the burden on RAM would be reduced. The second step is to open the webpage containing the list of countries. The concept of wait is used in the above code."
},
{
"code": null,
"e": 11787,
"s": 11581,
"text": "Implicit Wait: When created, is alive until the WebDriver object dies. And is common for all operations. It instructs the webdriver to wait for a certain amount of time before elements load on the webpage."
},
{
"code": null,
"e": 11968,
"s": 11787,
"text": "Explicit Wait: Intelligent waits that are confined to a particular web element, in this case, tag with class name “card__title”. It is generally used along with ExpectedConditions."
},
{
"code": null,
"e": 12168,
"s": 11968,
"text": "The third step is to extract the country names using the tag with class name “card__title”. Finally, the country names are written to a JSON file for persistence. Below is a glimpse of the JSON file."
},
{
"code": null,
"e": 12254,
"s": 12168,
"text": "countries_list.json[\"Afghanistan\", \"Algeria\", \"Andorra\", \"Antigua and Barbuda\", ... ]"
},
{
"code": null,
"e": 13212,
"s": 12254,
"text": "The next step after getting the list of countries is to get the URLs of every location that records PM2.5 data. To do this, we need to open the OpenAQ locations webpage and make use of the left-side panel to filter out countries and PM2.5 data. Once it is filtered, the right-side panel would be populated with cards to individual locations that record PM2.5 data. We extract the URLs corresponding to each of these cards and eventually write them to a file that would be used in the next step of extracting PM2.5 data. Some countries have more than 20 locations that record PM2.5 data. For example, Australia has 162 locations, Belgium has 69 locations, China has 1602 locations. For these countries, the right-side panel on locations webpage is subdivided into pages. It is highly imperative that we navigate through these pages and collect URLs of all the locations. The code below has a while TRUE: loop that performs this exact task of page navigation."
},
{
"code": null,
"e": 15676,
"s": 13212,
"text": "from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.common.action_chains import ActionChainsfrom logzero import loggerimport selenium.common.exceptions as exceptionimport timeimport jsondef get_urls():# Load the countries list written by get_countries() with open(\"countries_list.json\", \"r\") as f: countries_list = json.load(f) # driver = webdriver.Chrome() # Use headless option to not open a new browser window options = webdriver.ChromeOptions() options.add_argument(\"headless\") desired_capabilities = options.to_capabilities() driver = webdriver.Chrome(desired_capabilities=desired_capabilities)urls_final = [] for country in countries_list:# Opening locations webpage driver.get(\"https://openaq.org/#/locations\") driver.implicitly_wait(5) urls = []# Scrolling down the country filter till the country is visible action = ActionChains(driver) action.move_to_element(driver.find_element_by_xpath(\"//span[contains(text(),\" + '\"' + country + '\"' + \")]\")) action.perform()# Identifying country and PM2.5 checkboxes country_button = driver.find_element_by_xpath(\"//label[contains(@for,\" + '\"' + country + '\"' + \")]\") values_button = driver.find_element_by_xpath(\"//span[contains(text(),'PM2.5')]\") # Clicking the checkboxes country_button.click() time.sleep(2) values_button.click() time.sleep(2)while True: # Navigating subpages where there are more PM2.5 data. For example, Australia has 162 PM2.5 readings from 162 different locations that are spread across 11 subpages.locations = driver.find_elements_by_xpath(\"//h1[@class='card__title']/a\")for loc in locations: link = loc.get_attribute(\"href\") urls.append(link)try: next_button = driver.find_element_by_xpath(\"//li[@class='next']\") next_button.click() except exception.NoSuchElementException: logger.debug(f\"Last page reached for {country}\") breaklogger.info(f\"{country} has {len(urls)} PM2.5 URLs\") urls_final.extend(urls)logger.info(f\"Total PM2.5 URLs: {len(urls_final)}\") driver.quit()# Write the URLs to a file with open(\"urls.json\", \"w\") as f: json.dump(urls_final, f)"
},
{
"code": null,
"e": 15888,
"s": 15676,
"text": "It is always a good practice to log the output of programs that tend to run longer than 5 minutes. For this purpose, the above code makes use of logzero. The output JSON file containing the URLs looks like this."
},
{
"code": null,
"e": 16091,
"s": 15888,
"text": "urls.json[ \"https://openaq.org/#/location/US%20Diplomatic%20Post%3A%20Kabul\", \"https://openaq.org/#/location/Kabul\", \"https://openaq.org/#/location/US%20Diplomatic%20Post%3A%20Algiers\", ...]"
},
{
"code": null,
"e": 16701,
"s": 16091,
"text": "The process of getting PM2.5 data from the individual location is a straight forward web scraping task of identifying the HTML tag containing the data and extracting it with text processing. The same happens in the code provided below. The code extracts the country, city, location, PM2.5 value, URL of the location, date and time of recording PM2.5 value. Since there are over 5000 URLs to be opened, there would be a problem with RAM usage unless the RAM installed is over 64GB. To make this program to run on machines with minimum 8GB of RAM, the webdriver is terminated and re-instantiated every 200 URLs."
},
{
"code": null,
"e": 19376,
"s": 16701,
"text": "from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.common.action_chains import ActionChainsfrom logzero import loggerimport selenium.common.exceptions as exceptionimport timeimport jsondef get_pm_data():# Load the URLs list written by get_urls() with open(\"urls.json\", \"r\") as f: urls = json.load(f)# Use headless option to not open a new browser window options = webdriver.ChromeOptions() options.add_argument(\"headless\") desired_capabilities = options.to_capabilities() driver = webdriver.Chrome(desired_capabilities=desired_capabilities)list_data_dict = [] count = 0for i, url in enumerate(urls): data_dict = {}# Open the webpage corresponding to each URL driver.get(url) driver.implicitly_wait(10) time.sleep(2)try: # Extract Location and City loc = driver.find_element_by_xpath(\"//h1[@class='inpage__title']\").text.split(\"\\n\") logger.info(f\"loc: {loc}\") location = loc[0] city_country = loc[1].replace(\"in \", \"\", 1).split(\",\") city = city_country[0] country = city_country[1] data_dict[\"country\"] = country data_dict[\"city\"] = city data_dict[\"location\"] = locationpm = driver.find_element_by_xpath(\"//dt[text()='PM2.5']/following-sibling::dd[1]\").textif pm is not None: # Extract PM2.5 value, Date and Time of recording split = pm.split(\"μg/m3\") pm = split[0] date_time = split[1].replace(\"at \", \"\").split(\" \") date_pm = date_time[1] time_pm = date_time[2] data_dict[\"pm25\"] = pm data_dict[\"url\"] = url data_dict[\"date\"] = date_pm data_dict[\"time\"] = time_pmlist_data_dict.append(data_dict) count += 1except exception.NoSuchElementException: # Logging the info of locations that do not have PM2.5 data for manual checking logger.error(f\"{location} in {city},{country} does not have PM2.5\")# Terminating and re-instantiating webdriver every 200 URL to reduce the load on RAM if (i != 0) and (i % 200 == 0): driver.quit() driver = webdriver.Chrome(desired_capabilities=desired_capabilities) logger.info(\"Chromedriver restarted\")# Write the extracted data into a JSON file with open(\"openaq_data.json\", \"w\") as f: json.dump(list_data_dict, f)logger.info(f\"Scraped {count} PM2.5 readings.\") driver.quit()"
},
{
"code": null,
"e": 19668,
"s": 19376,
"text": "The outcome of the program looks as shown below. The program has extracted PM2.5 values from 4114 individual locations. Imagine opening these individual webpages and manually extracting the data. It is times like this makes us appreciate the use of web scraping programs or bots, in general."
},
{
"code": null,
"e": 20457,
"s": 19668,
"text": "openaq_data.json[ { \"country\": \" Afghanistan\", \"city\": \"Kabul\", \"location\": \"US Diplomatic Post: Kabul\", \"pm25\": \"33\", \"url\": \"https://openaq.org/#/location/US%20Diplomatic%20Post%3A%20Kabul\", \"date\": \"2020/07/31\", \"time\": \"11:00\" }, { \"country\": \" Algeria\", \"city\": \"Algiers\", \"location\": \"US Diplomatic Post: Algiers\", \"pm25\": \"31\", \"url\": \"https://openaq.org/#/location/US%20Diplomatic%20Post%3A%20Algiers\", \"date\": \"2020/07/31\", \"time\": \"08:30\" }, { \"country\": \" Australia\", \"city\": \"Adelaide\", \"location\": \"CBD\", \"pm25\": \"9\", \"url\": \"https://openaq.org/#/location/CBD\", \"date\": \"2020/07/31\", \"time\": \"11:00\" }, ...]"
},
{
"code": null,
"e": 20693,
"s": 20457,
"text": "I hope this tutorial has given you the confidence to start web scraping with Selenium. The complete code of the example is available in my GitHub repository. In the next tutorial, I shall show you how to integrate Selenium with Scrapy."
}
] |
Python Shallow and Deep Copy operations
|
In Python there is a module called copy. Using this module, we can perform deep copy and shallow copy. In python the assignment statements do not copy the objects. They create a binding between the target and the main object.
To use this module, we should import it using −
import copy
This method is used to create a shallow copy of the object x. For the shallow copy, a reference of an object is copied to another object. So if there is any change on the copied reference, it will change the content of the main object.
This method is used to create a deep copy of the object x. For the deep copy, an individual object is created by taking the data from the main object. So if there is any change on the copied reference, the main object will remain same.
Live Demo
import copy
my_mat = [[11,22,33],[44,55,66],[11,22,33]]
print('Matrix Before Updation: ' + str(my_mat))
new_mat = copy.copy(my_mat) #Make a shallow copy and update on copied object
new_mat[2][0] = 77
new_mat[2][1] = 88
new_mat[2][2] = 99
print('Matrix After Updation: ' + str(my_mat)) #Original Matrix Updated
my_mat = [[11,22,33],[44,55,66],[11,22,33]]
new_mat_deep = copy.deepcopy(new_mat)
print('\nMatrix Before Updation: ' + str(my_mat))
new_mat_deep[2][0] = 77
new_mat_deep[2][1] = 88
new_mat_deep[2][2] = 99
print('Matrix After Updation: ' + str(my_mat)) # Original Matrix unchanged
print('New Matrix: ' + str(new_mat_deep)) # Original Matrix unchanged
Matrix Before Updation: [[11, 22, 33], [44, 55, 66], [11, 22, 33]]
Matrix After Updation: [[11, 22, 33], [44, 55, 66], [77, 88, 99]]
Matrix Before Updation: [[11, 22, 33], [44, 55, 66], [11, 22, 33]]
Matrix After Updation: [[11, 22, 33], [44, 55, 66], [11, 22, 33]]
New Matrix: [[11, 22, 33], [44, 55, 66], [77, 88, 99]]
|
[
{
"code": null,
"e": 1288,
"s": 1062,
"text": "In Python there is a module called copy. Using this module, we can perform deep copy and shallow copy. In python the assignment statements do not copy the objects. They create a binding between the target and the main object."
},
{
"code": null,
"e": 1336,
"s": 1288,
"text": "To use this module, we should import it using −"
},
{
"code": null,
"e": 1349,
"s": 1336,
"text": "import copy\n"
},
{
"code": null,
"e": 1585,
"s": 1349,
"text": "This method is used to create a shallow copy of the object x. For the shallow copy, a reference of an object is copied to another object. So if there is any change on the copied reference, it will change the content of the main object."
},
{
"code": null,
"e": 1821,
"s": 1585,
"text": "This method is used to create a deep copy of the object x. For the deep copy, an individual object is created by taking the data from the main object. So if there is any change on the copied reference, the main object will remain same."
},
{
"code": null,
"e": 1832,
"s": 1821,
"text": " Live Demo"
},
{
"code": null,
"e": 2491,
"s": 1832,
"text": "import copy\nmy_mat = [[11,22,33],[44,55,66],[11,22,33]]\nprint('Matrix Before Updation: ' + str(my_mat))\nnew_mat = copy.copy(my_mat) #Make a shallow copy and update on copied object\nnew_mat[2][0] = 77\nnew_mat[2][1] = 88\nnew_mat[2][2] = 99\nprint('Matrix After Updation: ' + str(my_mat)) #Original Matrix Updated\nmy_mat = [[11,22,33],[44,55,66],[11,22,33]]\nnew_mat_deep = copy.deepcopy(new_mat)\nprint('\\nMatrix Before Updation: ' + str(my_mat))\nnew_mat_deep[2][0] = 77\nnew_mat_deep[2][1] = 88\nnew_mat_deep[2][2] = 99\nprint('Matrix After Updation: ' + str(my_mat)) # Original Matrix unchanged\nprint('New Matrix: ' + str(new_mat_deep)) # Original Matrix unchanged"
},
{
"code": null,
"e": 2814,
"s": 2491,
"text": "Matrix Before Updation: [[11, 22, 33], [44, 55, 66], [11, 22, 33]]\nMatrix After Updation: [[11, 22, 33], [44, 55, 66], [77, 88, 99]]\n\nMatrix Before Updation: [[11, 22, 33], [44, 55, 66], [11, 22, 33]]\nMatrix After Updation: [[11, 22, 33], [44, 55, 66], [11, 22, 33]]\nNew Matrix: [[11, 22, 33], [44, 55, 66], [77, 88, 99]]\n"
}
] |
MariaDB - Drop Database
|
Creation or deletion of databases in MariaDB requires privileges, typically, only given to root users or admins. Under these accounts, you have two options for deleting a database: the mysqladmin binary and a PHP script.
Note that deleted databases are irrecoverable, so exercise care in performing this operation. Furthermore, PHP scripts used for deletion do not prompt you with a confirmation before the deletion.
The following example demonstrates how to use the mysqladmin binary to delete an existing database −
[root@host]# mysqladmin -u root -p drop PRODUCTS
Enter password:******
mysql> DROP PRODUCTS
ERROR 1008 (HY000): Can't drop database 'PRODUCTS'; database doesn't exist
PHP employs the mysql_query function in deleting MariaDB databases. The function uses two parameters, one optional, and returns either a value of “true” when successful, or “false” when not.
Review the following drop database script syntax −
bool mysql_query( sql, connection );
The description of the parameters is given below −
sql
This required parameter consists of the SQL query needed to perform the operation.
connection
When not specified, this optional parameter uses the most recent connection used.
Try the following example code for deleting a database −
<html>
<head>
<title>Delete a MariaDB Database</title>
</head>
<body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$sql = 'DROP DATABASE PRODUCTS';
$retval = mysql_query( $sql, $conn );
if(! $retval ){
die('Could not delete database: ' . mysql_error());
}
echo "Database PRODUCTS deleted successfully\n";
mysql_close($conn);
?>
</body>
</html>
On successful deletion, you will see the following output −
mysql> Database PRODUCTS deleted successfully
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2583,
"s": 2362,
"text": "Creation or deletion of databases in MariaDB requires privileges, typically, only given to root users or admins. Under these accounts, you have two options for deleting a database: the mysqladmin binary and a PHP script."
},
{
"code": null,
"e": 2779,
"s": 2583,
"text": "Note that deleted databases are irrecoverable, so exercise care in performing this operation. Furthermore, PHP scripts used for deletion do not prompt you with a confirmation before the deletion."
},
{
"code": null,
"e": 2880,
"s": 2779,
"text": "The following example demonstrates how to use the mysqladmin binary to delete an existing database −"
},
{
"code": null,
"e": 3048,
"s": 2880,
"text": "[root@host]# mysqladmin -u root -p drop PRODUCTS\nEnter password:******\nmysql> DROP PRODUCTS\nERROR 1008 (HY000): Can't drop database 'PRODUCTS'; database doesn't exist\n"
},
{
"code": null,
"e": 3239,
"s": 3048,
"text": "PHP employs the mysql_query function in deleting MariaDB databases. The function uses two parameters, one optional, and returns either a value of “true” when successful, or “false” when not."
},
{
"code": null,
"e": 3290,
"s": 3239,
"text": "Review the following drop database script syntax −"
},
{
"code": null,
"e": 3328,
"s": 3290,
"text": "bool mysql_query( sql, connection );\n"
},
{
"code": null,
"e": 3379,
"s": 3328,
"text": "The description of the parameters is given below −"
},
{
"code": null,
"e": 3383,
"s": 3379,
"text": "sql"
},
{
"code": null,
"e": 3466,
"s": 3383,
"text": "This required parameter consists of the SQL query needed to perform the operation."
},
{
"code": null,
"e": 3477,
"s": 3466,
"text": "connection"
},
{
"code": null,
"e": 3559,
"s": 3477,
"text": "When not specified, this optional parameter uses the most recent connection used."
},
{
"code": null,
"e": 3616,
"s": 3559,
"text": "Try the following example code for deleting a database −"
},
{
"code": null,
"e": 4341,
"s": 3616,
"text": "<html>\n <head>\n <title>Delete a MariaDB Database</title>\n </head>\n\n <body>\n <?php\n $dbhost = 'localhost:3036';\n $dbuser = 'root';\n $dbpass = 'rootpassword';\n $conn = mysql_connect($dbhost, $dbuser, $dbpass);\n \n if(! $conn ) {\n die('Could not connect: ' . mysql_error());\n }\n echo 'Connected successfully<br />';\n \n $sql = 'DROP DATABASE PRODUCTS';\n $retval = mysql_query( $sql, $conn );\n \n if(! $retval ){\n die('Could not delete database: ' . mysql_error());\n }\n\n echo \"Database PRODUCTS deleted successfully\\n\";\n mysql_close($conn);\n ?>\n </body>\n</html>"
},
{
"code": null,
"e": 4401,
"s": 4341,
"text": "On successful deletion, you will see the following output −"
},
{
"code": null,
"e": 4449,
"s": 4401,
"text": "mysql> Database PRODUCTS deleted successfully \n"
},
{
"code": null,
"e": 4456,
"s": 4449,
"text": " Print"
},
{
"code": null,
"e": 4467,
"s": 4456,
"text": " Add Notes"
}
] |
How to Create a Checkmark / Tick with CSS
|
We can create a customized checkmark using CSS. The following examples illustrate this effect −
Live Demo
<!DOCTYPE html>
<html>
<style>
div {
margin: 2%;
position: relative;
width: 40px;
height: 40px;
box-shadow: inset 0 0 12px lightblue;
}
div::before {
content: "";
position: absolute;
width: 8px;
top: 50%;
height: 50%;
border-radius: 2px;
background-color: rgb(123,45,20);
transform: translateX(12px) rotate(-45deg);
transform-origin: left bottom;
z-index: +1;
}
div::after {
content: "";
position: absolute;
bottom: 0;
height: 8px;
width: 100%;
border-radius: 2px;
background-color: rgb(200,52,120);
transform: translateX(12px) rotate(-45deg);
transform-origin: left bottom;
}
</style>
<body>
Custom mark!
<div></div>
</body>
</html>
This will produce the following result −
Live Demo
<!DOCTYPE html>
<html>
<style>
body {
padding: 2%;
text-align: center;
}
div {
display: inline-block;
height: 100px;
width: 35px;
border-bottom: 10px solid chartreuse;
border-right: 10px solid chartreuse;
transform: rotate(45deg);
}
</style>
<body>
<div></div>
</body>
</html>
This will produce the following result −
|
[
{
"code": null,
"e": 1158,
"s": 1062,
"text": "We can create a customized checkmark using CSS. The following examples illustrate this effect −"
},
{
"code": null,
"e": 1169,
"s": 1158,
"text": " Live Demo"
},
{
"code": null,
"e": 1875,
"s": 1169,
"text": "<!DOCTYPE html>\n<html>\n<style>\ndiv {\n margin: 2%;\n position: relative;\n width: 40px;\n height: 40px;\n box-shadow: inset 0 0 12px lightblue;\n}\ndiv::before {\n content: \"\";\n position: absolute;\n width: 8px;\n top: 50%;\n height: 50%;\n border-radius: 2px;\n background-color: rgb(123,45,20);\n transform: translateX(12px) rotate(-45deg);\n transform-origin: left bottom;\n z-index: +1;\n}\ndiv::after {\n content: \"\";\n position: absolute;\n bottom: 0;\n height: 8px;\n width: 100%;\n border-radius: 2px;\n background-color: rgb(200,52,120);\n transform: translateX(12px) rotate(-45deg);\n transform-origin: left bottom;\n}\n</style>\n<body>\nCustom mark!\n<div></div>\n</body>\n</html>"
},
{
"code": null,
"e": 1916,
"s": 1875,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 1927,
"s": 1916,
"text": " Live Demo"
},
{
"code": null,
"e": 2228,
"s": 1927,
"text": "<!DOCTYPE html>\n<html>\n<style>\nbody {\n padding: 2%;\n text-align: center;\n}\ndiv {\n display: inline-block;\n height: 100px;\n width: 35px;\n border-bottom: 10px solid chartreuse;\n border-right: 10px solid chartreuse;\n transform: rotate(45deg);\n}\n</style>\n<body>\n<div></div>\n</body>\n</html>"
},
{
"code": null,
"e": 2269,
"s": 2228,
"text": "This will produce the following result −"
}
] |
io.LimitReader() Function in Golang with Examples - GeeksforGeeks
|
03 May, 2020
In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The LimitReader() function in Go language is used to return a “Reader” that reads from the stated “r” but it pauses if the EOF i.e, end of file is reached after reading the stated “n” number of bytes. Moreover, this function is defined under the io package. Here, you need to import the “io” package in order to use these functions.
Syntax:
func LimitReader(r Reader, n int64) Reader
Here, “r” is the stated Reader, and “n” is the number of bytes.
Return value: It returns a Reader that reads from the stated “r”.
Below examples illustrates the use of above method:
Example 1:
// Golang program to illustrate the usage of// io.LimitReader() function // Including main packagepackage main // Importing fmt, io, strings, and osimport ( "fmt" "io" "os" "strings") // Calling mainfunc main() { // Defining r using NewReader r := strings.NewReader("Geeks\n") // Calling LimitReader method with its parameters res := io.LimitReader(r, 3) // Calling Copy method with its parameters op, err := io.Copy(os.Stdout, res) // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf("\nn: %v\n", op)}
Output:
Gee
n: 3
In the above example, the Copy() method is used in order to return the “Reader” and NewReader() method of strings is used from where the content to be read is written.
Example 2:
// Golang program to illustrate the usage of// io.LimitReader() function // Including main packagepackage main // Importing fmt, io, strings, and osimport ( "fmt" "io" "os" "strings") // Calling mainfunc main() { // Defining r using NewReader r := strings.NewReader("GfG\nis\na\nCS-Portal.\n") // Calling LimitReader method with its parameters res := io.LimitReader(r, 8) // Calling Copy method with its parameters op, err := io.Copy(os.Stdout, res) // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf("\nn: %v\n", op)}
Output:
GfG
is
a
n: 8
Golang-io
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Check if the String ends with specified suffix in Golang
Rune in Golang
Anonymous function in Go Language
How to Parse JSON in Golang?
Class and Object in Golang
Loops in Go Language
Methods in Golang
Structures in Golang
Golang program that uses structs as map keys
fmt.print() Function in Golang With Examples
|
[
{
"code": null,
"e": 24069,
"s": 24041,
"text": "\n03 May, 2020"
},
{
"code": null,
"e": 24575,
"s": 24069,
"text": "In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The LimitReader() function in Go language is used to return a “Reader” that reads from the stated “r” but it pauses if the EOF i.e, end of file is reached after reading the stated “n” number of bytes. Moreover, this function is defined under the io package. Here, you need to import the “io” package in order to use these functions."
},
{
"code": null,
"e": 24583,
"s": 24575,
"text": "Syntax:"
},
{
"code": null,
"e": 24627,
"s": 24583,
"text": "func LimitReader(r Reader, n int64) Reader\n"
},
{
"code": null,
"e": 24691,
"s": 24627,
"text": "Here, “r” is the stated Reader, and “n” is the number of bytes."
},
{
"code": null,
"e": 24757,
"s": 24691,
"text": "Return value: It returns a Reader that reads from the stated “r”."
},
{
"code": null,
"e": 24809,
"s": 24757,
"text": "Below examples illustrates the use of above method:"
},
{
"code": null,
"e": 24820,
"s": 24809,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate the usage of// io.LimitReader() function // Including main packagepackage main // Importing fmt, io, strings, and osimport ( \"fmt\" \"io\" \"os\" \"strings\") // Calling mainfunc main() { // Defining r using NewReader r := strings.NewReader(\"Geeks\\n\") // Calling LimitReader method with its parameters res := io.LimitReader(r, 3) // Calling Copy method with its parameters op, err := io.Copy(os.Stdout, res) // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf(\"\\nn: %v\\n\", op)}",
"e": 25428,
"s": 24820,
"text": null
},
{
"code": null,
"e": 25436,
"s": 25428,
"text": "Output:"
},
{
"code": null,
"e": 25446,
"s": 25436,
"text": "Gee\nn: 3\n"
},
{
"code": null,
"e": 25614,
"s": 25446,
"text": "In the above example, the Copy() method is used in order to return the “Reader” and NewReader() method of strings is used from where the content to be read is written."
},
{
"code": null,
"e": 25625,
"s": 25614,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate the usage of// io.LimitReader() function // Including main packagepackage main // Importing fmt, io, strings, and osimport ( \"fmt\" \"io\" \"os\" \"strings\") // Calling mainfunc main() { // Defining r using NewReader r := strings.NewReader(\"GfG\\nis\\na\\nCS-Portal.\\n\") // Calling LimitReader method with its parameters res := io.LimitReader(r, 8) // Calling Copy method with its parameters op, err := io.Copy(os.Stdout, res) // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf(\"\\nn: %v\\n\", op)}",
"e": 26250,
"s": 25625,
"text": null
},
{
"code": null,
"e": 26258,
"s": 26250,
"text": "Output:"
},
{
"code": null,
"e": 26273,
"s": 26258,
"text": "GfG\nis\na\nn: 8\n"
},
{
"code": null,
"e": 26283,
"s": 26273,
"text": "Golang-io"
},
{
"code": null,
"e": 26295,
"s": 26283,
"text": "Go Language"
},
{
"code": null,
"e": 26393,
"s": 26295,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26402,
"s": 26393,
"text": "Comments"
},
{
"code": null,
"e": 26415,
"s": 26402,
"text": "Old Comments"
},
{
"code": null,
"e": 26472,
"s": 26415,
"text": "Check if the String ends with specified suffix in Golang"
},
{
"code": null,
"e": 26487,
"s": 26472,
"text": "Rune in Golang"
},
{
"code": null,
"e": 26521,
"s": 26487,
"text": "Anonymous function in Go Language"
},
{
"code": null,
"e": 26550,
"s": 26521,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 26577,
"s": 26550,
"text": "Class and Object in Golang"
},
{
"code": null,
"e": 26598,
"s": 26577,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 26616,
"s": 26598,
"text": "Methods in Golang"
},
{
"code": null,
"e": 26637,
"s": 26616,
"text": "Structures in Golang"
},
{
"code": null,
"e": 26682,
"s": 26637,
"text": "Golang program that uses structs as map keys"
}
] |
Chord diagrams of protein interaction networks in Python | by Ford Combs | Towards Data Science
|
Humans are great at interpreting graphic displays of data. We can identify patterns in visual displays quickly and easily as compared to tabular displays. There are many reasons for this, e.g., about 30% of the cortex contains neurons dedicated to visual processing. This is why data visualization is extremely important for both understanding and communicating information. In a previous post, I described how NetworkX can be used to build informative and attractive graphic displays of protein network data. Here, I will show how the same data can be displayed as a Circos-style, chord diagram using nxviz.
Chord diagrams are circular plots that are great for displaying relationships between objects of a set, such as nodes and connections in a network. A basic chord diagram has a ring of objects connected by chords that indicate relationships. In Python, you can create these types of plots with nxviz, a package designed for use with NetworkX graphs. If you want to learn more about NetworkX, check out my previous story. The original Circos software that helped popularize chord diagrams is written in Perl and was introduced in a paper published in 2009. The software is well-documented and there are great tutorials that show you how to build beautiful plots that display multiple layers of information. Currently, nxviz is one of the few Python libraries that can be used to create plots in this style.
### The required libraries and packages ###import networkx as nximport requestsimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt# from matplotlib import cmfrom nxviz.plots import CircosPlot
The network we are going to visualize contains protein interaction data. The following code takes a list of proteins and uses the Python requests library to collect data from the STRING database of protein interactions. You can learn more about this process here, but the end result is a data frame in which each row contains a pair of proteins and the interaction score between them.
The next code chunk can be used to build the graph using NetworkX. The code below is the same as described previously, except for one optional modification: only high scoring interactions are used as weighted edges. This will reduce clutter in the simplified visualization. For the more advanced graph, you can keep all the edges by uncommenting the designated line below and commenting out the last two lines.
Now that the NetworkX graph has been created, a Circos-style plot can be generated very quickly with just three lines of code.
The above plot shows displays important, basic information about the network. For example, it is easy to see which nodes have relatively higher or lower degree. Recall that the degree of a node is the number of edges that connect to it. For example, the node HTR1A has a high degree; it has more connections compared to other proteins in the graph. This suggests that HTR1A is involved in many different processes. MAOA, on the other hand, has a low degree; only one edge connects it to another node. This suggests that it has a more specific role.
The graph above is useful, but more information can be displayed in these types of plots. Nxviz allows for the nodes and edges to be colored and sized based on user-defined characteristics. The code below shows how a nodelist and edgelist can be generated from graph G and used to build a new graph g. This new graph is identical to old graph, except that it has a ["class"] attribute for each node that stores its degree.
The above plot includes both the edge weight and node degree information. Note that the nodes are colored based on their degree. The proteins with the most interactions are pink and purple while the lower degree proteins are red. Also, note that the widths of the edges indicate the score of the interaction; the wider the edge, the higher the score.
This display can be improved further by making two alterations to the code. First, all edges can be kept by uncommenting the designated line in the create_graph_circos gist. Normally, this would result in a lot of clutter, but the widths are adjusted with one more change: the uncommenting of the alternate method in the improved_circos.py gist. This rescales the edge widths more dramatically so that high scoring interactions are much wider than low scoring interactions. Because of this dramatic change in the edge widths, it is possible to display all the edges without the graph becoming crowded and difficult to interpret.
The plots included in this article are effective for the visualization of protein interaction networks. The final plot does a particularly good job of displaying lots of details about the network. The node color helps indicate groups of nodes that have similar degree and the edge widths show which interactions have higher scores. This is useful in the analysis of networks, because high scoring edges likely indicate more tightly linked interactions. And, high scoring interactions linked to nodes of high degree, can indicate particularly important interactions in the network.
The proteins used in this example are related, but they were arbitrarily chosen as a proof of concept. Novel research would require more care in the creation of the protein set and in the design of the edge weights through the utilization of other scores and data. Also, improvements in chord diagram implementations in Python need to be developed. There are currently excellent options for drawing these plots in R. Stay tuned, as I hope to take a stab at a Python version soon.
|
[
{
"code": null,
"e": 781,
"s": 172,
"text": "Humans are great at interpreting graphic displays of data. We can identify patterns in visual displays quickly and easily as compared to tabular displays. There are many reasons for this, e.g., about 30% of the cortex contains neurons dedicated to visual processing. This is why data visualization is extremely important for both understanding and communicating information. In a previous post, I described how NetworkX can be used to build informative and attractive graphic displays of protein network data. Here, I will show how the same data can be displayed as a Circos-style, chord diagram using nxviz."
},
{
"code": null,
"e": 1586,
"s": 781,
"text": "Chord diagrams are circular plots that are great for displaying relationships between objects of a set, such as nodes and connections in a network. A basic chord diagram has a ring of objects connected by chords that indicate relationships. In Python, you can create these types of plots with nxviz, a package designed for use with NetworkX graphs. If you want to learn more about NetworkX, check out my previous story. The original Circos software that helped popularize chord diagrams is written in Perl and was introduced in a paper published in 2009. The software is well-documented and there are great tutorials that show you how to build beautiful plots that display multiple layers of information. Currently, nxviz is one of the few Python libraries that can be used to create plots in this style."
},
{
"code": null,
"e": 1795,
"s": 1586,
"text": "### The required libraries and packages ###import networkx as nximport requestsimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt# from matplotlib import cmfrom nxviz.plots import CircosPlot"
},
{
"code": null,
"e": 2180,
"s": 1795,
"text": "The network we are going to visualize contains protein interaction data. The following code takes a list of proteins and uses the Python requests library to collect data from the STRING database of protein interactions. You can learn more about this process here, but the end result is a data frame in which each row contains a pair of proteins and the interaction score between them."
},
{
"code": null,
"e": 2591,
"s": 2180,
"text": "The next code chunk can be used to build the graph using NetworkX. The code below is the same as described previously, except for one optional modification: only high scoring interactions are used as weighted edges. This will reduce clutter in the simplified visualization. For the more advanced graph, you can keep all the edges by uncommenting the designated line below and commenting out the last two lines."
},
{
"code": null,
"e": 2718,
"s": 2591,
"text": "Now that the NetworkX graph has been created, a Circos-style plot can be generated very quickly with just three lines of code."
},
{
"code": null,
"e": 3267,
"s": 2718,
"text": "The above plot shows displays important, basic information about the network. For example, it is easy to see which nodes have relatively higher or lower degree. Recall that the degree of a node is the number of edges that connect to it. For example, the node HTR1A has a high degree; it has more connections compared to other proteins in the graph. This suggests that HTR1A is involved in many different processes. MAOA, on the other hand, has a low degree; only one edge connects it to another node. This suggests that it has a more specific role."
},
{
"code": null,
"e": 3690,
"s": 3267,
"text": "The graph above is useful, but more information can be displayed in these types of plots. Nxviz allows for the nodes and edges to be colored and sized based on user-defined characteristics. The code below shows how a nodelist and edgelist can be generated from graph G and used to build a new graph g. This new graph is identical to old graph, except that it has a [\"class\"] attribute for each node that stores its degree."
},
{
"code": null,
"e": 4041,
"s": 3690,
"text": "The above plot includes both the edge weight and node degree information. Note that the nodes are colored based on their degree. The proteins with the most interactions are pink and purple while the lower degree proteins are red. Also, note that the widths of the edges indicate the score of the interaction; the wider the edge, the higher the score."
},
{
"code": null,
"e": 4670,
"s": 4041,
"text": "This display can be improved further by making two alterations to the code. First, all edges can be kept by uncommenting the designated line in the create_graph_circos gist. Normally, this would result in a lot of clutter, but the widths are adjusted with one more change: the uncommenting of the alternate method in the improved_circos.py gist. This rescales the edge widths more dramatically so that high scoring interactions are much wider than low scoring interactions. Because of this dramatic change in the edge widths, it is possible to display all the edges without the graph becoming crowded and difficult to interpret."
},
{
"code": null,
"e": 5251,
"s": 4670,
"text": "The plots included in this article are effective for the visualization of protein interaction networks. The final plot does a particularly good job of displaying lots of details about the network. The node color helps indicate groups of nodes that have similar degree and the edge widths show which interactions have higher scores. This is useful in the analysis of networks, because high scoring edges likely indicate more tightly linked interactions. And, high scoring interactions linked to nodes of high degree, can indicate particularly important interactions in the network."
}
] |
Display dates after NOW() + 10 days from a MySQL table?
|
You can use DATE_ADD() function with where clause for this. Let us first create a table −
mysql> create table DemoTable
(
ShippingDate date
);
Query OK, 0 rows affected (0.54 sec)
Note : The current date and time is as follows, we found using NOW() −
mysql> select now();
+-----------------------+
| now() |
+-----------------------+
| 2019-06-04 20 :43 :57 |
+-----------------------+
1 row in set (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('2019-06-16');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('2019-05-31');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('2019-05-24');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('2019-06-24');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+--------------+
| ShippingDate |
+--------------+
| 2019-06-16 |
| 2019-05-31 |
| 2019-05-24 |
| 2019-06-24 |
+--------------+
4 rows in set (0.00 sec)
Following is the query to display dates after NOW() + 10 days −
mysql> select *from DemoTable where ShippingDate > DATE_ADD(now(), INTERVAL 10 DAY);
+--------------+
| ShippingDate |
+--------------+
| 2019-06-16 |
| 2019-06-24 |
+--------------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1152,
"s": 1062,
"text": "You can use DATE_ADD() function with where clause for this. Let us first create a table −"
},
{
"code": null,
"e": 1251,
"s": 1152,
"text": "mysql> create table DemoTable\n (\n ShippingDate date\n );\nQuery OK, 0 rows affected (0.54 sec)"
},
{
"code": null,
"e": 1322,
"s": 1251,
"text": "Note : The current date and time is as follows, we found using NOW() −"
},
{
"code": null,
"e": 1497,
"s": 1322,
"text": "mysql> select now();\n+-----------------------+\n| now() |\n+-----------------------+\n| 2019-06-04 20 :43 :57 |\n+-----------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 1553,
"s": 1497,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1901,
"s": 1553,
"text": "mysql> insert into DemoTable values('2019-06-16');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable values('2019-05-31');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values('2019-05-24');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values('2019-06-24');\nQuery OK, 1 row affected (0.17 sec)"
},
{
"code": null,
"e": 1961,
"s": 1901,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1992,
"s": 1961,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2153,
"s": 1992,
"text": "+--------------+\n| ShippingDate |\n+--------------+\n| 2019-06-16 |\n| 2019-05-31 |\n| 2019-05-24 |\n| 2019-06-24 |\n+--------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2217,
"s": 2153,
"text": "Following is the query to display dates after NOW() + 10 days −"
},
{
"code": null,
"e": 2302,
"s": 2217,
"text": "mysql> select *from DemoTable where ShippingDate > DATE_ADD(now(), INTERVAL 10 DAY);"
},
{
"code": null,
"e": 2429,
"s": 2302,
"text": "+--------------+\n| ShippingDate |\n+--------------+\n| 2019-06-16 |\n| 2019-06-24 |\n+--------------+\n2 rows in set (0.00 sec)"
}
] |
Build A Text Recommendation System with Python | by Betty LD | Towards Data Science
|
Natural Language Processing is one of the most exciting fields of Machine Learning. It enables our computer to understand very dense corpus, analyze them, and provide us the information we are looking for.
In this article, we’ll create a recommendation system that acts like a vertical search engine [3]. It enables to search for documents within a very constrained number of documents that are highly tight with one topic. To leverage the power of NLP, we’ll combine search methodology with semantic similarity.
This article includes the dataset, theory, code, and results for different NLP models.
Machine Learning and Deep Learning are good at providing representation of textual data that captures word and document semantics, allowing a machine to say which words and documents are semantically similar. The use of deep learning enables more relevant results to its end users, increasing user satisfaction and the efficacy of the product. In this article, we’ll work on a solution that is tailored beautifully to your data and can, later on, compare your data with the user query to provide well-ranked results.For most common programming languages, like Python, many open source libraries provide tools to create and train very easily complex machine learning models on your own data. In this article, we’ll see how quick it is to build and train models on your own machine.
Machine Learning and Deep Learning are good at providing representation of textual data that captures word and document semantics, allowing a machine to say which words and documents are semantically similar. The use of deep learning enables more relevant results to its end users, increasing user satisfaction and the efficacy of the product. In this article, we’ll work on a solution that is tailored beautifully to your data and can, later on, compare your data with the user query to provide well-ranked results.
For most common programming languages, like Python, many open source libraries provide tools to create and train very easily complex machine learning models on your own data. In this article, we’ll see how quick it is to build and train models on your own machine.
Imagine you want to watch a movie, but you’ve already watched all the ones on your bucket list. Today you are feeling like watching a movie where a beautiful woman is involved in a crime. The recommendation system we’ll build will match your ideal movie description with a database of movie descriptions and suggest the top three movies that match your description.
This is very simple, to build this pipeline you’ll need:
a dataset that contains the collection of text items you want to recommend.a sentence cleaner algorithma matching algorithm.
a dataset that contains the collection of text items you want to recommend.
a sentence cleaner algorithm
a matching algorithm.
You can access all the code from this article in a jupyter notebook.
For this toy experiment, we use the movie dataset https://www.kaggle.com/rounakbanik/the-movies-dataset.
It contains the metadata of 44, 512 movies released before July 2017. Fortunately, we won’t watch all of them because we will take the one that matches our precise desires.
In our experiment, we’ll use only the table ``movies_metadata.csv`` which contains attributes such as budget, genre, webpage link, original title, description overview, release date, spoken language, IMDb vote average, ....
Our recommendation system will use the movie description overview sentence and apply a machine learning model to represent each sentence as a numerical feature vector. After applying an ML model to each sentence, we can concatenate these feature vectors to create an embed matrix that represents our whole dataset. This matrix is very important, it will be our lookup table for every query we make to the system.
Let’s say we have 100 movie description sentences and our embed vector size is 300, then our embed matrix size will be (100 x 300). When the user inputs a sentence, we embed its query sentence into a 300-dim vector with the same model and we compute the cosine distance between each of the 100 rows and the embed query vector.
Download the .csv file and load it as a data frame in your python script or notebook.
We’ll do basic pre-processing. We want to give a uniform text to the model, so we clean the sentences before embedding them into vectors. It would help the model to focus on the content rather than the formatting to find the relevant patterns in the data.
Let’s review our cleaning methodology below.
remove non-alphanumeric character/ punctuation,
remove the too long and too short sentences,
remove stopwords,
lemmatize,
tokenize
We use regex pattern matching to remove all non-alphabetical-numeric characters from the movie descriptions.
We create our own tokenizer. The tokenizer transforms a string into a list of strings where each element is one word.
word_tokenizer(‘the beautiful tree has lost its leaves’)>>> [‘the’, ‘beautiful’, ‘tree’, ‘has’, ‘lost’, ‘its’, ‘leaves’]
We use a lemmatizer that converts a word into a generic form:
from nltk.stem import WordNetLemmatizerstemmer = WordNetLemmatizer()[stemmer.lemmatize(w) for w in word_tokenize(sentence)]>>> ['the', 'beautiful', 'tree', 'ha', 'lost', 'his', 'leaf']
We remove too short and too long sentences from our dataset, by filtering with MIN_WORDS and MAX_WORDS. We remove common words (STOPWORDS) which won’t help to extract the specificity of a given sentence.
We converted the column “sentence” into two columns:
clean_sentence where the sentence is mainly alphanumerical text.
tok_lem_sentence where the data is lemmatized and tokenized.
Now our dataset is ready to be processed and we can compare different models that offer different compromises:
the baseline/ basic TF-IDF
Word2Vec, a simple feed-forward network
spaCy, very flexible and powerful NLP library
transformers, the state-of-art Deep Learning models.
I introduce below a function that I will use to rank the best recommendation given the cosine distance between vectors.
You can notice in l.11 that we use an average on the distance matrix. The shape of the distance matrix is (number of words in query sentence, number of sentence in our vocabulary). We compute the distance from each word of the query to each sentence of our database and take the average on the whole query. Then we can take the three-sentence with the lowest distance to the query.
A text corpus often contains words that appear often and don’t contain any useful discriminatory information. Tf-idf is designed to down weight these frequently occurring words in the feature vectors. It can be defined as the product of the term frequency (frequency of one word in a given document) and the inverse document frequency (occurrence of this word among all the documents) [1]. Term frequency / Document frequency measures the relevance of a term in a given document. In our case, one document is one sentence.
Once we fit our data on the Tf-idf model, we can generate an embedding 22,180 dimensions vector for each movie description. These features are stored in a feature matrix tfidf_mat where each row is a movie description record embedded into a feature vector.
When we get a query from user input, we’ll embed it into the same vector space and we’ll compare one by one the query sentence feature embed_query to the sentence vectors of embed matrix tfidf_mat.
The function that finds the best index from the distance matrix takes the average of the cosine distance for each embedded sentence and ranks the results. Don’t pay attention yet to the masking argument, we will use it for another model.
This model is very simple to use and can be set up with only a handful of lines of code, the training is very fast as well.
On the query sentence: ‘a crime story with a beautiful woman’,
- A beautiful vampire turns a crime lord into a creature of the night. Innocent Blood
- A vampire lures beautiful young women to his castle in Europe. Requiem pour un vampire
- The story of a young woman clinging on to her dream to become a beauty contest queen in a Mexico dominated by organized crime. Miss Bala.
Word2Vec is a powerful and efficient algorithm that can capture the semantics of the word in your corpus. Word2vec takes during training a corpus containing many documents/sentences and outputs a series of vectors one for each word in the text. a word vector contains the semantic meaning of this word, meaning that two that are close in the vector space share a similar meaning. King and queen are close like cake and coffee are. Word2Vec can be easily used to find synonyms for example. During the training, each word vector is weighted by the neural network according to the probability of occurrence inferred from the training dataset. How this probability is computed depends on the architecture you chose (Continuous Bag Of Words or skip-gram). In the end, the word2vec model is in fact a very simple 2 layers neural network, but we won’t care about the output, we’ll extract the hidden state where the information is encoded [3]. The advantage of word2vec is that it takes a high dimensional sparse word representation (like tf-idf or hot encoded vectors) and maps it into a dense representation, hopefully in a smaller dimension.
We use the gensim library to train a word2vec model on our corpus data. We first need to provide the vocabulary (the list of the words we want to vectorize) and then train the model on few epoch. By default, the model trains a CBOW.
The main downside of Word2Vec is that it can’t produce vectors for words that were not originally in the vocabulary used training. This is why we need to provide a utils function is_word_in_model that removes the words from the query sentence that are unseen in the training set.
We use their library function n_similarity to compute efficiently the distance between the query and dataset sentences.
- A tragic love story set in contemporary Shanghai. The film stars Zhou Xun in a dual role as two different women and Jia Hongsheng as a man obsessed with finding a woman from his past. 苏州河
- A glowing orb terrorizes a young girl with a collection of stories of dark fantasy, eroticism and horror. Heavy Metal.
- Fritz Lang’s psycho thriller tells the story of a woman who marries a stranger with a deadly hobby and through their love he attempts to fight off his obsessive-compulsive actions. Secret Beyond the Door
spaCy is a python open-source library contains many pre-computed models for a variety of languages (see the list of 64+ language here). Because we need to load the vector associated with each word, we use a trained pipeline for which we have access to the feature vectors, the en_core_web_lg. They called their NN Tok2Vec and we can use pre-trained weights that contain 685k keys as 685k unique vectors of dimension 300 trained on webpages corpus. SpaCy has their own Deep Learning library and models. You can read more about their default CNN+HashEmbedding model here. Their pipeline includes tokenizer, lemmatizer, and word-level vectorization so we only need to provide the sentences as strings.
We use a mask l.12 in case the word did not have a word in the pretrained corpus.
Even if spaCy is expected to be more powerful than TF-IDF, for this sentence, it gives the same results as TF-IDF.
If we want a robust and accurate method, we can use Deep Learning. Fortunately, many libraries have released their own pretrained weights and we don’t need to spend months to train a very deep model on the whole internet.
We’ll use BERT architecture. The cost is higher than previous models but the understanding of the context is more acute too.
SentenceTransformers’ team developed their own high-level pipeline to facilitate the use of transformers in Python. You can explore their list of models and recommendations here. I personally chose paraphrase-MiniLM-L6-v2 that satisfies “a quick model with high quality”.
- The story of a young woman clinging on to her dream to become a beauty contest queen in a Mexico dominated by organized crime. Miss Bala.
- Following the gruesome murder of a young woman in her neighborhood, a self-determined woman living in New York City--as if to test the limits of her own safety--propels herself into an impossibly risky sexual liaison. Soon she grows increasingly wary about the motives of every man with whom she has contact--and about her own. In the Cut.
- Story of the love between a struggling American artist and a beautiful Chinese prostitute in Hong Kong. The World of Suzie Wong
We can see the improvement in the results compared with previous models.
SentenceTransformer uses HuggingFace architecture in the backend. HuggingFace leads the research as an open-source provider of NLP technologies. They expose models, datasets, and code bases for free. Anyone can train their model and push the result to their database.
We’ll use tokenizer (AutoTokenizer) and model (AutoModel) that are retrievable for the sentence-transformer/paraphrase-MiniLM-L6-v2.
We can choose to train on CPU or GPU and we use fit_transform to generate our embed matrix using a batch of data not to overload the memory. Again in the transform method, we use mean_pooling function to infer a vector for each word and average them for each sentence. This pooling is more complex than previously because the attention mechanism in BERT uses masks and we apply them to the result before averaging.
The code is slightly longer than when we use SentenceTransformer but we have more flexibility too. The inferring method we need to design ourselves is also more transparent
Training takes time so if you have access to a GPU, use it to speed up your training. For this dataset, training took 12min on CPU for 20,000 sentence rows on my 16Gb 8 CPUs local computer, while training took only 6min when I use my local GPU (GeForce MX150) with the same training configuration.
QUERY: ‘A dog is playing with his friends’
BERT MODEL: ‘The story of a man who rescues a German shepherd and how the two become fast friends.’ [My Dog Tulip]
QUERY: ‘a heroe movie in europe’
BERT MODEL: ‘A cop in a dystopian Europe investigates a serial killings suspect using controversial methods written by his now disgraced former mentor.’ [Forbrydelsens element]
(we may conclude that it did not exist in the database)
QUERY: ‘the story of a waitress’’
BERT MODEL: ‘A waitress, desperate to fulfill her dreams as a restaurant owner, is set on a journey to turn a frog prince back into a human being, but she has to do face the same problem after she kisses him.’ [The Princess and the Frog]
Once we loaded and vectorized an initial dataset, we can use a new sentence as a query and retrieve the top-3 closest items from the dataset that match this query sentence.
For that, we have used the simple TF-IDF model that uses the frequency of the words and in the sentence to create vectors. We used the Word2Vec model, a simple neural network. We used spaCy which can process and compute vectors for many different languages with state-of-the-art performance.
Finally, we used transformer models to leverage the latest deep learning method for vectorization. Deep Learning techniques could achieve the best (subjectively) retrieval results but they are slower. Pick the method that fits your trade-off best!
[1] Python Machine Learning, Sebastian Raschka, Packt Edition (https://www.packtpub.com/product/python-machine-learning-third-edition/9781789955750)
[2] http://mccormickml.com/2016/04/19/word2vec-tutorial-the-skip-gram-model/, http://mccormickml.com/assets/word2vec/Alex_Minnaar_Word2Vec_Tutorial_Part_II_The_Continuous_Bag-of-Words_Model.pdf
[3] Deep Learning for Search, Tommaso Teofili, Manning Publications.
|
[
{
"code": null,
"e": 378,
"s": 172,
"text": "Natural Language Processing is one of the most exciting fields of Machine Learning. It enables our computer to understand very dense corpus, analyze them, and provide us the information we are looking for."
},
{
"code": null,
"e": 685,
"s": 378,
"text": "In this article, we’ll create a recommendation system that acts like a vertical search engine [3]. It enables to search for documents within a very constrained number of documents that are highly tight with one topic. To leverage the power of NLP, we’ll combine search methodology with semantic similarity."
},
{
"code": null,
"e": 772,
"s": 685,
"text": "This article includes the dataset, theory, code, and results for different NLP models."
},
{
"code": null,
"e": 1553,
"s": 772,
"text": "Machine Learning and Deep Learning are good at providing representation of textual data that captures word and document semantics, allowing a machine to say which words and documents are semantically similar. The use of deep learning enables more relevant results to its end users, increasing user satisfaction and the efficacy of the product. In this article, we’ll work on a solution that is tailored beautifully to your data and can, later on, compare your data with the user query to provide well-ranked results.For most common programming languages, like Python, many open source libraries provide tools to create and train very easily complex machine learning models on your own data. In this article, we’ll see how quick it is to build and train models on your own machine."
},
{
"code": null,
"e": 2070,
"s": 1553,
"text": "Machine Learning and Deep Learning are good at providing representation of textual data that captures word and document semantics, allowing a machine to say which words and documents are semantically similar. The use of deep learning enables more relevant results to its end users, increasing user satisfaction and the efficacy of the product. In this article, we’ll work on a solution that is tailored beautifully to your data and can, later on, compare your data with the user query to provide well-ranked results."
},
{
"code": null,
"e": 2335,
"s": 2070,
"text": "For most common programming languages, like Python, many open source libraries provide tools to create and train very easily complex machine learning models on your own data. In this article, we’ll see how quick it is to build and train models on your own machine."
},
{
"code": null,
"e": 2701,
"s": 2335,
"text": "Imagine you want to watch a movie, but you’ve already watched all the ones on your bucket list. Today you are feeling like watching a movie where a beautiful woman is involved in a crime. The recommendation system we’ll build will match your ideal movie description with a database of movie descriptions and suggest the top three movies that match your description."
},
{
"code": null,
"e": 2758,
"s": 2701,
"text": "This is very simple, to build this pipeline you’ll need:"
},
{
"code": null,
"e": 2883,
"s": 2758,
"text": "a dataset that contains the collection of text items you want to recommend.a sentence cleaner algorithma matching algorithm."
},
{
"code": null,
"e": 2959,
"s": 2883,
"text": "a dataset that contains the collection of text items you want to recommend."
},
{
"code": null,
"e": 2988,
"s": 2959,
"text": "a sentence cleaner algorithm"
},
{
"code": null,
"e": 3010,
"s": 2988,
"text": "a matching algorithm."
},
{
"code": null,
"e": 3079,
"s": 3010,
"text": "You can access all the code from this article in a jupyter notebook."
},
{
"code": null,
"e": 3184,
"s": 3079,
"text": "For this toy experiment, we use the movie dataset https://www.kaggle.com/rounakbanik/the-movies-dataset."
},
{
"code": null,
"e": 3357,
"s": 3184,
"text": "It contains the metadata of 44, 512 movies released before July 2017. Fortunately, we won’t watch all of them because we will take the one that matches our precise desires."
},
{
"code": null,
"e": 3581,
"s": 3357,
"text": "In our experiment, we’ll use only the table ``movies_metadata.csv`` which contains attributes such as budget, genre, webpage link, original title, description overview, release date, spoken language, IMDb vote average, ...."
},
{
"code": null,
"e": 3994,
"s": 3581,
"text": "Our recommendation system will use the movie description overview sentence and apply a machine learning model to represent each sentence as a numerical feature vector. After applying an ML model to each sentence, we can concatenate these feature vectors to create an embed matrix that represents our whole dataset. This matrix is very important, it will be our lookup table for every query we make to the system."
},
{
"code": null,
"e": 4321,
"s": 3994,
"text": "Let’s say we have 100 movie description sentences and our embed vector size is 300, then our embed matrix size will be (100 x 300). When the user inputs a sentence, we embed its query sentence into a 300-dim vector with the same model and we compute the cosine distance between each of the 100 rows and the embed query vector."
},
{
"code": null,
"e": 4407,
"s": 4321,
"text": "Download the .csv file and load it as a data frame in your python script or notebook."
},
{
"code": null,
"e": 4663,
"s": 4407,
"text": "We’ll do basic pre-processing. We want to give a uniform text to the model, so we clean the sentences before embedding them into vectors. It would help the model to focus on the content rather than the formatting to find the relevant patterns in the data."
},
{
"code": null,
"e": 4708,
"s": 4663,
"text": "Let’s review our cleaning methodology below."
},
{
"code": null,
"e": 4756,
"s": 4708,
"text": "remove non-alphanumeric character/ punctuation,"
},
{
"code": null,
"e": 4801,
"s": 4756,
"text": "remove the too long and too short sentences,"
},
{
"code": null,
"e": 4819,
"s": 4801,
"text": "remove stopwords,"
},
{
"code": null,
"e": 4830,
"s": 4819,
"text": "lemmatize,"
},
{
"code": null,
"e": 4839,
"s": 4830,
"text": "tokenize"
},
{
"code": null,
"e": 4948,
"s": 4839,
"text": "We use regex pattern matching to remove all non-alphabetical-numeric characters from the movie descriptions."
},
{
"code": null,
"e": 5066,
"s": 4948,
"text": "We create our own tokenizer. The tokenizer transforms a string into a list of strings where each element is one word."
},
{
"code": null,
"e": 5187,
"s": 5066,
"text": "word_tokenizer(‘the beautiful tree has lost its leaves’)>>> [‘the’, ‘beautiful’, ‘tree’, ‘has’, ‘lost’, ‘its’, ‘leaves’]"
},
{
"code": null,
"e": 5249,
"s": 5187,
"text": "We use a lemmatizer that converts a word into a generic form:"
},
{
"code": null,
"e": 5434,
"s": 5249,
"text": "from nltk.stem import WordNetLemmatizerstemmer = WordNetLemmatizer()[stemmer.lemmatize(w) for w in word_tokenize(sentence)]>>> ['the', 'beautiful', 'tree', 'ha', 'lost', 'his', 'leaf']"
},
{
"code": null,
"e": 5638,
"s": 5434,
"text": "We remove too short and too long sentences from our dataset, by filtering with MIN_WORDS and MAX_WORDS. We remove common words (STOPWORDS) which won’t help to extract the specificity of a given sentence."
},
{
"code": null,
"e": 5691,
"s": 5638,
"text": "We converted the column “sentence” into two columns:"
},
{
"code": null,
"e": 5756,
"s": 5691,
"text": "clean_sentence where the sentence is mainly alphanumerical text."
},
{
"code": null,
"e": 5817,
"s": 5756,
"text": "tok_lem_sentence where the data is lemmatized and tokenized."
},
{
"code": null,
"e": 5928,
"s": 5817,
"text": "Now our dataset is ready to be processed and we can compare different models that offer different compromises:"
},
{
"code": null,
"e": 5955,
"s": 5928,
"text": "the baseline/ basic TF-IDF"
},
{
"code": null,
"e": 5995,
"s": 5955,
"text": "Word2Vec, a simple feed-forward network"
},
{
"code": null,
"e": 6041,
"s": 5995,
"text": "spaCy, very flexible and powerful NLP library"
},
{
"code": null,
"e": 6094,
"s": 6041,
"text": "transformers, the state-of-art Deep Learning models."
},
{
"code": null,
"e": 6214,
"s": 6094,
"text": "I introduce below a function that I will use to rank the best recommendation given the cosine distance between vectors."
},
{
"code": null,
"e": 6596,
"s": 6214,
"text": "You can notice in l.11 that we use an average on the distance matrix. The shape of the distance matrix is (number of words in query sentence, number of sentence in our vocabulary). We compute the distance from each word of the query to each sentence of our database and take the average on the whole query. Then we can take the three-sentence with the lowest distance to the query."
},
{
"code": null,
"e": 7119,
"s": 6596,
"text": "A text corpus often contains words that appear often and don’t contain any useful discriminatory information. Tf-idf is designed to down weight these frequently occurring words in the feature vectors. It can be defined as the product of the term frequency (frequency of one word in a given document) and the inverse document frequency (occurrence of this word among all the documents) [1]. Term frequency / Document frequency measures the relevance of a term in a given document. In our case, one document is one sentence."
},
{
"code": null,
"e": 7376,
"s": 7119,
"text": "Once we fit our data on the Tf-idf model, we can generate an embedding 22,180 dimensions vector for each movie description. These features are stored in a feature matrix tfidf_mat where each row is a movie description record embedded into a feature vector."
},
{
"code": null,
"e": 7574,
"s": 7376,
"text": "When we get a query from user input, we’ll embed it into the same vector space and we’ll compare one by one the query sentence feature embed_query to the sentence vectors of embed matrix tfidf_mat."
},
{
"code": null,
"e": 7812,
"s": 7574,
"text": "The function that finds the best index from the distance matrix takes the average of the cosine distance for each embedded sentence and ranks the results. Don’t pay attention yet to the masking argument, we will use it for another model."
},
{
"code": null,
"e": 7936,
"s": 7812,
"text": "This model is very simple to use and can be set up with only a handful of lines of code, the training is very fast as well."
},
{
"code": null,
"e": 7999,
"s": 7936,
"text": "On the query sentence: ‘a crime story with a beautiful woman’,"
},
{
"code": null,
"e": 8085,
"s": 7999,
"text": "- A beautiful vampire turns a crime lord into a creature of the night. Innocent Blood"
},
{
"code": null,
"e": 8174,
"s": 8085,
"text": "- A vampire lures beautiful young women to his castle in Europe. Requiem pour un vampire"
},
{
"code": null,
"e": 8314,
"s": 8174,
"text": "- The story of a young woman clinging on to her dream to become a beauty contest queen in a Mexico dominated by organized crime. Miss Bala."
},
{
"code": null,
"e": 9452,
"s": 8314,
"text": "Word2Vec is a powerful and efficient algorithm that can capture the semantics of the word in your corpus. Word2vec takes during training a corpus containing many documents/sentences and outputs a series of vectors one for each word in the text. a word vector contains the semantic meaning of this word, meaning that two that are close in the vector space share a similar meaning. King and queen are close like cake and coffee are. Word2Vec can be easily used to find synonyms for example. During the training, each word vector is weighted by the neural network according to the probability of occurrence inferred from the training dataset. How this probability is computed depends on the architecture you chose (Continuous Bag Of Words or skip-gram). In the end, the word2vec model is in fact a very simple 2 layers neural network, but we won’t care about the output, we’ll extract the hidden state where the information is encoded [3]. The advantage of word2vec is that it takes a high dimensional sparse word representation (like tf-idf or hot encoded vectors) and maps it into a dense representation, hopefully in a smaller dimension."
},
{
"code": null,
"e": 9685,
"s": 9452,
"text": "We use the gensim library to train a word2vec model on our corpus data. We first need to provide the vocabulary (the list of the words we want to vectorize) and then train the model on few epoch. By default, the model trains a CBOW."
},
{
"code": null,
"e": 9965,
"s": 9685,
"text": "The main downside of Word2Vec is that it can’t produce vectors for words that were not originally in the vocabulary used training. This is why we need to provide a utils function is_word_in_model that removes the words from the query sentence that are unseen in the training set."
},
{
"code": null,
"e": 10085,
"s": 9965,
"text": "We use their library function n_similarity to compute efficiently the distance between the query and dataset sentences."
},
{
"code": null,
"e": 10275,
"s": 10085,
"text": "- A tragic love story set in contemporary Shanghai. The film stars Zhou Xun in a dual role as two different women and Jia Hongsheng as a man obsessed with finding a woman from his past. 苏州河"
},
{
"code": null,
"e": 10396,
"s": 10275,
"text": "- A glowing orb terrorizes a young girl with a collection of stories of dark fantasy, eroticism and horror. Heavy Metal."
},
{
"code": null,
"e": 10602,
"s": 10396,
"text": "- Fritz Lang’s psycho thriller tells the story of a woman who marries a stranger with a deadly hobby and through their love he attempts to fight off his obsessive-compulsive actions. Secret Beyond the Door"
},
{
"code": null,
"e": 11301,
"s": 10602,
"text": "spaCy is a python open-source library contains many pre-computed models for a variety of languages (see the list of 64+ language here). Because we need to load the vector associated with each word, we use a trained pipeline for which we have access to the feature vectors, the en_core_web_lg. They called their NN Tok2Vec and we can use pre-trained weights that contain 685k keys as 685k unique vectors of dimension 300 trained on webpages corpus. SpaCy has their own Deep Learning library and models. You can read more about their default CNN+HashEmbedding model here. Their pipeline includes tokenizer, lemmatizer, and word-level vectorization so we only need to provide the sentences as strings."
},
{
"code": null,
"e": 11383,
"s": 11301,
"text": "We use a mask l.12 in case the word did not have a word in the pretrained corpus."
},
{
"code": null,
"e": 11498,
"s": 11383,
"text": "Even if spaCy is expected to be more powerful than TF-IDF, for this sentence, it gives the same results as TF-IDF."
},
{
"code": null,
"e": 11720,
"s": 11498,
"text": "If we want a robust and accurate method, we can use Deep Learning. Fortunately, many libraries have released their own pretrained weights and we don’t need to spend months to train a very deep model on the whole internet."
},
{
"code": null,
"e": 11845,
"s": 11720,
"text": "We’ll use BERT architecture. The cost is higher than previous models but the understanding of the context is more acute too."
},
{
"code": null,
"e": 12117,
"s": 11845,
"text": "SentenceTransformers’ team developed their own high-level pipeline to facilitate the use of transformers in Python. You can explore their list of models and recommendations here. I personally chose paraphrase-MiniLM-L6-v2 that satisfies “a quick model with high quality”."
},
{
"code": null,
"e": 12257,
"s": 12117,
"text": "- The story of a young woman clinging on to her dream to become a beauty contest queen in a Mexico dominated by organized crime. Miss Bala."
},
{
"code": null,
"e": 12599,
"s": 12257,
"text": "- Following the gruesome murder of a young woman in her neighborhood, a self-determined woman living in New York City--as if to test the limits of her own safety--propels herself into an impossibly risky sexual liaison. Soon she grows increasingly wary about the motives of every man with whom she has contact--and about her own. In the Cut."
},
{
"code": null,
"e": 12729,
"s": 12599,
"text": "- Story of the love between a struggling American artist and a beautiful Chinese prostitute in Hong Kong. The World of Suzie Wong"
},
{
"code": null,
"e": 12802,
"s": 12729,
"text": "We can see the improvement in the results compared with previous models."
},
{
"code": null,
"e": 13070,
"s": 12802,
"text": "SentenceTransformer uses HuggingFace architecture in the backend. HuggingFace leads the research as an open-source provider of NLP technologies. They expose models, datasets, and code bases for free. Anyone can train their model and push the result to their database."
},
{
"code": null,
"e": 13203,
"s": 13070,
"text": "We’ll use tokenizer (AutoTokenizer) and model (AutoModel) that are retrievable for the sentence-transformer/paraphrase-MiniLM-L6-v2."
},
{
"code": null,
"e": 13618,
"s": 13203,
"text": "We can choose to train on CPU or GPU and we use fit_transform to generate our embed matrix using a batch of data not to overload the memory. Again in the transform method, we use mean_pooling function to infer a vector for each word and average them for each sentence. This pooling is more complex than previously because the attention mechanism in BERT uses masks and we apply them to the result before averaging."
},
{
"code": null,
"e": 13791,
"s": 13618,
"text": "The code is slightly longer than when we use SentenceTransformer but we have more flexibility too. The inferring method we need to design ourselves is also more transparent"
},
{
"code": null,
"e": 14089,
"s": 13791,
"text": "Training takes time so if you have access to a GPU, use it to speed up your training. For this dataset, training took 12min on CPU for 20,000 sentence rows on my 16Gb 8 CPUs local computer, while training took only 6min when I use my local GPU (GeForce MX150) with the same training configuration."
},
{
"code": null,
"e": 14132,
"s": 14089,
"text": "QUERY: ‘A dog is playing with his friends’"
},
{
"code": null,
"e": 14247,
"s": 14132,
"text": "BERT MODEL: ‘The story of a man who rescues a German shepherd and how the two become fast friends.’ [My Dog Tulip]"
},
{
"code": null,
"e": 14280,
"s": 14247,
"text": "QUERY: ‘a heroe movie in europe’"
},
{
"code": null,
"e": 14457,
"s": 14280,
"text": "BERT MODEL: ‘A cop in a dystopian Europe investigates a serial killings suspect using controversial methods written by his now disgraced former mentor.’ [Forbrydelsens element]"
},
{
"code": null,
"e": 14513,
"s": 14457,
"text": "(we may conclude that it did not exist in the database)"
},
{
"code": null,
"e": 14547,
"s": 14513,
"text": "QUERY: ‘the story of a waitress’’"
},
{
"code": null,
"e": 14785,
"s": 14547,
"text": "BERT MODEL: ‘A waitress, desperate to fulfill her dreams as a restaurant owner, is set on a journey to turn a frog prince back into a human being, but she has to do face the same problem after she kisses him.’ [The Princess and the Frog]"
},
{
"code": null,
"e": 14958,
"s": 14785,
"text": "Once we loaded and vectorized an initial dataset, we can use a new sentence as a query and retrieve the top-3 closest items from the dataset that match this query sentence."
},
{
"code": null,
"e": 15250,
"s": 14958,
"text": "For that, we have used the simple TF-IDF model that uses the frequency of the words and in the sentence to create vectors. We used the Word2Vec model, a simple neural network. We used spaCy which can process and compute vectors for many different languages with state-of-the-art performance."
},
{
"code": null,
"e": 15498,
"s": 15250,
"text": "Finally, we used transformer models to leverage the latest deep learning method for vectorization. Deep Learning techniques could achieve the best (subjectively) retrieval results but they are slower. Pick the method that fits your trade-off best!"
},
{
"code": null,
"e": 15647,
"s": 15498,
"text": "[1] Python Machine Learning, Sebastian Raschka, Packt Edition (https://www.packtpub.com/product/python-machine-learning-third-edition/9781789955750)"
},
{
"code": null,
"e": 15841,
"s": 15647,
"text": "[2] http://mccormickml.com/2016/04/19/word2vec-tutorial-the-skip-gram-model/, http://mccormickml.com/assets/word2vec/Alex_Minnaar_Word2Vec_Tutorial_Part_II_The_Continuous_Bag-of-Words_Model.pdf"
}
] |
How to display the name of the Current Thread in C#?
|
Use the Name property to display the name of the current thread in C#.
Firstly, use the currentThread property to display information about a thread −
Thread thread = Thread.CurrentThread;
Now use the thread.Name property to display name of the thread −
thread.Name
Let us see the complete code show current thread’s name in C# −
Live Demo
using System;
using System.Threading;
namespace Demo {
class MyClass {
static void Main(string[] args) {
Thread thread = Thread.CurrentThread;
thread.Name = "My Thread";
Console.WriteLine("Thread Name = {0}", thread.Name);
Console.ReadKey();
}
}
}
Thread Name = My Thread
|
[
{
"code": null,
"e": 1133,
"s": 1062,
"text": "Use the Name property to display the name of the current thread in C#."
},
{
"code": null,
"e": 1213,
"s": 1133,
"text": "Firstly, use the currentThread property to display information about a thread −"
},
{
"code": null,
"e": 1251,
"s": 1213,
"text": "Thread thread = Thread.CurrentThread;"
},
{
"code": null,
"e": 1316,
"s": 1251,
"text": "Now use the thread.Name property to display name of the thread −"
},
{
"code": null,
"e": 1328,
"s": 1316,
"text": "thread.Name"
},
{
"code": null,
"e": 1392,
"s": 1328,
"text": "Let us see the complete code show current thread’s name in C# −"
},
{
"code": null,
"e": 1403,
"s": 1392,
"text": " Live Demo"
},
{
"code": null,
"e": 1707,
"s": 1403,
"text": "using System;\nusing System.Threading;\n\nnamespace Demo {\n class MyClass {\n static void Main(string[] args) {\n Thread thread = Thread.CurrentThread;\n thread.Name = \"My Thread\";\n\n Console.WriteLine(\"Thread Name = {0}\", thread.Name);\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 1731,
"s": 1707,
"text": "Thread Name = My Thread"
}
] |
JasmineJS - Null Check
|
Jasmine provides a different variety of method to check whether the actual output is Null, defined or undefined. In this chapter, we will learn how to implement different Jasmine methods to check the above-mentioned scenarios.
This matcher is used to check whether any variable in the code is predefined or not. Let us modify our customerMatcherSpec.js file according to this example.
currentVal = 0;
describe("Different Methods of Expect Block",function () {
it("Example of toBeDefined", function () {
expect(currentVal).toBeDefined();
});
});
In the above code, toBeDefined() will check whether the variable currentVal is defined in the system or not. As currentVal is defined to 0 in the beginning, this test will pass and generate a green screenshot as an output.
Again in the above example, let us remove the first line, where we actually define “currentVal” and run again. Then we will get a red screen, which means the test actually fails because we are expecting an undefined value to be defined. The following screenshot will be the output file.
This matcher helps to check whether any variable is previously undefined or not, basically it works simply opposite to the previous matcher that is toBeDefined. In the following example, we will learn how to use this matcher. Let us modify our Spec file, i.e. customerMatcher.js file with the following entry.
describe("Different Methods of Expect Block",function () {
it("Example of toBeUndefine()", function () {
var undefineValue;
expect(undefineValue).toBeUndefined();
});
});
In the above section, we will verify whether our variable “undefineValue” is actually undefined or not. After adding this file into the SpecRunner, we will receive a green color screenshot as an output, which tells us that this value is actually not defined previously.
Again let us define the variable with some predefined value and see whether it will throw an error or not. The new customerMatcher.js looks like the following.
describe("Different Methods of Expect Block",function () {
it("Example oftoBeUndefine()", function () {
var undefineValue = 0;
expect(undefineValue).toBeUndefined();
});
});
The above piece of code will throw an error and generate a red color screenshot because we have already defined the “undefineValue” value to “0” and expecting it to be not defined. The following screenshot will be generated on run SpecRunner.html file.
As the name signifies this matcher helps to check null values. Let us again modify our customerMatcherSpec.js file with the following piece of code.
describe("Different Methods of Expect Block",function () {
var value = null;
it("Example of toBeNull()", function () {
expect(value).toBeNull();
});
});
In the above code, we have mentioned one variable ”value” and we have explicitly mentioned this value as null. In the expect block, the toBeNull() matcher will check this value and give us the result accordingly. Following is the output of the above-mentioned code when it is run through the help of the SpecRunner.html file.
Now let us test by providing some defined value other than null. Please modify the customerMatcher.js file accordingly.
describe("Different Methods of Expect Block",function () {
var value = "TutorialsPoint";
it("Example of toBeNull()", function () {
expect(value).toBeNull();
});
});
In the above example, we have modified the variable value with “TutorialsPoint” which is not a null value. Hence, this test will fail and produce a red screenshot as an output.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2277,
"s": 2050,
"text": "Jasmine provides a different variety of method to check whether the actual output is Null, defined or undefined. In this chapter, we will learn how to implement different Jasmine methods to check the above-mentioned scenarios."
},
{
"code": null,
"e": 2435,
"s": 2277,
"text": "This matcher is used to check whether any variable in the code is predefined or not. Let us modify our customerMatcherSpec.js file according to this example."
},
{
"code": null,
"e": 2613,
"s": 2435,
"text": "currentVal = 0; \n\ndescribe(\"Different Methods of Expect Block\",function () { \n it(\"Example of toBeDefined\", function () {\n expect(currentVal).toBeDefined();\n });\n});"
},
{
"code": null,
"e": 2837,
"s": 2613,
"text": "In the above code, toBeDefined() will check whether the variable currentVal is defined in the system or not. As currentVal is defined to 0 in the beginning, this test will pass and generate a green screenshot as an output."
},
{
"code": null,
"e": 3124,
"s": 2837,
"text": "Again in the above example, let us remove the first line, where we actually define “currentVal” and run again. Then we will get a red screen, which means the test actually fails because we are expecting an undefined value to be defined. The following screenshot will be the output file."
},
{
"code": null,
"e": 3434,
"s": 3124,
"text": "This matcher helps to check whether any variable is previously undefined or not, basically it works simply opposite to the previous matcher that is toBeDefined. In the following example, we will learn how to use this matcher. Let us modify our Spec file, i.e. customerMatcher.js file with the following entry."
},
{
"code": null,
"e": 3628,
"s": 3434,
"text": "describe(\"Different Methods of Expect Block\",function () { \n it(\"Example of toBeUndefine()\", function () { \n var undefineValue; \n expect(undefineValue).toBeUndefined(); \n });\n}); "
},
{
"code": null,
"e": 3898,
"s": 3628,
"text": "In the above section, we will verify whether our variable “undefineValue” is actually undefined or not. After adding this file into the SpecRunner, we will receive a green color screenshot as an output, which tells us that this value is actually not defined previously."
},
{
"code": null,
"e": 4058,
"s": 3898,
"text": "Again let us define the variable with some predefined value and see whether it will throw an error or not. The new customerMatcher.js looks like the following."
},
{
"code": null,
"e": 4251,
"s": 4058,
"text": "describe(\"Different Methods of Expect Block\",function () {\n it(\"Example oftoBeUndefine()\", function () { \n var undefineValue = 0;\n expect(undefineValue).toBeUndefined();\n });\n});"
},
{
"code": null,
"e": 4504,
"s": 4251,
"text": "The above piece of code will throw an error and generate a red color screenshot because we have already defined the “undefineValue” value to “0” and expecting it to be not defined. The following screenshot will be generated on run SpecRunner.html file."
},
{
"code": null,
"e": 4653,
"s": 4504,
"text": "As the name signifies this matcher helps to check null values. Let us again modify our customerMatcherSpec.js file with the following piece of code."
},
{
"code": null,
"e": 4827,
"s": 4653,
"text": "describe(\"Different Methods of Expect Block\",function () { \n var value = null; \n\t\n it(\"Example of toBeNull()\", function () { \n expect(value).toBeNull();\n });\n}); "
},
{
"code": null,
"e": 5153,
"s": 4827,
"text": "In the above code, we have mentioned one variable ”value” and we have explicitly mentioned this value as null. In the expect block, the toBeNull() matcher will check this value and give us the result accordingly. Following is the output of the above-mentioned code when it is run through the help of the SpecRunner.html file."
},
{
"code": null,
"e": 5273,
"s": 5153,
"text": "Now let us test by providing some defined value other than null. Please modify the customerMatcher.js file accordingly."
},
{
"code": null,
"e": 5459,
"s": 5273,
"text": "describe(\"Different Methods of Expect Block\",function () {\n var value = \"TutorialsPoint\"; \n\t\n it(\"Example of toBeNull()\", function () { \n expect(value).toBeNull();\n });\n}); "
},
{
"code": null,
"e": 5636,
"s": 5459,
"text": "In the above example, we have modified the variable value with “TutorialsPoint” which is not a null value. Hence, this test will fail and produce a red screenshot as an output."
},
{
"code": null,
"e": 5643,
"s": 5636,
"text": " Print"
},
{
"code": null,
"e": 5654,
"s": 5643,
"text": " Add Notes"
}
] |
How to extract a particular value based on index from an R data frame column?
|
Sometimes we want to figure out which value lies at some position in an R data frame column, this helps us to understand the data collection or data simulation process. For example, if we have a data frame df that contain columns x, y, and z each with 5000 values then we can use df$x[[253]] to find which values lies at 253rd row in column x of data frame df.
Consider the below data frame −
Live Demo
set.seed(987)
x<-rnorm(20,521,30.7)
y<-rnorm(20,20,4.05)
z<-rnorm(20,31,1)
a<-rpois(20,8)
b<-rpois(20,10)
c<-rpois(20,2)
df<-data.frame(x,y,z,a,b,c)
df
x y z a b c
1 519.2497 26.62916 31.48431 14 18 0
2 529.2888 16.46887 32.70400 5 5 1
3 547.8463 13.71248 29.73358 10 11 2
4 515.1564 22.82227 30.12065 6 5 5
5 554.7914 20.28892 32.52483 7 2 4
6 493.5616 15.45613 31.23513 14 10 3
7 491.6825 22.32123 30.81875 4 9 4
8 494.7252 18.33388 32.50834 8 13 1
9 486.8303 13.96303 30.71686 5 10 2
10 481.4361 18.60518 32.32576 13 9 3
11 544.2612 19.79058 32.56325 7 8 1
12 494.0999 23.56244 30.83515 4 14 3
13 574.9847 27.61496 29.30917 9 6 0
14 520.7027 27.62166 29.93995 10 12 0
15 507.2346 22.38830 31.16826 7 15 0
16 517.3553 22.60314 31.76175 6 9 2
17 507.0164 18.61279 31.86548 10 10 3
18 484.6791 24.74147 31.88115 5 6 5
19 507.0228 25.21739 32.09461 5 4 0
20 552.1552 16.49131 31.39587 5 7 2
Extracting values from column x using index −
df$x[[1]]
[1] 519.2497
df$x[[5]]
[1] 554.7914
df$x[[6]]
[1] 493.5616
df$x[[7]]
[1] 491.6825
df$x[[12]]
[1] 494.0999
df$x[[15]]
[1] 507.2346
df$x[[19]]
[1] 507.0228
df$x[[20]]
[1] 552.1552
Extracting values from column y using index −
df$y[[19]]
[1] 25.21739
df$y[[1]]
[1] 26.62916
df$y[[4]]
[1] 22.82227
df$y[[3]]
[1] 13.71248
df$y[[5]]
[1] 20.28892
df$y[[7]]
[1] 22.32123
df$y[[10]]
[1] 18.60518
df$y[[9]]
[1] 13.96303
df$y[[13]]
[1] 27.61496
df$y[[14]]
[1] 27.62166
df$y[[18]]
[1] 24.74147
Extracting values from column z using index:
df$z[[2]]
[1] 32.704
df$z[[5]]
[1] 32.52483
df$z[[10]]
[1] 32.32576
df$z[[15]]
[1] 31.16826
df$z[[20]]
[1] 31.39587
df$z[[17]]
[1] 31.86548
Extracting values from column a using index −
df$a[[20]]
[1] 5
df$a[[1]]
[1] 14
df$a[[10]]
[1] 13
df$a[[12]]
[1] 4
df$a[[5]]
[1] 7
df$a[[13]]
[1] 9
df$a[[17]]
[1] 10
df$a[[18]]
[1] 5
df$a[[19]]
[1] 5
Extracting values from column b using index −
df$b[[1]]
[1] 18
df$b[[5]]
[1] 2
df$b[[10]]
[1] 9
df$b[[15]]
[1] 15
df$b[[20]]
[1] 7
Extracting values from column c using index −
df$c[[3]]
[1] 2
df$c[[6]]
[1] 3
df$c[[9]]
[1] 2
df$c[[12]]
[1] 3
df$c[[15]]
[1] 0
df$c[[18]]
[1] 5
|
[
{
"code": null,
"e": 1423,
"s": 1062,
"text": "Sometimes we want to figure out which value lies at some position in an R data frame column, this helps us to understand the data collection or data simulation process. For example, if we have a data frame df that contain columns x, y, and z each with 5000 values then we can use df$x[[253]] to find which values lies at 253rd row in column x of data frame df."
},
{
"code": null,
"e": 1455,
"s": 1423,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1466,
"s": 1455,
"text": " Live Demo"
},
{
"code": null,
"e": 1618,
"s": 1466,
"text": "set.seed(987)\nx<-rnorm(20,521,30.7)\ny<-rnorm(20,20,4.05)\nz<-rnorm(20,31,1)\na<-rpois(20,8)\nb<-rpois(20,10)\nc<-rpois(20,2)\ndf<-data.frame(x,y,z,a,b,c)\ndf"
},
{
"code": null,
"e": 2378,
"s": 1618,
"text": " x y z a b c\n1 519.2497 26.62916 31.48431 14 18 0\n2 529.2888 16.46887 32.70400 5 5 1\n3 547.8463 13.71248 29.73358 10 11 2\n4 515.1564 22.82227 30.12065 6 5 5\n5 554.7914 20.28892 32.52483 7 2 4\n6 493.5616 15.45613 31.23513 14 10 3\n7 491.6825 22.32123 30.81875 4 9 4\n8 494.7252 18.33388 32.50834 8 13 1\n9 486.8303 13.96303 30.71686 5 10 2\n10 481.4361 18.60518 32.32576 13 9 3\n11 544.2612 19.79058 32.56325 7 8 1\n12 494.0999 23.56244 30.83515 4 14 3\n13 574.9847 27.61496 29.30917 9 6 0\n14 520.7027 27.62166 29.93995 10 12 0\n15 507.2346 22.38830 31.16826 7 15 0\n16 517.3553 22.60314 31.76175 6 9 2\n17 507.0164 18.61279 31.86548 10 10 3\n18 484.6791 24.74147 31.88115 5 6 5\n19 507.0228 25.21739 32.09461 5 4 0\n20 552.1552 16.49131 31.39587 5 7 2"
},
{
"code": null,
"e": 2424,
"s": 2378,
"text": "Extracting values from column x using index −"
},
{
"code": null,
"e": 2612,
"s": 2424,
"text": "df$x[[1]]\n[1] 519.2497\ndf$x[[5]]\n[1] 554.7914\ndf$x[[6]]\n[1] 493.5616\ndf$x[[7]]\n[1] 491.6825\ndf$x[[12]]\n[1] 494.0999\ndf$x[[15]]\n[1] 507.2346\ndf$x[[19]]\n[1] 507.0228\ndf$x[[20]]\n[1] 552.1552"
},
{
"code": null,
"e": 2658,
"s": 2612,
"text": "Extracting values from column y using index −"
},
{
"code": null,
"e": 2916,
"s": 2658,
"text": "df$y[[19]]\n[1] 25.21739\ndf$y[[1]]\n[1] 26.62916\ndf$y[[4]]\n[1] 22.82227\ndf$y[[3]]\n[1] 13.71248\ndf$y[[5]]\n[1] 20.28892\ndf$y[[7]]\n[1] 22.32123\ndf$y[[10]]\n[1] 18.60518\ndf$y[[9]]\n[1] 13.96303\ndf$y[[13]]\n[1] 27.61496\ndf$y[[14]]\n[1] 27.62166\ndf$y[[18]]\n[1] 24.74147"
},
{
"code": null,
"e": 2961,
"s": 2916,
"text": "Extracting values from column z using index:"
},
{
"code": null,
"e": 3101,
"s": 2961,
"text": "df$z[[2]]\n[1] 32.704\ndf$z[[5]]\n[1] 32.52483\ndf$z[[10]]\n[1] 32.32576\ndf$z[[15]]\n[1] 31.16826\ndf$z[[20]]\n[1] 31.39587\ndf$z[[17]]\n[1] 31.86548"
},
{
"code": null,
"e": 3147,
"s": 3101,
"text": "Extracting values from column a using index −"
},
{
"code": null,
"e": 3301,
"s": 3147,
"text": "df$a[[20]]\n[1] 5\ndf$a[[1]]\n[1] 14\ndf$a[[10]]\n[1] 13\ndf$a[[12]]\n[1] 4\ndf$a[[5]]\n[1] 7\ndf$a[[13]]\n[1] 9\ndf$a[[17]]\n[1] 10\ndf$a[[18]]\n[1] 5\ndf$a[[19]]\n[1] 5"
},
{
"code": null,
"e": 3347,
"s": 3301,
"text": "Extracting values from column b using index −"
},
{
"code": null,
"e": 3432,
"s": 3347,
"text": "df$b[[1]]\n[1] 18\ndf$b[[5]]\n[1] 2\ndf$b[[10]]\n[1] 9\ndf$b[[15]]\n[1] 15\ndf$b[[20]]\n[1] 7"
},
{
"code": null,
"e": 3478,
"s": 3432,
"text": "Extracting values from column c using index −"
},
{
"code": null,
"e": 3577,
"s": 3478,
"text": "df$c[[3]]\n[1] 2\ndf$c[[6]]\n[1] 3\ndf$c[[9]]\n[1] 2\ndf$c[[12]]\n[1] 3\ndf$c[[15]]\n[1] 0\ndf$c[[18]]\n[1] 5"
}
] |
Arithmetic Operators in C
|
The following table shows all the arithmetic operators supported by the C language. Assume variable A holds 10 and variable B holds 20, then −
Try the following example to understand all the arithmetic operators available in C −
#include <stdio.h>
main() {
int a = 21;
int b = 10;
int c ;
c = a + b;
printf("Line 1 - Value of c is %d\n", c );
c = a - b;
printf("Line 2 - Value of c is %d\n", c );
c = a * b;
printf("Line 3 - Value of c is %d\n", c );
c = a / b;
printf("Line 4 - Value of c is %d\n", c );
c = a % b;
printf("Line 5 - Value of c is %d\n", c );
c = a++;
printf("Line 6 - Value of c is %d\n", c );
c = a--;
printf("Line 7 - Value of c is %d\n", c );
}
When you compile and execute the above program, it produces the following result −
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2227,
"s": 2084,
"text": "The following table shows all the arithmetic operators supported by the C language. Assume variable A holds 10 and variable B holds 20, then −"
},
{
"code": null,
"e": 2313,
"s": 2227,
"text": "Try the following example to understand all the arithmetic operators available in C −"
},
{
"code": null,
"e": 2817,
"s": 2313,
"text": "#include <stdio.h>\n\nmain() {\n\n int a = 21;\n int b = 10;\n int c ;\n\n c = a + b;\n printf(\"Line 1 - Value of c is %d\\n\", c );\n\t\n c = a - b;\n printf(\"Line 2 - Value of c is %d\\n\", c );\n\t\n c = a * b;\n printf(\"Line 3 - Value of c is %d\\n\", c );\n\t\n c = a / b;\n printf(\"Line 4 - Value of c is %d\\n\", c );\n\t\n c = a % b;\n printf(\"Line 5 - Value of c is %d\\n\", c );\n\t\n c = a++; \n printf(\"Line 6 - Value of c is %d\\n\", c );\n\t\n c = a--; \n printf(\"Line 7 - Value of c is %d\\n\", c );\n}"
},
{
"code": null,
"e": 2900,
"s": 2817,
"text": "When you compile and execute the above program, it produces the following result −"
},
{
"code": null,
"e": 3082,
"s": 2900,
"text": "Line 1 - Value of c is 31\nLine 2 - Value of c is 11\nLine 3 - Value of c is 210\nLine 4 - Value of c is 2\nLine 5 - Value of c is 1\nLine 6 - Value of c is 21\nLine 7 - Value of c is 22\n"
},
{
"code": null,
"e": 3089,
"s": 3082,
"text": " Print"
},
{
"code": null,
"e": 3100,
"s": 3089,
"text": " Add Notes"
}
] |
How to insert mm/dd/yyyy format dates in MySQL?
|
For this, use STR_TO_DATE(). Following is the syntax −
insert into yourTableName values(STR_TO_DATE(yourDateValue,yourFormatSpecifier));
Let us first create a table −
mysql> create table DemoTable
(
ShippingDate date
);
Query OK, 0 rows affected (0.81 sec)
Insert some records in the table using insert command : Here, we are inserting formatted dates using date formats like m, d, y, etc −
mysql> insert into DemoTable values(STR_TO_DATE('06-01-2019', '%m-%d-%Y'));
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values(STR_TO_DATE('01-31-2019', '%m-%d-%Y'));
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values(STR_TO_DATE('02-01-2018', '%m-%d-%Y'));
Query OK, 1 row affected (0.27 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+--------------+
| ShippingDate |
+--------------+
| 2019-06-01 |
| 2019-01-31 |
| 2018-02-01 |
+--------------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1117,
"s": 1062,
"text": "For this, use STR_TO_DATE(). Following is the syntax −"
},
{
"code": null,
"e": 1199,
"s": 1117,
"text": "insert into yourTableName values(STR_TO_DATE(yourDateValue,yourFormatSpecifier));"
},
{
"code": null,
"e": 1229,
"s": 1199,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1328,
"s": 1229,
"text": "mysql> create table DemoTable\n (\n ShippingDate date\n );\nQuery OK, 0 rows affected (0.81 sec)"
},
{
"code": null,
"e": 1462,
"s": 1328,
"text": "Insert some records in the table using insert command : Here, we are inserting formatted dates using date formats like m, d, y, etc −"
},
{
"code": null,
"e": 1798,
"s": 1462,
"text": "mysql> insert into DemoTable values(STR_TO_DATE('06-01-2019', '%m-%d-%Y'));\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into DemoTable values(STR_TO_DATE('01-31-2019', '%m-%d-%Y'));\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into DemoTable values(STR_TO_DATE('02-01-2018', '%m-%d-%Y'));\nQuery OK, 1 row affected (0.27 sec)"
},
{
"code": null,
"e": 1858,
"s": 1798,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1889,
"s": 1858,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2033,
"s": 1889,
"text": "+--------------+\n| ShippingDate |\n+--------------+\n| 2019-06-01 |\n| 2019-01-31 |\n| 2018-02-01 |\n+--------------+\n3 rows in set (0.00 sec)"
}
] |
Creating a TensorFlow CNN in C++ (Part 2) | by Benny Friedman | Towards Data Science
|
In the last two years, Google’s TensorFlow has been gaining popularity. It is by far the most popular deep learning framework and together with Keras it is the most dominant framework.
Now with version 2, TensorFlow includes Keras built it.
However, when it comes to the C++ API, you can’t really find much information about using it. Most of the code samples and documentation are in Python. As I had mentioned in my previous posts, I want to allow C++ users, such as myself, to use the TensorFlow C++ API, which is a low-level API, which practically means that you have to put in more work to implement it. My post is here to help you.
As I wrote in the past, I like C++. I have nothing against Python, but I would like to be able to build my models in C++ and also have the ecosystem of tools to help me debug and optimize it.
I read the documentation, and looked for code samples that will show me how to create a convolutional neural network. There are a couple of them, here and here which inspired me. That’s all!
I had to reverse engineer some of the APIs and went through a lot of trial and errors until it worked.
I hope this article will serve others who would like to start using the C++ API.
I’m using XCode on MacOS, but I tried to build the code in a way that it will also work on Windows or Linux. I did not test that, so if you have any suggestions for a change, let me know.
I am assuming you already have TensorFlow installed, and you have an XCode project ready to use it. If you need help with that, please read and follow my instructions here.
As I wrote in part 1, the goal is to implement the AlexNet scaled-down version from part 4 of the famous article series by Arden Dertat.
I’m also assuming you know the terminology of convolutional networks, if not, I suggest you read Arden’s articles.
To get the data for training, you will need to download the images from Kaggle.
Download the small version from here. There are enough images there for our purpose.
Extract the files and put them in a data folder under the project folder.
It should be organized so you have three sub-folders for train, validation and test.
Code for this article can be found here.
There’s a main.cpp which drives the execution and two class files CatDogCNN.cpp and CatDogCNN.h which are the implementation of the network itself.
mainV1.cpp is the previous article code.
In general, when writing code for TensorFlow, it is wise to separate the creation of the graph from its actual running. This is due to the simple fact that you usually create the graph once and run it many times with different inputs. Even if you do not change the variables of the graph (like weights) there is no need to recreate the graph each time you want to run it, unless it is extremely simple, and the effort of separation is useless.
CreateGraphForImage is a method that creates a graph similar to the one I showed in part 1.
It accepts a Boolean whether to unstack the image. Call it with false when you want to load only one image and true when you want to load a batch. This is since an additional dimension will be added when stacking a batch. But when you want to run the CNN with only one image, you need to have all 4 dimensions.
Note that when changing from unstack to stack you have to re-create the graph.
ReadTensorFromImageFile is in charge of running the graph created by the previous method. You feed it with a full path name of a file and get a 3 or 4 dimensional Tensor.
Code for both these methods is almost identical to the code in mainV1.cpp (article part 1).
ReadFileTensors deals with folders and the files. It accepts a base folder string and a vector of pairs of [sub-folder, label value].
If you downloaded the images from Kaggle, you may have noticed that under train for example, there are two sub-folders cats and dogs. Label each one of them with a number and pass these pairs as input.
The return is a vector of pairs, each one is a Tensor (of an image) and a label.
Here is one way of calling it:
base_folder = "/Users/bennyfriedman/Code/TF2example/TF2example/data/cats_and_dogs_small/train";vector<pair<Tensor, float>> all_files_tensors;model.ReadFileTensors(base_folder, {make_pair("cats", 0), make_pair("dogs", 1)}, all_files_tensors);
We need to open a directory, read its files and go over them one by one.
To join two path strings use io::JoinPath (include tensorflow/core/lib/io/path.h)
string folder_name = io::JoinPath(base_folder_name, “cats”);
To interact with the file system use “Env”. This is a utility class (not really documented) which gives you similar facilitation like C++17 std::filesystem.
Env* penv = Env::Default();TF_RETURN_IF_ERROR(penv->IsDirectory(folder_name));vector<string> file_names;TF_RETURN_IF_ERROR(penv->GetChildren(folder_name, &file_names));for(string file: file_names){...}
ReadFileTensors also shuffles the images in the vector, this is so we can feed different images while training (you do not want to feed all cats and then all dogs).
ReadBatches encapsulates all the logic main needs. You give it the base folder, the vectors of pair of sub-folders and labels and the size of a batch. In return you get two vectors of Tensors, one for images and one for labels. Each Tensor is a batch of images / labels according to the size you passed.
First it reads the folder and its sub-folders’ content into a vector. Next it does some calculations on how to split the batches. Then it breaks the pairs of Tensors and labels to create two Input vectors where each n-th element in the Tensor vector matches the n-th element in the labels vector.
To stack the two vectors, we create a tiny graph on the spot and run it for each iteration.
The results are added to the output vectors.
Note how Stack operation needs to get an InputList of image tensors to stack. The easiest way is to create a vector (or another container) and instantiate the InputList with it.
vector<Input> one_batch_image;one_batch_image.push_back(Input(tensor));//Add more tensorsInputList one_batch_inputs(one_batch_image);Scope root = Scope::NewRootScope();auto stacked_images = Stack(root, one_batch_inputs);ClientSession session(root);vector<Tensor> out_tensors;TF_CHECK_OK(session.Run({}, {stacked_images}, &out_tensors));//use out_tensors[0]
As written above, the tensors go in as 3 dimensional tensors and the batches that are created are 4 dimensional.
Now comes the interesting part.
We would like to create a model similar to AlexNet.
First we want to define the input to the graph: we already know we need to feed a batch of images:
input_batch_var = Placeholder(t_root.WithOpName("input"), DT_FLOAT);
A placeholder is like a function parameter. You specify its name and element type, but its shape is unknown at this time.
The variable getting the result from placeholder is a member of the CatDogCNN class type Output.
First we use it in the graph as input to the first layer and later we will need to specify it in the ClientSession Run command together with its value (the batch Tensor).
Next there are a couple of placeholders which I will explain later.
Unlike in the usual Python Keras networks, the C++ layers are a composition of Operations (Google calls them low level API). To know what layer each operation belongs to, we create a sub-scope per layer.
Scope scope_conv1 = t_root.NewSubScope("Conv1_layer");
The operations will be created with this scope object.
The first layer is a Convolution layer, so we need to define 4 parameters: filter height and width and in and out channels. In addition, we have the activation function (Relu) and a MaxPool operation that follows.
We have 4 Conv layers, so I created a function to create a generic one that includes these operations:
Input CatDogCNN::AddConvLayer(string idx, Scope scope, int in_channels, int out_channels, int filter_side, Input input){TensorShape sp({filter_side, filter_side, in_channels, out_channels});m_vars["W"+idx] = Variable(scope.WithOpName("W"), sp, DT_FLOAT);m_shapes["W"+idx] = sp;m_assigns["W"+idx+"_assign"] = Assign(scope.WithOpName("W_assign"), m_vars["W"+idx], XavierInit(scope, in_channels, out_channels, filter_side));sp = {out_channels};m_vars["B"+idx] = Variable(scope.WithOpName("B"), sp, DT_FLOAT);m_shapes["B"+idx] = sp;m_assigns["B"+idx+"_assign"] = Assign(scope.WithOpName("B_assign"), m_vars["B"+idx], Input::Initializer(0.f, sp));auto conv = Conv2D(scope.WithOpName("Conv"), input, m_vars["W"+idx], {1, 1, 1, 1}, "SAME");auto bias = BiasAdd(scope.WithOpName("Bias"), conv, m_vars["B"+idx]);auto relu = Relu(scope.WithOpName("Relu"), bias);return MaxPool(scope.WithOpName("Pool"), relu, {1, 2, 2, 1}, {1, 2, 2, 1}, "SAME");}
Let’s review the code:
AddConvLayer gets an index string (to distinguish between layers), the sub-scope, in and out channels, a filter size (we assume same height and width) and Input input.
For the first layer in channels is the number of colors the image has (3 colors) and the input is the image Tensor.
The Conv2D operation needs a Tensor variable which holds the different filters (32 in the first layer). This variable will be changed within each step when the network in training.
For that reason, there is a member map m_vars that holds these variables as well as the biases. In addition, we need to store the shapes of these variables (m_shapes map) and we also need to initialize these variable with values (similar to Python variable initializer) — these operations are stored in m_assigns. Xavier initialization is popular these days, so I’ve implemented XavierInit to do that for Conv and Dense.
After the Conv2D there is a call to BiasAdd to add the bias (which is initialized to 0).
Next is a call to Relu followed by a call to MaxPool.
Note that for MaxPool in the Python Keras version, you only need to specify the window size with its two dimensions (e.g. 2, 2). Here we need to supply two shapes of 4 dimensions (window size and strides). To halve the size of the image in each layer, you must put 1, 2, 2, 1 in both window size and strides.
Also note that in the CreateGraphForCNN function I track the sizes of the in and out channels since they have to match between the layers.
Also, since there is no way of getting the shape of the tensors coming out of operations (in is only known in runtime) we have to calculate the image size in each step.
Flattening means we will have only two dimensions, the batch and the flat data.
To do that, we need to reshape the Tensor. Since I don’t want to hard code the batch size (I do not know whether it will be batched or not), I have to know the size of the flat data. That’s why I have these calculations done through the layers until we get flat_len.
auto flat = Reshape(flatten, pool4, {-1, flat_len});
In Reshape you are allowed to pass -1 in one of the dimensions, so it will be automatically calculated. Reshape does not add data, it only changes the way it is organized in.
This layer is in charge of dropping random neurons so the network will not overfit.
We create a new tensor with same shape and fill it with either 0 or 1 randomly with a ratio according to the drop rate and multiply our data by it.
However, when you want to validate or predict, you do not want to drop out neurons.
The logical way to achieve that would be to put a condition in the graph. There are operations that support that in a very cumbersome way (Switch and Merge) but they do not support backpropagation in C++ so we can’t use them.
Instead I introduced two more input parameters to the network drop_rate and skip_drop so for example if you pass 0.4 and 0 respectively, you get 40% drop. If you pass 1 and 1 you get no drops.
Scope dropout = t_root.NewSubScope("Dropout_layer");auto rand = RandomUniform(dropout, Shape(dropout, flat), DT_FLOAT);//binary = floor(rand + (1 - drop_rate) + skip_drop)auto binary = Floor(dropout, Add(dropout, rand, Add(dropout, Sub(dropout, 1.f, drop_rate_var), skip_drop_var)));auto after_drop = Multiply(dropout.WithOpName("dropout"), Div(dropout, flat, drop_rate_var), binary)
When dropping, we increase the values of the remaining neurons by dividing by the drop rate.
Note that when skip_drop is 1, the floor will turn “binary” into all ones.
Next are three dense layers.
Dense is based on multiplying by weights and adding bias. We keep the variables in the map and do the same for shapes and assigns.
We also initialize the weights with Xavier init and the biases with 0.
Note that in the last dense layer, we need to skip the Relu activation (for that we have bActivation).
The last dense layer reduced the size to 1 (over batch size). This is called the logits.
To make logits a 0 (for cat) or 1 (for dog) we call Sigmoid and return this result out.
That’s how the network looks like when turning on TensorBoard (see part 1 for details):
I opened one of the sub-scopes so you can see the low-level operations in the fourth convolution layer.
This is encapsulated in the CreateOptimizationGraph function. It is not a separate graph, but additional nodes in the same graph (same t_root main scope).
We start with a placeholder for the labels. If the image tensors were the x, this is the y.
Next we calculate the loss. This is a classification problem, so we should use cross entropy however I’m not sure how to use the SoftmaxCrossEntropyWithLogits operation and could not find any meaningful information on it, so I had to use the regular mean square diff method.
input_labels_var = Placeholder(t_root.WithOpName("inputL"), DT_FLOAT);Scope scope_loss = t_root.NewSubScope("Loss_scope");out_loss_var = Mean(scope_loss.WithOpName("Loss"), SquaredDifference(scope_loss, out_classification, input_labels_var), {0});TF_CHECK_OK(scope_loss.status());
Next I collect all the weights and biases and send them together with the loss to the magical API call AddSymbolicGradients. This marvelous function is not an operation. It takes a graph (by its associated scope), adds all the relevant backpropagating operations and returns a vector of gradient with the same size as the number of weights and biases.
Then we use the ApplyAdam on each variable from the weights and biases with its respective gradient.
auto adam = ApplyAdam(t_root, i.second, m_var, v_var, 0.f, 0.f, learning_rate, 0.9f, 0.999f, 0.00000001f, {grad_outputs[index]});v_out_grads.push_back(adam.operation);
For some reason, m_var and v_var have to be variables (they cannot be constant).
The most important variable you pass to ApplyAdam is the learning rate. I can’t stress enough how important this value is. I started with 0.001 (from the python version) and could not stop puzzling over why the loss did not converge. Eventually I realized the optimization function jumps too long in between peaks. Only after a few days when I changed it to 0.0001 it started working. You can try different values to see how it works in your case.
You can change the other values ApplyAdam is getting as well, though I’m not sure what’s the impact of that.
Now the TensorBoard image looks “a bit” different:
I have already mentioned the need to initialize all the variables with the Assign operation.
We collect all the m_assigns elements (also the ones we added for ApplyAdam) into a vector and run them in the created session.
vector<Output> ops_to_run;for(pair<string, Output> i: m_assigns)ops_to_run.push_back(i.second);t_session = unique_ptr<ClientSession>(new ClientSession(t_root));TF_CHECK_OK(t_session->Run(ops_to_run, nullptr));
Leave the comments around the summary file writer code and use it only when you want to generate a new graph for TensorBoard visualization.
Let’s go back to main: we constructed an instance of the CatDogCNN class, created the graphs, loaded the images and ran initialization.
It is time for the main epoch / step loops.
An epoch is a run through all the training data. A step is a single run of a batch of images.
We define the number of epochs, loop through them, and then loop through the batches.
In each iteration, we call TrainCNN, we call ValidateCNN and we do some calculation to check the performance of the network.
TrainCNN gets a batch of images, a batch of labels (corresponding these images) and returns results and loss.
The function first runs the batch:
vector<Tensor> out_tensors;//Inputs: batch of images, labels, drop rate and do not skip drop.//Extract: Loss and result. Run also: Apply Adam commandsTF_CHECK_OK(t_session->Run({{input_batch_var, image_batch}, {input_labels_var, label_batch}, {drop_rate_var, 0.5f}, {skip_drop_var, 0.f}}, {out_loss_var, out_classification}, v_out_grads, &out_tensors));
Then it calculates accuracy. Notice the usage of Tensor methods to extract the data: out_tensors[0].scalar<float>()(0) to get a scalar and out_tensors[1].matrix<float>() to get a matrix (which is almost like a vector of vectors).
Validation is important due to the fact we run through the network images that network never saw. If in each epoch we get better performance we are not over fitting.
vector<Tensor> out_tensors;//Inputs: batch of images, drop rate 1 and skip drop.TF_CHECK_OK(t_session->Run({{input_batch_var, image_batch}, {drop_rate_var, 1.f}, {skip_drop_var, 1.f}}, {out_classification}, &out_tensors));
Note the differences: we skip the dropout (see above for the explanation), we do not evaluate loss and we do not run the gradients.
The output console looks like this:
Epoch 1/20:....................................................................................................Validation:..................................................Time: 74 seconds Loss: 0.243231 Results accuracy: 0.561 Validation accuracy: 0.642Epoch 2/20:....................................................................................................Validation:..................................................Time: 72 seconds Loss: 0.203312 Results accuracy: 0.6875 Validation accuracy: 0.692***Epoch 20/20:....................................................................................................Validation:..................................................Time: 73 seconds Loss: 0.041021 Results accuracy: 0.956 Validation accuracy: 0.742
The loss is constantly going down, the results accuracy is going us to 95% and the validation accuracy is going up to 75%.
Let’s test the trained network.
For that we need to recreate the load image graph so it will not unstack.
Then we call ReadFileTensors to load the images in the test sub-folder. Lastly we run a loop of a few of them to see the performance of the network.
Predict is similar to validation, though it runs a single image.
The output console looks like this:
Test number: 1 predicted: 0 actual is: 0Test number: 2 predicted: 1 actual is: 1***Test number: 20 predicted: 0 actual is: 0total successes: 16 out of 20
80% accuracy. There is some room for improvement, but we got better results than Arden got on his network.
We saw how a CNN can be implemented, trained and tested using only C++ and the TensorFlow API.
We saw how to prepare data (images for training, validation and test) and how to batch them so that we can feed these batches to the TensorFlow low level API.
We implemented gradients, and other optimization methods.
We got good results, but there is more work to be done.
Next I’m planning to do some improvements.
As you can see in the console output, I’m running on my local MacBook Pro CPU and it takes a long time to run...
I’m planning to implement freeze model function and GPU usage to speed things up.
Also, I’ll see if I can do some image augmentation to create more data for the training.
|
[
{
"code": null,
"e": 357,
"s": 172,
"text": "In the last two years, Google’s TensorFlow has been gaining popularity. It is by far the most popular deep learning framework and together with Keras it is the most dominant framework."
},
{
"code": null,
"e": 413,
"s": 357,
"text": "Now with version 2, TensorFlow includes Keras built it."
},
{
"code": null,
"e": 810,
"s": 413,
"text": "However, when it comes to the C++ API, you can’t really find much information about using it. Most of the code samples and documentation are in Python. As I had mentioned in my previous posts, I want to allow C++ users, such as myself, to use the TensorFlow C++ API, which is a low-level API, which practically means that you have to put in more work to implement it. My post is here to help you."
},
{
"code": null,
"e": 1002,
"s": 810,
"text": "As I wrote in the past, I like C++. I have nothing against Python, but I would like to be able to build my models in C++ and also have the ecosystem of tools to help me debug and optimize it."
},
{
"code": null,
"e": 1193,
"s": 1002,
"text": "I read the documentation, and looked for code samples that will show me how to create a convolutional neural network. There are a couple of them, here and here which inspired me. That’s all!"
},
{
"code": null,
"e": 1296,
"s": 1193,
"text": "I had to reverse engineer some of the APIs and went through a lot of trial and errors until it worked."
},
{
"code": null,
"e": 1377,
"s": 1296,
"text": "I hope this article will serve others who would like to start using the C++ API."
},
{
"code": null,
"e": 1565,
"s": 1377,
"text": "I’m using XCode on MacOS, but I tried to build the code in a way that it will also work on Windows or Linux. I did not test that, so if you have any suggestions for a change, let me know."
},
{
"code": null,
"e": 1738,
"s": 1565,
"text": "I am assuming you already have TensorFlow installed, and you have an XCode project ready to use it. If you need help with that, please read and follow my instructions here."
},
{
"code": null,
"e": 1875,
"s": 1738,
"text": "As I wrote in part 1, the goal is to implement the AlexNet scaled-down version from part 4 of the famous article series by Arden Dertat."
},
{
"code": null,
"e": 1990,
"s": 1875,
"text": "I’m also assuming you know the terminology of convolutional networks, if not, I suggest you read Arden’s articles."
},
{
"code": null,
"e": 2070,
"s": 1990,
"text": "To get the data for training, you will need to download the images from Kaggle."
},
{
"code": null,
"e": 2155,
"s": 2070,
"text": "Download the small version from here. There are enough images there for our purpose."
},
{
"code": null,
"e": 2229,
"s": 2155,
"text": "Extract the files and put them in a data folder under the project folder."
},
{
"code": null,
"e": 2314,
"s": 2229,
"text": "It should be organized so you have three sub-folders for train, validation and test."
},
{
"code": null,
"e": 2355,
"s": 2314,
"text": "Code for this article can be found here."
},
{
"code": null,
"e": 2503,
"s": 2355,
"text": "There’s a main.cpp which drives the execution and two class files CatDogCNN.cpp and CatDogCNN.h which are the implementation of the network itself."
},
{
"code": null,
"e": 2544,
"s": 2503,
"text": "mainV1.cpp is the previous article code."
},
{
"code": null,
"e": 2988,
"s": 2544,
"text": "In general, when writing code for TensorFlow, it is wise to separate the creation of the graph from its actual running. This is due to the simple fact that you usually create the graph once and run it many times with different inputs. Even if you do not change the variables of the graph (like weights) there is no need to recreate the graph each time you want to run it, unless it is extremely simple, and the effort of separation is useless."
},
{
"code": null,
"e": 3080,
"s": 2988,
"text": "CreateGraphForImage is a method that creates a graph similar to the one I showed in part 1."
},
{
"code": null,
"e": 3391,
"s": 3080,
"text": "It accepts a Boolean whether to unstack the image. Call it with false when you want to load only one image and true when you want to load a batch. This is since an additional dimension will be added when stacking a batch. But when you want to run the CNN with only one image, you need to have all 4 dimensions."
},
{
"code": null,
"e": 3470,
"s": 3391,
"text": "Note that when changing from unstack to stack you have to re-create the graph."
},
{
"code": null,
"e": 3641,
"s": 3470,
"text": "ReadTensorFromImageFile is in charge of running the graph created by the previous method. You feed it with a full path name of a file and get a 3 or 4 dimensional Tensor."
},
{
"code": null,
"e": 3733,
"s": 3641,
"text": "Code for both these methods is almost identical to the code in mainV1.cpp (article part 1)."
},
{
"code": null,
"e": 3867,
"s": 3733,
"text": "ReadFileTensors deals with folders and the files. It accepts a base folder string and a vector of pairs of [sub-folder, label value]."
},
{
"code": null,
"e": 4069,
"s": 3867,
"text": "If you downloaded the images from Kaggle, you may have noticed that under train for example, there are two sub-folders cats and dogs. Label each one of them with a number and pass these pairs as input."
},
{
"code": null,
"e": 4150,
"s": 4069,
"text": "The return is a vector of pairs, each one is a Tensor (of an image) and a label."
},
{
"code": null,
"e": 4181,
"s": 4150,
"text": "Here is one way of calling it:"
},
{
"code": null,
"e": 4423,
"s": 4181,
"text": "base_folder = \"/Users/bennyfriedman/Code/TF2example/TF2example/data/cats_and_dogs_small/train\";vector<pair<Tensor, float>> all_files_tensors;model.ReadFileTensors(base_folder, {make_pair(\"cats\", 0), make_pair(\"dogs\", 1)}, all_files_tensors);"
},
{
"code": null,
"e": 4496,
"s": 4423,
"text": "We need to open a directory, read its files and go over them one by one."
},
{
"code": null,
"e": 4578,
"s": 4496,
"text": "To join two path strings use io::JoinPath (include tensorflow/core/lib/io/path.h)"
},
{
"code": null,
"e": 4639,
"s": 4578,
"text": "string folder_name = io::JoinPath(base_folder_name, “cats”);"
},
{
"code": null,
"e": 4796,
"s": 4639,
"text": "To interact with the file system use “Env”. This is a utility class (not really documented) which gives you similar facilitation like C++17 std::filesystem."
},
{
"code": null,
"e": 4998,
"s": 4796,
"text": "Env* penv = Env::Default();TF_RETURN_IF_ERROR(penv->IsDirectory(folder_name));vector<string> file_names;TF_RETURN_IF_ERROR(penv->GetChildren(folder_name, &file_names));for(string file: file_names){...}"
},
{
"code": null,
"e": 5163,
"s": 4998,
"text": "ReadFileTensors also shuffles the images in the vector, this is so we can feed different images while training (you do not want to feed all cats and then all dogs)."
},
{
"code": null,
"e": 5467,
"s": 5163,
"text": "ReadBatches encapsulates all the logic main needs. You give it the base folder, the vectors of pair of sub-folders and labels and the size of a batch. In return you get two vectors of Tensors, one for images and one for labels. Each Tensor is a batch of images / labels according to the size you passed."
},
{
"code": null,
"e": 5764,
"s": 5467,
"text": "First it reads the folder and its sub-folders’ content into a vector. Next it does some calculations on how to split the batches. Then it breaks the pairs of Tensors and labels to create two Input vectors where each n-th element in the Tensor vector matches the n-th element in the labels vector."
},
{
"code": null,
"e": 5856,
"s": 5764,
"text": "To stack the two vectors, we create a tiny graph on the spot and run it for each iteration."
},
{
"code": null,
"e": 5901,
"s": 5856,
"text": "The results are added to the output vectors."
},
{
"code": null,
"e": 6079,
"s": 5901,
"text": "Note how Stack operation needs to get an InputList of image tensors to stack. The easiest way is to create a vector (or another container) and instantiate the InputList with it."
},
{
"code": null,
"e": 6436,
"s": 6079,
"text": "vector<Input> one_batch_image;one_batch_image.push_back(Input(tensor));//Add more tensorsInputList one_batch_inputs(one_batch_image);Scope root = Scope::NewRootScope();auto stacked_images = Stack(root, one_batch_inputs);ClientSession session(root);vector<Tensor> out_tensors;TF_CHECK_OK(session.Run({}, {stacked_images}, &out_tensors));//use out_tensors[0]"
},
{
"code": null,
"e": 6549,
"s": 6436,
"text": "As written above, the tensors go in as 3 dimensional tensors and the batches that are created are 4 dimensional."
},
{
"code": null,
"e": 6581,
"s": 6549,
"text": "Now comes the interesting part."
},
{
"code": null,
"e": 6633,
"s": 6581,
"text": "We would like to create a model similar to AlexNet."
},
{
"code": null,
"e": 6732,
"s": 6633,
"text": "First we want to define the input to the graph: we already know we need to feed a batch of images:"
},
{
"code": null,
"e": 6801,
"s": 6732,
"text": "input_batch_var = Placeholder(t_root.WithOpName(\"input\"), DT_FLOAT);"
},
{
"code": null,
"e": 6923,
"s": 6801,
"text": "A placeholder is like a function parameter. You specify its name and element type, but its shape is unknown at this time."
},
{
"code": null,
"e": 7020,
"s": 6923,
"text": "The variable getting the result from placeholder is a member of the CatDogCNN class type Output."
},
{
"code": null,
"e": 7191,
"s": 7020,
"text": "First we use it in the graph as input to the first layer and later we will need to specify it in the ClientSession Run command together with its value (the batch Tensor)."
},
{
"code": null,
"e": 7259,
"s": 7191,
"text": "Next there are a couple of placeholders which I will explain later."
},
{
"code": null,
"e": 7463,
"s": 7259,
"text": "Unlike in the usual Python Keras networks, the C++ layers are a composition of Operations (Google calls them low level API). To know what layer each operation belongs to, we create a sub-scope per layer."
},
{
"code": null,
"e": 7518,
"s": 7463,
"text": "Scope scope_conv1 = t_root.NewSubScope(\"Conv1_layer\");"
},
{
"code": null,
"e": 7573,
"s": 7518,
"text": "The operations will be created with this scope object."
},
{
"code": null,
"e": 7787,
"s": 7573,
"text": "The first layer is a Convolution layer, so we need to define 4 parameters: filter height and width and in and out channels. In addition, we have the activation function (Relu) and a MaxPool operation that follows."
},
{
"code": null,
"e": 7890,
"s": 7787,
"text": "We have 4 Conv layers, so I created a function to create a generic one that includes these operations:"
},
{
"code": null,
"e": 8826,
"s": 7890,
"text": "Input CatDogCNN::AddConvLayer(string idx, Scope scope, int in_channels, int out_channels, int filter_side, Input input){TensorShape sp({filter_side, filter_side, in_channels, out_channels});m_vars[\"W\"+idx] = Variable(scope.WithOpName(\"W\"), sp, DT_FLOAT);m_shapes[\"W\"+idx] = sp;m_assigns[\"W\"+idx+\"_assign\"] = Assign(scope.WithOpName(\"W_assign\"), m_vars[\"W\"+idx], XavierInit(scope, in_channels, out_channels, filter_side));sp = {out_channels};m_vars[\"B\"+idx] = Variable(scope.WithOpName(\"B\"), sp, DT_FLOAT);m_shapes[\"B\"+idx] = sp;m_assigns[\"B\"+idx+\"_assign\"] = Assign(scope.WithOpName(\"B_assign\"), m_vars[\"B\"+idx], Input::Initializer(0.f, sp));auto conv = Conv2D(scope.WithOpName(\"Conv\"), input, m_vars[\"W\"+idx], {1, 1, 1, 1}, \"SAME\");auto bias = BiasAdd(scope.WithOpName(\"Bias\"), conv, m_vars[\"B\"+idx]);auto relu = Relu(scope.WithOpName(\"Relu\"), bias);return MaxPool(scope.WithOpName(\"Pool\"), relu, {1, 2, 2, 1}, {1, 2, 2, 1}, \"SAME\");}"
},
{
"code": null,
"e": 8849,
"s": 8826,
"text": "Let’s review the code:"
},
{
"code": null,
"e": 9017,
"s": 8849,
"text": "AddConvLayer gets an index string (to distinguish between layers), the sub-scope, in and out channels, a filter size (we assume same height and width) and Input input."
},
{
"code": null,
"e": 9133,
"s": 9017,
"text": "For the first layer in channels is the number of colors the image has (3 colors) and the input is the image Tensor."
},
{
"code": null,
"e": 9314,
"s": 9133,
"text": "The Conv2D operation needs a Tensor variable which holds the different filters (32 in the first layer). This variable will be changed within each step when the network in training."
},
{
"code": null,
"e": 9735,
"s": 9314,
"text": "For that reason, there is a member map m_vars that holds these variables as well as the biases. In addition, we need to store the shapes of these variables (m_shapes map) and we also need to initialize these variable with values (similar to Python variable initializer) — these operations are stored in m_assigns. Xavier initialization is popular these days, so I’ve implemented XavierInit to do that for Conv and Dense."
},
{
"code": null,
"e": 9824,
"s": 9735,
"text": "After the Conv2D there is a call to BiasAdd to add the bias (which is initialized to 0)."
},
{
"code": null,
"e": 9878,
"s": 9824,
"text": "Next is a call to Relu followed by a call to MaxPool."
},
{
"code": null,
"e": 10187,
"s": 9878,
"text": "Note that for MaxPool in the Python Keras version, you only need to specify the window size with its two dimensions (e.g. 2, 2). Here we need to supply two shapes of 4 dimensions (window size and strides). To halve the size of the image in each layer, you must put 1, 2, 2, 1 in both window size and strides."
},
{
"code": null,
"e": 10326,
"s": 10187,
"text": "Also note that in the CreateGraphForCNN function I track the sizes of the in and out channels since they have to match between the layers."
},
{
"code": null,
"e": 10495,
"s": 10326,
"text": "Also, since there is no way of getting the shape of the tensors coming out of operations (in is only known in runtime) we have to calculate the image size in each step."
},
{
"code": null,
"e": 10575,
"s": 10495,
"text": "Flattening means we will have only two dimensions, the batch and the flat data."
},
{
"code": null,
"e": 10842,
"s": 10575,
"text": "To do that, we need to reshape the Tensor. Since I don’t want to hard code the batch size (I do not know whether it will be batched or not), I have to know the size of the flat data. That’s why I have these calculations done through the layers until we get flat_len."
},
{
"code": null,
"e": 10895,
"s": 10842,
"text": "auto flat = Reshape(flatten, pool4, {-1, flat_len});"
},
{
"code": null,
"e": 11070,
"s": 10895,
"text": "In Reshape you are allowed to pass -1 in one of the dimensions, so it will be automatically calculated. Reshape does not add data, it only changes the way it is organized in."
},
{
"code": null,
"e": 11154,
"s": 11070,
"text": "This layer is in charge of dropping random neurons so the network will not overfit."
},
{
"code": null,
"e": 11302,
"s": 11154,
"text": "We create a new tensor with same shape and fill it with either 0 or 1 randomly with a ratio according to the drop rate and multiply our data by it."
},
{
"code": null,
"e": 11386,
"s": 11302,
"text": "However, when you want to validate or predict, you do not want to drop out neurons."
},
{
"code": null,
"e": 11612,
"s": 11386,
"text": "The logical way to achieve that would be to put a condition in the graph. There are operations that support that in a very cumbersome way (Switch and Merge) but they do not support backpropagation in C++ so we can’t use them."
},
{
"code": null,
"e": 11805,
"s": 11612,
"text": "Instead I introduced two more input parameters to the network drop_rate and skip_drop so for example if you pass 0.4 and 0 respectively, you get 40% drop. If you pass 1 and 1 you get no drops."
},
{
"code": null,
"e": 12189,
"s": 11805,
"text": "Scope dropout = t_root.NewSubScope(\"Dropout_layer\");auto rand = RandomUniform(dropout, Shape(dropout, flat), DT_FLOAT);//binary = floor(rand + (1 - drop_rate) + skip_drop)auto binary = Floor(dropout, Add(dropout, rand, Add(dropout, Sub(dropout, 1.f, drop_rate_var), skip_drop_var)));auto after_drop = Multiply(dropout.WithOpName(\"dropout\"), Div(dropout, flat, drop_rate_var), binary)"
},
{
"code": null,
"e": 12282,
"s": 12189,
"text": "When dropping, we increase the values of the remaining neurons by dividing by the drop rate."
},
{
"code": null,
"e": 12357,
"s": 12282,
"text": "Note that when skip_drop is 1, the floor will turn “binary” into all ones."
},
{
"code": null,
"e": 12386,
"s": 12357,
"text": "Next are three dense layers."
},
{
"code": null,
"e": 12517,
"s": 12386,
"text": "Dense is based on multiplying by weights and adding bias. We keep the variables in the map and do the same for shapes and assigns."
},
{
"code": null,
"e": 12588,
"s": 12517,
"text": "We also initialize the weights with Xavier init and the biases with 0."
},
{
"code": null,
"e": 12691,
"s": 12588,
"text": "Note that in the last dense layer, we need to skip the Relu activation (for that we have bActivation)."
},
{
"code": null,
"e": 12780,
"s": 12691,
"text": "The last dense layer reduced the size to 1 (over batch size). This is called the logits."
},
{
"code": null,
"e": 12868,
"s": 12780,
"text": "To make logits a 0 (for cat) or 1 (for dog) we call Sigmoid and return this result out."
},
{
"code": null,
"e": 12956,
"s": 12868,
"text": "That’s how the network looks like when turning on TensorBoard (see part 1 for details):"
},
{
"code": null,
"e": 13060,
"s": 12956,
"text": "I opened one of the sub-scopes so you can see the low-level operations in the fourth convolution layer."
},
{
"code": null,
"e": 13215,
"s": 13060,
"text": "This is encapsulated in the CreateOptimizationGraph function. It is not a separate graph, but additional nodes in the same graph (same t_root main scope)."
},
{
"code": null,
"e": 13307,
"s": 13215,
"text": "We start with a placeholder for the labels. If the image tensors were the x, this is the y."
},
{
"code": null,
"e": 13582,
"s": 13307,
"text": "Next we calculate the loss. This is a classification problem, so we should use cross entropy however I’m not sure how to use the SoftmaxCrossEntropyWithLogits operation and could not find any meaningful information on it, so I had to use the regular mean square diff method."
},
{
"code": null,
"e": 13863,
"s": 13582,
"text": "input_labels_var = Placeholder(t_root.WithOpName(\"inputL\"), DT_FLOAT);Scope scope_loss = t_root.NewSubScope(\"Loss_scope\");out_loss_var = Mean(scope_loss.WithOpName(\"Loss\"), SquaredDifference(scope_loss, out_classification, input_labels_var), {0});TF_CHECK_OK(scope_loss.status());"
},
{
"code": null,
"e": 14215,
"s": 13863,
"text": "Next I collect all the weights and biases and send them together with the loss to the magical API call AddSymbolicGradients. This marvelous function is not an operation. It takes a graph (by its associated scope), adds all the relevant backpropagating operations and returns a vector of gradient with the same size as the number of weights and biases."
},
{
"code": null,
"e": 14316,
"s": 14215,
"text": "Then we use the ApplyAdam on each variable from the weights and biases with its respective gradient."
},
{
"code": null,
"e": 14484,
"s": 14316,
"text": "auto adam = ApplyAdam(t_root, i.second, m_var, v_var, 0.f, 0.f, learning_rate, 0.9f, 0.999f, 0.00000001f, {grad_outputs[index]});v_out_grads.push_back(adam.operation);"
},
{
"code": null,
"e": 14565,
"s": 14484,
"text": "For some reason, m_var and v_var have to be variables (they cannot be constant)."
},
{
"code": null,
"e": 15013,
"s": 14565,
"text": "The most important variable you pass to ApplyAdam is the learning rate. I can’t stress enough how important this value is. I started with 0.001 (from the python version) and could not stop puzzling over why the loss did not converge. Eventually I realized the optimization function jumps too long in between peaks. Only after a few days when I changed it to 0.0001 it started working. You can try different values to see how it works in your case."
},
{
"code": null,
"e": 15122,
"s": 15013,
"text": "You can change the other values ApplyAdam is getting as well, though I’m not sure what’s the impact of that."
},
{
"code": null,
"e": 15173,
"s": 15122,
"text": "Now the TensorBoard image looks “a bit” different:"
},
{
"code": null,
"e": 15266,
"s": 15173,
"text": "I have already mentioned the need to initialize all the variables with the Assign operation."
},
{
"code": null,
"e": 15394,
"s": 15266,
"text": "We collect all the m_assigns elements (also the ones we added for ApplyAdam) into a vector and run them in the created session."
},
{
"code": null,
"e": 15604,
"s": 15394,
"text": "vector<Output> ops_to_run;for(pair<string, Output> i: m_assigns)ops_to_run.push_back(i.second);t_session = unique_ptr<ClientSession>(new ClientSession(t_root));TF_CHECK_OK(t_session->Run(ops_to_run, nullptr));"
},
{
"code": null,
"e": 15744,
"s": 15604,
"text": "Leave the comments around the summary file writer code and use it only when you want to generate a new graph for TensorBoard visualization."
},
{
"code": null,
"e": 15880,
"s": 15744,
"text": "Let’s go back to main: we constructed an instance of the CatDogCNN class, created the graphs, loaded the images and ran initialization."
},
{
"code": null,
"e": 15924,
"s": 15880,
"text": "It is time for the main epoch / step loops."
},
{
"code": null,
"e": 16018,
"s": 15924,
"text": "An epoch is a run through all the training data. A step is a single run of a batch of images."
},
{
"code": null,
"e": 16104,
"s": 16018,
"text": "We define the number of epochs, loop through them, and then loop through the batches."
},
{
"code": null,
"e": 16229,
"s": 16104,
"text": "In each iteration, we call TrainCNN, we call ValidateCNN and we do some calculation to check the performance of the network."
},
{
"code": null,
"e": 16339,
"s": 16229,
"text": "TrainCNN gets a batch of images, a batch of labels (corresponding these images) and returns results and loss."
},
{
"code": null,
"e": 16374,
"s": 16339,
"text": "The function first runs the batch:"
},
{
"code": null,
"e": 16728,
"s": 16374,
"text": "vector<Tensor> out_tensors;//Inputs: batch of images, labels, drop rate and do not skip drop.//Extract: Loss and result. Run also: Apply Adam commandsTF_CHECK_OK(t_session->Run({{input_batch_var, image_batch}, {input_labels_var, label_batch}, {drop_rate_var, 0.5f}, {skip_drop_var, 0.f}}, {out_loss_var, out_classification}, v_out_grads, &out_tensors));"
},
{
"code": null,
"e": 16958,
"s": 16728,
"text": "Then it calculates accuracy. Notice the usage of Tensor methods to extract the data: out_tensors[0].scalar<float>()(0) to get a scalar and out_tensors[1].matrix<float>() to get a matrix (which is almost like a vector of vectors)."
},
{
"code": null,
"e": 17124,
"s": 16958,
"text": "Validation is important due to the fact we run through the network images that network never saw. If in each epoch we get better performance we are not over fitting."
},
{
"code": null,
"e": 17347,
"s": 17124,
"text": "vector<Tensor> out_tensors;//Inputs: batch of images, drop rate 1 and skip drop.TF_CHECK_OK(t_session->Run({{input_batch_var, image_batch}, {drop_rate_var, 1.f}, {skip_drop_var, 1.f}}, {out_classification}, &out_tensors));"
},
{
"code": null,
"e": 17479,
"s": 17347,
"text": "Note the differences: we skip the dropout (see above for the explanation), we do not evaluate loss and we do not run the gradients."
},
{
"code": null,
"e": 17515,
"s": 17479,
"text": "The output console looks like this:"
},
{
"code": null,
"e": 18283,
"s": 17515,
"text": "Epoch 1/20:....................................................................................................Validation:..................................................Time: 74 seconds Loss: 0.243231 Results accuracy: 0.561 Validation accuracy: 0.642Epoch 2/20:....................................................................................................Validation:..................................................Time: 72 seconds Loss: 0.203312 Results accuracy: 0.6875 Validation accuracy: 0.692***Epoch 20/20:....................................................................................................Validation:..................................................Time: 73 seconds Loss: 0.041021 Results accuracy: 0.956 Validation accuracy: 0.742"
},
{
"code": null,
"e": 18406,
"s": 18283,
"text": "The loss is constantly going down, the results accuracy is going us to 95% and the validation accuracy is going up to 75%."
},
{
"code": null,
"e": 18438,
"s": 18406,
"text": "Let’s test the trained network."
},
{
"code": null,
"e": 18512,
"s": 18438,
"text": "For that we need to recreate the load image graph so it will not unstack."
},
{
"code": null,
"e": 18661,
"s": 18512,
"text": "Then we call ReadFileTensors to load the images in the test sub-folder. Lastly we run a loop of a few of them to see the performance of the network."
},
{
"code": null,
"e": 18726,
"s": 18661,
"text": "Predict is similar to validation, though it runs a single image."
},
{
"code": null,
"e": 18762,
"s": 18726,
"text": "The output console looks like this:"
},
{
"code": null,
"e": 18916,
"s": 18762,
"text": "Test number: 1 predicted: 0 actual is: 0Test number: 2 predicted: 1 actual is: 1***Test number: 20 predicted: 0 actual is: 0total successes: 16 out of 20"
},
{
"code": null,
"e": 19023,
"s": 18916,
"text": "80% accuracy. There is some room for improvement, but we got better results than Arden got on his network."
},
{
"code": null,
"e": 19118,
"s": 19023,
"text": "We saw how a CNN can be implemented, trained and tested using only C++ and the TensorFlow API."
},
{
"code": null,
"e": 19277,
"s": 19118,
"text": "We saw how to prepare data (images for training, validation and test) and how to batch them so that we can feed these batches to the TensorFlow low level API."
},
{
"code": null,
"e": 19335,
"s": 19277,
"text": "We implemented gradients, and other optimization methods."
},
{
"code": null,
"e": 19391,
"s": 19335,
"text": "We got good results, but there is more work to be done."
},
{
"code": null,
"e": 19434,
"s": 19391,
"text": "Next I’m planning to do some improvements."
},
{
"code": null,
"e": 19547,
"s": 19434,
"text": "As you can see in the console output, I’m running on my local MacBook Pro CPU and it takes a long time to run..."
},
{
"code": null,
"e": 19629,
"s": 19547,
"text": "I’m planning to implement freeze model function and GPU usage to speed things up."
}
] |
How to emit an event when a checkbox is clicked using Socket.IO? - GeeksforGeeks
|
15 Dec, 2021
Problem Statement: Task is to perform an action by emitting an event from the backend whenever a particular checkbox is clicked in the frontend. This needs to be done using Socket.IO and Node.js
Prerequisite:
Node.js : It is an open-source JavaScript Back-End technology.Express.js : It is a node.js server framework.Socket.io : It helps us to create a real-time bi-direction event-based communication between the server and the client.
Node.js : It is an open-source JavaScript Back-End technology.
Express.js : It is a node.js server framework.
Socket.io : It helps us to create a real-time bi-direction event-based communication between the server and the client.
Now we need to install the required packages for our project.
Installing the modules.npm install express socket.io
Installing the modules.
npm install express socket.io
Project structure:
Step 1: Create a server file named server.js.
server.js
// Importing express moduleconst express = require('express'); const app = express(); // Calling the public folderapp.use(express.static("public")); // Handling get requestapp.get("/" , (req,res)=>{ res.send("GeeksforGeeks); }); // Listing the server app.listen(4000 , ()=>{ console.log("Server running on port 4000");)
Output: Now, If you open the local host i.e. localhost:4000 You will see the output i.e. — GeeksforGeeks.
Step 2: Now, Lets implement the socket into our server file i.e. server.js
Syntax:
const io = require('socket.io')(server);
server.js
// Importing express moduleconst express = require('express');const app = express();const server = require('http').Server(app);const io = require('socket.io')(server); // Calling the public folderapp.use(express.static('public')) // Handling get requestapp.get("/" , (req,res)=>{ res.render("index");}); // Listening to the serverserver.listen(4000 , ()=>{ console.log("server is running");})
Step 3: Now let’s create a basic Html file i.e. index.html and a JavaScript file i.e. index.js into our public folder.
Step 4 : Now let’s add socket.io into our front-end. Add this script into your html file.
<script src="socket.io/socket.io.js" defer></script>
Step 5 : Now let’s create check box functionality. In this we have created a simple check box, When we check the checkbox it will emit one socket event which listens by the server and then the server emits an acknowledged event which will be listened to by the client-side and after receiving that event it will alert the acknowledgment.
index.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"> <script src="socket.io/socket.io.js" defer></script> <script src="index.js" defer></script></head><body> <center> <h1>GeeksforGeeks</h1> <p><input id="check" type="checkbox" onchange="changed()"/> Click me </p> </center></body></html>
index.js
// Socket Initializedconst socket = io('/'); function changed(){ // Getting current state of checkbox. var a = document.getElementById('check').checked; if(a) { // Emiting the event. socket.emit("checkedTrue"); }} //Listening on the event.socket.on("acknowledged" , ()=>{ alert("Action acknowledged by the server");});
server.js
// Importing express moduleconst express = require('express');const app = express();const server = require('http').Server(app);const io = require('socket.io')(server); // Calling the public folderapp.use(express.static('public')) // Handling get requestapp.get("/" , (req,res)=>{ res.render("index");}); // Socketio.on("connection" , (socket)=>{ socket.on("checkedTrue" , ()=>{ socket.emit("acknowledged") })}) // Listening the serverserver.listen(4000 , ()=>{ console.log("server is running");})
Output:
sweetyty
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to build a basic CRUD app with Node.js and ReactJS ?
How to connect Node.js with React.js ?
Mongoose Populate() Method
Express.js req.params Property
Mongoose find() Function
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 24531,
"s": 24503,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 24726,
"s": 24531,
"text": "Problem Statement: Task is to perform an action by emitting an event from the backend whenever a particular checkbox is clicked in the frontend. This needs to be done using Socket.IO and Node.js"
},
{
"code": null,
"e": 24740,
"s": 24726,
"text": "Prerequisite:"
},
{
"code": null,
"e": 24968,
"s": 24740,
"text": "Node.js : It is an open-source JavaScript Back-End technology.Express.js : It is a node.js server framework.Socket.io : It helps us to create a real-time bi-direction event-based communication between the server and the client."
},
{
"code": null,
"e": 25031,
"s": 24968,
"text": "Node.js : It is an open-source JavaScript Back-End technology."
},
{
"code": null,
"e": 25078,
"s": 25031,
"text": "Express.js : It is a node.js server framework."
},
{
"code": null,
"e": 25198,
"s": 25078,
"text": "Socket.io : It helps us to create a real-time bi-direction event-based communication between the server and the client."
},
{
"code": null,
"e": 25260,
"s": 25198,
"text": "Now we need to install the required packages for our project."
},
{
"code": null,
"e": 25313,
"s": 25260,
"text": "Installing the modules.npm install express socket.io"
},
{
"code": null,
"e": 25337,
"s": 25313,
"text": "Installing the modules."
},
{
"code": null,
"e": 25367,
"s": 25337,
"text": "npm install express socket.io"
},
{
"code": null,
"e": 25386,
"s": 25367,
"text": "Project structure:"
},
{
"code": null,
"e": 25432,
"s": 25386,
"text": "Step 1: Create a server file named server.js."
},
{
"code": null,
"e": 25442,
"s": 25432,
"text": "server.js"
},
{
"code": "// Importing express moduleconst express = require('express'); const app = express(); // Calling the public folderapp.use(express.static(\"public\")); // Handling get requestapp.get(\"/\" , (req,res)=>{ res.send(\"GeeksforGeeks); }); // Listing the server app.listen(4000 , ()=>{ console.log(\"Server running on port 4000\");)",
"e": 25779,
"s": 25442,
"text": null
},
{
"code": null,
"e": 25885,
"s": 25779,
"text": "Output: Now, If you open the local host i.e. localhost:4000 You will see the output i.e. — GeeksforGeeks."
},
{
"code": null,
"e": 25960,
"s": 25885,
"text": "Step 2: Now, Lets implement the socket into our server file i.e. server.js"
},
{
"code": null,
"e": 25968,
"s": 25960,
"text": "Syntax:"
},
{
"code": null,
"e": 26009,
"s": 25968,
"text": "const io = require('socket.io')(server);"
},
{
"code": null,
"e": 26019,
"s": 26009,
"text": "server.js"
},
{
"code": "// Importing express moduleconst express = require('express');const app = express();const server = require('http').Server(app);const io = require('socket.io')(server); // Calling the public folderapp.use(express.static('public')) // Handling get requestapp.get(\"/\" , (req,res)=>{ res.render(\"index\");}); // Listening to the serverserver.listen(4000 , ()=>{ console.log(\"server is running\");})",
"e": 26423,
"s": 26019,
"text": null
},
{
"code": null,
"e": 26542,
"s": 26423,
"text": "Step 3: Now let’s create a basic Html file i.e. index.html and a JavaScript file i.e. index.js into our public folder."
},
{
"code": null,
"e": 26632,
"s": 26542,
"text": "Step 4 : Now let’s add socket.io into our front-end. Add this script into your html file."
},
{
"code": null,
"e": 26685,
"s": 26632,
"text": "<script src=\"socket.io/socket.io.js\" defer></script>"
},
{
"code": null,
"e": 27023,
"s": 26685,
"text": "Step 5 : Now let’s create check box functionality. In this we have created a simple check box, When we check the checkbox it will emit one socket event which listens by the server and then the server emits an acknowledged event which will be listened to by the client-side and after receiving that event it will alert the acknowledgment."
},
{
"code": null,
"e": 27034,
"s": 27023,
"text": "index.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\"> <script src=\"socket.io/socket.io.js\" defer></script> <script src=\"index.js\" defer></script></head><body> <center> <h1>GeeksforGeeks</h1> <p><input id=\"check\" type=\"checkbox\" onchange=\"changed()\"/> Click me </p> </center></body></html>",
"e": 27518,
"s": 27034,
"text": null
},
{
"code": null,
"e": 27527,
"s": 27518,
"text": "index.js"
},
{
"code": "// Socket Initializedconst socket = io('/'); function changed(){ // Getting current state of checkbox. var a = document.getElementById('check').checked; if(a) { // Emiting the event. socket.emit(\"checkedTrue\"); }} //Listening on the event.socket.on(\"acknowledged\" , ()=>{ alert(\"Action acknowledged by the server\");});",
"e": 27877,
"s": 27527,
"text": null
},
{
"code": null,
"e": 27887,
"s": 27877,
"text": "server.js"
},
{
"code": "// Importing express moduleconst express = require('express');const app = express();const server = require('http').Server(app);const io = require('socket.io')(server); // Calling the public folderapp.use(express.static('public')) // Handling get requestapp.get(\"/\" , (req,res)=>{ res.render(\"index\");}); // Socketio.on(\"connection\" , (socket)=>{ socket.on(\"checkedTrue\" , ()=>{ socket.emit(\"acknowledged\") })}) // Listening the serverserver.listen(4000 , ()=>{ console.log(\"server is running\");})",
"e": 28407,
"s": 27887,
"text": null
},
{
"code": null,
"e": 28415,
"s": 28407,
"text": "Output:"
},
{
"code": null,
"e": 28424,
"s": 28415,
"text": "sweetyty"
},
{
"code": null,
"e": 28441,
"s": 28424,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 28448,
"s": 28441,
"text": "Picked"
},
{
"code": null,
"e": 28456,
"s": 28448,
"text": "Node.js"
},
{
"code": null,
"e": 28473,
"s": 28456,
"text": "Web Technologies"
},
{
"code": null,
"e": 28571,
"s": 28473,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28580,
"s": 28571,
"text": "Comments"
},
{
"code": null,
"e": 28593,
"s": 28580,
"text": "Old Comments"
},
{
"code": null,
"e": 28650,
"s": 28593,
"text": "How to build a basic CRUD app with Node.js and ReactJS ?"
},
{
"code": null,
"e": 28689,
"s": 28650,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 28716,
"s": 28689,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 28747,
"s": 28716,
"text": "Express.js req.params Property"
},
{
"code": null,
"e": 28772,
"s": 28747,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 28828,
"s": 28772,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 28890,
"s": 28828,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28933,
"s": 28890,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28983,
"s": 28933,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
MySQL query to display a substring before a special character in a string
|
Use the LOCATE() and SUBSTRING() method for this in MySQL. Let us first create a table −
mysql> create table DemoTable
-> (
-> Title text
-> );
Query OK, 0 rows affected (0.54 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Introduction To Java');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Introduction - To MySQL');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------------------------+
| Title |
+-------------------------+
| Introduction To Java |
| Introduction - To MySQL |
+-------------------------+
2 rows in set (0.00 sec)
Following is the query to display a substring before a special character in a substring −
mysql> select distinct
-> if(LOCATE(' - ',Title)>0, SUBSTRING(Title, 1, LOCATE(' - ', Title)), Title) from DemoTable;
This will produce the following output −
+-----------------------------------------------------------------------------+
| if(LOCATE(' - ',Title)>0, SUBSTRING(Title, 1, LOCATE(' - ', Title)), Title) |
+-----------------------------------------------------------------------------+
| Introduction To Java |
| Introduction |
+-----------------------------------------------------------------------------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1151,
"s": 1062,
"text": "Use the LOCATE() and SUBSTRING() method for this in MySQL. Let us first create a table −"
},
{
"code": null,
"e": 1252,
"s": 1151,
"text": "mysql> create table DemoTable\n -> (\n -> Title text\n -> );\nQuery OK, 0 rows affected (0.54 sec)"
},
{
"code": null,
"e": 1308,
"s": 1252,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1506,
"s": 1308,
"text": "mysql> insert into DemoTable values('Introduction To Java');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable values('Introduction - To MySQL');\nQuery OK, 1 row affected (0.16 sec)"
},
{
"code": null,
"e": 1566,
"s": 1506,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1597,
"s": 1566,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1638,
"s": 1597,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1831,
"s": 1638,
"text": "+-------------------------+\n| Title |\n+-------------------------+\n| Introduction To Java |\n| Introduction - To MySQL |\n+-------------------------+\n2 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1921,
"s": 1831,
"text": "Following is the query to display a substring before a special character in a substring −"
},
{
"code": null,
"e": 2042,
"s": 1921,
"text": "mysql> select distinct\n -> if(LOCATE(' - ',Title)>0, SUBSTRING(Title, 1, LOCATE(' - ', Title)), Title) from DemoTable;"
},
{
"code": null,
"e": 2083,
"s": 2042,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2588,
"s": 2083,
"text": "+-----------------------------------------------------------------------------+\n| if(LOCATE(' - ',Title)>0, SUBSTRING(Title, 1, LOCATE(' - ', Title)), Title) |\n+-----------------------------------------------------------------------------+\n| Introduction To Java |\n| Introduction |\n+-----------------------------------------------------------------------------+\n2 rows in set (0.00 sec)"
}
] |
Solving a Reinforcement Learning Problem Using Cross-Entropy Method | by Jordi TORRES.AI | Towards Data Science
|
After a parenthesis of three posts introducing basics in Deep Learning and Pytorch, in this post we put the focus back to merge Reinforcement Learning and Deep Learning.
In a previous posts we advanced that an Agent make decisions to solve complex decision-making problems under uncertainty. For this purpouse the Agent employs a policy π, as a strategy to determine the next action a based on the current state s. From this post onwards we will explore different methods to obtain a policy that allows an Agent to make decisions.
In this post we will start with Cross-Entropy method that will help to the reader to warm-up in merging Deep Learning and Reinforcement Learning. It is an evolutionary algorithm for parameterized policy optimization that John Schulman claims works “embarrassingly well” on complex RL problems.
Cross-Entropy is considered an Evolutionary Algorithm: Some individuals are sampled from a population, and only the “elite” ones govern future generations’ characteristics.
Essentially, what the Cross-Entropy method does is take a bunch of inputs, see the outputs produced, choose the inputs that have led to the best outputs and tune the Agent till we are satisfied with the outputs we see.
Remember that a policy, denoted by π(a|s), says which action the Agent should take for every state observed. In this post, we will consider that the core of our Agent will be a neural network that produces the policy.
We refer to the methods that solve this type of problem as Policy-Based methods that train the neural network that produces the policy. In future posts, we will go in more deeply about this type of method.
In practice, the policy is usually represented as a probability distribution over actions (that the Agent can take at a given state), which makes it very similar to a classification problem presented before (in the Deep Learning post), with the amount of classes being equal to the amount of actions we can carry out. In our case the output of our neural network is an action vector that represents a probability distribution as shown visually in the following Figure:
In this case we refer to it as a stochastic policy, because it returns a probability distribution over actions rather than returning a deterministic single action.
We want a policy, a probability distribution, and we initialize it at random. Then we improve our policy by playing a few episodes and then adjusting our policy (parameter of the neural network) in a way that it is more efficient. Then repeat this process in order to our policy gradually gets better. This is the base of the Cross-Entropy method.
Since we will consider a neural network as the heart of this first Agent, we need to find some way to obtain data that we can assimilate as a training dataset, which includes input data and their respective labels.
The way we’re going to do this is considering the problem as a supervised learning problem where observed states are considered the features (input data) and the actions constitute the labels.
During the agent’s lifetime, its experience is presented as episodes. Every episode is a sequence of observations of states that the Agent has got from the Environment, actions it has issued, and rewards for these actions. The core of the Cross-Entropy method is to throw away bad episodes and train on better ones, so how we find the better ones?. Imagine that our Agent has played several such episodes. For every episode, we can calculate the return (total reward) that the Agent has claimed. Remember that an Agent tries to accumulate as much total reward as possible by interacting with the Environment.
Again, for simplicity we will use the Frozen-Lake example. To understand what’s going on, we need to look deeper at the reward structure of the Frozen-Lake Environment. We get the reward of 1.0 only when we reach the goal, and this reward says nothing about how good each episode was. Was it quick and efficient? or did we make many rounds on the lake before we randomly stepped into the final cell? We don’t know; it’s just 1.0 reward and that’s it.
Let’s imagine that we already have the Agent programmed and we use it to create 4 episodes, that we can visualize with the .render() method:
Note that due to randomness in the Environment and the way that the Agent selects actions to take, the episodes have different lenght and also shown different rewards. Obviously an episode that has a reward of 1.0 is better than one that has a reward of 0.0. What about episodes that end with the same reward?
It is clear that we can consider some episodes “better” than others, e.g. the third is shortest that the second. For this, the discount factor gamma is very helpful. We can use γ = 0,9. In this case, the discounted return will be equal to the reward r (1.0 or 0.0) obtained at the end of the episode at time step t by gamma to t.
Let’s illustrate these four episodes with a diagram where each cell represents the Agent’s step, a transition, in the episode, and the corresponding discounted return:
We can see that the discounted return for shorter episodes will be higher than for longer ones.
The core of the Cross-Entropy method is simple. Basically, it generates batches of episodes, throw away bad episodes in a batch to train the neural network of the Agent on better ones. To decide which ones to throw away, we used the 70th percentile in our example, which means that we only kept the 30% that did better than 70% of the others.
As a result, the neural network learns to repeat actions that lead to the results of neural network decisions becoming better and better as we use new batches of elite episodes. The Agent must be trained until a certain mean average reward for the batch of episodes threshold is reached.
So, a pseudocode of the method can be described by the following steps:
0. Initialize the Agent neural network model
Create a batch of episodes playing in the Environment using our current Agent model.Calculate the expected return for every episode and decide on a return boundary using a percentile of all rewards.Throw away all episodes with a return below the return boundary.Train the neural network of the Agent using episode steps, that means the transitions <s,a,r>) from the remaining “elite” episodes, using the state s as the input and issued actions a as the label.Repeat from step 1 until we become satisfied with the mean average Reward for the batch of episodes.
Create a batch of episodes playing in the Environment using our current Agent model.
Calculate the expected return for every episode and decide on a return boundary using a percentile of all rewards.
Throw away all episodes with a return below the return boundary.
Train the neural network of the Agent using episode steps, that means the transitions <s,a,r>) from the remaining “elite” episodes, using the state s as the input and issued actions a as the label.
Repeat from step 1 until we become satisfied with the mean average Reward for the batch of episodes.
A variant of the method, which we will discuss in the next post is that we can keep “elite” episodes for a longer time. I mean that the default version of the algorithm samples episodes from the Environment, train on the best ones, and threw them away. However, when the number of succesful episodes is small, the “elite” episodes can be maintained longer, keeping them for several iterations to train on them.
The Environment is the source of data from which we are going to create the dataset that will be used to train the neural network of our Agent.
The Agent will start from a random policy, where the probability of all actions is uniform, and while training, the Agent will hopefully learn from data obtained from the Environment to optimize its policy toward reaching the optimal policy.
The data that comes from the Environment are episode steps that should be expressed with tuples of the form <s,a,r> (state, action and reward) which are obtained in each time step as indicated in the following scheme:
The entire code of this post can be found on GitHub and can be run as a Colab google notebook using this link.
As we have done in other posts in this series, the code presented in this post has been inspired by the code of Maxim Lapan who has written an excellent practical book on the subject.
Let’s code it. We must first import several packages:
import numpy as npimport torchimport torch.nn as nnimport gymimport gym.spaces
We will start by using the not slippery FrozenLake Environment (in the next post we will discuss more about the slippery version):
env = gym.make(‘FrozenLake-v0’, is_slippery=False)
Our state space is discrete, which means that it’s just a number from zero to fifteen inclusive (our current position in the grid). The action space is also discrete, from zero to three.
Our neural network expects a vector of numbers. To get this, we can apply the traditional onehot encoding of discrete inputs (presented in this previous post), which means that the input to our network will have 16 numbers with zero everywhere except the index that we will encode. To ease the code, we can use the ObservationWrapper class from Gym and implement our OneHotWrapper class:
class OneHotWrapper(gym.ObservationWrapper):def __init__(self, env): super(OneHotWrapper, self).__init__(env) self.observation_space = gym.spaces.Box(0.0, 1.0, (env.observation_space.n, ), dtype=np.float32)def observation(self, observation): r = np.copy(self.observation_space.low) r[observation] = 1.0 return renv = OneHotWrapper(env)
As a summary, we have in env a not slippery Frozen-Lake Environment that we will use for obtain episodes in order to obtain data to train our Agent.
We have already advanced that our Agent is based on a neural network. Let’s see how to code this neural network and how it is used to perform the selection of actions that an Agent does.
Our model’s core is a one-hidden-layer neural network with 32 neurons using a Sigmoid activation function. There is nothing special about our neural network. We start with an arbitrary number of layers and number of neurons.
obs_size = env.observation_space.shape[0]n_actions = env.action_space.nHIDDEN_SIZE = 32net= nn.Sequential( nn.Linear(obs_size, HIDDEN_SIZE), nn.Sigmoid(), nn.Linear(HIDDEN_SIZE, n_actions))
The neural network takes a single observation from the Environment as an input vector and outputs a number for every action we can perform, a probability distribution over actions. A straightforward way to proceed would be to include softmax nonlinearity after the last layer. However, remember from a previous post that we try to avoid apply softmax to increase the numerical stability of the training process. Rather than calculating softmax and then calculating Cross-Entropy loss, in this example we use the PyTorch class nn.CrossEntropyLoss, which combines both softmax and Cross-Entropy in a single, more numerically stable expression. CrossEntropyLoss requires raw, unnormalized values from the neural network (also called logits).
Other “hyperparameters” as Loss function and the Optimizer are also set for this example using the following code:
objective = nn.CrossEntropyLoss()optimizer = optim.SGD(params=net.parameters(), lr=0.001)
This abstraction makes our Agent very simple: it needs to pass an observed state that receives from the Environment to the neural network model and perform random sampling using the probability distribution to get an action to carry out:
sm = nn.Softmax(dim=1) def select_action(state):1: state_t = torch.FloatTensor([state])2: act_probs_t = sm(net(state_t))3: act_probs = act_probs_t.data.numpy()[0]4: action = np.random.choice(len(act_probs), p=act_probs) return action
Let’s explain in detail this code:
Line 1: This functions requires that a first step transform the state to a tensor to ingest it to our neural network. At every iteration, we convert our current observation (Numpy array of 16 positions) to a PyTorch tensor and pass it to the model to obtain action probabilities. Remember that our neural network model needs tensors as a input data (to clarify the code we use the suffix _t to indicate that the variable is a tensor).
Line 2: A consequence of using nn.CrossEntropyLoss we need to remember to apply softmax every time we need to get probabilities from our neural network output.
Line 3: We need to convert the output tensor (remember that the model and softmax function return tensors) into a NumPy array. This array will have the same 2D structure as the input, with the batch dimension on axis 0, so we need to get the first batch element to obtain a 1D vector of action probabilities.
Line 4: With the probability distribution of actions, we can use it to obtain the actual action for the current step by sampling this distribution using NumPy’s function random.choice().
In the next figure we show a screenshot of the training loop indicating the general steps of the Cross-Entropy algorithm :
In order not to make this post too long, and specially because this method is introduced as a warm-up in the DRL coding, we leave for the next post the detailed explanation of this algorithm. And in this way we are able to go directly to test the model and become familiar with it before entering with details of the training process.
For now I simply propose to run the code of this loop and see the results. Just to mention that we considered a good result to have a reward in 80% of the cases. Remember that entire code of this post can be found on GitHub.
What remains now is to see if the Agent really makes good decisions. To check this, we can create a new Environment ( test_env), and check if our Agent is able to reach the Goal cell after being trained. The following code will do that:
test_env = OneHotWrapper(gym.make(‘FrozenLake-v0’, is_slippery=False))state= test_env.reset()test_env.render()is_done = Falsewhile not is_done: action = select_action(state) new_state, reward, is_done, _ = test_env.step(action) test_env.render() state = new_stateprint(“reward = “, reward)
The code is a simple loop that interact with the Environment with the .step()method until the episode finishes (is_done). Thanks to the .render() method, we can see the behavior of the Agent more visually:
If we try it several times we will see that it does it well enough.
In the next post we will describe in detail the training loop (which we have skipped in this post) as well as see how we can improve the learning of the Agent taking into account a better neural network (with more neurons or different activation functions). Also we will consider the variant of the method that keeps “elite” episodes for several iterations of the training process. See you in the following post.
The entire code of this post can be found on GitHub and can be run as a Colab google notebook using this link.
by UPC Barcelona Tech and Barcelona Supercomputing Center
A relaxed introductory series that gradually and with a practical approach introduces the reader to this exciting technology that is the real enabler of the latest disruptive advances in the field of Artificial Intelligence.
I started to write this series in May, during the period of lockdown in Barcelona. Honestly, writing these posts in my spare time helped me to #StayAtHome because of the lockdown. Thank you for reading this publication in those days; it justifies the effort I made.
Disclaimers — These posts were written during this period of lockdown in Barcelona as a personal distraction and dissemination of scientific knowledge, in case it could be of help to someone, but without the purpose of being an academic reference document in the DRL area. If the reader needs a more rigorous document, the last post in the series offers an extensive list of academic resources and books that the reader can consult. The author is aware that this series of posts may contain some errors and suffers from a revision of the English text to improve it if the purpose were an academic document. But although the author would like to improve the content in quantity and quality, his professional commitments do not leave him free time to do so. However, the author agrees to refine all those errors that readers can report as soon as he can.
|
[
{
"code": null,
"e": 341,
"s": 171,
"text": "After a parenthesis of three posts introducing basics in Deep Learning and Pytorch, in this post we put the focus back to merge Reinforcement Learning and Deep Learning."
},
{
"code": null,
"e": 702,
"s": 341,
"text": "In a previous posts we advanced that an Agent make decisions to solve complex decision-making problems under uncertainty. For this purpouse the Agent employs a policy π, as a strategy to determine the next action a based on the current state s. From this post onwards we will explore different methods to obtain a policy that allows an Agent to make decisions."
},
{
"code": null,
"e": 996,
"s": 702,
"text": "In this post we will start with Cross-Entropy method that will help to the reader to warm-up in merging Deep Learning and Reinforcement Learning. It is an evolutionary algorithm for parameterized policy optimization that John Schulman claims works “embarrassingly well” on complex RL problems."
},
{
"code": null,
"e": 1169,
"s": 996,
"text": "Cross-Entropy is considered an Evolutionary Algorithm: Some individuals are sampled from a population, and only the “elite” ones govern future generations’ characteristics."
},
{
"code": null,
"e": 1388,
"s": 1169,
"text": "Essentially, what the Cross-Entropy method does is take a bunch of inputs, see the outputs produced, choose the inputs that have led to the best outputs and tune the Agent till we are satisfied with the outputs we see."
},
{
"code": null,
"e": 1606,
"s": 1388,
"text": "Remember that a policy, denoted by π(a|s), says which action the Agent should take for every state observed. In this post, we will consider that the core of our Agent will be a neural network that produces the policy."
},
{
"code": null,
"e": 1812,
"s": 1606,
"text": "We refer to the methods that solve this type of problem as Policy-Based methods that train the neural network that produces the policy. In future posts, we will go in more deeply about this type of method."
},
{
"code": null,
"e": 2281,
"s": 1812,
"text": "In practice, the policy is usually represented as a probability distribution over actions (that the Agent can take at a given state), which makes it very similar to a classification problem presented before (in the Deep Learning post), with the amount of classes being equal to the amount of actions we can carry out. In our case the output of our neural network is an action vector that represents a probability distribution as shown visually in the following Figure:"
},
{
"code": null,
"e": 2445,
"s": 2281,
"text": "In this case we refer to it as a stochastic policy, because it returns a probability distribution over actions rather than returning a deterministic single action."
},
{
"code": null,
"e": 2793,
"s": 2445,
"text": "We want a policy, a probability distribution, and we initialize it at random. Then we improve our policy by playing a few episodes and then adjusting our policy (parameter of the neural network) in a way that it is more efficient. Then repeat this process in order to our policy gradually gets better. This is the base of the Cross-Entropy method."
},
{
"code": null,
"e": 3008,
"s": 2793,
"text": "Since we will consider a neural network as the heart of this first Agent, we need to find some way to obtain data that we can assimilate as a training dataset, which includes input data and their respective labels."
},
{
"code": null,
"e": 3201,
"s": 3008,
"text": "The way we’re going to do this is considering the problem as a supervised learning problem where observed states are considered the features (input data) and the actions constitute the labels."
},
{
"code": null,
"e": 3810,
"s": 3201,
"text": "During the agent’s lifetime, its experience is presented as episodes. Every episode is a sequence of observations of states that the Agent has got from the Environment, actions it has issued, and rewards for these actions. The core of the Cross-Entropy method is to throw away bad episodes and train on better ones, so how we find the better ones?. Imagine that our Agent has played several such episodes. For every episode, we can calculate the return (total reward) that the Agent has claimed. Remember that an Agent tries to accumulate as much total reward as possible by interacting with the Environment."
},
{
"code": null,
"e": 4261,
"s": 3810,
"text": "Again, for simplicity we will use the Frozen-Lake example. To understand what’s going on, we need to look deeper at the reward structure of the Frozen-Lake Environment. We get the reward of 1.0 only when we reach the goal, and this reward says nothing about how good each episode was. Was it quick and efficient? or did we make many rounds on the lake before we randomly stepped into the final cell? We don’t know; it’s just 1.0 reward and that’s it."
},
{
"code": null,
"e": 4402,
"s": 4261,
"text": "Let’s imagine that we already have the Agent programmed and we use it to create 4 episodes, that we can visualize with the .render() method:"
},
{
"code": null,
"e": 4712,
"s": 4402,
"text": "Note that due to randomness in the Environment and the way that the Agent selects actions to take, the episodes have different lenght and also shown different rewards. Obviously an episode that has a reward of 1.0 is better than one that has a reward of 0.0. What about episodes that end with the same reward?"
},
{
"code": null,
"e": 5042,
"s": 4712,
"text": "It is clear that we can consider some episodes “better” than others, e.g. the third is shortest that the second. For this, the discount factor gamma is very helpful. We can use γ = 0,9. In this case, the discounted return will be equal to the reward r (1.0 or 0.0) obtained at the end of the episode at time step t by gamma to t."
},
{
"code": null,
"e": 5210,
"s": 5042,
"text": "Let’s illustrate these four episodes with a diagram where each cell represents the Agent’s step, a transition, in the episode, and the corresponding discounted return:"
},
{
"code": null,
"e": 5306,
"s": 5210,
"text": "We can see that the discounted return for shorter episodes will be higher than for longer ones."
},
{
"code": null,
"e": 5649,
"s": 5306,
"text": "The core of the Cross-Entropy method is simple. Basically, it generates batches of episodes, throw away bad episodes in a batch to train the neural network of the Agent on better ones. To decide which ones to throw away, we used the 70th percentile in our example, which means that we only kept the 30% that did better than 70% of the others."
},
{
"code": null,
"e": 5937,
"s": 5649,
"text": "As a result, the neural network learns to repeat actions that lead to the results of neural network decisions becoming better and better as we use new batches of elite episodes. The Agent must be trained until a certain mean average reward for the batch of episodes threshold is reached."
},
{
"code": null,
"e": 6009,
"s": 5937,
"text": "So, a pseudocode of the method can be described by the following steps:"
},
{
"code": null,
"e": 6054,
"s": 6009,
"text": "0. Initialize the Agent neural network model"
},
{
"code": null,
"e": 6614,
"s": 6054,
"text": "Create a batch of episodes playing in the Environment using our current Agent model.Calculate the expected return for every episode and decide on a return boundary using a percentile of all rewards.Throw away all episodes with a return below the return boundary.Train the neural network of the Agent using episode steps, that means the transitions <s,a,r>) from the remaining “elite” episodes, using the state s as the input and issued actions a as the label.Repeat from step 1 until we become satisfied with the mean average Reward for the batch of episodes."
},
{
"code": null,
"e": 6699,
"s": 6614,
"text": "Create a batch of episodes playing in the Environment using our current Agent model."
},
{
"code": null,
"e": 6814,
"s": 6699,
"text": "Calculate the expected return for every episode and decide on a return boundary using a percentile of all rewards."
},
{
"code": null,
"e": 6879,
"s": 6814,
"text": "Throw away all episodes with a return below the return boundary."
},
{
"code": null,
"e": 7077,
"s": 6879,
"text": "Train the neural network of the Agent using episode steps, that means the transitions <s,a,r>) from the remaining “elite” episodes, using the state s as the input and issued actions a as the label."
},
{
"code": null,
"e": 7178,
"s": 7077,
"text": "Repeat from step 1 until we become satisfied with the mean average Reward for the batch of episodes."
},
{
"code": null,
"e": 7589,
"s": 7178,
"text": "A variant of the method, which we will discuss in the next post is that we can keep “elite” episodes for a longer time. I mean that the default version of the algorithm samples episodes from the Environment, train on the best ones, and threw them away. However, when the number of succesful episodes is small, the “elite” episodes can be maintained longer, keeping them for several iterations to train on them."
},
{
"code": null,
"e": 7733,
"s": 7589,
"text": "The Environment is the source of data from which we are going to create the dataset that will be used to train the neural network of our Agent."
},
{
"code": null,
"e": 7975,
"s": 7733,
"text": "The Agent will start from a random policy, where the probability of all actions is uniform, and while training, the Agent will hopefully learn from data obtained from the Environment to optimize its policy toward reaching the optimal policy."
},
{
"code": null,
"e": 8193,
"s": 7975,
"text": "The data that comes from the Environment are episode steps that should be expressed with tuples of the form <s,a,r> (state, action and reward) which are obtained in each time step as indicated in the following scheme:"
},
{
"code": null,
"e": 8304,
"s": 8193,
"text": "The entire code of this post can be found on GitHub and can be run as a Colab google notebook using this link."
},
{
"code": null,
"e": 8488,
"s": 8304,
"text": "As we have done in other posts in this series, the code presented in this post has been inspired by the code of Maxim Lapan who has written an excellent practical book on the subject."
},
{
"code": null,
"e": 8542,
"s": 8488,
"text": "Let’s code it. We must first import several packages:"
},
{
"code": null,
"e": 8621,
"s": 8542,
"text": "import numpy as npimport torchimport torch.nn as nnimport gymimport gym.spaces"
},
{
"code": null,
"e": 8752,
"s": 8621,
"text": "We will start by using the not slippery FrozenLake Environment (in the next post we will discuss more about the slippery version):"
},
{
"code": null,
"e": 8803,
"s": 8752,
"text": "env = gym.make(‘FrozenLake-v0’, is_slippery=False)"
},
{
"code": null,
"e": 8990,
"s": 8803,
"text": "Our state space is discrete, which means that it’s just a number from zero to fifteen inclusive (our current position in the grid). The action space is also discrete, from zero to three."
},
{
"code": null,
"e": 9378,
"s": 8990,
"text": "Our neural network expects a vector of numbers. To get this, we can apply the traditional onehot encoding of discrete inputs (presented in this previous post), which means that the input to our network will have 16 numbers with zero everywhere except the index that we will encode. To ease the code, we can use the ObservationWrapper class from Gym and implement our OneHotWrapper class:"
},
{
"code": null,
"e": 9741,
"s": 9378,
"text": "class OneHotWrapper(gym.ObservationWrapper):def __init__(self, env): super(OneHotWrapper, self).__init__(env) self.observation_space = gym.spaces.Box(0.0, 1.0, (env.observation_space.n, ), dtype=np.float32)def observation(self, observation): r = np.copy(self.observation_space.low) r[observation] = 1.0 return renv = OneHotWrapper(env)"
},
{
"code": null,
"e": 9890,
"s": 9741,
"text": "As a summary, we have in env a not slippery Frozen-Lake Environment that we will use for obtain episodes in order to obtain data to train our Agent."
},
{
"code": null,
"e": 10077,
"s": 9890,
"text": "We have already advanced that our Agent is based on a neural network. Let’s see how to code this neural network and how it is used to perform the selection of actions that an Agent does."
},
{
"code": null,
"e": 10302,
"s": 10077,
"text": "Our model’s core is a one-hidden-layer neural network with 32 neurons using a Sigmoid activation function. There is nothing special about our neural network. We start with an arbitrary number of layers and number of neurons."
},
{
"code": null,
"e": 10504,
"s": 10302,
"text": "obs_size = env.observation_space.shape[0]n_actions = env.action_space.nHIDDEN_SIZE = 32net= nn.Sequential( nn.Linear(obs_size, HIDDEN_SIZE), nn.Sigmoid(), nn.Linear(HIDDEN_SIZE, n_actions))"
},
{
"code": null,
"e": 11243,
"s": 10504,
"text": "The neural network takes a single observation from the Environment as an input vector and outputs a number for every action we can perform, a probability distribution over actions. A straightforward way to proceed would be to include softmax nonlinearity after the last layer. However, remember from a previous post that we try to avoid apply softmax to increase the numerical stability of the training process. Rather than calculating softmax and then calculating Cross-Entropy loss, in this example we use the PyTorch class nn.CrossEntropyLoss, which combines both softmax and Cross-Entropy in a single, more numerically stable expression. CrossEntropyLoss requires raw, unnormalized values from the neural network (also called logits)."
},
{
"code": null,
"e": 11358,
"s": 11243,
"text": "Other “hyperparameters” as Loss function and the Optimizer are also set for this example using the following code:"
},
{
"code": null,
"e": 11448,
"s": 11358,
"text": "objective = nn.CrossEntropyLoss()optimizer = optim.SGD(params=net.parameters(), lr=0.001)"
},
{
"code": null,
"e": 11686,
"s": 11448,
"text": "This abstraction makes our Agent very simple: it needs to pass an observed state that receives from the Environment to the neural network model and perform random sampling using the probability distribution to get an action to carry out:"
},
{
"code": null,
"e": 11952,
"s": 11686,
"text": " sm = nn.Softmax(dim=1) def select_action(state):1: state_t = torch.FloatTensor([state])2: act_probs_t = sm(net(state_t))3: act_probs = act_probs_t.data.numpy()[0]4: action = np.random.choice(len(act_probs), p=act_probs) return action"
},
{
"code": null,
"e": 11987,
"s": 11952,
"text": "Let’s explain in detail this code:"
},
{
"code": null,
"e": 12422,
"s": 11987,
"text": "Line 1: This functions requires that a first step transform the state to a tensor to ingest it to our neural network. At every iteration, we convert our current observation (Numpy array of 16 positions) to a PyTorch tensor and pass it to the model to obtain action probabilities. Remember that our neural network model needs tensors as a input data (to clarify the code we use the suffix _t to indicate that the variable is a tensor)."
},
{
"code": null,
"e": 12582,
"s": 12422,
"text": "Line 2: A consequence of using nn.CrossEntropyLoss we need to remember to apply softmax every time we need to get probabilities from our neural network output."
},
{
"code": null,
"e": 12891,
"s": 12582,
"text": "Line 3: We need to convert the output tensor (remember that the model and softmax function return tensors) into a NumPy array. This array will have the same 2D structure as the input, with the batch dimension on axis 0, so we need to get the first batch element to obtain a 1D vector of action probabilities."
},
{
"code": null,
"e": 13078,
"s": 12891,
"text": "Line 4: With the probability distribution of actions, we can use it to obtain the actual action for the current step by sampling this distribution using NumPy’s function random.choice()."
},
{
"code": null,
"e": 13201,
"s": 13078,
"text": "In the next figure we show a screenshot of the training loop indicating the general steps of the Cross-Entropy algorithm :"
},
{
"code": null,
"e": 13536,
"s": 13201,
"text": "In order not to make this post too long, and specially because this method is introduced as a warm-up in the DRL coding, we leave for the next post the detailed explanation of this algorithm. And in this way we are able to go directly to test the model and become familiar with it before entering with details of the training process."
},
{
"code": null,
"e": 13761,
"s": 13536,
"text": "For now I simply propose to run the code of this loop and see the results. Just to mention that we considered a good result to have a reward in 80% of the cases. Remember that entire code of this post can be found on GitHub."
},
{
"code": null,
"e": 13998,
"s": 13761,
"text": "What remains now is to see if the Agent really makes good decisions. To check this, we can create a new Environment ( test_env), and check if our Agent is able to reach the Goal cell after being trained. The following code will do that:"
},
{
"code": null,
"e": 14307,
"s": 13998,
"text": "test_env = OneHotWrapper(gym.make(‘FrozenLake-v0’, is_slippery=False))state= test_env.reset()test_env.render()is_done = Falsewhile not is_done: action = select_action(state) new_state, reward, is_done, _ = test_env.step(action) test_env.render() state = new_stateprint(“reward = “, reward)"
},
{
"code": null,
"e": 14513,
"s": 14307,
"text": "The code is a simple loop that interact with the Environment with the .step()method until the episode finishes (is_done). Thanks to the .render() method, we can see the behavior of the Agent more visually:"
},
{
"code": null,
"e": 14581,
"s": 14513,
"text": "If we try it several times we will see that it does it well enough."
},
{
"code": null,
"e": 14994,
"s": 14581,
"text": "In the next post we will describe in detail the training loop (which we have skipped in this post) as well as see how we can improve the learning of the Agent taking into account a better neural network (with more neurons or different activation functions). Also we will consider the variant of the method that keeps “elite” episodes for several iterations of the training process. See you in the following post."
},
{
"code": null,
"e": 15105,
"s": 14994,
"text": "The entire code of this post can be found on GitHub and can be run as a Colab google notebook using this link."
},
{
"code": null,
"e": 15163,
"s": 15105,
"text": "by UPC Barcelona Tech and Barcelona Supercomputing Center"
},
{
"code": null,
"e": 15388,
"s": 15163,
"text": "A relaxed introductory series that gradually and with a practical approach introduces the reader to this exciting technology that is the real enabler of the latest disruptive advances in the field of Artificial Intelligence."
},
{
"code": null,
"e": 15654,
"s": 15388,
"text": "I started to write this series in May, during the period of lockdown in Barcelona. Honestly, writing these posts in my spare time helped me to #StayAtHome because of the lockdown. Thank you for reading this publication in those days; it justifies the effort I made."
}
] |
ggplot2 - Marginal Plots
|
In this chapter, we shall discuss about Marginal Plots.
Marginal plots are used to assess relationship between two variables and examine their distributions. When we speak about creating marginal plots, they are nothing but scatter plots that has histograms, box plots or dot plots in the margins of respective x and y axes.
Following steps will be used to create marginal plot with R using package “ggExtra”. This package is designed to enhance the features of “ggplot2” package and includes various functions for creating successful marginal plots.
Install “ggExtra” package using following command for successful execution (if the package is not installed in your system).
> install.packages("ggExtra")
Include the required libraries in the workspace to create marginal plots.
> library(ggplot2)
> library(ggExtra)
Reading the required dataset “mpg” which we have used in previous chapters.
> data(mpg)
> head(mpg)
# A tibble: 6 x 11
manufacturer model displ year cyl trans drv cty hwy fl class
<chr> <chr> <dbl> <int> <int> <chr> <chr> <int> <int> <chr> <chr>
1 audi a4 1.8 1999 4 auto(l5) f 18 29 p compa~
2 audi a4 1.8 1999 4 manual(m5) f 21 29 p compa~
3 audi a4 2 2008 4 manual(m6) f 20 31 p compa~
4 audi a4 2 2008 4 auto(av) f 21 30 p compa~
5 audi a4 2.8 1999 6 auto(l5) f 16 26 p compa~
6 audi a4 2.8 1999 6 manual(m5) f 18 26 p compa~
>
Now let us create a simple plot using “ggplot2” which will help us understand the concept of marginal plots.
> #Plot
> g <- ggplot(mpg, aes(cty, hwy)) +
+ geom_count() +
+ geom_smooth(method="lm", se=F)
> g
Now let us create the marginal plots using ggMarginal function which helps to generate relationship between two attributes “hwy” and “cty”.
> ggMarginal(g, type = "histogram", fill="transparent")
> ggMarginal(g, type = "boxplot", fill="transparent")
The output for histogram marginal plots is mentioned below −
The output for box marginal plots is mentioned below −
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2078,
"s": 2022,
"text": "In this chapter, we shall discuss about Marginal Plots."
},
{
"code": null,
"e": 2347,
"s": 2078,
"text": "Marginal plots are used to assess relationship between two variables and examine their distributions. When we speak about creating marginal plots, they are nothing but scatter plots that has histograms, box plots or dot plots in the margins of respective x and y axes."
},
{
"code": null,
"e": 2573,
"s": 2347,
"text": "Following steps will be used to create marginal plot with R using package “ggExtra”. This package is designed to enhance the features of “ggplot2” package and includes various functions for creating successful marginal plots."
},
{
"code": null,
"e": 2698,
"s": 2573,
"text": "Install “ggExtra” package using following command for successful execution (if the package is not installed in your system)."
},
{
"code": null,
"e": 2729,
"s": 2698,
"text": "> install.packages(\"ggExtra\")\n"
},
{
"code": null,
"e": 2803,
"s": 2729,
"text": "Include the required libraries in the workspace to create marginal plots."
},
{
"code": null,
"e": 2842,
"s": 2803,
"text": "> library(ggplot2)\n> library(ggExtra)\n"
},
{
"code": null,
"e": 2918,
"s": 2842,
"text": "Reading the required dataset “mpg” which we have used in previous chapters."
},
{
"code": null,
"e": 3603,
"s": 2918,
"text": "> data(mpg)\n> head(mpg)\n# A tibble: 6 x 11\nmanufacturer model displ year cyl trans drv cty hwy fl class\n<chr> <chr> <dbl> <int> <int> <chr> <chr> <int> <int> <chr> <chr>\n1 audi a4 1.8 1999 4 auto(l5) f 18 29 p compa~\n2 audi a4 1.8 1999 4 manual(m5) f 21 29 p compa~\n3 audi a4 2 2008 4 manual(m6) f 20 31 p compa~\n4 audi a4 2 2008 4 auto(av) f 21 30 p compa~\n5 audi a4 2.8 1999 6 auto(l5) f 16 26 p compa~\n6 audi a4 2.8 1999 6 manual(m5) f 18 26 p compa~\n>\n"
},
{
"code": null,
"e": 3712,
"s": 3603,
"text": "Now let us create a simple plot using “ggplot2” which will help us understand the concept of marginal plots."
},
{
"code": null,
"e": 3817,
"s": 3712,
"text": "> #Plot\n> g <- ggplot(mpg, aes(cty, hwy)) +\n+ geom_count() +\n+ geom_smooth(method=\"lm\", se=F)\n> g\n"
},
{
"code": null,
"e": 3957,
"s": 3817,
"text": "Now let us create the marginal plots using ggMarginal function which helps to generate relationship between two attributes “hwy” and “cty”."
},
{
"code": null,
"e": 4068,
"s": 3957,
"text": "> ggMarginal(g, type = \"histogram\", fill=\"transparent\")\n> ggMarginal(g, type = \"boxplot\", fill=\"transparent\")\n"
},
{
"code": null,
"e": 4129,
"s": 4068,
"text": "The output for histogram marginal plots is mentioned below −"
},
{
"code": null,
"e": 4184,
"s": 4129,
"text": "The output for box marginal plots is mentioned below −"
},
{
"code": null,
"e": 4191,
"s": 4184,
"text": " Print"
},
{
"code": null,
"e": 4202,
"s": 4191,
"text": " Add Notes"
}
] |
C# program to check the validity of a Password
|
For validity of a password, you need to recall the concept when your create a password to signup to a website.
While creating a password, you may have seen the validation requirements on a website like a password should be strong and have −
Min 8 char and max 14 char
Min 8 char and max 14 char
One upper case
One upper case
One special char
One special char
One lower case
One lower case
No white space
No white space
Let us see how to check the conditions one by one.
if (passwd.Length < 8 || passwd.Length > 14)
return false;
if (!passwd.Any(char.IsUpper))
return false;
if (!passwd.Any(char.IsLower))
return false;
if (passwd.Contains(" "))
return false;
string specialCh = @"%!@#$%^&*()?/>.<,:;'\|}]{[_~`+=-" + "\"";
char[] specialCh = specialCh.ToCharArray();
foreach (char ch in specialChArray) {
if (passwd.Contains(ch))
return true;
}
|
[
{
"code": null,
"e": 1173,
"s": 1062,
"text": "For validity of a password, you need to recall the concept when your create a password to signup to a website."
},
{
"code": null,
"e": 1303,
"s": 1173,
"text": "While creating a password, you may have seen the validation requirements on a website like a password should be strong and have −"
},
{
"code": null,
"e": 1330,
"s": 1303,
"text": "Min 8 char and max 14 char"
},
{
"code": null,
"e": 1357,
"s": 1330,
"text": "Min 8 char and max 14 char"
},
{
"code": null,
"e": 1372,
"s": 1357,
"text": "One upper case"
},
{
"code": null,
"e": 1387,
"s": 1372,
"text": "One upper case"
},
{
"code": null,
"e": 1404,
"s": 1387,
"text": "One special char"
},
{
"code": null,
"e": 1421,
"s": 1404,
"text": "One special char"
},
{
"code": null,
"e": 1436,
"s": 1421,
"text": "One lower case"
},
{
"code": null,
"e": 1451,
"s": 1436,
"text": "One lower case"
},
{
"code": null,
"e": 1466,
"s": 1451,
"text": "No white space"
},
{
"code": null,
"e": 1481,
"s": 1466,
"text": "No white space"
},
{
"code": null,
"e": 1532,
"s": 1481,
"text": "Let us see how to check the conditions one by one."
},
{
"code": null,
"e": 1591,
"s": 1532,
"text": "if (passwd.Length < 8 || passwd.Length > 14)\nreturn false;"
},
{
"code": null,
"e": 1636,
"s": 1591,
"text": "if (!passwd.Any(char.IsUpper))\nreturn false;"
},
{
"code": null,
"e": 1681,
"s": 1636,
"text": "if (!passwd.Any(char.IsLower))\nreturn false;"
},
{
"code": null,
"e": 1721,
"s": 1681,
"text": "if (passwd.Contains(\" \"))\nreturn false;"
},
{
"code": null,
"e": 1912,
"s": 1721,
"text": "string specialCh = @\"%!@#$%^&*()?/>.<,:;'\\|}]{[_~`+=-\" + \"\\\"\";\nchar[] specialCh = specialCh.ToCharArray();\nforeach (char ch in specialChArray) {\n if (passwd.Contains(ch))\n return true;\n}"
}
] |
DateField - Django Forms - GeeksforGeeks
|
13 Feb, 2020
DateField in Django Forms is a date field, for taking input of dates from user. The default widget for this input is DateInput. It Normalizes to: A Python datetime.date object. It validates that the given value is either a datetime.date, datetime.datetime or string formatted in a particular date format.
DateField has one optional arguments:
input_formats :- A list of formats used to attempt to convert a string to a valid datetime.date object.
If no input_formats argument is provided, the default input formats are:
['%Y-%m-%d', # '2006-10-25'
'%m/%d/%Y', # '10/25/2006'
'%m/%d/%y'] # '10/25/06'
Syntax
field_name = forms.DateField(**options)
Illustration of DateField 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 ?
Enter the following code into forms.py file of geeks app.
from django import forms # creating a form class GeeksForm(forms.Form): geeks_field = forms.DateField( )
Add the geeks app to INSTALLED_APPS
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]
Now to render this form into a view we need a view and a URL mapped to that URL. Let’s create a view first in views.py of geeks app,
from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} context['form'] = GeeksForm() return render( request, "home.html", context)
Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html.
<form method = "GET"> {{ form }} <input type = "submit" value = "Submit"></form>
Finally, a URL to map to this view in urls.py
from django.urls import path # importing views from views..pyfrom .views import home_view urlpatterns = [ path('', home_view ),]
Let’s run the server and check what has actually happened, Run
Python manage.py runserver
Thus, an geeks_field DateField is created by replacing “_” with ” “. It is a field to input date from the user.
DateField is used for input of date in the database. One can input date of submission, birthdate, etc. Till now we have discussed how to implement DateField but how to use it in the view for performing the logical part. To perform some logic we would need to get the value entered into field into a python string instance.In views.py,
from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context ={} form = GeeksForm() context['form']= form if request.GET: temp = request.GET['geeks_field'] print(type(temp)) return render(request, "home.html", context)
Let’s try something other than a date in a Datefield.
So it accepts a date input only otherwise validation errors will be seen. Now let’s try entering a valid date into the field.Date data can be fetched using corresponding request dictionary. If method is GET, data would be available in request.GET and if post, request.POST correspondingly. In above example we have the value in temp which we can use for any purpose.
Core Field arguments are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument required = False to DateField will enable it to be left blank by the user. Each Field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:
NaveenArora
Django-forms
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Read a file line by line in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Reading and Writing to text files in Python
Python OOPs Concepts
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 24194,
"s": 24166,
"text": "\n13 Feb, 2020"
},
{
"code": null,
"e": 24499,
"s": 24194,
"text": "DateField in Django Forms is a date field, for taking input of dates from user. The default widget for this input is DateInput. It Normalizes to: A Python datetime.date object. It validates that the given value is either a datetime.date, datetime.datetime or string formatted in a particular date format."
},
{
"code": null,
"e": 24537,
"s": 24499,
"text": "DateField has one optional arguments:"
},
{
"code": null,
"e": 24641,
"s": 24537,
"text": "input_formats :- A list of formats used to attempt to convert a string to a valid datetime.date object."
},
{
"code": null,
"e": 24714,
"s": 24641,
"text": "If no input_formats argument is provided, the default input formats are:"
},
{
"code": null,
"e": 24813,
"s": 24714,
"text": "['%Y-%m-%d', # '2006-10-25'\n '%m/%d/%Y', # '10/25/2006'\n '%m/%d/%y'] # '10/25/06' \n"
},
{
"code": null,
"e": 24820,
"s": 24813,
"text": "Syntax"
},
{
"code": null,
"e": 24860,
"s": 24820,
"text": "field_name = forms.DateField(**options)"
},
{
"code": null,
"e": 24970,
"s": 24860,
"text": "Illustration of DateField using an Example. Consider a project named geeksforgeeks having an app named geeks."
},
{
"code": null,
"e": 25057,
"s": 24970,
"text": "Refer to the following articles to check how to create a project and an app in Django."
},
{
"code": null,
"e": 25108,
"s": 25057,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 25141,
"s": 25108,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 25199,
"s": 25141,
"text": "Enter the following code into forms.py file of geeks app."
},
{
"code": "from django import forms # creating a form class GeeksForm(forms.Form): geeks_field = forms.DateField( )",
"e": 25308,
"s": 25199,
"text": null
},
{
"code": null,
"e": 25344,
"s": 25308,
"text": "Add the geeks app to INSTALLED_APPS"
},
{
"code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]",
"e": 25582,
"s": 25344,
"text": null
},
{
"code": null,
"e": 25715,
"s": 25582,
"text": "Now to render this form into a view we need a view and a URL mapped to that URL. Let’s create a view first in views.py of geeks app,"
},
{
"code": "from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} context['form'] = GeeksForm() return render( request, \"home.html\", context)",
"e": 25927,
"s": 25715,
"text": null
},
{
"code": null,
"e": 26213,
"s": 25927,
"text": "Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html."
},
{
"code": "<form method = \"GET\"> {{ form }} <input type = \"submit\" value = \"Submit\"></form>",
"e": 26300,
"s": 26213,
"text": null
},
{
"code": null,
"e": 26346,
"s": 26300,
"text": "Finally, a URL to map to this view in urls.py"
},
{
"code": "from django.urls import path # importing views from views..pyfrom .views import home_view urlpatterns = [ path('', home_view ),]",
"e": 26480,
"s": 26346,
"text": null
},
{
"code": null,
"e": 26543,
"s": 26480,
"text": "Let’s run the server and check what has actually happened, Run"
},
{
"code": null,
"e": 26570,
"s": 26543,
"text": "Python manage.py runserver"
},
{
"code": null,
"e": 26682,
"s": 26570,
"text": "Thus, an geeks_field DateField is created by replacing “_” with ” “. It is a field to input date from the user."
},
{
"code": null,
"e": 27017,
"s": 26682,
"text": "DateField is used for input of date in the database. One can input date of submission, birthdate, etc. Till now we have discussed how to implement DateField but how to use it in the view for performing the logical part. To perform some logic we would need to get the value entered into field into a python string instance.In views.py,"
},
{
"code": "from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context ={} form = GeeksForm() context['form']= form if request.GET: temp = request.GET['geeks_field'] print(type(temp)) return render(request, \"home.html\", context)",
"e": 27326,
"s": 27017,
"text": null
},
{
"code": null,
"e": 27380,
"s": 27326,
"text": "Let’s try something other than a date in a Datefield."
},
{
"code": null,
"e": 27747,
"s": 27380,
"text": "So it accepts a date input only otherwise validation errors will be seen. Now let’s try entering a valid date into the field.Date data can be fetched using corresponding request dictionary. If method is GET, data would be available in request.GET and if post, request.POST correspondingly. In above example we have the value in temp which we can use for any purpose."
},
{
"code": null,
"e": 28174,
"s": 27747,
"text": "Core Field arguments are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument required = False to DateField will enable it to be left blank by the user. Each Field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:"
},
{
"code": null,
"e": 28186,
"s": 28174,
"text": "NaveenArora"
},
{
"code": null,
"e": 28199,
"s": 28186,
"text": "Django-forms"
},
{
"code": null,
"e": 28213,
"s": 28199,
"text": "Python Django"
},
{
"code": null,
"e": 28220,
"s": 28213,
"text": "Python"
},
{
"code": null,
"e": 28318,
"s": 28220,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28327,
"s": 28318,
"text": "Comments"
},
{
"code": null,
"e": 28340,
"s": 28327,
"text": "Old Comments"
},
{
"code": null,
"e": 28358,
"s": 28340,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28390,
"s": 28358,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28412,
"s": 28390,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28447,
"s": 28412,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28477,
"s": 28447,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28519,
"s": 28477,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28562,
"s": 28519,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28606,
"s": 28562,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28627,
"s": 28606,
"text": "Python OOPs Concepts"
}
] |
K-means clustering using Spotify song features | by Alejandra Vlerick | Towards Data Science
|
The spotify API allows us to create a simple server-side application that accesses user related data from the Spotify app. It also gives you access to information that is not available on the app, such as artist popularity, song metrics, album cover images, etc. It allows you to create, delete and modify existing playlists in a user’s account.
The goal of this project is to use a clustering algorithm to break down a large playlist into smaller ones. For this, song metrics such as ‘danceability’, ‘valence’, ‘tempo’, ‘liveness’, ‘speechiness’ are used.
Data collection using the Spotify API
Finding the ideal number of clusters
Elbow method and silhouette analysis
Feature selection
Clustering algorithm
Playlist creation and performance analysis
If you’re not already a member, get your Medium Membership here!
import spotipyfrom spotipy.oauth2 import SpotifyOAuthfrom spotipy.oauth2 import SpotifyClientCredentials
Connecting to the spotify API was pretty straightforward and the content is pretty well documented. This link will give you all the information you need for connecting and this will give you python sample code.
Go to https://developer.spotify.com/dashboard/ and click Create a Client ID or Create an App to get your “Client ID” and “Client Secret”. After that, Redirect URI must be changed to any page you decide on in the settings of your Spotify application.
scope = "user-library-read playlist-modify-private"OAuth = SpotifyOAuth( scope=scope, redirect_uri='http://localhost:8888/callback', client_id = 'client_id', client_secret = 'client_secret', username= 'username')
The variable “sp” will work as the access key to Spotify data and will allow us to use all the functions to GET and POST requests to and from spotify.
sp = spotipy.Spotify(auth_manager=OAuth)
The next step is to collect the data from my “Liked Songs” Playlist.
The API can only extract 50 songs at a time therefore we run a while loop that goes through the entire playlist in sets of 50. The function used to access my personal liked songs is current_user_saved_tracks().
offset = 0songs = []items = []ids = []while True: content = sp.current_user_saved_tracks(limit=50, offset=offset) songs += content['items'] if content['next'] is not None: offset += 100 else: break
The following step is to extract the audio features of each song by using the audio_features() function:
for i in songs: ids.append(i['track']['id'])while index < len(ids): audio_features += sp.audio_features(ids[index:index + 50]) index += 50features_list = []for features in audio_features: features_list.append([features['energy'], features['liveness'], features['tempo'],features['speechiness'], ... features['mode'], features['type'], features['uri']])df = pd.DataFrame(features_list, columns=['energy', 'liveness', 'tempo', 'speechiness', ... 'mode', 'type','uri'])
The result is a pandas dataframe that gathers the songs on the rows and their respective features on the columns. Each song is identified by its unique uri.
Just for fun, I decided to look at the distribution of the feature values across all the songs in my playlist:
I concluded very quickly that there is no strong correlation between these metrics. Songs did not follow a set pattern depending on their genre. When trying to perform clustering based of all 12 features, the results were not great... For this I decided to use a lower number of metrics and tested all the possible combinations of features that would yield the best clusters.
Before trying a clustering algorithm on all 12 features, I decided to handpick a few features for the clustering in the hope that it would yield a better cluster quality.
The first step was to normalise all the values such that they lie within [0 ; 1].
from sklearn import preprocessingx = df.values min_max_scaler = preprocessing.MinMaxScaler()x_scaled = min_max_scaler.fit_transform(x)df = pd.DataFrame(x_scaled)
The following step was to find a cluster quality metric based on a selection of a few features. The first thing I did was create a list with all the song metrics and then used the permutations() function to create a set of all possible combinations using three song features at the time.
columns = ["energy", "speechiness", "acousticness", "instrumentalness", "loudness","tempo","danceability",'valence' , "liveness", "time_signature", "key"]perm = permutations(columns, 3)output = set(map(lambda x: tuple(sorted(x)),perm))
For each permutation I computed a cluster score using the elbow method.
The elbow method is a heuristic approach used in determining the number of clusters in a data set. The method consists of plotting the explained variation as a function of the number of clusters, and picking the elbow of the curve as the number of clusters to use.
For each permutation I extracted an elbow score and an elbow value. The score tells me how good the clustering was for this permutation, the elbow value tells me the ideal number of clusters for that permutation.
model = KMeans(random_state=0)visualizer = KElbowVisualizer(model, k=(2,12), metric='silhouette', timings=False)visualizer.fit(x_scaled)score = visualizer.elbow_score_value = visualizer.elbow_value_
The result is a pandas dataframe of feature permutations and their corresponding ideal number of clusters and the quality score of these clusters.
Once the scores are calculated for each permutation, I decided to pick the ones above >0.4 and to save them in a separate dataframe.
if score>0.4: idx = df.columns mylist = idx.tolist() dict = { "features": mylist, "score": score, "elbow": value } df2 = df2.append(dict, ignore_index=True)
There were many permutations that yielded great results with scores even above >0.5.
The permutation [‘instrumentalness’, ‘speechiness’, ‘valence’] suggested creating 4 clusters and had a score of 0.504. This is the one I selected for my playlist creation.
I scaled a dataframe only containing those three metrics and then performed the clustering using the KMeans() function.
from sklearn.cluster import KMeanskmeans = KMeans(init="k-means++", n_clusters=4, random_state=15, max_iter = 500).fit(x_scaled)df1['kmeans'] = kmeans.labels_df1.columns = ['energy', 'instrumentalness', 'loudness','kmeans' ]
The result is a dataframe that contains a song per row with a label [0, 1, 2, 3] corresponding to each cluster that particular song was assigned to. The feature distribution clearly shows that energy and loudness are distributed differently across all clusters.
The 3D scatter plot gives a different perspective showing that higher values of instrumentalness were sorted into the same cluster while energy and loudness differentiated the remaining three clusters.
For more articles like this, find me on Medium here!
If you have any questions, suggestions or ideas on how to improve, please leave a comment below or get in touch through LinkedIn here.
All the code can be found on Github here. The permutations script can be found in analysis_v2.py and the clustering can be found in feature_analysis.py.
|
[
{
"code": null,
"e": 518,
"s": 172,
"text": "The spotify API allows us to create a simple server-side application that accesses user related data from the Spotify app. It also gives you access to information that is not available on the app, such as artist popularity, song metrics, album cover images, etc. It allows you to create, delete and modify existing playlists in a user’s account."
},
{
"code": null,
"e": 729,
"s": 518,
"text": "The goal of this project is to use a clustering algorithm to break down a large playlist into smaller ones. For this, song metrics such as ‘danceability’, ‘valence’, ‘tempo’, ‘liveness’, ‘speechiness’ are used."
},
{
"code": null,
"e": 767,
"s": 729,
"text": "Data collection using the Spotify API"
},
{
"code": null,
"e": 804,
"s": 767,
"text": "Finding the ideal number of clusters"
},
{
"code": null,
"e": 841,
"s": 804,
"text": "Elbow method and silhouette analysis"
},
{
"code": null,
"e": 859,
"s": 841,
"text": "Feature selection"
},
{
"code": null,
"e": 880,
"s": 859,
"text": "Clustering algorithm"
},
{
"code": null,
"e": 923,
"s": 880,
"text": "Playlist creation and performance analysis"
},
{
"code": null,
"e": 988,
"s": 923,
"text": "If you’re not already a member, get your Medium Membership here!"
},
{
"code": null,
"e": 1093,
"s": 988,
"text": "import spotipyfrom spotipy.oauth2 import SpotifyOAuthfrom spotipy.oauth2 import SpotifyClientCredentials"
},
{
"code": null,
"e": 1304,
"s": 1093,
"text": "Connecting to the spotify API was pretty straightforward and the content is pretty well documented. This link will give you all the information you need for connecting and this will give you python sample code."
},
{
"code": null,
"e": 1554,
"s": 1304,
"text": "Go to https://developer.spotify.com/dashboard/ and click Create a Client ID or Create an App to get your “Client ID” and “Client Secret”. After that, Redirect URI must be changed to any page you decide on in the settings of your Spotify application."
},
{
"code": null,
"e": 1811,
"s": 1554,
"text": "scope = \"user-library-read playlist-modify-private\"OAuth = SpotifyOAuth( scope=scope, redirect_uri='http://localhost:8888/callback', client_id = 'client_id', client_secret = 'client_secret', username= 'username')"
},
{
"code": null,
"e": 1962,
"s": 1811,
"text": "The variable “sp” will work as the access key to Spotify data and will allow us to use all the functions to GET and POST requests to and from spotify."
},
{
"code": null,
"e": 2003,
"s": 1962,
"text": "sp = spotipy.Spotify(auth_manager=OAuth)"
},
{
"code": null,
"e": 2072,
"s": 2003,
"text": "The next step is to collect the data from my “Liked Songs” Playlist."
},
{
"code": null,
"e": 2283,
"s": 2072,
"text": "The API can only extract 50 songs at a time therefore we run a while loop that goes through the entire playlist in sets of 50. The function used to access my personal liked songs is current_user_saved_tracks()."
},
{
"code": null,
"e": 2507,
"s": 2283,
"text": "offset = 0songs = []items = []ids = []while True: content = sp.current_user_saved_tracks(limit=50, offset=offset) songs += content['items'] if content['next'] is not None: offset += 100 else: break"
},
{
"code": null,
"e": 2612,
"s": 2507,
"text": "The following step is to extract the audio features of each song by using the audio_features() function:"
},
{
"code": null,
"e": 3314,
"s": 2612,
"text": "for i in songs: ids.append(i['track']['id'])while index < len(ids): audio_features += sp.audio_features(ids[index:index + 50]) index += 50features_list = []for features in audio_features: features_list.append([features['energy'], features['liveness'], features['tempo'],features['speechiness'], ... features['mode'], features['type'], features['uri']])df = pd.DataFrame(features_list, columns=['energy', 'liveness', 'tempo', 'speechiness', ... 'mode', 'type','uri'])"
},
{
"code": null,
"e": 3471,
"s": 3314,
"text": "The result is a pandas dataframe that gathers the songs on the rows and their respective features on the columns. Each song is identified by its unique uri."
},
{
"code": null,
"e": 3582,
"s": 3471,
"text": "Just for fun, I decided to look at the distribution of the feature values across all the songs in my playlist:"
},
{
"code": null,
"e": 3958,
"s": 3582,
"text": "I concluded very quickly that there is no strong correlation between these metrics. Songs did not follow a set pattern depending on their genre. When trying to perform clustering based of all 12 features, the results were not great... For this I decided to use a lower number of metrics and tested all the possible combinations of features that would yield the best clusters."
},
{
"code": null,
"e": 4129,
"s": 3958,
"text": "Before trying a clustering algorithm on all 12 features, I decided to handpick a few features for the clustering in the hope that it would yield a better cluster quality."
},
{
"code": null,
"e": 4211,
"s": 4129,
"text": "The first step was to normalise all the values such that they lie within [0 ; 1]."
},
{
"code": null,
"e": 4373,
"s": 4211,
"text": "from sklearn import preprocessingx = df.values min_max_scaler = preprocessing.MinMaxScaler()x_scaled = min_max_scaler.fit_transform(x)df = pd.DataFrame(x_scaled)"
},
{
"code": null,
"e": 4661,
"s": 4373,
"text": "The following step was to find a cluster quality metric based on a selection of a few features. The first thing I did was create a list with all the song metrics and then used the permutations() function to create a set of all possible combinations using three song features at the time."
},
{
"code": null,
"e": 4898,
"s": 4661,
"text": "columns = [\"energy\", \"speechiness\", \"acousticness\", \"instrumentalness\", \"loudness\",\"tempo\",\"danceability\",'valence' , \"liveness\", \"time_signature\", \"key\"]perm = permutations(columns, 3)output = set(map(lambda x: tuple(sorted(x)),perm))"
},
{
"code": null,
"e": 4970,
"s": 4898,
"text": "For each permutation I computed a cluster score using the elbow method."
},
{
"code": null,
"e": 5235,
"s": 4970,
"text": "The elbow method is a heuristic approach used in determining the number of clusters in a data set. The method consists of plotting the explained variation as a function of the number of clusters, and picking the elbow of the curve as the number of clusters to use."
},
{
"code": null,
"e": 5448,
"s": 5235,
"text": "For each permutation I extracted an elbow score and an elbow value. The score tells me how good the clustering was for this permutation, the elbow value tells me the ideal number of clusters for that permutation."
},
{
"code": null,
"e": 5647,
"s": 5448,
"text": "model = KMeans(random_state=0)visualizer = KElbowVisualizer(model, k=(2,12), metric='silhouette', timings=False)visualizer.fit(x_scaled)score = visualizer.elbow_score_value = visualizer.elbow_value_"
},
{
"code": null,
"e": 5794,
"s": 5647,
"text": "The result is a pandas dataframe of feature permutations and their corresponding ideal number of clusters and the quality score of these clusters."
},
{
"code": null,
"e": 5927,
"s": 5794,
"text": "Once the scores are calculated for each permutation, I decided to pick the ones above >0.4 and to save them in a separate dataframe."
},
{
"code": null,
"e": 6120,
"s": 5927,
"text": "if score>0.4: idx = df.columns mylist = idx.tolist() dict = { \"features\": mylist, \"score\": score, \"elbow\": value } df2 = df2.append(dict, ignore_index=True)"
},
{
"code": null,
"e": 6205,
"s": 6120,
"text": "There were many permutations that yielded great results with scores even above >0.5."
},
{
"code": null,
"e": 6377,
"s": 6205,
"text": "The permutation [‘instrumentalness’, ‘speechiness’, ‘valence’] suggested creating 4 clusters and had a score of 0.504. This is the one I selected for my playlist creation."
},
{
"code": null,
"e": 6497,
"s": 6377,
"text": "I scaled a dataframe only containing those three metrics and then performed the clustering using the KMeans() function."
},
{
"code": null,
"e": 6767,
"s": 6497,
"text": "from sklearn.cluster import KMeanskmeans = KMeans(init=\"k-means++\", n_clusters=4, random_state=15, max_iter = 500).fit(x_scaled)df1['kmeans'] = kmeans.labels_df1.columns = ['energy', 'instrumentalness', 'loudness','kmeans' ]"
},
{
"code": null,
"e": 7029,
"s": 6767,
"text": "The result is a dataframe that contains a song per row with a label [0, 1, 2, 3] corresponding to each cluster that particular song was assigned to. The feature distribution clearly shows that energy and loudness are distributed differently across all clusters."
},
{
"code": null,
"e": 7231,
"s": 7029,
"text": "The 3D scatter plot gives a different perspective showing that higher values of instrumentalness were sorted into the same cluster while energy and loudness differentiated the remaining three clusters."
},
{
"code": null,
"e": 7284,
"s": 7231,
"text": "For more articles like this, find me on Medium here!"
},
{
"code": null,
"e": 7419,
"s": 7284,
"text": "If you have any questions, suggestions or ideas on how to improve, please leave a comment below or get in touch through LinkedIn here."
}
] |
How to Teach Your Panda SQL in 10 Minutes | by Andrew Cole | Towards Data Science
|
Managing your data in a comprehensible and organized fashion is an absolute essential skill for any data scientist or analyst. Pandas DataFrames allow for clean views and operations on very large datasets, while it also is perhaps one of the most widely used Python packages. SQL is perhaps an even more widely applicable tool used for database management and for grabbing data directly from several data tables within a database schema.
Any time that data is being captured, organized, or operated on, there are normally large amounts of criterion which much be accounted for. Pandas typically requires more steps, utilizing various package methods and functions to clean the data in a multi-step process. SQL queries require a bit more big picture thinking, as constructed queries grab data and aggregate it according to criterion all in one step.
As someone who started with Python and then made my way over to SQL, I tend to lean towards using Pandas when cleaning data, but integrating SQL queries into my data cleaning process has helped alleviate several nuances from my data-working toolbox. Let’s take a look at integrating queries into your Pandas DataFrames.
Within the Jupyter Notebook environment, my preferred package for SQL querying is ‘sqlite3’. Let’s import the necessary libraries for data cleaning with both pandas and SQL:
import Pandas as pdimport sqlite3from pandasql import sqldf
If your system does not have pandasql already installed, you must do so by installing via terminal:
pip install pandasql
Pandas does already support a very basic query option. Normally we must slice and index through a pandas DataFrame, but we can easily get the same results with a simple query.
Let’s start by using traditional slicing syntax:
df2 = df1[df1[(df1[df1[‘Column1'] != df1['Column2']]) OR (df1['Column1'] == 'X')]]
Note how this query is pretty complex because it requires multiple layers of slicing and a seemingly infinite number of brackets.
This can easily be simplified using a ‘.query()’ method:
df2 = df.query("Column1 != Column2 | Column1 = 'X'")
Note how we condensed the necessary syntax significantly and can now clearly understand what criteria we are trying to query. Also, note the use of ‘|’. It is important to note that when writing query syntax we can substitute ‘|’ for ‘OR’ while using ‘&’ for ‘AND’.Syntax
The above query was pretty straightforward as there were only two conditions which we were querying on. In real database management, there will be tons of criteria, filled with aggregate functions, table joins, and subqueries. These can get a little messy to follow if we just use the .query() method, so we will instead create a function to run our queries in a more organized manner.
We begin by creating a lambda function which will pass in global variables to your query object so that we don’t have to do this every single time we run a query.
pysqldf = lambda q: sqldf(q, globals())
This function takes a query, q (which we will write at a later time), as well as a general globals() argument to expedite the query process and save computational expenses.
Now all we have to do is write the actual query we want to use:
q = SELECT c.Name, c.Age, c.Address, o.Income, c.Height FROM customers c JOIN occupation o USING(CustomerId)
|
[
{
"code": null,
"e": 609,
"s": 171,
"text": "Managing your data in a comprehensible and organized fashion is an absolute essential skill for any data scientist or analyst. Pandas DataFrames allow for clean views and operations on very large datasets, while it also is perhaps one of the most widely used Python packages. SQL is perhaps an even more widely applicable tool used for database management and for grabbing data directly from several data tables within a database schema."
},
{
"code": null,
"e": 1021,
"s": 609,
"text": "Any time that data is being captured, organized, or operated on, there are normally large amounts of criterion which much be accounted for. Pandas typically requires more steps, utilizing various package methods and functions to clean the data in a multi-step process. SQL queries require a bit more big picture thinking, as constructed queries grab data and aggregate it according to criterion all in one step."
},
{
"code": null,
"e": 1341,
"s": 1021,
"text": "As someone who started with Python and then made my way over to SQL, I tend to lean towards using Pandas when cleaning data, but integrating SQL queries into my data cleaning process has helped alleviate several nuances from my data-working toolbox. Let’s take a look at integrating queries into your Pandas DataFrames."
},
{
"code": null,
"e": 1515,
"s": 1341,
"text": "Within the Jupyter Notebook environment, my preferred package for SQL querying is ‘sqlite3’. Let’s import the necessary libraries for data cleaning with both pandas and SQL:"
},
{
"code": null,
"e": 1575,
"s": 1515,
"text": "import Pandas as pdimport sqlite3from pandasql import sqldf"
},
{
"code": null,
"e": 1675,
"s": 1575,
"text": "If your system does not have pandasql already installed, you must do so by installing via terminal:"
},
{
"code": null,
"e": 1696,
"s": 1675,
"text": "pip install pandasql"
},
{
"code": null,
"e": 1872,
"s": 1696,
"text": "Pandas does already support a very basic query option. Normally we must slice and index through a pandas DataFrame, but we can easily get the same results with a simple query."
},
{
"code": null,
"e": 1921,
"s": 1872,
"text": "Let’s start by using traditional slicing syntax:"
},
{
"code": null,
"e": 2004,
"s": 1921,
"text": "df2 = df1[df1[(df1[df1[‘Column1'] != df1['Column2']]) OR (df1['Column1'] == 'X')]]"
},
{
"code": null,
"e": 2134,
"s": 2004,
"text": "Note how this query is pretty complex because it requires multiple layers of slicing and a seemingly infinite number of brackets."
},
{
"code": null,
"e": 2191,
"s": 2134,
"text": "This can easily be simplified using a ‘.query()’ method:"
},
{
"code": null,
"e": 2244,
"s": 2191,
"text": "df2 = df.query(\"Column1 != Column2 | Column1 = 'X'\")"
},
{
"code": null,
"e": 2516,
"s": 2244,
"text": "Note how we condensed the necessary syntax significantly and can now clearly understand what criteria we are trying to query. Also, note the use of ‘|’. It is important to note that when writing query syntax we can substitute ‘|’ for ‘OR’ while using ‘&’ for ‘AND’.Syntax"
},
{
"code": null,
"e": 2902,
"s": 2516,
"text": "The above query was pretty straightforward as there were only two conditions which we were querying on. In real database management, there will be tons of criteria, filled with aggregate functions, table joins, and subqueries. These can get a little messy to follow if we just use the .query() method, so we will instead create a function to run our queries in a more organized manner."
},
{
"code": null,
"e": 3065,
"s": 2902,
"text": "We begin by creating a lambda function which will pass in global variables to your query object so that we don’t have to do this every single time we run a query."
},
{
"code": null,
"e": 3105,
"s": 3065,
"text": "pysqldf = lambda q: sqldf(q, globals())"
},
{
"code": null,
"e": 3278,
"s": 3105,
"text": "This function takes a query, q (which we will write at a later time), as well as a general globals() argument to expedite the query process and save computational expenses."
},
{
"code": null,
"e": 3342,
"s": 3278,
"text": "Now all we have to do is write the actual query we want to use:"
}
] |
Descendant Selectors in CSS
|
The CSS element selector is used to select the descendant of first element with element name matching the second selector.
The syntax for CSS descendant selector is as follows −
element element {
/*declarations*/
}
The following examples illustrate CSS descendant selector −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
div {
float: right;
margin: 25px;
padding: 5px;
width: 80px;
height: 80px;
border: solid aqua;
}
div div {
border-color: blue;
border-radius: 50%;
}
div div div {
border-color: orange;
border-radius: unset;
}
</style>
</head>
<body>
<div>
<div>
<div>
</div>
</div>
</div>
</body>
</html>
This gives the following output −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
li li {
background-color: lightsteelblue;
}
</style>
</head>
<body>
<ol>
<li></li>
<ul>
<li>
<ul>
<li></li>
</ul>
</li>
</ul>
<li></li>
</ol>
</body>
</html>
This gives the following output −
|
[
{
"code": null,
"e": 1185,
"s": 1062,
"text": "The CSS element selector is used to select the descendant of first element with element name matching the second selector."
},
{
"code": null,
"e": 1240,
"s": 1185,
"text": "The syntax for CSS descendant selector is as follows −"
},
{
"code": null,
"e": 1280,
"s": 1240,
"text": "element element {\n /*declarations*/\n}"
},
{
"code": null,
"e": 1340,
"s": 1280,
"text": "The following examples illustrate CSS descendant selector −"
},
{
"code": null,
"e": 1351,
"s": 1340,
"text": " Live Demo"
},
{
"code": null,
"e": 1707,
"s": 1351,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\ndiv {\n float: right;\n margin: 25px;\n padding: 5px;\n width: 80px;\n height: 80px;\n border: solid aqua;\n}\ndiv div {\n border-color: blue;\n border-radius: 50%;\n}\ndiv div div {\n border-color: orange;\n border-radius: unset;\n}\n</style>\n</head>\n<body>\n<div>\n<div>\n<div>\n</div>\n</div>\n</div>\n</body>\n</html>"
},
{
"code": null,
"e": 1741,
"s": 1707,
"text": "This gives the following output −"
},
{
"code": null,
"e": 1752,
"s": 1741,
"text": " Live Demo"
},
{
"code": null,
"e": 1951,
"s": 1752,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nli li {\n background-color: lightsteelblue;\n}\n</style>\n</head>\n<body>\n<ol>\n<li></li>\n<ul>\n<li>\n<ul>\n<li></li>\n</ul>\n</li>\n</ul>\n<li></li>\n</ol>\n</body>\n</html>"
},
{
"code": null,
"e": 1985,
"s": 1951,
"text": "This gives the following output −"
}
] |
A One-Bit Sliding Window Protocol
|
Sliding window protocols are data link layer protocols for reliable and sequential delivery of data frames. The sliding window is also used in Transmission Control Protocol. In these protocols, the sender has a buffer called the sending window and the receiver has buffer called the receiving window.
In one – bit sliding window protocol, the size of the window is 1. So the sender transmits a frame, waits for its acknowledgment, then transmits the next frame. Thus it uses the concept of stop and waits for the protocol. This protocol provides for full – duplex communications. Hence, the acknowledgment is attached along with the next data frame to be sent by piggybacking.
The data frames to be transmitted additionally have an acknowledgment field, ack field that is of a few bits length. The ack field contains the sequence number of the last frame received without error. If this sequence number matches with the sequence number of the frame to be sent, then it is inferred that there is no error and the frame is transmitted. Otherwise, it is inferred that there is an error in the frame and the previous frame is retransmitted.
Since this is a bi-directional protocol, the same algorithm applies to both the communicating parties.
begin
frame s, r; //s and r denotes frames to be sent and received
SeqNo = 0; // Initialise sequence number of outbound frame
RSeqNo = 0; // Initialise sequence number of expected frame
while (true) //check repeatedly
do
Wait_For_Event(); //wait for availability of packet
if ( Event(Request_For_Transfer) AND canSend) then
Get_Data_From_Network_Layer();
s = Make_Frame(SeqNo);
Store_Copy_Frame(s);
Start_Timer(s);
SeqNo = SeqNo + 1;
end if;
Wait_For_Event(); //wait for arrival of frame
if ( Event(Frame_Arrival) then
r = Receive_Frame_From_Physical_Layer();
if ( r.SeqNo = RSeqNo ) then
Extract_Data(r);
Deliver_Data_To_Network_Layer(r);
Stop_Timer(r);
RSeqNo = RSeqNo + 1;
end if
end if
s.ack = r.SeqNo;
Send_Frame_To_Physical_Layer(s);
Start_Timer(s);
SeqNo = SeqNo + 1;
end while
end
The following diagram depicts a scenario with sequence numbers 0, 1, 2, 3, 0, 1, 2 and so on. It depicts the sliding windows in the sending and the receiving stations during frame transmission.
|
[
{
"code": null,
"e": 1363,
"s": 1062,
"text": "Sliding window protocols are data link layer protocols for reliable and sequential delivery of data frames. The sliding window is also used in Transmission Control Protocol. In these protocols, the sender has a buffer called the sending window and the receiver has buffer called the receiving window."
},
{
"code": null,
"e": 1739,
"s": 1363,
"text": "In one – bit sliding window protocol, the size of the window is 1. So the sender transmits a frame, waits for its acknowledgment, then transmits the next frame. Thus it uses the concept of stop and waits for the protocol. This protocol provides for full – duplex communications. Hence, the acknowledgment is attached along with the next data frame to be sent by piggybacking."
},
{
"code": null,
"e": 2199,
"s": 1739,
"text": "The data frames to be transmitted additionally have an acknowledgment field, ack field that is of a few bits length. The ack field contains the sequence number of the last frame received without error. If this sequence number matches with the sequence number of the frame to be sent, then it is inferred that there is no error and the frame is transmitted. Otherwise, it is inferred that there is an error in the frame and the previous frame is retransmitted."
},
{
"code": null,
"e": 2302,
"s": 2199,
"text": "Since this is a bi-directional protocol, the same algorithm applies to both the communicating parties."
},
{
"code": null,
"e": 3291,
"s": 2302,
"text": "begin\n frame s, r; //s and r denotes frames to be sent and received\n SeqNo = 0; // Initialise sequence number of outbound frame \n RSeqNo = 0; // Initialise sequence number of expected frame\n while (true) //check repeatedly\n do\n Wait_For_Event(); //wait for availability of packet\n if ( Event(Request_For_Transfer) AND canSend) then\n Get_Data_From_Network_Layer();\n s = Make_Frame(SeqNo);\n Store_Copy_Frame(s);\n Start_Timer(s);\n SeqNo = SeqNo + 1;\n end if;\n Wait_For_Event(); //wait for arrival of frame\n if ( Event(Frame_Arrival) then\n r = Receive_Frame_From_Physical_Layer();\n if ( r.SeqNo = RSeqNo ) then\n Extract_Data(r);\n Deliver_Data_To_Network_Layer(r);\n Stop_Timer(r);\n RSeqNo = RSeqNo + 1;\n end if\n end if\n s.ack = r.SeqNo;\n Send_Frame_To_Physical_Layer(s);\n Start_Timer(s);\n SeqNo = SeqNo + 1;\n end while\nend"
},
{
"code": null,
"e": 3485,
"s": 3291,
"text": "The following diagram depicts a scenario with sequence numbers 0, 1, 2, 3, 0, 1, 2 and so on. It depicts the sliding windows in the sending and the receiving stations during frame transmission."
}
] |
Feature detection and matching with OpenCV-Python - GeeksforGeeks
|
28 Nov, 2021
In this article, we are going to see about feature detection in computer vision with OpenCV in Python. Feature detection is the process of checking the important features of the image in this case features of the image can be edges, corners, ridges, and blobs in the images.
In OpenCV, there are a number of methods to detect the features of the image and each technique has its own perks and flaws.
Note: The images we give into these algorithms should be in black and white. This helps the algorithms to focus on the features more.
Image in use:
Haris corner detection is a method in which we can detect the corners of the image by sliding a slider box all over the image by finding the corners and it will apply a threshold and the corners will be marked in the image. This algorithm is mainly used to detect the corners of the image.
Syntax:
cv2.cornerHarris(image, dest, blockSize, kSize, freeParameter, borderType)
Parameters:
Image – The source image to detect the features
Dest – Variable to store the output image
Block size – Neighborhood size
Ksize – Aperture parameter
Border type: The pixel revealing type.
Example: Feature detection and matching using OpenCV
Python3
# Importing the librariesimport cv2import numpy as np # Reading the image and converting the image to B/Wimage = cv2.imread('book.png')gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)gray_image = np.float32(gray_image) # Applying the functiondst = cv2.cornerHarris(gray_image, blockSize=2, ksize=3, k=0.04) # dilate to mark the cornersdst = cv2.dilate(dst, None)image[dst > 0.01 * dst.max()] = [0, 255, 0] cv2.imshow('haris_corner', image)cv2.waitKey()
Output:
Shi and Tomasi came up with a different corner detection algorithm which is mostly similar to the Haris corner detection algorithm in which the only difference will be the kernel value in which we can find only the n strongest corners of the image. This can greatly help while we need only the limited and very important features of the image.
Syntax:
cv2.goodFeaturesToTrack(image, maxc, Quality, maxD)
Parameters:
image – The source image we need to extract the features.
maxc – Maximum number of corners we want [Negative values gives all the corners]
Quality – Quality level parameter (preferred value=0.01)
maxD – Maximum distance (preferred value=10)
Example: Feature detection and matching using OpenCV
Python3
# Importing the librariesimport cv2import numpy as np # Reading the image and converting into B?Wimage = cv2.imread("book.png")gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Applying the functioncorners = cv2.goodFeaturesToTrack( gray_image, maxCorners=50, qualityLevel=0.02, minDistance=20)corners = np.float32(corners) for item in corners: x, y = item[0] x = int(x) y = int(y) cv2.circle(image, (x, y), 6, (0, 255, 0), -1) # Showing the imagecv2.imshow('good_features', image)cv2.waitKey()
Output:
While Haris and shi-Tomasi are the algorithms to detect the corners of the image. SIFT is one of the important algorithms that detect objects irrelevant to the scale and rotation of the image and the reference. This helps a lot while we are comparing the real-world objects to an image though it is independent of the angle and scale of the image. This method will return the key points of the images which we need to mark in the image.
Syntax:
sift = cv2.xfeatures2d.SIFT_create()
kp, des = sift.detectAndCompute(gray_img, None)
This function returns key points which we later use with drawkeypoints() method to draw the keypoints.
Note: The circles in the image represent the keypoints, where the size of the circle directly represents the strength of the key points.
Example: Feature detection and matching using OpenCV
Python3
# Importing the librariesimport cv2 # Reading the image and converting into B/Wimage = cv2.imread('book.jpg')gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Applying the functionsift = cv2.xfeatures2d.SIFT_create()kp, des = sift.detectAndCompute(gray_image, None) # Applying the functionkp_image = cv2.drawKeypoints(image, kp, None, color=( 0, 255, 0), flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)cv2.imshow('SIFT', kp_image)cv2.waitKey()
Output:
SURF is fast when compared to SIFT but not as fast to use with real-time devices like mobile phones and surveillance cameras. So FAST algorithm was introduced with a very fast computing time. However FAST gives us only the key points and we may need to compute descriptors with other algorithms like SIFT and SURF. With a Fast algorithm, we can detect corners and also blobs.
Syntax:
fast = cv2.FastFeatureDetector_create()
fast.setNonmaxSuppression(False)
kp = fast.detect(gray_img, None)
Example: Feature detection and matching using OpenCV
Python3
# Importing the librariesimport cv2 # Reading the image and converting into B/Wimage = cv2.imread('book.png')gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Applying the functionfast = cv2.FastFeatureDetector_create()fast.setNonmaxSuppression(False) # Drawing the keypointskp = fast.detect(gray_image, None)kp_image = cv2.drawKeypoints(image, kp, None, color=(0, 255, 0)) cv2.imshow('FAST', kp_image)cv2.waitKey()
Output:
ORB is a very effective way of detecting the features of the image when compared to SIFT and SURF. ORB is programmed to find fewer features in the image when compared to the SIFT and SURF algorithm because it detects the very important features in less time than them yet this algorithm is considered as a very effective algorithm when compared to other detecting algorithms.
Syntax:
orb = cv2.ORB_create(nfeatures=2000)
kp, des = orb.detectAndCompute(gray_img, None)
Example: Feature detection and matching using OpenCV
Python3
# Importing the librariesimport cv2 # Reading the image and converting into B/Wimage = cv2.imread('book.png')gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Applying the functionorb = cv2.ORB_create(nfeatures=2000)kp, des = orb.detectAndCompute(gray_image, None) # Drawing the keypointskp_image = cv2.drawKeypoints(image, kp, None, color=(0, 255, 0), flags=0) cv2.imshow('ORB', kp_image)cv2.waitKey()
Output:
Picked
Python-OpenCV
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 Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
Defaultdict in Python
|
[
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 25830,
"s": 25555,
"text": "In this article, we are going to see about feature detection in computer vision with OpenCV in Python. Feature detection is the process of checking the important features of the image in this case features of the image can be edges, corners, ridges, and blobs in the images."
},
{
"code": null,
"e": 25955,
"s": 25830,
"text": "In OpenCV, there are a number of methods to detect the features of the image and each technique has its own perks and flaws."
},
{
"code": null,
"e": 26089,
"s": 25955,
"text": "Note: The images we give into these algorithms should be in black and white. This helps the algorithms to focus on the features more."
},
{
"code": null,
"e": 26104,
"s": 26089,
"text": "Image in use: "
},
{
"code": null,
"e": 26394,
"s": 26104,
"text": "Haris corner detection is a method in which we can detect the corners of the image by sliding a slider box all over the image by finding the corners and it will apply a threshold and the corners will be marked in the image. This algorithm is mainly used to detect the corners of the image."
},
{
"code": null,
"e": 26403,
"s": 26394,
"text": "Syntax: "
},
{
"code": null,
"e": 26478,
"s": 26403,
"text": "cv2.cornerHarris(image, dest, blockSize, kSize, freeParameter, borderType)"
},
{
"code": null,
"e": 26492,
"s": 26478,
"text": "Parameters: "
},
{
"code": null,
"e": 26540,
"s": 26492,
"text": "Image – The source image to detect the features"
},
{
"code": null,
"e": 26582,
"s": 26540,
"text": "Dest – Variable to store the output image"
},
{
"code": null,
"e": 26613,
"s": 26582,
"text": "Block size – Neighborhood size"
},
{
"code": null,
"e": 26640,
"s": 26613,
"text": "Ksize – Aperture parameter"
},
{
"code": null,
"e": 26679,
"s": 26640,
"text": "Border type: The pixel revealing type."
},
{
"code": null,
"e": 26732,
"s": 26679,
"text": "Example: Feature detection and matching using OpenCV"
},
{
"code": null,
"e": 26740,
"s": 26732,
"text": "Python3"
},
{
"code": "# Importing the librariesimport cv2import numpy as np # Reading the image and converting the image to B/Wimage = cv2.imread('book.png')gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)gray_image = np.float32(gray_image) # Applying the functiondst = cv2.cornerHarris(gray_image, blockSize=2, ksize=3, k=0.04) # dilate to mark the cornersdst = cv2.dilate(dst, None)image[dst > 0.01 * dst.max()] = [0, 255, 0] cv2.imshow('haris_corner', image)cv2.waitKey()",
"e": 27201,
"s": 26740,
"text": null
},
{
"code": null,
"e": 27209,
"s": 27201,
"text": "Output:"
},
{
"code": null,
"e": 27553,
"s": 27209,
"text": "Shi and Tomasi came up with a different corner detection algorithm which is mostly similar to the Haris corner detection algorithm in which the only difference will be the kernel value in which we can find only the n strongest corners of the image. This can greatly help while we need only the limited and very important features of the image."
},
{
"code": null,
"e": 27562,
"s": 27553,
"text": "Syntax: "
},
{
"code": null,
"e": 27614,
"s": 27562,
"text": "cv2.goodFeaturesToTrack(image, maxc, Quality, maxD)"
},
{
"code": null,
"e": 27626,
"s": 27614,
"text": "Parameters:"
},
{
"code": null,
"e": 27684,
"s": 27626,
"text": "image – The source image we need to extract the features."
},
{
"code": null,
"e": 27765,
"s": 27684,
"text": "maxc – Maximum number of corners we want [Negative values gives all the corners]"
},
{
"code": null,
"e": 27822,
"s": 27765,
"text": "Quality – Quality level parameter (preferred value=0.01)"
},
{
"code": null,
"e": 27867,
"s": 27822,
"text": "maxD – Maximum distance (preferred value=10)"
},
{
"code": null,
"e": 27920,
"s": 27867,
"text": "Example: Feature detection and matching using OpenCV"
},
{
"code": null,
"e": 27928,
"s": 27920,
"text": "Python3"
},
{
"code": "# Importing the librariesimport cv2import numpy as np # Reading the image and converting into B?Wimage = cv2.imread(\"book.png\")gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Applying the functioncorners = cv2.goodFeaturesToTrack( gray_image, maxCorners=50, qualityLevel=0.02, minDistance=20)corners = np.float32(corners) for item in corners: x, y = item[0] x = int(x) y = int(y) cv2.circle(image, (x, y), 6, (0, 255, 0), -1) # Showing the imagecv2.imshow('good_features', image)cv2.waitKey()",
"e": 28447,
"s": 27928,
"text": null
},
{
"code": null,
"e": 28455,
"s": 28447,
"text": "Output:"
},
{
"code": null,
"e": 28892,
"s": 28455,
"text": "While Haris and shi-Tomasi are the algorithms to detect the corners of the image. SIFT is one of the important algorithms that detect objects irrelevant to the scale and rotation of the image and the reference. This helps a lot while we are comparing the real-world objects to an image though it is independent of the angle and scale of the image. This method will return the key points of the images which we need to mark in the image."
},
{
"code": null,
"e": 28902,
"s": 28892,
"text": "Syntax: "
},
{
"code": null,
"e": 28939,
"s": 28902,
"text": "sift = cv2.xfeatures2d.SIFT_create()"
},
{
"code": null,
"e": 28987,
"s": 28939,
"text": "kp, des = sift.detectAndCompute(gray_img, None)"
},
{
"code": null,
"e": 29090,
"s": 28987,
"text": "This function returns key points which we later use with drawkeypoints() method to draw the keypoints."
},
{
"code": null,
"e": 29227,
"s": 29090,
"text": "Note: The circles in the image represent the keypoints, where the size of the circle directly represents the strength of the key points."
},
{
"code": null,
"e": 29280,
"s": 29227,
"text": "Example: Feature detection and matching using OpenCV"
},
{
"code": null,
"e": 29288,
"s": 29280,
"text": "Python3"
},
{
"code": "# Importing the librariesimport cv2 # Reading the image and converting into B/Wimage = cv2.imread('book.jpg')gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Applying the functionsift = cv2.xfeatures2d.SIFT_create()kp, des = sift.detectAndCompute(gray_image, None) # Applying the functionkp_image = cv2.drawKeypoints(image, kp, None, color=( 0, 255, 0), flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)cv2.imshow('SIFT', kp_image)cv2.waitKey()",
"e": 29747,
"s": 29288,
"text": null
},
{
"code": null,
"e": 29755,
"s": 29747,
"text": "Output:"
},
{
"code": null,
"e": 30131,
"s": 29755,
"text": "SURF is fast when compared to SIFT but not as fast to use with real-time devices like mobile phones and surveillance cameras. So FAST algorithm was introduced with a very fast computing time. However FAST gives us only the key points and we may need to compute descriptors with other algorithms like SIFT and SURF. With a Fast algorithm, we can detect corners and also blobs."
},
{
"code": null,
"e": 30139,
"s": 30131,
"text": "Syntax:"
},
{
"code": null,
"e": 30179,
"s": 30139,
"text": "fast = cv2.FastFeatureDetector_create()"
},
{
"code": null,
"e": 30212,
"s": 30179,
"text": "fast.setNonmaxSuppression(False)"
},
{
"code": null,
"e": 30245,
"s": 30212,
"text": "kp = fast.detect(gray_img, None)"
},
{
"code": null,
"e": 30298,
"s": 30245,
"text": "Example: Feature detection and matching using OpenCV"
},
{
"code": null,
"e": 30306,
"s": 30298,
"text": "Python3"
},
{
"code": "# Importing the librariesimport cv2 # Reading the image and converting into B/Wimage = cv2.imread('book.png')gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Applying the functionfast = cv2.FastFeatureDetector_create()fast.setNonmaxSuppression(False) # Drawing the keypointskp = fast.detect(gray_image, None)kp_image = cv2.drawKeypoints(image, kp, None, color=(0, 255, 0)) cv2.imshow('FAST', kp_image)cv2.waitKey()",
"e": 30735,
"s": 30306,
"text": null
},
{
"code": null,
"e": 30743,
"s": 30735,
"text": "Output:"
},
{
"code": null,
"e": 31119,
"s": 30743,
"text": "ORB is a very effective way of detecting the features of the image when compared to SIFT and SURF. ORB is programmed to find fewer features in the image when compared to the SIFT and SURF algorithm because it detects the very important features in less time than them yet this algorithm is considered as a very effective algorithm when compared to other detecting algorithms."
},
{
"code": null,
"e": 31129,
"s": 31119,
"text": "Syntax: "
},
{
"code": null,
"e": 31166,
"s": 31129,
"text": "orb = cv2.ORB_create(nfeatures=2000)"
},
{
"code": null,
"e": 31213,
"s": 31166,
"text": "kp, des = orb.detectAndCompute(gray_img, None)"
},
{
"code": null,
"e": 31266,
"s": 31213,
"text": "Example: Feature detection and matching using OpenCV"
},
{
"code": null,
"e": 31274,
"s": 31266,
"text": "Python3"
},
{
"code": "# Importing the librariesimport cv2 # Reading the image and converting into B/Wimage = cv2.imread('book.png')gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Applying the functionorb = cv2.ORB_create(nfeatures=2000)kp, des = orb.detectAndCompute(gray_image, None) # Drawing the keypointskp_image = cv2.drawKeypoints(image, kp, None, color=(0, 255, 0), flags=0) cv2.imshow('ORB', kp_image)cv2.waitKey()",
"e": 31686,
"s": 31274,
"text": null
},
{
"code": null,
"e": 31694,
"s": 31686,
"text": "Output:"
},
{
"code": null,
"e": 31701,
"s": 31694,
"text": "Picked"
},
{
"code": null,
"e": 31715,
"s": 31701,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 31722,
"s": 31715,
"text": "Python"
},
{
"code": null,
"e": 31820,
"s": 31722,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31852,
"s": 31820,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31894,
"s": 31852,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 31936,
"s": 31894,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 31992,
"s": 31936,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 32019,
"s": 31992,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 32050,
"s": 32019,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 32079,
"s": 32050,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 32118,
"s": 32079,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 32154,
"s": 32118,
"text": "Python | Pandas dataframe.groupby()"
}
] |
GATE | GATE-CS-2009 | Question 60 - GeeksforGeeks
|
28 Jun, 2021
Consider a system with 4 types of resources R1 (3 units), R2 (2 units), R3 (3 units), R4 (2 units). A non-preemptive resource allocation policy is used. At any given instance, a request is not entertained if it cannot be completely satisfied. Three processes P1, P2, P3 request the sources as follows if executed independently.
Process P1:
t=0: requests 2 units of R2
t=1: requests 1 unit of R3
t=3: requests 2 units of R1
t=5: releases 1 unit of R2
and 1 unit of R1.
t=7: releases 1 unit of R3
t=8: requests 2 units of R4
t=10: Finishes
Process P2:
t=0: requests 2 units of R3
t=2: requests 1 unit of R4
t=4: requests 1 unit of R1
t=6: releases 1 unit of R3
t=8: Finishes
Process P3:
t=0: requests 1 unit of R4
t=2: requests 2 units of R1
t=5: releases 2 units of R1
t=7: requests 1 unit of R2
t=8: requests 1 unit of R3
t=9: Finishes
Which one of the following statements is TRUE if all three processes run concurrently starting at time t=0? (A) All processes will finish without any deadlock(B) Only P1 and P2 will be in deadlock.(C) Only P1 and P3 will be in a deadlock.(D) All three processes will be in deadlockAnswer: (A)Explanation:
We can apply the following Deadlock Detection algorithm and see that there is no process waiting indefinitely for a resource. See this for deadlock detection algorithm.
Quiz of this Question
GATE-CS-2009
GATE-GATE-CS-2009
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2007 | Question 64
|
[
{
"code": null,
"e": 24538,
"s": 24510,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24866,
"s": 24538,
"text": "Consider a system with 4 types of resources R1 (3 units), R2 (2 units), R3 (3 units), R4 (2 units). A non-preemptive resource allocation policy is used. At any given instance, a request is not entertained if it cannot be completely satisfied. Three processes P1, P2, P3 request the sources as follows if executed independently."
},
{
"code": null,
"e": 25406,
"s": 24866,
"text": "Process P1: \nt=0: requests 2 units of R2 \nt=1: requests 1 unit of R3 \nt=3: requests 2 units of R1 \nt=5: releases 1 unit of R2 \n and 1 unit of R1. \nt=7: releases 1 unit of R3 \nt=8: requests 2 units of R4 \nt=10: Finishes\n\nProcess P2: \nt=0: requests 2 units of R3 \nt=2: requests 1 unit of R4 \nt=4: requests 1 unit of R1 \nt=6: releases 1 unit of R3 \nt=8: Finishes\n\nProcess P3: \nt=0: requests 1 unit of R4 \nt=2: requests 2 units of R1 \nt=5: releases 2 units of R1 \nt=7: requests 1 unit of R2 \nt=8: requests 1 unit of R3 \nt=9: Finishes"
},
{
"code": null,
"e": 25711,
"s": 25406,
"text": "Which one of the following statements is TRUE if all three processes run concurrently starting at time t=0? (A) All processes will finish without any deadlock(B) Only P1 and P2 will be in deadlock.(C) Only P1 and P3 will be in a deadlock.(D) All three processes will be in deadlockAnswer: (A)Explanation:"
},
{
"code": null,
"e": 25880,
"s": 25711,
"text": "We can apply the following Deadlock Detection algorithm and see that there is no process waiting indefinitely for a resource. See this for deadlock detection algorithm."
},
{
"code": null,
"e": 25902,
"s": 25880,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 25915,
"s": 25902,
"text": "GATE-CS-2009"
},
{
"code": null,
"e": 25933,
"s": 25915,
"text": "GATE-GATE-CS-2009"
},
{
"code": null,
"e": 25938,
"s": 25933,
"text": "GATE"
},
{
"code": null,
"e": 26036,
"s": 25938,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26045,
"s": 26036,
"text": "Comments"
},
{
"code": null,
"e": 26058,
"s": 26045,
"text": "Old Comments"
},
{
"code": null,
"e": 26092,
"s": 26058,
"text": "GATE | GATE-IT-2004 | Question 71"
},
{
"code": null,
"e": 26125,
"s": 26092,
"text": "GATE | GATE CS 2011 | Question 7"
},
{
"code": null,
"e": 26167,
"s": 26125,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 26209,
"s": 26167,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 38"
},
{
"code": null,
"e": 26251,
"s": 26209,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 26285,
"s": 26251,
"text": "GATE | GATE CS 2018 | Question 37"
},
{
"code": null,
"e": 26319,
"s": 26285,
"text": "GATE | GATE-IT-2004 | Question 83"
},
{
"code": null,
"e": 26361,
"s": 26319,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 65"
},
{
"code": null,
"e": 26403,
"s": 26361,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 63"
}
] |
C# | Remove the element with the specified key from the Hashtable - GeeksforGeeks
|
01 Feb, 2019
The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.Remove(Object) Method is used to remove the element with the specified key from the Hashtable.
Syntax:
public virtual void Remove (object key);
Parameter:
key: It is the key of the element to remove of type System.Object.
Exceptions:
ArgumentNullException: If the key is null.
NotSupportedException: If the Hashtable is read-only or has a fixed size.
Example:
// C# code to remove the element// with the specified key from Hashtableusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable Hashtable myTable = new Hashtable(); // Adding elements in Hashtable myTable.Add("2", "Even & Prime"); myTable.Add("3", "Odd & Prime"); myTable.Add("4", "Even & non-prime"); myTable.Add("9", "Odd & non-prime"); // Print the number of entries in Hashtable Console.WriteLine("Total number of entries in Hashtable : " + myTable.Count); // To remove the elements from Hashtable // which has key as "3" myTable.Remove("3"); // Print the number of entries in Hashtable Console.WriteLine("Total number of entries in Hashtable : " + myTable.Count); // To remove the elements from Hashtable // which has key as "4" myTable.Remove("4"); // Print the number of entries in Hashtable Console.WriteLine("Total number of entries in Hashtable : " + myTable.Count); // Adding elements in Hashtable myTable.Add("g", "geeks"); myTable.Add("c", "c++"); myTable.Add("d", "data structures"); // Print the number of entries in Hashtable Console.WriteLine("Total number of entries in Hashtable : " + myTable.Count); // To remove the elements from Hashtable // which has key as "c" myTable.Remove("c"); // Print the number of entries in Hashtable Console.WriteLine("Total number of entries in Hashtable : " + myTable.Count); }}
Total number of entries in Hashtable : 4
Total number of entries in Hashtable : 3
Total number of entries in Hashtable : 2
Total number of entries in Hashtable : 5
Total number of entries in Hashtable : 4
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.remove?view=netframework-4.7.2
CSharp-Collections-Hashtable
CSharp-Collections-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Method Overriding
C# | Class and Object
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
Extension Method in C#
C# | Delegates
Introduction to .NET Framework
C# | Data Types
Difference between Ref and Out keywords in C#
C# | Replace() Method
|
[
{
"code": null,
"e": 24644,
"s": 24616,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 24925,
"s": 24644,
"text": "The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.Remove(Object) Method is used to remove the element with the specified key from the Hashtable."
},
{
"code": null,
"e": 24933,
"s": 24925,
"text": "Syntax:"
},
{
"code": null,
"e": 24975,
"s": 24933,
"text": "public virtual void Remove (object key);\n"
},
{
"code": null,
"e": 24986,
"s": 24975,
"text": "Parameter:"
},
{
"code": null,
"e": 25053,
"s": 24986,
"text": "key: It is the key of the element to remove of type System.Object."
},
{
"code": null,
"e": 25065,
"s": 25053,
"text": "Exceptions:"
},
{
"code": null,
"e": 25108,
"s": 25065,
"text": "ArgumentNullException: If the key is null."
},
{
"code": null,
"e": 25182,
"s": 25108,
"text": "NotSupportedException: If the Hashtable is read-only or has a fixed size."
},
{
"code": null,
"e": 25191,
"s": 25182,
"text": "Example:"
},
{
"code": "// C# code to remove the element// with the specified key from Hashtableusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable Hashtable myTable = new Hashtable(); // Adding elements in Hashtable myTable.Add(\"2\", \"Even & Prime\"); myTable.Add(\"3\", \"Odd & Prime\"); myTable.Add(\"4\", \"Even & non-prime\"); myTable.Add(\"9\", \"Odd & non-prime\"); // Print the number of entries in Hashtable Console.WriteLine(\"Total number of entries in Hashtable : \" + myTable.Count); // To remove the elements from Hashtable // which has key as \"3\" myTable.Remove(\"3\"); // Print the number of entries in Hashtable Console.WriteLine(\"Total number of entries in Hashtable : \" + myTable.Count); // To remove the elements from Hashtable // which has key as \"4\" myTable.Remove(\"4\"); // Print the number of entries in Hashtable Console.WriteLine(\"Total number of entries in Hashtable : \" + myTable.Count); // Adding elements in Hashtable myTable.Add(\"g\", \"geeks\"); myTable.Add(\"c\", \"c++\"); myTable.Add(\"d\", \"data structures\"); // Print the number of entries in Hashtable Console.WriteLine(\"Total number of entries in Hashtable : \" + myTable.Count); // To remove the elements from Hashtable // which has key as \"c\" myTable.Remove(\"c\"); // Print the number of entries in Hashtable Console.WriteLine(\"Total number of entries in Hashtable : \" + myTable.Count); }}",
"e": 27081,
"s": 25191,
"text": null
},
{
"code": null,
"e": 27287,
"s": 27081,
"text": "Total number of entries in Hashtable : 4\nTotal number of entries in Hashtable : 3\nTotal number of entries in Hashtable : 2\nTotal number of entries in Hashtable : 5\nTotal number of entries in Hashtable : 4\n"
},
{
"code": null,
"e": 27298,
"s": 27287,
"text": "Reference:"
},
{
"code": null,
"e": 27402,
"s": 27298,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.remove?view=netframework-4.7.2"
},
{
"code": null,
"e": 27431,
"s": 27402,
"text": "CSharp-Collections-Hashtable"
},
{
"code": null,
"e": 27460,
"s": 27431,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 27474,
"s": 27460,
"text": "CSharp-method"
},
{
"code": null,
"e": 27477,
"s": 27474,
"text": "C#"
},
{
"code": null,
"e": 27575,
"s": 27477,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27584,
"s": 27575,
"text": "Comments"
},
{
"code": null,
"e": 27597,
"s": 27584,
"text": "Old Comments"
},
{
"code": null,
"e": 27620,
"s": 27597,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 27642,
"s": 27620,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 27660,
"s": 27642,
"text": "C# | Constructors"
},
{
"code": null,
"e": 27700,
"s": 27660,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 27723,
"s": 27700,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27738,
"s": 27723,
"text": "C# | Delegates"
},
{
"code": null,
"e": 27769,
"s": 27738,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 27785,
"s": 27769,
"text": "C# | Data Types"
},
{
"code": null,
"e": 27831,
"s": 27785,
"text": "Difference between Ref and Out keywords in C#"
}
] |
Bootstrap Progress Bar and Jumbotron - GeeksforGeeks
|
12 Jan, 2022
BootStrap articles :
Introduction and InstallationGrid SystemButtons, Glyphicons, TablesVertical Forms, Horizontal Forms, Inline FormsDropDowns and Responsive Tabs
Introduction and Installation
Grid System
Buttons, Glyphicons, Tables
Vertical Forms, Horizontal Forms, Inline Forms
DropDowns and Responsive Tabs
Progress Bar
We all have seen a progress bar while executing some process in our computer. A progress bar shows how much of the process is completed and how much is left. You can add a progress bar in your web page using predefined bootstrap classes. Bootstrap has some predefined classes which can be easily used with HTML to style your webpages brilliantly and make your webpage responsive. Bootstrap provides many types of progress bars.We can add a progress bar to our webpage using progress class in a div class.Use this code in your HTML code to add a default progress bar.To create a progress bar:
Use class progress inside a div class.Inside the already made div class, add another div tag with a class .progress-bar.Mention the progress of the bar under a style attribute using width as percentage. For eg- style=”width:50%
Use class progress inside a div class.
Inside the already made div class, add another div tag with a class .progress-bar.
Mention the progress of the bar under a style attribute using width as percentage. For eg- style=”width:50%
Code for default progress bar with label.
<div class="progress"> <div class="progress-bar" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100" style="width:50%"> <span>50% Complete</span> </div></div>
Output:
<div class="progress"> <div class="progress-bar" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100" style="width:50%"> </div></div>
Output
Green – .progress-bar-successBlue – .progress-bar-infoYellow- .progress-bar-warningRed – .progress-bar-dangerUse these class inside the div element to colour your progress barCode for Coloured Progress Bar
<div class="progress"> <div class="progress-bar progress-bar-success" role="progressbar"aria-valuenow="50" aria-valuemin="0" aria-valuemax="100" style="width:50%"> </div> </div>
Output
Jumbotron
Jumbotron is a big grey box used to indicate some text which require extra attention. Any text that seems to be important can be written inside a jumbotron to make it appear big and noticeable.To add a Jumbotron –
Inside a div element, use a jumbotron class.After this div tag, you can add any text or information you want.CLose the div element with class jumbotron.Code for a jumbotron<div class="container"> <div class="jumbotron"> <h1>Jumbotron</h1> <p>This is a Jumbotron.</p> </div></div>Output
Inside a div element, use a jumbotron class.
After this div tag, you can add any text or information you want.
CLose the div element with class jumbotron.Code for a jumbotron<div class="container"> <div class="jumbotron"> <h1>Jumbotron</h1> <p>This is a Jumbotron.</p> </div></div>Output
<div class="container"> <div class="jumbotron"> <h1>Jumbotron</h1> <p>This is a Jumbotron.</p> </div></div>
Output
This article is contributed by Ayush Saxena. 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.
Web technologies
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to change navigation bar color in Bootstrap ?
Form validation using jQuery
How to align navbar items to the right in Bootstrap 4 ?
How to pass data into a bootstrap modal?
How to Show Images on Click using HTML ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28384,
"s": 28356,
"text": "\n12 Jan, 2022"
},
{
"code": null,
"e": 28405,
"s": 28384,
"text": "BootStrap articles :"
},
{
"code": null,
"e": 28548,
"s": 28405,
"text": "Introduction and InstallationGrid SystemButtons, Glyphicons, TablesVertical Forms, Horizontal Forms, Inline FormsDropDowns and Responsive Tabs"
},
{
"code": null,
"e": 28578,
"s": 28548,
"text": "Introduction and Installation"
},
{
"code": null,
"e": 28590,
"s": 28578,
"text": "Grid System"
},
{
"code": null,
"e": 28618,
"s": 28590,
"text": "Buttons, Glyphicons, Tables"
},
{
"code": null,
"e": 28665,
"s": 28618,
"text": "Vertical Forms, Horizontal Forms, Inline Forms"
},
{
"code": null,
"e": 28695,
"s": 28665,
"text": "DropDowns and Responsive Tabs"
},
{
"code": null,
"e": 28708,
"s": 28695,
"text": "Progress Bar"
},
{
"code": null,
"e": 29300,
"s": 28708,
"text": "We all have seen a progress bar while executing some process in our computer. A progress bar shows how much of the process is completed and how much is left. You can add a progress bar in your web page using predefined bootstrap classes. Bootstrap has some predefined classes which can be easily used with HTML to style your webpages brilliantly and make your webpage responsive. Bootstrap provides many types of progress bars.We can add a progress bar to our webpage using progress class in a div class.Use this code in your HTML code to add a default progress bar.To create a progress bar:"
},
{
"code": null,
"e": 29528,
"s": 29300,
"text": "Use class progress inside a div class.Inside the already made div class, add another div tag with a class .progress-bar.Mention the progress of the bar under a style attribute using width as percentage. For eg- style=”width:50%"
},
{
"code": null,
"e": 29567,
"s": 29528,
"text": "Use class progress inside a div class."
},
{
"code": null,
"e": 29650,
"s": 29567,
"text": "Inside the already made div class, add another div tag with a class .progress-bar."
},
{
"code": null,
"e": 29758,
"s": 29650,
"text": "Mention the progress of the bar under a style attribute using width as percentage. For eg- style=”width:50%"
},
{
"code": null,
"e": 29800,
"s": 29758,
"text": "Code for default progress bar with label."
},
{
"code": "<div class=\"progress\"> <div class=\"progress-bar\" role=\"progressbar\" aria-valuenow=\"50\" aria-valuemin=\"0\" aria-valuemax=\"100\" style=\"width:50%\"> <span>50% Complete</span> </div></div>",
"e": 30012,
"s": 29800,
"text": null
},
{
"code": null,
"e": 30020,
"s": 30012,
"text": "Output:"
},
{
"code": "<div class=\"progress\"> <div class=\"progress-bar\" role=\"progressbar\" aria-valuenow=\"50\" aria-valuemin=\"0\" aria-valuemax=\"100\" style=\"width:50%\"> </div></div>",
"e": 30186,
"s": 30020,
"text": null
},
{
"code": null,
"e": 30193,
"s": 30186,
"text": "Output"
},
{
"code": null,
"e": 30399,
"s": 30193,
"text": "Green – .progress-bar-successBlue – .progress-bar-infoYellow- .progress-bar-warningRed – .progress-bar-dangerUse these class inside the div element to colour your progress barCode for Coloured Progress Bar"
},
{
"code": "<div class=\"progress\"> <div class=\"progress-bar progress-bar-success\" role=\"progressbar\"aria-valuenow=\"50\" aria-valuemin=\"0\" aria-valuemax=\"100\" style=\"width:50%\"> </div> </div>",
"e": 30585,
"s": 30399,
"text": null
},
{
"code": null,
"e": 30592,
"s": 30585,
"text": "Output"
},
{
"code": null,
"e": 30602,
"s": 30592,
"text": "Jumbotron"
},
{
"code": null,
"e": 30816,
"s": 30602,
"text": "Jumbotron is a big grey box used to indicate some text which require extra attention. Any text that seems to be important can be written inside a jumbotron to make it appear big and noticeable.To add a Jumbotron –"
},
{
"code": null,
"e": 31110,
"s": 30816,
"text": "Inside a div element, use a jumbotron class.After this div tag, you can add any text or information you want.CLose the div element with class jumbotron.Code for a jumbotron<div class=\"container\"> <div class=\"jumbotron\"> <h1>Jumbotron</h1> <p>This is a Jumbotron.</p> </div></div>Output"
},
{
"code": null,
"e": 31155,
"s": 31110,
"text": "Inside a div element, use a jumbotron class."
},
{
"code": null,
"e": 31221,
"s": 31155,
"text": "After this div tag, you can add any text or information you want."
},
{
"code": null,
"e": 31406,
"s": 31221,
"text": "CLose the div element with class jumbotron.Code for a jumbotron<div class=\"container\"> <div class=\"jumbotron\"> <h1>Jumbotron</h1> <p>This is a Jumbotron.</p> </div></div>Output"
},
{
"code": "<div class=\"container\"> <div class=\"jumbotron\"> <h1>Jumbotron</h1> <p>This is a Jumbotron.</p> </div></div>",
"e": 31522,
"s": 31406,
"text": null
},
{
"code": null,
"e": 31529,
"s": 31522,
"text": "Output"
},
{
"code": null,
"e": 31825,
"s": 31529,
"text": "This article is contributed by Ayush Saxena. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 31950,
"s": 31825,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 31967,
"s": 31950,
"text": "Web technologies"
},
{
"code": null,
"e": 31977,
"s": 31967,
"text": "Bootstrap"
},
{
"code": null,
"e": 31994,
"s": 31977,
"text": "Web Technologies"
},
{
"code": null,
"e": 32092,
"s": 31994,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32101,
"s": 32092,
"text": "Comments"
},
{
"code": null,
"e": 32114,
"s": 32101,
"text": "Old Comments"
},
{
"code": null,
"e": 32164,
"s": 32114,
"text": "How to change navigation bar color in Bootstrap ?"
},
{
"code": null,
"e": 32193,
"s": 32164,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 32249,
"s": 32193,
"text": "How to align navbar items to the right in Bootstrap 4 ?"
},
{
"code": null,
"e": 32290,
"s": 32249,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 32331,
"s": 32290,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 32373,
"s": 32331,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 32406,
"s": 32373,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32468,
"s": 32406,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 32518,
"s": 32468,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to log a Python exception? - GeeksforGeeks
|
29 Sep, 2021
To log an exception in Python we can use logging module and through that we can log the error.
Logging module provides a set of functions for simple logging and for following purposes
DEBUG
INFO
WARNING
ERROR
CRITICAL
Logging an exception in python with an error can be done in the logging.exception() method. This function logs a message with level ERROR on this logger. The arguments are interpreted as for debug(). Exception info is added to the logging message. This method should only be called from an exception handler.
See the following code for more clarity:
Example 1 :
Python3
# importing the moduleimport logging try: printf("GeeksforGeeks")except Exception as Argument: logging.exception("Error occurred while printing GeeksforGeeks")
Output :
ERROR:root:Error occurred while printing GeeksforGeeks
Traceback (most recent call last):
File "/home/gfg.py", line 3, in
printf("GeeksforGeeks")
NameError: name 'printf' is not defined
Example 2: We can also log the error message into a different file without showing error in the console by the following method:
Python3
# importing the moduleimport logging try: printf("GeeksforGeeks")except Exception as Argument: # creating/opening a file f = open("demofile2.txt", "a") # writing in the file f.write(str(Argument)) # closing the file f.close()
Error message will be stored in file name demofille2.txt in same directory as code.
Output :
Traceback (most recent call last):
File "/home/gfg.py", line 5, in
printf("GeeksforGeeks")
NameError: name 'printf' is not defined
khushboogoyal499
sooda367
Python-exceptions
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Create a directory in Python
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
|
[
{
"code": null,
"e": 25647,
"s": 25619,
"text": "\n29 Sep, 2021"
},
{
"code": null,
"e": 25742,
"s": 25647,
"text": "To log an exception in Python we can use logging module and through that we can log the error."
},
{
"code": null,
"e": 25831,
"s": 25742,
"text": "Logging module provides a set of functions for simple logging and for following purposes"
},
{
"code": null,
"e": 25837,
"s": 25831,
"text": "DEBUG"
},
{
"code": null,
"e": 25842,
"s": 25837,
"text": "INFO"
},
{
"code": null,
"e": 25850,
"s": 25842,
"text": "WARNING"
},
{
"code": null,
"e": 25856,
"s": 25850,
"text": "ERROR"
},
{
"code": null,
"e": 25865,
"s": 25856,
"text": "CRITICAL"
},
{
"code": null,
"e": 26174,
"s": 25865,
"text": "Logging an exception in python with an error can be done in the logging.exception() method. This function logs a message with level ERROR on this logger. The arguments are interpreted as for debug(). Exception info is added to the logging message. This method should only be called from an exception handler."
},
{
"code": null,
"e": 26215,
"s": 26174,
"text": "See the following code for more clarity:"
},
{
"code": null,
"e": 26227,
"s": 26215,
"text": "Example 1 :"
},
{
"code": null,
"e": 26235,
"s": 26227,
"text": "Python3"
},
{
"code": "# importing the moduleimport logging try: printf(\"GeeksforGeeks\")except Exception as Argument: logging.exception(\"Error occurred while printing GeeksforGeeks\")",
"e": 26401,
"s": 26235,
"text": null
},
{
"code": null,
"e": 26410,
"s": 26401,
"text": "Output :"
},
{
"code": null,
"e": 26603,
"s": 26410,
"text": "ERROR:root:Error occurred while printing GeeksforGeeks\nTraceback (most recent call last):\n File \"/home/gfg.py\", line 3, in \n printf(\"GeeksforGeeks\")\nNameError: name 'printf' is not defined"
},
{
"code": null,
"e": 26732,
"s": 26603,
"text": "Example 2: We can also log the error message into a different file without showing error in the console by the following method:"
},
{
"code": null,
"e": 26740,
"s": 26732,
"text": "Python3"
},
{
"code": "# importing the moduleimport logging try: printf(\"GeeksforGeeks\")except Exception as Argument: # creating/opening a file f = open(\"demofile2.txt\", \"a\") # writing in the file f.write(str(Argument)) # closing the file f.close()",
"e": 27001,
"s": 26740,
"text": null
},
{
"code": null,
"e": 27085,
"s": 27001,
"text": "Error message will be stored in file name demofille2.txt in same directory as code."
},
{
"code": null,
"e": 27094,
"s": 27085,
"text": "Output :"
},
{
"code": null,
"e": 27232,
"s": 27094,
"text": "Traceback (most recent call last):\n File \"/home/gfg.py\", line 5, in \n printf(\"GeeksforGeeks\")\nNameError: name 'printf' is not defined"
},
{
"code": null,
"e": 27249,
"s": 27232,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 27258,
"s": 27249,
"text": "sooda367"
},
{
"code": null,
"e": 27276,
"s": 27258,
"text": "Python-exceptions"
},
{
"code": null,
"e": 27291,
"s": 27276,
"text": "python-utility"
},
{
"code": null,
"e": 27298,
"s": 27291,
"text": "Python"
},
{
"code": null,
"e": 27396,
"s": 27298,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27428,
"s": 27396,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27470,
"s": 27428,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27512,
"s": 27470,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27568,
"s": 27512,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27595,
"s": 27568,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27617,
"s": 27595,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27646,
"s": 27617,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27677,
"s": 27646,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27713,
"s": 27677,
"text": "Python | Pandas dataframe.groupby()"
}
] |
Check if array can be sorted with one swap - GeeksforGeeks
|
03 Jun, 2021
Given an array containing N elements. Find if it is possible to sort it in non-decreasing order using atmost one swap.Examples:
Input : arr[] = {1, 2, 3, 4} Output : YES The array is already sortedInput : arr[] = {3, 2, 1} Output : YES Swap 3 and 1 to get [1, 2, 3]Input : arr[] = {4, 1, 2, 3} Output :NO
A simple approach is to sort the array and compare the required position of the element and the current position of the element. If there are no mismatches, the array is already sorted. If there are exactly 2 mismatches, we can swap the terms that are not in the position to get the sorted array.
C++
Java
Python 3
C#
Javascript
// CPP program to check if an array can be sorted// with at-most one swap#include <bits/stdc++.h>using namespace std; bool checkSorted(int n, int arr[]){ // Create a sorted copy of original array int b[n]; for (int i = 0; i < n; i++) b[i] = arr[i]; sort(b, b + n); // Check if 0 or 1 swap required to // get the sorted array int ct = 0; for (int i = 0; i < n; i++) if (arr[i] != b[i]) ct++; if (ct == 0 || ct == 2) return true; else return false;} // Driver Program to test above functionint main(){ int arr[] = {1, 5, 3, 4, 2}; int n = sizeof(arr) / sizeof(arr[0]); if (checkSorted(n, arr)) cout << "Yes"; else cout << "No"; return 0;}
// Java program to check if an array// can be sorted with at-most one swapimport java.util.Arrays; class GFG{static boolean checkSorted(int n, int arr[]){ // Create a sorted copy of original array int []b = new int[n]; for (int i = 0; i < n; i++) b[i] = arr[i]; Arrays.sort(b, 0, n); // Check if 0 or 1 swap required to // get the sorted array int ct = 0; for (int i = 0; i < n; i++) if (arr[i] != b[i]) ct++; if (ct == 0 || ct == 2) return true; else return false;} // Driver Codepublic static void main(String[] args){ int arr[] = {1, 5, 3, 4, 2}; int n = arr.length; if (checkSorted(n, arr)) System.out.println("Yes"); else System.out.println("No");}} // This code is contributed by 29AjayKumar
# A linear Python 3 program to check# if array becomes sorted after one swap def checkSorted(n, arr): # Create a sorted copy of # original array b = [] for i in range(n): b.append(arr[i]) b.sort() # Check if 0 or 1 swap required # to get the sorted array ct = 0 for i in range(n): if arr[i] != b[i]: ct += 1 if ct == 0 or ct == 2: return True else: return False # Driver Code if __name__ == '__main__': arr = [1, 5, 3, 4, 2] n = len(arr) if checkSorted(n, arr): print("Yes") else: print("No") # This code is contributed# by Rituraj Jain
// C# program to check if an array// can be sorted with at-most one swapusing System; class GFG{static Boolean checkSorted(int n, int []arr){ // Create a sorted copy of original array int []b = new int[n]; for (int i = 0; i < n; i++) b[i] = arr[i]; Array.Sort(b, 0, n); // Check if 0 or 1 swap required to // get the sorted array int ct = 0; for (int i = 0; i < n; i++) if (arr[i] != b[i]) ct++; if (ct == 0 || ct == 2) return true; else return false;} // Driver Codepublic static void Main(String[] args){ int []arr = {1, 5, 3, 4, 2}; int n = arr.Length; if (checkSorted(n, arr)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed by 29AjayKumar
<script>// javascript program to check if an array can be sorted// with at-most one swapfunction checkSorted(n, arr){ // Create a sorted copy of original array var b = Array(n).fill(0); for (var i = 0; i < n; i++) b[i] = arr[i]; b.sort(); // Check if 0 or 1 swap required to // get the sorted array var ct = 0; for (var i = 0; i < n; i++) if (arr[i] != b[i]) ct++; if (ct == 0 || ct == 2) return true; else return false;} // Driver Program to test above functionvar arr = [ 1, 5, 3, 4, 2 ];var n = arr.length;if (checkSorted(n, arr)) document.write( "Yes");else document.write("No"); // This code is contributed by noob2000.</script>
Yes
Time Complexity: O(n Log n)An efficient solution is to check in linear time. Let us consider different cases that may appear after one swap.
We swap adjacent elements. For example {1, 2, 3, 4, 5} becomes {1, 2, 4, 3, 5}We swap non-adjacent elements. For example {1, 2, 3, 4, 5} becomes {1, 5, 3, 4, 2}
We swap adjacent elements. For example {1, 2, 3, 4, 5} becomes {1, 2, 4, 3, 5}
We swap non-adjacent elements. For example {1, 2, 3, 4, 5} becomes {1, 5, 3, 4, 2}
We traverse the given array. For every element, we check if it is smaller than the previous element. We count such occurrences. If the count of such occurrences is more than 2, then we cannot sort the array with one swap. If the count is one, we can find elements to swap (smaller and its previous). If the count is two, we can find elements to swap (previous of first smaller and second smaller). After swapping, we again check if array becomes sorted or not. We check this to handle cases like {4, 1, 2, 3}
C++
Java
Python 3
C#
Javascript
// A linear CPP program to check if array becomes// sorted after one swap#include <bits/stdc++.h>using namespace std; int checkSorted(int n, int arr[]){ // Find counts and positions of // elements that are out of order. int first = 0, second = 0; int count = 0; for (int i = 1; i < n; i++) { if (arr[i] < arr[i - 1]) { count++; if (first == 0) first = i; else second = i; } } // If there are more than two elements // are out of order. if (count > 2) return false; // If all elements are sorted already if (count == 0) return true; // Cases like {1, 5, 3, 4, 2} // We swap 5 and 2. if (count == 2) swap(arr[first - 1], arr[second]); // Cases like {1, 2, 4, 3, 5} else if (count == 1) swap(arr[first - 1], arr[first]); // Now check if array becomes sorted // for cases like {4, 1, 2, 3} for (int i = 1; i < n; i++) if (arr[i] < arr[i - 1]) return false; return true;} // Driver Program to test above functionint main(){ int arr[] = { 1, 4, 3, 2 }; int n = sizeof(arr) / sizeof(arr[0]); if (checkSorted(n, arr)) cout << "Yes"; else cout << "No"; return 0;}
// A linear Java program to check if// array becomes sorted after one swapclass GFG{static boolean checkSorted(int n, int arr[]){ // Find counts and positions of // elements that are out of order. int first = 0, second = 0; int count = 0; for (int i = 1; i < n; i++) { if (arr[i] < arr[i - 1]) { count++; if (first == 0) first = i; else second = i; } } // If there are more than two elements // are out of order. if (count > 2) return false; // If all elements are sorted already if (count == 0) return true; // Cases like {1, 5, 3, 4, 2} // We swap 5 and 2. if (count == 2) swap(arr, first - 1, second); // Cases like {1, 2, 4, 3, 5} else if (count == 1) swap(arr, first - 1, first); // Now check if array becomes sorted // for cases like {4, 1, 2, 3} for (int i = 1; i < n; i++) if (arr[i] < arr[i - 1]) return false; return true;} static int[] swap(int []arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} // Driver Codepublic static void main(String[] args){ int arr[] = { 1, 4, 3, 2 }; int n = arr.length; if (checkSorted(n, arr)) System.out.println("Yes"); else System.out.println("No");}} // This code is contributed by Rajput-Ji
# A linear Python 3 program to check# if array becomes sorted after one swap def checkSorted(n, arr): # Find counts and positions of # elements that are out of order. first, second = 0, 0 count = 0 for i in range(1, n): if arr[i] < arr[i - 1]: count += 1 if first == 0: first = i else: second = i # If there are more than two elements # which are out of order. if count > 2: return False # If all elements are sorted already if count == 0: return True # Cases like {1, 5, 3, 4, 2} # We swap 5 and 2. if count == 2: (arr[first - 1], arr[second]) = (arr[second], arr[first - 1]) # Cases like {1, 2, 4, 3, 5} elif count == 1: (arr[first - 1], arr[first]) = (arr[first], arr[first - 1]) # Now check if array becomes sorted # for cases like {4, 1, 2, 3} for i in range(1, n): if arr[i] < arr[i - 1]: return False return True # Driver Codeif __name__ == '__main__': arr = [1, 4, 3, 2] n = len(arr) if checkSorted(n, arr): print("Yes") else: print("No") # This code is contributed# by Rituraj Jain
// A linear C# program to check if// array becomes sorted after one swapusing System; class GFG{static bool checkSorted(int n, int []arr){ // Find counts and positions of // elements that are out of order. int first = 0, second = 0; int count = 0; for (int i = 1; i < n; i++) { if (arr[i] < arr[i - 1]) { count++; if (first == 0) first = i; else second = i; } } // If there are more than two elements // are out of order. if (count > 2) return false; // If all elements are sorted already if (count == 0) return true; // Cases like {1, 5, 3, 4, 2} // We swap 5 and 2. if (count == 2) swap(arr, first - 1, second); // Cases like {1, 2, 4, 3, 5} else if (count == 1) swap(arr, first - 1, first); // Now check if array becomes sorted // for cases like {4, 1, 2, 3} for (int i = 1; i < n; i++) if (arr[i] < arr[i - 1]) return false; return true;} static int[] swap(int []arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} // Driver Codepublic static void Main(String[] args){ int []arr = { 1, 4, 3, 2 }; int n = arr.Length; if (checkSorted(n, arr)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed by Rajput-Ji
<script> // A linear Javascript program to check if array becomes// sorted after one swap function checkSorted(n, arr){ // Find counts and positions of // elements that are out of order. var first = 0, second = 0; var count = 0; for (var i = 1; i < n; i++) { if (arr[i] < arr[i - 1]) { count++; if (first == 0) first = i; else second = i; } } // If there are more than two elements // are out of order. if (count > 2) return false; // If all elements are sorted already if (count == 0) return true; // Cases like {1, 5, 3, 4, 2} // We swap 5 and 2. if (count == 2) [arr[first - 1], arr[second]] = [arr[second], arr[first - 1]]; // Cases like {1, 2, 4, 3, 5} else if (count == 1) [arr[first - 1], arr[first]] = [arr[first], arr[first - 1]]; // Now check if array becomes sorted // for cases like {4, 1, 2, 3} for (var i = 1; i < n; i++) if (arr[i] < arr[i - 1]) return false; return true;} // Driver Program to test above functionvar arr = [1, 4, 3, 2];var n = arr.length;if (checkSorted(n, arr)) document.write( "Yes");else document.write( "No"); // This code is contributed by famously.</script>
Yes
Time Complexity: O(n)Exercise : How to check if an array can be sorted with two swaps?
rituraj_jain
29AjayKumar
Rajput-Ji
noob2000
famously
Arrays
Sorting Quiz
Arrays
Searching
Sorting
Arrays
Searching
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Reversal algorithm for array rotation
Window Sliding Technique
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Binary Search
Median of two sorted arrays of different sizes
Find the index of an array element in Java
Two Pointers Technique
Count number of occurrences (or frequency) in a sorted array
|
[
{
"code": null,
"e": 26175,
"s": 26147,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 26305,
"s": 26175,
"text": "Given an array containing N elements. Find if it is possible to sort it in non-decreasing order using atmost one swap.Examples: "
},
{
"code": null,
"e": 26482,
"s": 26305,
"text": "Input : arr[] = {1, 2, 3, 4} Output : YES The array is already sortedInput : arr[] = {3, 2, 1} Output : YES Swap 3 and 1 to get [1, 2, 3]Input : arr[] = {4, 1, 2, 3} Output :NO"
},
{
"code": null,
"e": 26782,
"s": 26484,
"text": "A simple approach is to sort the array and compare the required position of the element and the current position of the element. If there are no mismatches, the array is already sorted. If there are exactly 2 mismatches, we can swap the terms that are not in the position to get the sorted array. "
},
{
"code": null,
"e": 26786,
"s": 26782,
"text": "C++"
},
{
"code": null,
"e": 26791,
"s": 26786,
"text": "Java"
},
{
"code": null,
"e": 26800,
"s": 26791,
"text": "Python 3"
},
{
"code": null,
"e": 26803,
"s": 26800,
"text": "C#"
},
{
"code": null,
"e": 26814,
"s": 26803,
"text": "Javascript"
},
{
"code": "// CPP program to check if an array can be sorted// with at-most one swap#include <bits/stdc++.h>using namespace std; bool checkSorted(int n, int arr[]){ // Create a sorted copy of original array int b[n]; for (int i = 0; i < n; i++) b[i] = arr[i]; sort(b, b + n); // Check if 0 or 1 swap required to // get the sorted array int ct = 0; for (int i = 0; i < n; i++) if (arr[i] != b[i]) ct++; if (ct == 0 || ct == 2) return true; else return false;} // Driver Program to test above functionint main(){ int arr[] = {1, 5, 3, 4, 2}; int n = sizeof(arr) / sizeof(arr[0]); if (checkSorted(n, arr)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 27550,
"s": 26814,
"text": null
},
{
"code": "// Java program to check if an array// can be sorted with at-most one swapimport java.util.Arrays; class GFG{static boolean checkSorted(int n, int arr[]){ // Create a sorted copy of original array int []b = new int[n]; for (int i = 0; i < n; i++) b[i] = arr[i]; Arrays.sort(b, 0, n); // Check if 0 or 1 swap required to // get the sorted array int ct = 0; for (int i = 0; i < n; i++) if (arr[i] != b[i]) ct++; if (ct == 0 || ct == 2) return true; else return false;} // Driver Codepublic static void main(String[] args){ int arr[] = {1, 5, 3, 4, 2}; int n = arr.length; if (checkSorted(n, arr)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code is contributed by 29AjayKumar",
"e": 28344,
"s": 27550,
"text": null
},
{
"code": "# A linear Python 3 program to check# if array becomes sorted after one swap def checkSorted(n, arr): # Create a sorted copy of # original array b = [] for i in range(n): b.append(arr[i]) b.sort() # Check if 0 or 1 swap required # to get the sorted array ct = 0 for i in range(n): if arr[i] != b[i]: ct += 1 if ct == 0 or ct == 2: return True else: return False # Driver Code if __name__ == '__main__': arr = [1, 5, 3, 4, 2] n = len(arr) if checkSorted(n, arr): print(\"Yes\") else: print(\"No\") # This code is contributed# by Rituraj Jain",
"e": 29036,
"s": 28344,
"text": null
},
{
"code": "// C# program to check if an array// can be sorted with at-most one swapusing System; class GFG{static Boolean checkSorted(int n, int []arr){ // Create a sorted copy of original array int []b = new int[n]; for (int i = 0; i < n; i++) b[i] = arr[i]; Array.Sort(b, 0, n); // Check if 0 or 1 swap required to // get the sorted array int ct = 0; for (int i = 0; i < n; i++) if (arr[i] != b[i]) ct++; if (ct == 0 || ct == 2) return true; else return false;} // Driver Codepublic static void Main(String[] args){ int []arr = {1, 5, 3, 4, 2}; int n = arr.Length; if (checkSorted(n, arr)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed by 29AjayKumar",
"e": 29814,
"s": 29036,
"text": null
},
{
"code": "<script>// javascript program to check if an array can be sorted// with at-most one swapfunction checkSorted(n, arr){ // Create a sorted copy of original array var b = Array(n).fill(0); for (var i = 0; i < n; i++) b[i] = arr[i]; b.sort(); // Check if 0 or 1 swap required to // get the sorted array var ct = 0; for (var i = 0; i < n; i++) if (arr[i] != b[i]) ct++; if (ct == 0 || ct == 2) return true; else return false;} // Driver Program to test above functionvar arr = [ 1, 5, 3, 4, 2 ];var n = arr.length;if (checkSorted(n, arr)) document.write( \"Yes\");else document.write(\"No\"); // This code is contributed by noob2000.</script>",
"e": 30525,
"s": 29814,
"text": null
},
{
"code": null,
"e": 30529,
"s": 30525,
"text": "Yes"
},
{
"code": null,
"e": 30674,
"s": 30531,
"text": "Time Complexity: O(n Log n)An efficient solution is to check in linear time. Let us consider different cases that may appear after one swap. "
},
{
"code": null,
"e": 30835,
"s": 30674,
"text": "We swap adjacent elements. For example {1, 2, 3, 4, 5} becomes {1, 2, 4, 3, 5}We swap non-adjacent elements. For example {1, 2, 3, 4, 5} becomes {1, 5, 3, 4, 2}"
},
{
"code": null,
"e": 30914,
"s": 30835,
"text": "We swap adjacent elements. For example {1, 2, 3, 4, 5} becomes {1, 2, 4, 3, 5}"
},
{
"code": null,
"e": 30997,
"s": 30914,
"text": "We swap non-adjacent elements. For example {1, 2, 3, 4, 5} becomes {1, 5, 3, 4, 2}"
},
{
"code": null,
"e": 31507,
"s": 30997,
"text": "We traverse the given array. For every element, we check if it is smaller than the previous element. We count such occurrences. If the count of such occurrences is more than 2, then we cannot sort the array with one swap. If the count is one, we can find elements to swap (smaller and its previous). If the count is two, we can find elements to swap (previous of first smaller and second smaller). After swapping, we again check if array becomes sorted or not. We check this to handle cases like {4, 1, 2, 3} "
},
{
"code": null,
"e": 31511,
"s": 31507,
"text": "C++"
},
{
"code": null,
"e": 31516,
"s": 31511,
"text": "Java"
},
{
"code": null,
"e": 31525,
"s": 31516,
"text": "Python 3"
},
{
"code": null,
"e": 31528,
"s": 31525,
"text": "C#"
},
{
"code": null,
"e": 31539,
"s": 31528,
"text": "Javascript"
},
{
"code": "// A linear CPP program to check if array becomes// sorted after one swap#include <bits/stdc++.h>using namespace std; int checkSorted(int n, int arr[]){ // Find counts and positions of // elements that are out of order. int first = 0, second = 0; int count = 0; for (int i = 1; i < n; i++) { if (arr[i] < arr[i - 1]) { count++; if (first == 0) first = i; else second = i; } } // If there are more than two elements // are out of order. if (count > 2) return false; // If all elements are sorted already if (count == 0) return true; // Cases like {1, 5, 3, 4, 2} // We swap 5 and 2. if (count == 2) swap(arr[first - 1], arr[second]); // Cases like {1, 2, 4, 3, 5} else if (count == 1) swap(arr[first - 1], arr[first]); // Now check if array becomes sorted // for cases like {4, 1, 2, 3} for (int i = 1; i < n; i++) if (arr[i] < arr[i - 1]) return false; return true;} // Driver Program to test above functionint main(){ int arr[] = { 1, 4, 3, 2 }; int n = sizeof(arr) / sizeof(arr[0]); if (checkSorted(n, arr)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 32812,
"s": 31539,
"text": null
},
{
"code": "// A linear Java program to check if// array becomes sorted after one swapclass GFG{static boolean checkSorted(int n, int arr[]){ // Find counts and positions of // elements that are out of order. int first = 0, second = 0; int count = 0; for (int i = 1; i < n; i++) { if (arr[i] < arr[i - 1]) { count++; if (first == 0) first = i; else second = i; } } // If there are more than two elements // are out of order. if (count > 2) return false; // If all elements are sorted already if (count == 0) return true; // Cases like {1, 5, 3, 4, 2} // We swap 5 and 2. if (count == 2) swap(arr, first - 1, second); // Cases like {1, 2, 4, 3, 5} else if (count == 1) swap(arr, first - 1, first); // Now check if array becomes sorted // for cases like {4, 1, 2, 3} for (int i = 1; i < n; i++) if (arr[i] < arr[i - 1]) return false; return true;} static int[] swap(int []arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} // Driver Codepublic static void main(String[] args){ int arr[] = { 1, 4, 3, 2 }; int n = arr.length; if (checkSorted(n, arr)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code is contributed by Rajput-Ji",
"e": 34219,
"s": 32812,
"text": null
},
{
"code": "# A linear Python 3 program to check# if array becomes sorted after one swap def checkSorted(n, arr): # Find counts and positions of # elements that are out of order. first, second = 0, 0 count = 0 for i in range(1, n): if arr[i] < arr[i - 1]: count += 1 if first == 0: first = i else: second = i # If there are more than two elements # which are out of order. if count > 2: return False # If all elements are sorted already if count == 0: return True # Cases like {1, 5, 3, 4, 2} # We swap 5 and 2. if count == 2: (arr[first - 1], arr[second]) = (arr[second], arr[first - 1]) # Cases like {1, 2, 4, 3, 5} elif count == 1: (arr[first - 1], arr[first]) = (arr[first], arr[first - 1]) # Now check if array becomes sorted # for cases like {4, 1, 2, 3} for i in range(1, n): if arr[i] < arr[i - 1]: return False return True # Driver Codeif __name__ == '__main__': arr = [1, 4, 3, 2] n = len(arr) if checkSorted(n, arr): print(\"Yes\") else: print(\"No\") # This code is contributed# by Rituraj Jain",
"e": 35525,
"s": 34219,
"text": null
},
{
"code": "// A linear C# program to check if// array becomes sorted after one swapusing System; class GFG{static bool checkSorted(int n, int []arr){ // Find counts and positions of // elements that are out of order. int first = 0, second = 0; int count = 0; for (int i = 1; i < n; i++) { if (arr[i] < arr[i - 1]) { count++; if (first == 0) first = i; else second = i; } } // If there are more than two elements // are out of order. if (count > 2) return false; // If all elements are sorted already if (count == 0) return true; // Cases like {1, 5, 3, 4, 2} // We swap 5 and 2. if (count == 2) swap(arr, first - 1, second); // Cases like {1, 2, 4, 3, 5} else if (count == 1) swap(arr, first - 1, first); // Now check if array becomes sorted // for cases like {4, 1, 2, 3} for (int i = 1; i < n; i++) if (arr[i] < arr[i - 1]) return false; return true;} static int[] swap(int []arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} // Driver Codepublic static void Main(String[] args){ int []arr = { 1, 4, 3, 2 }; int n = arr.Length; if (checkSorted(n, arr)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed by Rajput-Ji",
"e": 36939,
"s": 35525,
"text": null
},
{
"code": "<script> // A linear Javascript program to check if array becomes// sorted after one swap function checkSorted(n, arr){ // Find counts and positions of // elements that are out of order. var first = 0, second = 0; var count = 0; for (var i = 1; i < n; i++) { if (arr[i] < arr[i - 1]) { count++; if (first == 0) first = i; else second = i; } } // If there are more than two elements // are out of order. if (count > 2) return false; // If all elements are sorted already if (count == 0) return true; // Cases like {1, 5, 3, 4, 2} // We swap 5 and 2. if (count == 2) [arr[first - 1], arr[second]] = [arr[second], arr[first - 1]]; // Cases like {1, 2, 4, 3, 5} else if (count == 1) [arr[first - 1], arr[first]] = [arr[first], arr[first - 1]]; // Now check if array becomes sorted // for cases like {4, 1, 2, 3} for (var i = 1; i < n; i++) if (arr[i] < arr[i - 1]) return false; return true;} // Driver Program to test above functionvar arr = [1, 4, 3, 2];var n = arr.length;if (checkSorted(n, arr)) document.write( \"Yes\");else document.write( \"No\"); // This code is contributed by famously.</script>",
"e": 38231,
"s": 36939,
"text": null
},
{
"code": null,
"e": 38235,
"s": 38231,
"text": "Yes"
},
{
"code": null,
"e": 38325,
"s": 38237,
"text": "Time Complexity: O(n)Exercise : How to check if an array can be sorted with two swaps? "
},
{
"code": null,
"e": 38338,
"s": 38325,
"text": "rituraj_jain"
},
{
"code": null,
"e": 38350,
"s": 38338,
"text": "29AjayKumar"
},
{
"code": null,
"e": 38360,
"s": 38350,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 38369,
"s": 38360,
"text": "noob2000"
},
{
"code": null,
"e": 38378,
"s": 38369,
"text": "famously"
},
{
"code": null,
"e": 38385,
"s": 38378,
"text": "Arrays"
},
{
"code": null,
"e": 38398,
"s": 38385,
"text": "Sorting Quiz"
},
{
"code": null,
"e": 38405,
"s": 38398,
"text": "Arrays"
},
{
"code": null,
"e": 38415,
"s": 38405,
"text": "Searching"
},
{
"code": null,
"e": 38423,
"s": 38415,
"text": "Sorting"
},
{
"code": null,
"e": 38430,
"s": 38423,
"text": "Arrays"
},
{
"code": null,
"e": 38440,
"s": 38430,
"text": "Searching"
},
{
"code": null,
"e": 38448,
"s": 38440,
"text": "Sorting"
},
{
"code": null,
"e": 38546,
"s": 38448,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38577,
"s": 38546,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 38615,
"s": 38577,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 38640,
"s": 38615,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 38661,
"s": 38640,
"text": "Next Greater Element"
},
{
"code": null,
"e": 38719,
"s": 38661,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 38733,
"s": 38719,
"text": "Binary Search"
},
{
"code": null,
"e": 38780,
"s": 38733,
"text": "Median of two sorted arrays of different sizes"
},
{
"code": null,
"e": 38823,
"s": 38780,
"text": "Find the index of an array element in Java"
},
{
"code": null,
"e": 38846,
"s": 38823,
"text": "Two Pointers Technique"
}
] |
Print an N x M matrix such that each row and column has all the vowels in it
|
30 May, 2022
Given two integers N and M, the task is to print an N x M matrix such that each row and column contain all the vowels in it. If it is impossible to do so, then print -1. Examples:
Input: N = 5, M = 5 Output: a e i o u e i o u a i o u a e o u a e i u a e i oInput: N = 6, M = 2 Output: -1
Approach: Since the number of vowels are 5, hence we need a minimum of 5 rows and 5 columns in order to generate a valid matrix. A pattern can be followed by filling “aeiouaeiou..” in the first row, “eiouaeio..” in the second row, and so on and the generated matrix will contain all the vowels in every row and column.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print the required matrixvoid printMatrix(int n, int m){ // Impossible to generate // the required matrix if (n < 5 || m < 5) { cout << -1; return; } // Store all the vowels string s = "aeiou"; // Print the matrix for (int i = 0; i < n; i++) { // Print vowels for every index for (int j = 0; j < m; j++) { cout << s[j % 5] << " "; } cout << endl; char c = s[0]; // Shift the vowels by one for (int i = 0; i < 4; i++) { s[i] = s[i + 1]; } s[4] = c; }} // Driver codeint main(){ int n = 5, m = 5; printMatrix(n, m); return 0;}
// Java implementation of the approachclass GFG{ // Function to print the required matrixstatic void printMatrix(int n, int m){ // Impossible to generate // the required matrix if (n < 5 || m < 5) { System.out.print(-1); return; } // Store all the vowels char[] s = "aeiou".toCharArray(); // Print the matrix for (int i = 0; i < n; i++) { // Print vowels for every index for (int j = 0; j < m; j++) { System.out.print(s[j % 5] + " "); } System.out.println(); char c = s[0]; // Shift the vowels by one for (int k = 0; k < 4; k++) { s[k] = s[k + 1]; } s[4] = c; }} // Driver codepublic static void main(String[] args){ int n = 5, m = 5; printMatrix(n, m);}} // This code has been contributed by 29AjayKumar
# Python3 implementation of the approach # Function to print the required matrixdef printMatrix(n, m) : # Impossible to generate # the required matrix if (n < 5 or m < 5) : print(-1,end = " "); return; # Store all the vowels s = "aeiou"; s = list(s); # Print the matrix for i in range(n) : # Print vowels for every index for j in range(m) : print(s[j % 5],end= " "); print() c = s[0]; # Shift the vowels by one for i in range(4) : s[i] = s[i + 1]; s[4] = c; # Driver codeif __name__ == "__main__" : n = 5; m = 5; printMatrix(n, m); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System; class GFG{ // Function to print the required matrixstatic void printMatrix(int n, int m){ // Impossible to generate // the required matrix if (n < 5 || m < 5) { Console.Write(-1); return; } // Store all the vowels char[] s = "aeiou".ToCharArray(); // Print the matrix for (int i = 0; i < n; i++) { // Print vowels for every index for (int j = 0; j < m; j++) { Console.Write(s[j % 5] + " "); } Console.WriteLine(); char c = s[0]; // Shift the vowels by one for (int k = 0; k < 4; k++) { s[k] = s[k + 1]; } s[4] = c; }} // Driver codepublic static void Main(String[] args){ int n = 5, m = 5; printMatrix(n, m);}} /* This code contributed by PrinciRaj1992 */
<?php// PHP implementation of the approach // Function to print the required matrixfunction printMatrix($n, $m){ // Impossible to generate // the required matrix if ($n < 5 || $m < 5) { echo -1; return; } // Store all the vowels $s = "aeiou"; // Print the matrix for ($i = 0; $i < $n; $i++) { // Print vowels for every index for ($j = 0; $j < $m; $j++) { echo $s[$j % 5] . " "; } echo "\n"; $c = $s[0]; // Shift the vowels by one for ($k = 0; $k < 4; $k++) { $s[$k] = $s[$k + 1]; } $s[4] = $c; }} // Driver code $n = 5; $m = 5; printMatrix($n, $m); return 0; // This code is contributed by ChitraNayal ?>
<script> // JavaScript implementation of the approach // Function to print the required matrix function printMatrix(n , m) { // Impossible to generate // the required matrix if (n < 5 || m < 5) { document.write(-1); return; } // Store all the vowels var s = "aeiou"; // Print the matrix for (var i = 0; i < n; i++) { // Print vowels for every index for (j = 0; j < m; j++) { document.write(s[j % 5] + " "); } document.write("<br/>"); var c = s[0]; s = s.substring(1,s.length)+s.substring(0,1); s[4] = c; } } // Driver code var n = 5, m = 5; printMatrix(n, m); // This code contributed by Rajput-Ji </script>
a e i o u
e i o u a
i o u a e
o u a e i
u a e i o
Time Complexity: O(N*M), as we are using nested loops to traverse N*M times.
Auxiliary Space: O(1) as we are not using any extra space.
ankthon
29AjayKumar
princiraj1992
ukasp
Rajput-Ji
rohitsingh57
vowel-consonant
Matrix
Strings
Strings
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 May, 2022"
},
{
"code": null,
"e": 210,
"s": 28,
"text": "Given two integers N and M, the task is to print an N x M matrix such that each row and column contain all the vowels in it. If it is impossible to do so, then print -1. Examples: "
},
{
"code": null,
"e": 320,
"s": 210,
"text": "Input: N = 5, M = 5 Output: a e i o u e i o u a i o u a e o u a e i u a e i oInput: N = 6, M = 2 Output: -1 "
},
{
"code": null,
"e": 693,
"s": 322,
"text": "Approach: Since the number of vowels are 5, hence we need a minimum of 5 rows and 5 columns in order to generate a valid matrix. A pattern can be followed by filling “aeiouaeiou..” in the first row, “eiouaeio..” in the second row, and so on and the generated matrix will contain all the vowels in every row and column.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 697,
"s": 693,
"text": "C++"
},
{
"code": null,
"e": 702,
"s": 697,
"text": "Java"
},
{
"code": null,
"e": 710,
"s": 702,
"text": "Python3"
},
{
"code": null,
"e": 713,
"s": 710,
"text": "C#"
},
{
"code": null,
"e": 717,
"s": 713,
"text": "PHP"
},
{
"code": null,
"e": 728,
"s": 717,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print the required matrixvoid printMatrix(int n, int m){ // Impossible to generate // the required matrix if (n < 5 || m < 5) { cout << -1; return; } // Store all the vowels string s = \"aeiou\"; // Print the matrix for (int i = 0; i < n; i++) { // Print vowels for every index for (int j = 0; j < m; j++) { cout << s[j % 5] << \" \"; } cout << endl; char c = s[0]; // Shift the vowels by one for (int i = 0; i < 4; i++) { s[i] = s[i + 1]; } s[4] = c; }} // Driver codeint main(){ int n = 5, m = 5; printMatrix(n, m); return 0;}",
"e": 1493,
"s": 728,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function to print the required matrixstatic void printMatrix(int n, int m){ // Impossible to generate // the required matrix if (n < 5 || m < 5) { System.out.print(-1); return; } // Store all the vowels char[] s = \"aeiou\".toCharArray(); // Print the matrix for (int i = 0; i < n; i++) { // Print vowels for every index for (int j = 0; j < m; j++) { System.out.print(s[j % 5] + \" \"); } System.out.println(); char c = s[0]; // Shift the vowels by one for (int k = 0; k < 4; k++) { s[k] = s[k + 1]; } s[4] = c; }} // Driver codepublic static void main(String[] args){ int n = 5, m = 5; printMatrix(n, m);}} // This code has been contributed by 29AjayKumar",
"e": 2357,
"s": 1493,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to print the required matrixdef printMatrix(n, m) : # Impossible to generate # the required matrix if (n < 5 or m < 5) : print(-1,end = \" \"); return; # Store all the vowels s = \"aeiou\"; s = list(s); # Print the matrix for i in range(n) : # Print vowels for every index for j in range(m) : print(s[j % 5],end= \" \"); print() c = s[0]; # Shift the vowels by one for i in range(4) : s[i] = s[i + 1]; s[4] = c; # Driver codeif __name__ == \"__main__\" : n = 5; m = 5; printMatrix(n, m); # This code is contributed by AnkitRai01",
"e": 3080,
"s": 2357,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to print the required matrixstatic void printMatrix(int n, int m){ // Impossible to generate // the required matrix if (n < 5 || m < 5) { Console.Write(-1); return; } // Store all the vowels char[] s = \"aeiou\".ToCharArray(); // Print the matrix for (int i = 0; i < n; i++) { // Print vowels for every index for (int j = 0; j < m; j++) { Console.Write(s[j % 5] + \" \"); } Console.WriteLine(); char c = s[0]; // Shift the vowels by one for (int k = 0; k < 4; k++) { s[k] = s[k + 1]; } s[4] = c; }} // Driver codepublic static void Main(String[] args){ int n = 5, m = 5; printMatrix(n, m);}} /* This code contributed by PrinciRaj1992 */",
"e": 3945,
"s": 3080,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to print the required matrixfunction printMatrix($n, $m){ // Impossible to generate // the required matrix if ($n < 5 || $m < 5) { echo -1; return; } // Store all the vowels $s = \"aeiou\"; // Print the matrix for ($i = 0; $i < $n; $i++) { // Print vowels for every index for ($j = 0; $j < $m; $j++) { echo $s[$j % 5] . \" \"; } echo \"\\n\"; $c = $s[0]; // Shift the vowels by one for ($k = 0; $k < 4; $k++) { $s[$k] = $s[$k + 1]; } $s[4] = $c; }} // Driver code $n = 5; $m = 5; printMatrix($n, $m); return 0; // This code is contributed by ChitraNayal ?>",
"e": 4723,
"s": 3945,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function to print the required matrix function printMatrix(n , m) { // Impossible to generate // the required matrix if (n < 5 || m < 5) { document.write(-1); return; } // Store all the vowels var s = \"aeiou\"; // Print the matrix for (var i = 0; i < n; i++) { // Print vowels for every index for (j = 0; j < m; j++) { document.write(s[j % 5] + \" \"); } document.write(\"<br/>\"); var c = s[0]; s = s.substring(1,s.length)+s.substring(0,1); s[4] = c; } } // Driver code var n = 5, m = 5; printMatrix(n, m); // This code contributed by Rajput-Ji </script>",
"e": 5568,
"s": 4723,
"text": null
},
{
"code": null,
"e": 5622,
"s": 5568,
"text": "a e i o u \ne i o u a \ni o u a e \no u a e i \nu a e i o"
},
{
"code": null,
"e": 5701,
"s": 5624,
"text": "Time Complexity: O(N*M), as we are using nested loops to traverse N*M times."
},
{
"code": null,
"e": 5760,
"s": 5701,
"text": "Auxiliary Space: O(1) as we are not using any extra space."
},
{
"code": null,
"e": 5768,
"s": 5760,
"text": "ankthon"
},
{
"code": null,
"e": 5780,
"s": 5768,
"text": "29AjayKumar"
},
{
"code": null,
"e": 5794,
"s": 5780,
"text": "princiraj1992"
},
{
"code": null,
"e": 5800,
"s": 5794,
"text": "ukasp"
},
{
"code": null,
"e": 5810,
"s": 5800,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 5823,
"s": 5810,
"text": "rohitsingh57"
},
{
"code": null,
"e": 5839,
"s": 5823,
"text": "vowel-consonant"
},
{
"code": null,
"e": 5846,
"s": 5839,
"text": "Matrix"
},
{
"code": null,
"e": 5854,
"s": 5846,
"text": "Strings"
},
{
"code": null,
"e": 5862,
"s": 5854,
"text": "Strings"
},
{
"code": null,
"e": 5869,
"s": 5862,
"text": "Matrix"
}
] |
double_click method – Action Chains in Selenium Python
|
15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around double_click method on Action Chains in Python Selenium. double_click method is used to double click on an element or current position.
Syntax –
double_click(on_element=None)
Example –
<input type ="text" name ="passwd" id ="passwd-id" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")element = driver.find_element_by_name("passwd")
Now one can use double_click method as an Action chain as below –
double_click(on_element=element)
To demonstrate, double_click method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element.
Program –
# import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get element element = driver.find_element_by_link_text("Courses") # create action chain objectaction = ActionChains(driver) # double click the itemaction.double_click(on_element = element) # perform the operationaction.perform()
Output –
Python-selenium
selenium
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 May, 2020"
},
{
"code": null,
"e": 616,
"s": 28,
"text": "Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around double_click method on Action Chains in Python Selenium. double_click method is used to double click on an element or current position."
},
{
"code": null,
"e": 625,
"s": 616,
"text": "Syntax –"
},
{
"code": null,
"e": 655,
"s": 625,
"text": "double_click(on_element=None)"
},
{
"code": null,
"e": 665,
"s": 655,
"text": "Example –"
},
{
"code": "<input type =\"text\" name =\"passwd\" id =\"passwd-id\" />",
"e": 719,
"s": 665,
"text": null
},
{
"code": null,
"e": 800,
"s": 719,
"text": "To find an element one needs to use one of the locating strategies, For example,"
},
{
"code": "element = driver.find_element_by_id(\"passwd-id\")element = driver.find_element_by_name(\"passwd\")",
"e": 896,
"s": 800,
"text": null
},
{
"code": null,
"e": 962,
"s": 896,
"text": "Now one can use double_click method as an Action chain as below –"
},
{
"code": null,
"e": 996,
"s": 962,
"text": "double_click(on_element=element)\n"
},
{
"code": null,
"e": 1140,
"s": 996,
"text": "To demonstrate, double_click method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element."
},
{
"code": null,
"e": 1150,
"s": 1140,
"text": "Program –"
},
{
"code": "# import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get element element = driver.find_element_by_link_text(\"Courses\") # create action chain objectaction = ActionChains(driver) # double click the itemaction.double_click(on_element = element) # perform the operationaction.perform()",
"e": 1647,
"s": 1150,
"text": null
},
{
"code": null,
"e": 1656,
"s": 1647,
"text": "Output –"
},
{
"code": null,
"e": 1672,
"s": 1656,
"text": "Python-selenium"
},
{
"code": null,
"e": 1681,
"s": 1672,
"text": "selenium"
},
{
"code": null,
"e": 1698,
"s": 1681,
"text": "Machine Learning"
},
{
"code": null,
"e": 1715,
"s": 1698,
"text": "Machine Learning"
}
] |
Implementation of Artificial Neural Network for XNOR Logic Gate with 2-bit Binary Input
|
06 Jan, 2022
Artificial Neural Network (ANN) is a computational model based on the biological neural networks of animal brains. ANN is modeled with three types of layers: an input layer, hidden layers (one or more), and an output layer. Each layer comprises nodes (like biological neurons) are called Artificial Neurons. All nodes are connected with weighted edges (like synapses in biological brains) between two layers. Initially, with the forward propagation function, the output is predicted. Then through backpropagation, the weight and bias to the nodes are updated to minimizing the error in prediction to attain the convergence of cost function in determining the final output.
XNOR logical function truth table for 2-bit binary variables, i.e, the input vector and the corresponding output –
Approach: Step1: Import the required Python libraries Step2: Define Activation Function : Sigmoid Function Step3: Initialize neural network parameters (weights, bias) and define model hyperparameters (number of iterations, learning rate) Step4: Forward Propagation Step5: Backward Propagation Step6: Update weight and bias parameters Step7: Train the learning model Step8: Plot Loss value vs Epoch Step9: Test the model performance
Python Implementation:
Python3
# import Python Librariesimport numpy as npfrom matplotlib import pyplot as plt # Sigmoid Functiondef sigmoid(z): return 1 / (1 + np.exp(-z)) # Initialization of the neural network parameters# Initialized all the weights in the range of between 0 and 1# Bias values are initialized to 0def initializeParameters(inputFeatures, neuronsInHiddenLayers, outputFeatures): W1 = np.random.randn(neuronsInHiddenLayers, inputFeatures) W2 = np.random.randn(outputFeatures, neuronsInHiddenLayers) b1 = np.zeros((neuronsInHiddenLayers, 1)) b2 = np.zeros((outputFeatures, 1)) parameters = {"W1" : W1, "b1": b1, "W2" : W2, "b2": b2} return parameters # Forward Propagationdef forwardPropagation(X, Y, parameters): m = X.shape[1] W1 = parameters["W1"] W2 = parameters["W2"] b1 = parameters["b1"] b2 = parameters["b2"] Z1 = np.dot(W1, X) + b1 A1 = sigmoid(Z1) Z2 = np.dot(W2, A1) + b2 A2 = sigmoid(Z2) cache = (Z1, A1, W1, b1, Z2, A2, W2, b2) logprobs = np.multiply(np.log(A2), Y) + np.multiply(np.log(1 - A2), (1 - Y)) cost = -np.sum(logprobs) / m return cost, cache, A2 # Backward Propagationdef backwardPropagation(X, Y, cache): m = X.shape[1] (Z1, A1, W1, b1, Z2, A2, W2, b2) = cache dZ2 = A2 - Y dW2 = np.dot(dZ2, A1.T) / m db2 = np.sum(dZ2, axis = 1, keepdims = True) dA1 = np.dot(W2.T, dZ2) dZ1 = np.multiply(dA1, A1 * (1- A1)) dW1 = np.dot(dZ1, X.T) / m db1 = np.sum(dZ1, axis = 1, keepdims = True) / m gradients = {"dZ2": dZ2, "dW2": dW2, "db2": db2, "dZ1": dZ1, "dW1": dW1, "db1": db1} return gradients # Updating the weights based on the negative gradientsdef updateParameters(parameters, gradients, learningRate): parameters["W1"] = parameters["W1"] - learningRate * gradients["dW1"] parameters["W2"] = parameters["W2"] - learningRate * gradients["dW2"] parameters["b1"] = parameters["b1"] - learningRate * gradients["db1"] parameters["b2"] = parameters["b2"] - learningRate * gradients["db2"] return parameters # Model to learn the XNOR truth table X = np.array([[0, 0, 1, 1], [0, 1, 0, 1]]) # XNOR inputY = np.array([[1, 0, 0, 1]]) # XNOR output # Define model parametersneuronsInHiddenLayers = 2 # number of hidden layer neurons (2)inputFeatures = X.shape[0] # number of input features (2)outputFeatures = Y.shape[0] # number of output features (1)parameters = initializeParameters(inputFeatures, neuronsInHiddenLayers, outputFeatures)epoch = 100000learningRate = 0.01losses = np.zeros((epoch, 1)) for i in range(epoch): losses[i, 0], cache, A2 = forwardPropagation(X, Y, parameters) gradients = backwardPropagation(X, Y, cache) parameters = updateParameters(parameters, gradients, learningRate) # Evaluating the performanceplt.figure()plt.plot(losses)plt.xlabel("EPOCHS")plt.ylabel("Loss value")plt.show() # TestingX = np.array([[1, 1, 0, 0], [0, 1, 0, 1]]) # XNOR inputcost, _, A2 = forwardPropagation(X, Y, parameters)prediction = (A2 > 0.5) * 1.0# print(A2)print(prediction)
Output:
[[ 0. 1. 1. 0.]]
Here, the model predicted output for each of the test inputs are exactly matched with the XNOR logic gate conventional output () according to the truth table and the cost function is also continuously converging. Hence, it signifies that the Artificial Neural Network for the XNOR logic gate is correctly implemented.
sweetyty
Neural Network
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Jan, 2022"
},
{
"code": null,
"e": 728,
"s": 54,
"text": "Artificial Neural Network (ANN) is a computational model based on the biological neural networks of animal brains. ANN is modeled with three types of layers: an input layer, hidden layers (one or more), and an output layer. Each layer comprises nodes (like biological neurons) are called Artificial Neurons. All nodes are connected with weighted edges (like synapses in biological brains) between two layers. Initially, with the forward propagation function, the output is predicted. Then through backpropagation, the weight and bias to the nodes are updated to minimizing the error in prediction to attain the convergence of cost function in determining the final output. "
},
{
"code": null,
"e": 844,
"s": 728,
"text": "XNOR logical function truth table for 2-bit binary variables, i.e, the input vector and the corresponding output – "
},
{
"code": null,
"e": 1278,
"s": 844,
"text": "Approach: Step1: Import the required Python libraries Step2: Define Activation Function : Sigmoid Function Step3: Initialize neural network parameters (weights, bias) and define model hyperparameters (number of iterations, learning rate) Step4: Forward Propagation Step5: Backward Propagation Step6: Update weight and bias parameters Step7: Train the learning model Step8: Plot Loss value vs Epoch Step9: Test the model performance "
},
{
"code": null,
"e": 1303,
"s": 1278,
"text": "Python Implementation: "
},
{
"code": null,
"e": 1311,
"s": 1303,
"text": "Python3"
},
{
"code": "# import Python Librariesimport numpy as npfrom matplotlib import pyplot as plt # Sigmoid Functiondef sigmoid(z): return 1 / (1 + np.exp(-z)) # Initialization of the neural network parameters# Initialized all the weights in the range of between 0 and 1# Bias values are initialized to 0def initializeParameters(inputFeatures, neuronsInHiddenLayers, outputFeatures): W1 = np.random.randn(neuronsInHiddenLayers, inputFeatures) W2 = np.random.randn(outputFeatures, neuronsInHiddenLayers) b1 = np.zeros((neuronsInHiddenLayers, 1)) b2 = np.zeros((outputFeatures, 1)) parameters = {\"W1\" : W1, \"b1\": b1, \"W2\" : W2, \"b2\": b2} return parameters # Forward Propagationdef forwardPropagation(X, Y, parameters): m = X.shape[1] W1 = parameters[\"W1\"] W2 = parameters[\"W2\"] b1 = parameters[\"b1\"] b2 = parameters[\"b2\"] Z1 = np.dot(W1, X) + b1 A1 = sigmoid(Z1) Z2 = np.dot(W2, A1) + b2 A2 = sigmoid(Z2) cache = (Z1, A1, W1, b1, Z2, A2, W2, b2) logprobs = np.multiply(np.log(A2), Y) + np.multiply(np.log(1 - A2), (1 - Y)) cost = -np.sum(logprobs) / m return cost, cache, A2 # Backward Propagationdef backwardPropagation(X, Y, cache): m = X.shape[1] (Z1, A1, W1, b1, Z2, A2, W2, b2) = cache dZ2 = A2 - Y dW2 = np.dot(dZ2, A1.T) / m db2 = np.sum(dZ2, axis = 1, keepdims = True) dA1 = np.dot(W2.T, dZ2) dZ1 = np.multiply(dA1, A1 * (1- A1)) dW1 = np.dot(dZ1, X.T) / m db1 = np.sum(dZ1, axis = 1, keepdims = True) / m gradients = {\"dZ2\": dZ2, \"dW2\": dW2, \"db2\": db2, \"dZ1\": dZ1, \"dW1\": dW1, \"db1\": db1} return gradients # Updating the weights based on the negative gradientsdef updateParameters(parameters, gradients, learningRate): parameters[\"W1\"] = parameters[\"W1\"] - learningRate * gradients[\"dW1\"] parameters[\"W2\"] = parameters[\"W2\"] - learningRate * gradients[\"dW2\"] parameters[\"b1\"] = parameters[\"b1\"] - learningRate * gradients[\"db1\"] parameters[\"b2\"] = parameters[\"b2\"] - learningRate * gradients[\"db2\"] return parameters # Model to learn the XNOR truth table X = np.array([[0, 0, 1, 1], [0, 1, 0, 1]]) # XNOR inputY = np.array([[1, 0, 0, 1]]) # XNOR output # Define model parametersneuronsInHiddenLayers = 2 # number of hidden layer neurons (2)inputFeatures = X.shape[0] # number of input features (2)outputFeatures = Y.shape[0] # number of output features (1)parameters = initializeParameters(inputFeatures, neuronsInHiddenLayers, outputFeatures)epoch = 100000learningRate = 0.01losses = np.zeros((epoch, 1)) for i in range(epoch): losses[i, 0], cache, A2 = forwardPropagation(X, Y, parameters) gradients = backwardPropagation(X, Y, cache) parameters = updateParameters(parameters, gradients, learningRate) # Evaluating the performanceplt.figure()plt.plot(losses)plt.xlabel(\"EPOCHS\")plt.ylabel(\"Loss value\")plt.show() # TestingX = np.array([[1, 1, 0, 0], [0, 1, 0, 1]]) # XNOR inputcost, _, A2 = forwardPropagation(X, Y, parameters)prediction = (A2 > 0.5) * 1.0# print(A2)print(prediction)",
"e": 4392,
"s": 1311,
"text": null
},
{
"code": null,
"e": 4401,
"s": 4392,
"text": "Output: "
},
{
"code": null,
"e": 4418,
"s": 4401,
"text": "[[ 0. 1. 1. 0.]]"
},
{
"code": null,
"e": 4737,
"s": 4418,
"text": "Here, the model predicted output for each of the test inputs are exactly matched with the XNOR logic gate conventional output () according to the truth table and the cost function is also continuously converging. Hence, it signifies that the Artificial Neural Network for the XNOR logic gate is correctly implemented. "
},
{
"code": null,
"e": 4748,
"s": 4739,
"text": "sweetyty"
},
{
"code": null,
"e": 4763,
"s": 4748,
"text": "Neural Network"
},
{
"code": null,
"e": 4780,
"s": 4763,
"text": "Machine Learning"
},
{
"code": null,
"e": 4787,
"s": 4780,
"text": "Python"
},
{
"code": null,
"e": 4804,
"s": 4787,
"text": "Machine Learning"
}
] |
Understanding for loops in Java
|
18 Oct, 2018
Suppose it is required to print numbers from 1 to 5. One possible way to do this is with the help of below code:
class GFG { public static void main(String args[]) { int a; a = 1; System.out.println(a); a=2; System.out.println(a); a=3; System.out.println(a); a=4; System.out.println(a); a=5; System.out.println(a); }}
The above code might look simple, but it has many disadvantages, such as:
Fixed Code: The code is made to print only numbers 1 to 5. What if some other numbers or some other pattern is required? In that case, this solution would suggest to write another program with the new required values or change each individual values in the existing program. And this will go on every time resulting in a long and fixed structure written multiple times.
Repetitive Code: As mentioned in the last point, this solution suggests to write the whole program again with the modified value or modify the values in the existing program every time. But what if 100s of such patterns are required. This would result in a lot of repetitive and unnecessary code.
Not Generalised: The suggested solution is not generalised. It means that the numbers to be printed are fed to the code by the user statically. There is no predefined pattern that the code is following and printing the code according to the pattern.
Not Scalable: Every code written in computer science must be written in a scalable manner. It means that the code must run fine with minimum number of changes to print the numbers 1 to 100.
Here comes the “Loop” for help, whenever repetition of a process is required.
Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true.Java provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition checking time.
while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.Syntax :while (boolean condition)
{
loop statements...
}
Flowchart:for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.Syntax:for (initialization condition; testing condition;
increment/decrement)
{
statement(s)
}
Flowchart:Enhanced For loopJava also includes another version of for loop introduced in Java 5. Enhanced for loop provides a simpler way to iterate through the elements of a collection or array. It is inflexible and should be used only when there is a need to iterate through the elements in sequential manner without knowing the index of currently processed element.Syntax:for (T element:Collection obj/array)
{
statement(s)
}
do while: do while loop is similar to while loop with only difference that it checks for condition after executing the statements, and therefore is an example of Exit Control Loop.Syntax:do
{
statements..
}
while (condition);
Flowchart:How to write a loop?On carefully observing the code given above, it can be broken into following processes or steps:1) Initialize a value to a variable2) Print the value3) Change the value4) Print the valueThese processes are repeated again and again. This can be replaced with a loop as follows:In the code shown above, initialization is a=1, the same thing can be made in for loop.The second expression is condition. The condition should specify how many times the loop should execute. It depends on the number of times the process should be repeated. In this case, it should run for 5 times. The value of “a” starts from 1 and it should be printed till its value is 5. So the condition to be added is a<=5.The third expression is the updation. Every time the loop variable, here ‘a’, needs to be updated according to the expected code. Here the value of ‘a’ is incremented by 1 on every print operation. Hence a++ would be suitable in this situation.The last expression is the body, which is the required action to be performed repetitively. Here the value of ‘a’ is printed on every execution.Below is the execution of the required code with the help of Loop:class GFG { public static void main(String args[]) { int a; for (a = 1; a <= 5; a++) { System.out.println(a); } }}My Personal Notes
arrow_drop_upSave
while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.Syntax :while (boolean condition)
{
loop statements...
}
Flowchart:
while (boolean condition)
{
loop statements...
}
Flowchart:
for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.Syntax:for (initialization condition; testing condition;
increment/decrement)
{
statement(s)
}
Flowchart:Enhanced For loopJava also includes another version of for loop introduced in Java 5. Enhanced for loop provides a simpler way to iterate through the elements of a collection or array. It is inflexible and should be used only when there is a need to iterate through the elements in sequential manner without knowing the index of currently processed element.Syntax:for (T element:Collection obj/array)
{
statement(s)
}
for (initialization condition; testing condition;
increment/decrement)
{
statement(s)
}
Flowchart:
Enhanced For loop
Java also includes another version of for loop introduced in Java 5. Enhanced for loop provides a simpler way to iterate through the elements of a collection or array. It is inflexible and should be used only when there is a need to iterate through the elements in sequential manner without knowing the index of currently processed element.Syntax:
for (T element:Collection obj/array)
{
statement(s)
}
do while: do while loop is similar to while loop with only difference that it checks for condition after executing the statements, and therefore is an example of Exit Control Loop.Syntax:do
{
statements..
}
while (condition);
Flowchart:
do
{
statements..
}
while (condition);
Flowchart:
On carefully observing the code given above, it can be broken into following processes or steps:1) Initialize a value to a variable2) Print the value3) Change the value4) Print the value
These processes are repeated again and again. This can be replaced with a loop as follows:
In the code shown above, initialization is a=1, the same thing can be made in for loop.
The second expression is condition. The condition should specify how many times the loop should execute. It depends on the number of times the process should be repeated. In this case, it should run for 5 times. The value of “a” starts from 1 and it should be printed till its value is 5. So the condition to be added is a<=5.
The third expression is the updation. Every time the loop variable, here ‘a’, needs to be updated according to the expected code. Here the value of ‘a’ is incremented by 1 on every print operation. Hence a++ would be suitable in this situation.
The last expression is the body, which is the required action to be performed repetitively. Here the value of ‘a’ is printed on every execution.
Below is the execution of the required code with the help of Loop:
class GFG { public static void main(String args[]) { int a; for (a = 1; a <= 5; a++) { System.out.println(a); } }}
Java-Control-Flow
Technical Scripter 2018
Java
School Programming
Java-Control-Flow
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n18 Oct, 2018"
},
{
"code": null,
"e": 166,
"s": 53,
"text": "Suppose it is required to print numbers from 1 to 5. One possible way to do this is with the help of below code:"
},
{
"code": "class GFG { public static void main(String args[]) { int a; a = 1; System.out.println(a); a=2; System.out.println(a); a=3; System.out.println(a); a=4; System.out.println(a); a=5; System.out.println(a); }}",
"e": 459,
"s": 166,
"text": null
},
{
"code": null,
"e": 533,
"s": 459,
"text": "The above code might look simple, but it has many disadvantages, such as:"
},
{
"code": null,
"e": 903,
"s": 533,
"text": "Fixed Code: The code is made to print only numbers 1 to 5. What if some other numbers or some other pattern is required? In that case, this solution would suggest to write another program with the new required values or change each individual values in the existing program. And this will go on every time resulting in a long and fixed structure written multiple times."
},
{
"code": null,
"e": 1200,
"s": 903,
"text": "Repetitive Code: As mentioned in the last point, this solution suggests to write the whole program again with the modified value or modify the values in the existing program every time. But what if 100s of such patterns are required. This would result in a lot of repetitive and unnecessary code."
},
{
"code": null,
"e": 1450,
"s": 1200,
"text": "Not Generalised: The suggested solution is not generalised. It means that the numbers to be printed are fed to the code by the user statically. There is no predefined pattern that the code is following and printing the code according to the pattern."
},
{
"code": null,
"e": 1640,
"s": 1450,
"text": "Not Scalable: Every code written in computer science must be written in a scalable manner. It means that the code must run fine with minimum number of changes to print the numbers 1 to 100."
},
{
"code": null,
"e": 1718,
"s": 1640,
"text": "Here comes the “Loop” for help, whenever repetition of a process is required."
},
{
"code": null,
"e": 2044,
"s": 1718,
"text": "Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true.Java provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition checking time."
},
{
"code": null,
"e": 4712,
"s": 2044,
"text": "while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.Syntax :while (boolean condition)\n{\n loop statements...\n}\nFlowchart:for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.Syntax:for (initialization condition; testing condition; \n increment/decrement)\n{\n statement(s)\n}\nFlowchart:Enhanced For loopJava also includes another version of for loop introduced in Java 5. Enhanced for loop provides a simpler way to iterate through the elements of a collection or array. It is inflexible and should be used only when there is a need to iterate through the elements in sequential manner without knowing the index of currently processed element.Syntax:for (T element:Collection obj/array)\n{\n statement(s)\n}\ndo while: do while loop is similar to while loop with only difference that it checks for condition after executing the statements, and therefore is an example of Exit Control Loop.Syntax:do\n{\n statements..\n}\nwhile (condition);\nFlowchart:How to write a loop?On carefully observing the code given above, it can be broken into following processes or steps:1) Initialize a value to a variable2) Print the value3) Change the value4) Print the valueThese processes are repeated again and again. This can be replaced with a loop as follows:In the code shown above, initialization is a=1, the same thing can be made in for loop.The second expression is condition. The condition should specify how many times the loop should execute. It depends on the number of times the process should be repeated. In this case, it should run for 5 times. The value of “a” starts from 1 and it should be printed till its value is 5. So the condition to be added is a<=5.The third expression is the updation. Every time the loop variable, here ‘a’, needs to be updated according to the expected code. Here the value of ‘a’ is incremented by 1 on every print operation. Hence a++ would be suitable in this situation.The last expression is the body, which is the required action to be performed repetitively. Here the value of ‘a’ is printed on every execution.Below is the execution of the required code with the help of Loop:class GFG { public static void main(String args[]) { int a; for (a = 1; a <= 5; a++) { System.out.println(a); } }}My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 4976,
"s": 4712,
"text": "while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.Syntax :while (boolean condition)\n{\n loop statements...\n}\nFlowchart:"
},
{
"code": null,
"e": 5029,
"s": 4976,
"text": "while (boolean condition)\n{\n loop statements...\n}\n"
},
{
"code": null,
"e": 5040,
"s": 5029,
"text": "Flowchart:"
},
{
"code": null,
"e": 5852,
"s": 5040,
"text": "for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.Syntax:for (initialization condition; testing condition; \n increment/decrement)\n{\n statement(s)\n}\nFlowchart:Enhanced For loopJava also includes another version of for loop introduced in Java 5. Enhanced for loop provides a simpler way to iterate through the elements of a collection or array. It is inflexible and should be used only when there is a need to iterate through the elements in sequential manner without knowing the index of currently processed element.Syntax:for (T element:Collection obj/array)\n{\n statement(s)\n}\n"
},
{
"code": null,
"e": 5976,
"s": 5852,
"text": "for (initialization condition; testing condition; \n increment/decrement)\n{\n statement(s)\n}\n"
},
{
"code": null,
"e": 5987,
"s": 5976,
"text": "Flowchart:"
},
{
"code": null,
"e": 6005,
"s": 5987,
"text": "Enhanced For loop"
},
{
"code": null,
"e": 6353,
"s": 6005,
"text": "Java also includes another version of for loop introduced in Java 5. Enhanced for loop provides a simpler way to iterate through the elements of a collection or array. It is inflexible and should be used only when there is a need to iterate through the elements in sequential manner without knowing the index of currently processed element.Syntax:"
},
{
"code": null,
"e": 6412,
"s": 6353,
"text": "for (T element:Collection obj/array)\n{\n statement(s)\n}\n"
},
{
"code": null,
"e": 6653,
"s": 6412,
"text": "do while: do while loop is similar to while loop with only difference that it checks for condition after executing the statements, and therefore is an example of Exit Control Loop.Syntax:do\n{\n statements..\n}\nwhile (condition);\nFlowchart:"
},
{
"code": null,
"e": 6697,
"s": 6653,
"text": "do\n{\n statements..\n}\nwhile (condition);\n"
},
{
"code": null,
"e": 6708,
"s": 6697,
"text": "Flowchart:"
},
{
"code": null,
"e": 6895,
"s": 6708,
"text": "On carefully observing the code given above, it can be broken into following processes or steps:1) Initialize a value to a variable2) Print the value3) Change the value4) Print the value"
},
{
"code": null,
"e": 6986,
"s": 6895,
"text": "These processes are repeated again and again. This can be replaced with a loop as follows:"
},
{
"code": null,
"e": 7074,
"s": 6986,
"text": "In the code shown above, initialization is a=1, the same thing can be made in for loop."
},
{
"code": null,
"e": 7401,
"s": 7074,
"text": "The second expression is condition. The condition should specify how many times the loop should execute. It depends on the number of times the process should be repeated. In this case, it should run for 5 times. The value of “a” starts from 1 and it should be printed till its value is 5. So the condition to be added is a<=5."
},
{
"code": null,
"e": 7646,
"s": 7401,
"text": "The third expression is the updation. Every time the loop variable, here ‘a’, needs to be updated according to the expected code. Here the value of ‘a’ is incremented by 1 on every print operation. Hence a++ would be suitable in this situation."
},
{
"code": null,
"e": 7791,
"s": 7646,
"text": "The last expression is the body, which is the required action to be performed repetitively. Here the value of ‘a’ is printed on every execution."
},
{
"code": null,
"e": 7858,
"s": 7791,
"text": "Below is the execution of the required code with the help of Loop:"
},
{
"code": "class GFG { public static void main(String args[]) { int a; for (a = 1; a <= 5; a++) { System.out.println(a); } }}",
"e": 8014,
"s": 7858,
"text": null
},
{
"code": null,
"e": 8032,
"s": 8014,
"text": "Java-Control-Flow"
},
{
"code": null,
"e": 8056,
"s": 8032,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 8061,
"s": 8056,
"text": "Java"
},
{
"code": null,
"e": 8080,
"s": 8061,
"text": "School Programming"
},
{
"code": null,
"e": 8098,
"s": 8080,
"text": "Java-Control-Flow"
},
{
"code": null,
"e": 8103,
"s": 8098,
"text": "Java"
}
] |
Given a linked list, reverse alternate nodes and append at the end
|
23 Jun, 2022
Given a linked list, reverse alternate nodes and append them to the end of the list. Extra allowed space is O(1)
Examples:
Input: 1->2->3->4->5->6
Output: 1->3->5->6->4->2
Explanation: Two lists are 1->3->5 and 2->4->6,
reverse the 2nd list: 6->4->2.
Merge the lists
Input: 12->14->16->18->20
Output: 12->16->20->18->14
Explanation: Two lists are 12->16->20 and 14->18,
reverse the 2nd list: 18->14.
Merge the lists
Approach:
The idea is to maintain two linked lists, one list of all odd positioned nodes and other list of all even positioned nodes .Traverse the given linked list which is considered as an odd list or oddly positioned nodes.If the node is even node, remove it from the odd list and add it to the front of even node list. Nodes are added at front to keep the reverse order.Append the even node list at the end of odd node list.
The idea is to maintain two linked lists, one list of all odd positioned nodes and other list of all even positioned nodes .
Traverse the given linked list which is considered as an odd list or oddly positioned nodes.
If the node is even node, remove it from the odd list and add it to the front of even node list. Nodes are added at front to keep the reverse order.
Append the even node list at the end of odd node list.
Illustration:
Implementation:
C++
C
Java
Python3
C#
Javascript
// C++ program to reverse alternate// nodes of a linked list and append// at the end#include <bits/stdc++.h>using namespace std; /* A linked list node */class Node {public: int data; Node* next;}; /* Function to reverse all even positionednode and append at the end odd is the headnode of given linked list */void rearrange(Node* odd){ // If linked list has less than 3 // nodes, no change is required if (odd == NULL || odd->next == NULL || odd->next->next == NULL) return; // even points to the beginning of even list Node* even = odd->next; // Remove the first even node odd->next = odd->next->next; // odd points to next node in odd list odd = odd->next; // Set terminator for even list even->next = NULL; // Traverse the list while (odd->next) { // Store the next node in odd list Node* temp = odd->next->next; // Link the next even node at // the beginning of even list odd->next->next = even; even = odd->next; // Remove the even node from middle odd->next = temp; // Move odd to the next odd node if (temp != NULL) odd = temp; } // Append the even list at the end of odd list odd->next = even;} /* Function to add a node atthe beginning of Linked List */void push(Node** head_ref, int new_data){ Node* new_node = new Node(); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} /* Function to print nodesin a given linked list */void printList(Node* node){ while (node != NULL) { cout << node->data << " "; node = node->next; }} /* Driver code */int main(){ Node* start = NULL; /* The constructed linked list is: 1->2->3->4->5->6->7 */ push(&start, 7); push(&start, 6); push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); cout << "Linked list before calling rearrange() "; printList(start); rearrange(start); cout << "\nLinked list after calling rearrange() "; printList(start); return 0;} // This code is contributed by rathbhupendra
#include <stdio.h>#include <stdlib.h> /* A linked list node */struct Node { int data; struct Node* next;}; /* Function to reverse all even positioned node and append at the end odd is the head node of given linked list */void rearrange(struct Node* odd){ // If linked list has less than 3 nodes, // no change is required if (odd == NULL || odd->next == NULL || odd->next->next == NULL) return; // even points to the beginning of even list struct Node* even = odd->next; // Remove the first even node odd->next = odd->next->next; // odd points to next node in odd list odd = odd->next; // Set terminator for even list even->next = NULL; // Traverse the list while (odd->next) { // Store the next node in odd list struct Node* temp = odd->next->next; // Link the next even node at the // beginning of even list odd->next->next = even; even = odd->next; // Remove the even node from middle odd->next = temp; // Move odd to the next odd node if (temp != NULL) odd = temp; } // Append the even list at the end of odd list odd->next = even;} /* Function to add a node at the beginning of Linked List */void push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc( sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} /* Driver program to test above function */int main(){ struct Node* start = NULL; /* The constructed linked list is: 1->2->3->4->5->6->7 */ push(&start, 7); push(&start, 6); push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); printf("\n Linked list before calling rearrange() "); printList(start); rearrange(start); printf("\n Linked list after calling rearrange() "); printList(start); return 0;}
// Java program to reverse alternate// nodes of a linked list and append// at the end class LinkedList { static Node head; static class Node { int data; Node next; Node(int item) { data = item; next = null; } } /* Function to reverse all even positioned node and append at the end odd is the head node of given linked list */ void rearrange(Node odd) { // If linked list has less than 3 nodes, // no change is required if (odd == null || odd.next == null || odd.next.next == null) { return; } // even points to the beginning // of even list Node even = odd.next; // Remove the first even node odd.next = odd.next.next; // odd points to next node in odd list odd = odd.next; // Set terminator for even list even.next = null; // Traverse the list while (odd.next != null) { // Store the next node in odd list Node temp = odd.next.next; // Link the next even node at the // beginning of even list odd.next.next = even; even = odd.next; // Remove the even node from middle odd.next = temp; // Move odd to the next odd node if (temp != null) { odd = temp; } } // Append the even list at the end of odd list odd.next = even; } /* Function to print nodes in a given linked list */ void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } public static void main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node(1); list.head.next = new Node(2); list.head.next.next = new Node(3); list.head.next.next.next = new Node(4); list.head.next.next.next.next = new Node(5); list.head.next.next.next.next.next = new Node(6); list.head.next.next.next.next.next.next = new Node(7); System.out.println("Linked list before calling rearrange : "); list.printList(head); System.out.println(""); list.rearrange(head); System.out.println("Linked list after calling rearrange : "); list.printList(head); }}
# Python program to reverse alternate nodes and append# at end# Extra space allowed - O(1) # Node Classclass Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None # Linked list class contains node objectclass LinkedList: # Constructor to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def printList(self): temp = self.head while(temp): print (temp.data,end=" ") temp = temp.next def rearrange(self): # If linked list has less than 3 nodes, no change # is required odd = self.head if (odd is None or odd.next is None or odd.next.next is None): return # Even points to the beginning of even list even = odd.next # Remove the first even node odd.next = odd.next.next # Odd points to next node in odd list odd = odd.next # Set terminator for even list even.next = None # Traverse the list while (odd.next): # Store the next node in odd list temp = odd.next.next # Link the next even node at the beginning # of even list odd.next.next = even even = odd.next # Remove the even node from middle odd.next = temp # Move odd to the next odd node if temp is not None: odd = temp # Append the even list at the end of odd list odd.next = even # Code execution starts hereif __name__ == '__main__': start = LinkedList() # The constructed linked list is ; # 1->2->3->4->5->6->7 start.push(7) start.push(6) start.push(5) start.push(4) start.push(3) start.push(2) start.push(1) print ("Linked list before calling rearrange() ") start.printList() start.rearrange() print ("\nLinked list after calling rearrange()") start.printList() # This code is contributed by NIkhil Kumar Singh(nickzuck_007)
// C# program to reverse alternate// nodes of a linked list// and append at the endusing System; public class LinkedList { Node head; public class Node { public int data; public Node next; public Node(int item) { data = item; next = null; } } /* Function to reverse all even positioned node and append at the end odd is the head node of given linked list */ void rearrange(Node odd) { // If linked list has less than 3 // nodes, no change is required if (odd == null || odd.next == null || odd.next.next == null) { return; } // even points to the beginning of even list Node even = odd.next; // Remove the first even node odd.next = odd.next.next; // odd points to next node in odd list odd = odd.next; // Set terminator for even list even.next = null; // Traverse the list while (odd.next != null) { // Store the next node in odd list Node temp = odd.next.next; // Link the next even node at // the beginning of even list odd.next.next = even; even = odd.next; // Remove the even node from middle odd.next = temp; // Move odd to the next odd node if (temp != null) { odd = temp; } } // Append the even list at the end of odd list odd.next = even; } /* Function to print nodes in a given linked list */ void printList(Node node) { while (node != null) { Console.Write(node.data + " "); node = node.next; } } // Driver code public static void Main() { LinkedList list = new LinkedList(); list.head = new Node(1); list.head.next = new Node(2); list.head.next.next = new Node(3); list.head.next.next.next = new Node(4); list.head.next.next.next.next = new Node(5); list.head.next.next.next.next.next = new Node(6); list.head.next.next.next.next.next.next = new Node(7); Console.WriteLine("Linked list before calling rearrange : "); list.printList(list.head); Console.WriteLine(""); list.rearrange(list.head); Console.WriteLine("Linked list after calling rearrange : "); list.printList(list.head); }} /* This code contributed by PrinciRaj1992 */
<script> // Javascript program to reverse alternate// nodes of a linked list and append// at the endclass Node{ constructor(item) { this.data = item; this.next = null; }} let head; // Function to reverse all even positioned// node and append at the end odd is the// head node of given linked listfunction rearrange(odd){ // If linked list has less than 3 nodes, // no change is required if (odd == null || odd.next == null || odd.next.next == null) { return; } // Even points to the beginning // of even list let even = odd.next; // Remove the first even node odd.next = odd.next.next; // Odd points to next node in odd list odd = odd.next; // Set terminator for even list even.next = null; // Traverse the list while (odd.next != null) { // Store the next node in odd list let temp = odd.next.next; // Link the next even node at the // beginning of even list odd.next.next = even; even = odd.next; // Remove the even node from middle odd.next = temp; // Move odd to the next odd node if (temp != null) { odd = temp; } } // Append the even list at the // end of odd list odd.next = even;} // Function to print nodes in a// given linked listfunction printList(node){ while (node != null) { document.write(node.data + " "); node = node.next; }} // Driver codehead = new Node(1);head.next = new Node(2);head.next.next = new Node(3);head.next.next.next = new Node(4);head.next.next.next.next = new Node(5);head.next.next.next.next.next = new Node(6);head.next.next.next.next.next.next = new Node(7); document.write("Linked list before " + "calling rearrange : <br>");printList(head); document.write("<br>");rearrange(head); document.write("Linked list after " + "calling rearrange : <br>");printList(head); // This code is contributed by avanitrachhadiya2155 </script>
Linked list before calling rearrange() 1 2 3 4 5 6 7
Linked list after calling rearrange() 1 3 5 7 6 4 2
Complexity Analysis:
Time Complexity: O(n). The above code simply traverses the given linked list. So time complexity is O(n)
Auxiliary Space: O(1). No extra space is required.
princiraj1992
rathbhupendra
nidhi_biet
andrew1234
avanitrachhadiya2155
chandrajeet yadav
amartyaghoshgfg
hardikkoriintern
Reverse
Linked List
Linked List
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 168,
"s": 54,
"text": "Given a linked list, reverse alternate nodes and append them to the end of the list. Extra allowed space is O(1) "
},
{
"code": null,
"e": 179,
"s": 168,
"text": "Examples: "
},
{
"code": null,
"e": 479,
"s": 179,
"text": "Input: 1->2->3->4->5->6\nOutput: 1->3->5->6->4->2\nExplanation: Two lists are 1->3->5 and 2->4->6, \nreverse the 2nd list: 6->4->2. \nMerge the lists \n\nInput: 12->14->16->18->20\nOutput: 12->16->20->18->14\nExplanation: Two lists are 12->16->20 and 14->18, \nreverse the 2nd list: 18->14. \nMerge the lists "
},
{
"code": null,
"e": 490,
"s": 479,
"text": "Approach: "
},
{
"code": null,
"e": 909,
"s": 490,
"text": "The idea is to maintain two linked lists, one list of all odd positioned nodes and other list of all even positioned nodes .Traverse the given linked list which is considered as an odd list or oddly positioned nodes.If the node is even node, remove it from the odd list and add it to the front of even node list. Nodes are added at front to keep the reverse order.Append the even node list at the end of odd node list."
},
{
"code": null,
"e": 1034,
"s": 909,
"text": "The idea is to maintain two linked lists, one list of all odd positioned nodes and other list of all even positioned nodes ."
},
{
"code": null,
"e": 1127,
"s": 1034,
"text": "Traverse the given linked list which is considered as an odd list or oddly positioned nodes."
},
{
"code": null,
"e": 1276,
"s": 1127,
"text": "If the node is even node, remove it from the odd list and add it to the front of even node list. Nodes are added at front to keep the reverse order."
},
{
"code": null,
"e": 1331,
"s": 1276,
"text": "Append the even node list at the end of odd node list."
},
{
"code": null,
"e": 1346,
"s": 1331,
"text": "Illustration: "
},
{
"code": null,
"e": 1362,
"s": 1346,
"text": "Implementation:"
},
{
"code": null,
"e": 1366,
"s": 1362,
"text": "C++"
},
{
"code": null,
"e": 1368,
"s": 1366,
"text": "C"
},
{
"code": null,
"e": 1373,
"s": 1368,
"text": "Java"
},
{
"code": null,
"e": 1381,
"s": 1373,
"text": "Python3"
},
{
"code": null,
"e": 1384,
"s": 1381,
"text": "C#"
},
{
"code": null,
"e": 1395,
"s": 1384,
"text": "Javascript"
},
{
"code": "// C++ program to reverse alternate// nodes of a linked list and append// at the end#include <bits/stdc++.h>using namespace std; /* A linked list node */class Node {public: int data; Node* next;}; /* Function to reverse all even positionednode and append at the end odd is the headnode of given linked list */void rearrange(Node* odd){ // If linked list has less than 3 // nodes, no change is required if (odd == NULL || odd->next == NULL || odd->next->next == NULL) return; // even points to the beginning of even list Node* even = odd->next; // Remove the first even node odd->next = odd->next->next; // odd points to next node in odd list odd = odd->next; // Set terminator for even list even->next = NULL; // Traverse the list while (odd->next) { // Store the next node in odd list Node* temp = odd->next->next; // Link the next even node at // the beginning of even list odd->next->next = even; even = odd->next; // Remove the even node from middle odd->next = temp; // Move odd to the next odd node if (temp != NULL) odd = temp; } // Append the even list at the end of odd list odd->next = even;} /* Function to add a node atthe beginning of Linked List */void push(Node** head_ref, int new_data){ Node* new_node = new Node(); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} /* Function to print nodesin a given linked list */void printList(Node* node){ while (node != NULL) { cout << node->data << \" \"; node = node->next; }} /* Driver code */int main(){ Node* start = NULL; /* The constructed linked list is: 1->2->3->4->5->6->7 */ push(&start, 7); push(&start, 6); push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); cout << \"Linked list before calling rearrange() \"; printList(start); rearrange(start); cout << \"\\nLinked list after calling rearrange() \"; printList(start); return 0;} // This code is contributed by rathbhupendra",
"e": 3536,
"s": 1395,
"text": null
},
{
"code": "#include <stdio.h>#include <stdlib.h> /* A linked list node */struct Node { int data; struct Node* next;}; /* Function to reverse all even positioned node and append at the end odd is the head node of given linked list */void rearrange(struct Node* odd){ // If linked list has less than 3 nodes, // no change is required if (odd == NULL || odd->next == NULL || odd->next->next == NULL) return; // even points to the beginning of even list struct Node* even = odd->next; // Remove the first even node odd->next = odd->next->next; // odd points to next node in odd list odd = odd->next; // Set terminator for even list even->next = NULL; // Traverse the list while (odd->next) { // Store the next node in odd list struct Node* temp = odd->next->next; // Link the next even node at the // beginning of even list odd->next->next = even; even = odd->next; // Remove the even node from middle odd->next = temp; // Move odd to the next odd node if (temp != NULL) odd = temp; } // Append the even list at the end of odd list odd->next = even;} /* Function to add a node at the beginning of Linked List */void push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc( sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} /* Driver program to test above function */int main(){ struct Node* start = NULL; /* The constructed linked list is: 1->2->3->4->5->6->7 */ push(&start, 7); push(&start, 6); push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); printf(\"\\n Linked list before calling rearrange() \"); printList(start); rearrange(start); printf(\"\\n Linked list after calling rearrange() \"); printList(start); return 0;}",
"e": 5703,
"s": 3536,
"text": null
},
{
"code": "// Java program to reverse alternate// nodes of a linked list and append// at the end class LinkedList { static Node head; static class Node { int data; Node next; Node(int item) { data = item; next = null; } } /* Function to reverse all even positioned node and append at the end odd is the head node of given linked list */ void rearrange(Node odd) { // If linked list has less than 3 nodes, // no change is required if (odd == null || odd.next == null || odd.next.next == null) { return; } // even points to the beginning // of even list Node even = odd.next; // Remove the first even node odd.next = odd.next.next; // odd points to next node in odd list odd = odd.next; // Set terminator for even list even.next = null; // Traverse the list while (odd.next != null) { // Store the next node in odd list Node temp = odd.next.next; // Link the next even node at the // beginning of even list odd.next.next = even; even = odd.next; // Remove the even node from middle odd.next = temp; // Move odd to the next odd node if (temp != null) { odd = temp; } } // Append the even list at the end of odd list odd.next = even; } /* Function to print nodes in a given linked list */ void printList(Node node) { while (node != null) { System.out.print(node.data + \" \"); node = node.next; } } public static void main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node(1); list.head.next = new Node(2); list.head.next.next = new Node(3); list.head.next.next.next = new Node(4); list.head.next.next.next.next = new Node(5); list.head.next.next.next.next.next = new Node(6); list.head.next.next.next.next.next.next = new Node(7); System.out.println(\"Linked list before calling rearrange : \"); list.printList(head); System.out.println(\"\"); list.rearrange(head); System.out.println(\"Linked list after calling rearrange : \"); list.printList(head); }}",
"e": 8111,
"s": 5703,
"text": null
},
{
"code": "# Python program to reverse alternate nodes and append# at end# Extra space allowed - O(1) # Node Classclass Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None # Linked list class contains node objectclass LinkedList: # Constructor to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def printList(self): temp = self.head while(temp): print (temp.data,end=\" \") temp = temp.next def rearrange(self): # If linked list has less than 3 nodes, no change # is required odd = self.head if (odd is None or odd.next is None or odd.next.next is None): return # Even points to the beginning of even list even = odd.next # Remove the first even node odd.next = odd.next.next # Odd points to next node in odd list odd = odd.next # Set terminator for even list even.next = None # Traverse the list while (odd.next): # Store the next node in odd list temp = odd.next.next # Link the next even node at the beginning # of even list odd.next.next = even even = odd.next # Remove the even node from middle odd.next = temp # Move odd to the next odd node if temp is not None: odd = temp # Append the even list at the end of odd list odd.next = even # Code execution starts hereif __name__ == '__main__': start = LinkedList() # The constructed linked list is ; # 1->2->3->4->5->6->7 start.push(7) start.push(6) start.push(5) start.push(4) start.push(3) start.push(2) start.push(1) print (\"Linked list before calling rearrange() \") start.printList() start.rearrange() print (\"\\nLinked list after calling rearrange()\") start.printList() # This code is contributed by NIkhil Kumar Singh(nickzuck_007)",
"e": 10416,
"s": 8111,
"text": null
},
{
"code": "// C# program to reverse alternate// nodes of a linked list// and append at the endusing System; public class LinkedList { Node head; public class Node { public int data; public Node next; public Node(int item) { data = item; next = null; } } /* Function to reverse all even positioned node and append at the end odd is the head node of given linked list */ void rearrange(Node odd) { // If linked list has less than 3 // nodes, no change is required if (odd == null || odd.next == null || odd.next.next == null) { return; } // even points to the beginning of even list Node even = odd.next; // Remove the first even node odd.next = odd.next.next; // odd points to next node in odd list odd = odd.next; // Set terminator for even list even.next = null; // Traverse the list while (odd.next != null) { // Store the next node in odd list Node temp = odd.next.next; // Link the next even node at // the beginning of even list odd.next.next = even; even = odd.next; // Remove the even node from middle odd.next = temp; // Move odd to the next odd node if (temp != null) { odd = temp; } } // Append the even list at the end of odd list odd.next = even; } /* Function to print nodes in a given linked list */ void printList(Node node) { while (node != null) { Console.Write(node.data + \" \"); node = node.next; } } // Driver code public static void Main() { LinkedList list = new LinkedList(); list.head = new Node(1); list.head.next = new Node(2); list.head.next.next = new Node(3); list.head.next.next.next = new Node(4); list.head.next.next.next.next = new Node(5); list.head.next.next.next.next.next = new Node(6); list.head.next.next.next.next.next.next = new Node(7); Console.WriteLine(\"Linked list before calling rearrange : \"); list.printList(list.head); Console.WriteLine(\"\"); list.rearrange(list.head); Console.WriteLine(\"Linked list after calling rearrange : \"); list.printList(list.head); }} /* This code contributed by PrinciRaj1992 */",
"e": 12887,
"s": 10416,
"text": null
},
{
"code": "<script> // Javascript program to reverse alternate// nodes of a linked list and append// at the endclass Node{ constructor(item) { this.data = item; this.next = null; }} let head; // Function to reverse all even positioned// node and append at the end odd is the// head node of given linked listfunction rearrange(odd){ // If linked list has less than 3 nodes, // no change is required if (odd == null || odd.next == null || odd.next.next == null) { return; } // Even points to the beginning // of even list let even = odd.next; // Remove the first even node odd.next = odd.next.next; // Odd points to next node in odd list odd = odd.next; // Set terminator for even list even.next = null; // Traverse the list while (odd.next != null) { // Store the next node in odd list let temp = odd.next.next; // Link the next even node at the // beginning of even list odd.next.next = even; even = odd.next; // Remove the even node from middle odd.next = temp; // Move odd to the next odd node if (temp != null) { odd = temp; } } // Append the even list at the // end of odd list odd.next = even;} // Function to print nodes in a// given linked listfunction printList(node){ while (node != null) { document.write(node.data + \" \"); node = node.next; }} // Driver codehead = new Node(1);head.next = new Node(2);head.next.next = new Node(3);head.next.next.next = new Node(4);head.next.next.next.next = new Node(5);head.next.next.next.next.next = new Node(6);head.next.next.next.next.next.next = new Node(7); document.write(\"Linked list before \" + \"calling rearrange : <br>\");printList(head); document.write(\"<br>\");rearrange(head); document.write(\"Linked list after \" + \"calling rearrange : <br>\");printList(head); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 14926,
"s": 12887,
"text": null
},
{
"code": null,
"e": 15033,
"s": 14926,
"text": "Linked list before calling rearrange() 1 2 3 4 5 6 7 \nLinked list after calling rearrange() 1 3 5 7 6 4 2 "
},
{
"code": null,
"e": 15055,
"s": 15033,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 15160,
"s": 15055,
"text": "Time Complexity: O(n). The above code simply traverses the given linked list. So time complexity is O(n)"
},
{
"code": null,
"e": 15211,
"s": 15160,
"text": "Auxiliary Space: O(1). No extra space is required."
},
{
"code": null,
"e": 15225,
"s": 15211,
"text": "princiraj1992"
},
{
"code": null,
"e": 15239,
"s": 15225,
"text": "rathbhupendra"
},
{
"code": null,
"e": 15250,
"s": 15239,
"text": "nidhi_biet"
},
{
"code": null,
"e": 15261,
"s": 15250,
"text": "andrew1234"
},
{
"code": null,
"e": 15282,
"s": 15261,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 15300,
"s": 15282,
"text": "chandrajeet yadav"
},
{
"code": null,
"e": 15316,
"s": 15300,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 15333,
"s": 15316,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 15341,
"s": 15333,
"text": "Reverse"
},
{
"code": null,
"e": 15353,
"s": 15341,
"text": "Linked List"
},
{
"code": null,
"e": 15365,
"s": 15353,
"text": "Linked List"
},
{
"code": null,
"e": 15373,
"s": 15365,
"text": "Reverse"
}
] |
Python | Indices of numbers greater than K
|
02 Apr, 2019
Many times we might have problem in which we need to find indices rather than the actual numbers and more often, the result is conditioned. First approach coming to mind can be a simple index function and get indices greater than particular number, but this approach fails in case of duplicate numbers. Let’s discuss certain ways in which this problem can be successfully solved.
Method #1 : Using loopThis problem can easily be solved using loop with a brute force approach in which we can just check for the index as we iterate and append it in a new list as we proceed forward.
# Python3 code to demonstrate# index of matching element using loop # initializing list test_list = [12, 10, 18, 15, 8, 18] # printing original listprint("The original list : " + str(test_list)) # using loop# index of matching elementres = []for idx in range(0, len(test_list)) : if test_list[idx] > 10: res.append(idx) # print resultprint("The list of indices greater than 10 : " + str(res))
The original list : [12, 10, 18, 15, 8, 18]
The list of indices greater than 10 : [0, 2, 3, 5]
Method #2 : Using list comprehension + enumerate()The combination of these two function can also perform this particular task efficiently and in one line. The enumerate function is used to get element and its index simultaneously.
# Python3 code to demonstrate# index of matching element# using list comprehension + enumerate() # initializing list test_list = [12, 10, 18, 15, 8, 18] # printing original listprint("The original list : " + str(test_list)) # using list comprehension + enumerate()# index of matching elementres = [idx for idx, val in enumerate(test_list) if val > 10] # print resultprint("The list of indices greater than 10 : " + str(res))
The original list : [12, 10, 18, 15, 8, 18]
The list of indices greater than 10 : [0, 2, 3, 5]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Apr, 2019"
},
{
"code": null,
"e": 408,
"s": 28,
"text": "Many times we might have problem in which we need to find indices rather than the actual numbers and more often, the result is conditioned. First approach coming to mind can be a simple index function and get indices greater than particular number, but this approach fails in case of duplicate numbers. Let’s discuss certain ways in which this problem can be successfully solved."
},
{
"code": null,
"e": 609,
"s": 408,
"text": "Method #1 : Using loopThis problem can easily be solved using loop with a brute force approach in which we can just check for the index as we iterate and append it in a new list as we proceed forward."
},
{
"code": "# Python3 code to demonstrate# index of matching element using loop # initializing list test_list = [12, 10, 18, 15, 8, 18] # printing original listprint(\"The original list : \" + str(test_list)) # using loop# index of matching elementres = []for idx in range(0, len(test_list)) : if test_list[idx] > 10: res.append(idx) # print resultprint(\"The list of indices greater than 10 : \" + str(res))",
"e": 1016,
"s": 609,
"text": null
},
{
"code": null,
"e": 1112,
"s": 1016,
"text": "The original list : [12, 10, 18, 15, 8, 18]\nThe list of indices greater than 10 : [0, 2, 3, 5]\n"
},
{
"code": null,
"e": 1345,
"s": 1114,
"text": "Method #2 : Using list comprehension + enumerate()The combination of these two function can also perform this particular task efficiently and in one line. The enumerate function is used to get element and its index simultaneously."
},
{
"code": "# Python3 code to demonstrate# index of matching element# using list comprehension + enumerate() # initializing list test_list = [12, 10, 18, 15, 8, 18] # printing original listprint(\"The original list : \" + str(test_list)) # using list comprehension + enumerate()# index of matching elementres = [idx for idx, val in enumerate(test_list) if val > 10] # print resultprint(\"The list of indices greater than 10 : \" + str(res))",
"e": 1774,
"s": 1345,
"text": null
},
{
"code": null,
"e": 1870,
"s": 1774,
"text": "The original list : [12, 10, 18, 15, 8, 18]\nThe list of indices greater than 10 : [0, 2, 3, 5]\n"
},
{
"code": null,
"e": 1891,
"s": 1870,
"text": "Python list-programs"
},
{
"code": null,
"e": 1898,
"s": 1891,
"text": "Python"
},
{
"code": null,
"e": 1914,
"s": 1898,
"text": "Python Programs"
},
{
"code": null,
"e": 2012,
"s": 1914,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2030,
"s": 2012,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2072,
"s": 2030,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2107,
"s": 2072,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2133,
"s": 2107,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2165,
"s": 2133,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2208,
"s": 2165,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2230,
"s": 2208,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2269,
"s": 2230,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2307,
"s": 2269,
"text": "Python | Convert a list to dictionary"
}
] |
Sum of the series 5+55+555+.. up to n terms
|
15 Jun, 2022
Find the sum up to n terms of the sequence: 5 + 55 + 555 + ... up to n. Examples :
Input : 2
Output: 60
Input : 3
Output: 595
Approach:The above problem can be solved using the following formula:
Sum = 5 + 55 + 555 + .... n terms. = 5/9[9 + 99 + 999 + .... n terms] = 5/9[(10 – 1) + (100 – 1) + (1000 – 1) + ... n terms] = 5/9[10 + 100 + 1000 ..... – (1 + 1 + ... 1)] = 5/9[10(10n – 1)/(10 – 1) + (1 + 1 + ... n times)) = 50/81(10n – 1) – 5n/9
Below is the Implementation to find the sum of given series:
C++
Java
Python3
C#
PHP
Javascript
// C++ program for sum of the// series 5 + 55 + 555.....n#include <bits/stdc++.h>using namespace std; // function which return the// the sum of seriesint sumOfSeries(int n){ return 0.6172 * (pow(10, n) - 1) - 0.55 * n; } // Driver codeint main(){ int n = 2; cout << sumOfSeries(n); return 0;}
// Java program for sum of the// series 5 + 55 + 555.....n class GFG{ // function which return the // the sum of series static int sumOfSeries(int n) { return (int) (0.6172 * (Math.pow(10, n) - 1) - 0.55 * n); } // Driver code public static void main(String []args) { int n = 2; System.out.println(sumOfSeries(n)); }} // This code is contributed by UPENDRA BARTWAL.
# python program for sum of the# series 5 + 55 + 555.....n def sumOfSeries(n): return (int) (0.6172 * (pow(10, n) - 1) - 0.55 * n) # Driver Coden = 2print(sumOfSeries(n)) # This code is contributed# by Upendra Singh Bartwal
// C# program for sum of the// series 5 + 55 + 555.....nusing System; class GFG{ // Function which return the // the sum of series static int sumOfSeries(int n) { return (int)(0.6172 * (Math.Pow(10, n) - 1) - 0.55 * n); } // Driver code public static void Main() { int n = 2; Console.Write(sumOfSeries(n)); }} // This code is contributed by vt_m.
<?php// PHP program for sum of the// series 5 + 55 + 555.....n // function which return the// the sum of seriesfunction sumOfSeries($n){ return (int)(0.6172 * (pow(10, $n) - 1) - 0.55 * $n);} // Driver code$n = 2;echo(sumOfSeries($n)); // This code is contributed by Ajit.?>
<script>// javascript program for sum of the// series 5 + 55 + 555.....n // function which return the // the sum of series function sumOfSeries(n) { return parseInt( (0.6172 * (Math.pow(10, n) - 1) - 0.55 * n)); } // Driver code var n = 2; document.write(sumOfSeries(n)); // This code is contributed by aashish1995</script>
Output :
60
Time complexity: O(log n) since using the inbuilt power function.
Auxiliary Space: O(1)
jit_t
aashish1995
polymatir3j
series
series-sum
Mathematical
School Programming
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n15 Jun, 2022"
},
{
"code": null,
"e": 138,
"s": 53,
"text": "Find the sum up to n terms of the sequence: 5 + 55 + 555 + ... up to n. Examples : "
},
{
"code": null,
"e": 182,
"s": 138,
"text": "Input : 2\nOutput: 60\n\nInput : 3\nOutput: 595"
},
{
"code": null,
"e": 255,
"s": 184,
"text": "Approach:The above problem can be solved using the following formula: "
},
{
"code": null,
"e": 503,
"s": 255,
"text": "Sum = 5 + 55 + 555 + .... n terms. = 5/9[9 + 99 + 999 + .... n terms] = 5/9[(10 – 1) + (100 – 1) + (1000 – 1) + ... n terms] = 5/9[10 + 100 + 1000 ..... – (1 + 1 + ... 1)] = 5/9[10(10n – 1)/(10 – 1) + (1 + 1 + ... n times)) = 50/81(10n – 1) – 5n/9"
},
{
"code": null,
"e": 566,
"s": 503,
"text": "Below is the Implementation to find the sum of given series: "
},
{
"code": null,
"e": 570,
"s": 566,
"text": "C++"
},
{
"code": null,
"e": 575,
"s": 570,
"text": "Java"
},
{
"code": null,
"e": 583,
"s": 575,
"text": "Python3"
},
{
"code": null,
"e": 586,
"s": 583,
"text": "C#"
},
{
"code": null,
"e": 590,
"s": 586,
"text": "PHP"
},
{
"code": null,
"e": 601,
"s": 590,
"text": "Javascript"
},
{
"code": "// C++ program for sum of the// series 5 + 55 + 555.....n#include <bits/stdc++.h>using namespace std; // function which return the// the sum of seriesint sumOfSeries(int n){ return 0.6172 * (pow(10, n) - 1) - 0.55 * n; } // Driver codeint main(){ int n = 2; cout << sumOfSeries(n); return 0;}",
"e": 939,
"s": 601,
"text": null
},
{
"code": "// Java program for sum of the// series 5 + 55 + 555.....n class GFG{ // function which return the // the sum of series static int sumOfSeries(int n) { return (int) (0.6172 * (Math.pow(10, n) - 1) - 0.55 * n); } // Driver code public static void main(String []args) { int n = 2; System.out.println(sumOfSeries(n)); }} // This code is contributed by UPENDRA BARTWAL.",
"e": 1410,
"s": 939,
"text": null
},
{
"code": "# python program for sum of the# series 5 + 55 + 555.....n def sumOfSeries(n): return (int) (0.6172 * (pow(10, n) - 1) - 0.55 * n) # Driver Coden = 2print(sumOfSeries(n)) # This code is contributed# by Upendra Singh Bartwal",
"e": 1677,
"s": 1410,
"text": null
},
{
"code": "// C# program for sum of the// series 5 + 55 + 555.....nusing System; class GFG{ // Function which return the // the sum of series static int sumOfSeries(int n) { return (int)(0.6172 * (Math.Pow(10, n) - 1) - 0.55 * n); } // Driver code public static void Main() { int n = 2; Console.Write(sumOfSeries(n)); }} // This code is contributed by vt_m.",
"e": 2129,
"s": 1677,
"text": null
},
{
"code": "<?php// PHP program for sum of the// series 5 + 55 + 555.....n // function which return the// the sum of seriesfunction sumOfSeries($n){ return (int)(0.6172 * (pow(10, $n) - 1) - 0.55 * $n);} // Driver code$n = 2;echo(sumOfSeries($n)); // This code is contributed by Ajit.?>",
"e": 2446,
"s": 2129,
"text": null
},
{
"code": "<script>// javascript program for sum of the// series 5 + 55 + 555.....n // function which return the // the sum of series function sumOfSeries(n) { return parseInt( (0.6172 * (Math.pow(10, n) - 1) - 0.55 * n)); } // Driver code var n = 2; document.write(sumOfSeries(n)); // This code is contributed by aashish1995</script>",
"e": 2803,
"s": 2446,
"text": null
},
{
"code": null,
"e": 2814,
"s": 2803,
"text": "Output : "
},
{
"code": null,
"e": 2817,
"s": 2814,
"text": "60"
},
{
"code": null,
"e": 2883,
"s": 2817,
"text": "Time complexity: O(log n) since using the inbuilt power function."
},
{
"code": null,
"e": 2907,
"s": 2883,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 2913,
"s": 2907,
"text": "jit_t"
},
{
"code": null,
"e": 2925,
"s": 2913,
"text": "aashish1995"
},
{
"code": null,
"e": 2937,
"s": 2925,
"text": "polymatir3j"
},
{
"code": null,
"e": 2944,
"s": 2937,
"text": "series"
},
{
"code": null,
"e": 2955,
"s": 2944,
"text": "series-sum"
},
{
"code": null,
"e": 2968,
"s": 2955,
"text": "Mathematical"
},
{
"code": null,
"e": 2987,
"s": 2968,
"text": "School Programming"
},
{
"code": null,
"e": 3000,
"s": 2987,
"text": "Mathematical"
},
{
"code": null,
"e": 3007,
"s": 3000,
"text": "series"
}
] |
jQuery | Create a div element
|
28 Mar, 2019
Creating a <div> element using jQuery can be done in following steps:
Steps:
Create a new <div> element.
Choose a parent element, where to put this newly created element.
Put the created div element into parent element.
Example 1: This example creates a <div> element and uses append() method to append the element at the end of parent element.
<!DOCTYPE html> <html> <head> <title> Create div element using jQuery </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <style> #parent { height: 100px; width: 300px; background: green; margin: 0 auto; } #newElement { height: 40px; width: 100px; margin: 0 auto; color: white } </style></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <div id= "parent"></div> <br><br> <button onclick="insert()"> insert </button> <!-- Script to insert div element --> <script> function insert() { $("#parent").append('<div id = "newElement">A ' + 'Computer Science portal for geeks</div>'); } </script> </body> </html>
Output:
Before clicking the button:
After clicking the button:
Example 2: This example creates a <div> element and uses prependTo() method to append the element at the start of parent element.
<!DOCTYPE html> <html> <head> <title> Create div element using jQuery </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <style> #parent { height: 100px; width: 300px; background: green; margin: 0 auto; } #newElement { height: 40px; width: 100px; margin: 0 auto; color: white } </style></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <div id= "parent"></div> <br><br> <button onclick="insert()"> insert </button> <script> function insert() { $('<div id = "newElement">A Computer Science portal' + ' for geeks</div>').prependTo($('#parent')); } </script> </body> </html>
Output:
Before clicking the button:
After clicking the button:
jQuery-Basics
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
jQuery | children() with Examples
Scroll to the top of the page using JavaScript/jQuery
How to get the value in an input text box using jQuery ?
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": "\n28 Mar, 2019"
},
{
"code": null,
"e": 98,
"s": 28,
"text": "Creating a <div> element using jQuery can be done in following steps:"
},
{
"code": null,
"e": 105,
"s": 98,
"text": "Steps:"
},
{
"code": null,
"e": 133,
"s": 105,
"text": "Create a new <div> element."
},
{
"code": null,
"e": 199,
"s": 133,
"text": "Choose a parent element, where to put this newly created element."
},
{
"code": null,
"e": 248,
"s": 199,
"text": "Put the created div element into parent element."
},
{
"code": null,
"e": 373,
"s": 248,
"text": "Example 1: This example creates a <div> element and uses append() method to append the element at the end of parent element."
},
{
"code": "<!DOCTYPE html> <html> <head> <title> Create div element using jQuery </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <style> #parent { height: 100px; width: 300px; background: green; margin: 0 auto; } #newElement { height: 40px; width: 100px; margin: 0 auto; color: white } </style></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <div id= \"parent\"></div> <br><br> <button onclick=\"insert()\"> insert </button> <!-- Script to insert div element --> <script> function insert() { $(\"#parent\").append('<div id = \"newElement\">A ' + 'Computer Science portal for geeks</div>'); } </script> </body> </html>",
"e": 1366,
"s": 373,
"text": null
},
{
"code": null,
"e": 1374,
"s": 1366,
"text": "Output:"
},
{
"code": null,
"e": 1402,
"s": 1374,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 1429,
"s": 1402,
"text": "After clicking the button:"
},
{
"code": null,
"e": 1559,
"s": 1429,
"text": "Example 2: This example creates a <div> element and uses prependTo() method to append the element at the start of parent element."
},
{
"code": "<!DOCTYPE html> <html> <head> <title> Create div element using jQuery </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <style> #parent { height: 100px; width: 300px; background: green; margin: 0 auto; } #newElement { height: 40px; width: 100px; margin: 0 auto; color: white } </style></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <div id= \"parent\"></div> <br><br> <button onclick=\"insert()\"> insert </button> <script> function insert() { $('<div id = \"newElement\">A Computer Science portal' + ' for geeks</div>').prependTo($('#parent')); } </script> </body> </html>",
"e": 2524,
"s": 1559,
"text": null
},
{
"code": null,
"e": 2532,
"s": 2524,
"text": "Output:"
},
{
"code": null,
"e": 2560,
"s": 2532,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 2587,
"s": 2560,
"text": "After clicking the button:"
},
{
"code": null,
"e": 2601,
"s": 2587,
"text": "jQuery-Basics"
},
{
"code": null,
"e": 2608,
"s": 2601,
"text": "JQuery"
},
{
"code": null,
"e": 2625,
"s": 2608,
"text": "Web Technologies"
},
{
"code": null,
"e": 2652,
"s": 2625,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2750,
"s": 2652,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2779,
"s": 2750,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 2835,
"s": 2779,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
},
{
"code": null,
"e": 2869,
"s": 2835,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 2923,
"s": 2869,
"text": "Scroll to the top of the page using JavaScript/jQuery"
},
{
"code": null,
"e": 2980,
"s": 2923,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 3013,
"s": 2980,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3075,
"s": 3013,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3136,
"s": 3075,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3186,
"s": 3136,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Queries on count of points lie inside a circle
|
22 Jun, 2022
Given n coordinate (x, y) of points on 2D plane and Q queries. Each query contains an integer r, the task is to count the number of points lying inside or on the circumference of the circle having radius r and centered at the origin.Examples :
Input : n = 5
Coordinates:
1 1
2 2
3 3
-1 -1
4 4
Query 1: 3
Query 2: 32
Output :
3
5
For first query radius = 3, number of points lie
inside or on the circumference are (1, 1), (-1, -1),
(2, 2). There are only 3 points lie inside or on
the circumference of the circle.
For second query radius = 32, all five points are
inside the circle.
The equation for the circle centered at origin (0, 0) with radius r, x2 + y2 = r2. And condition for a point at (x1, y1) to lie inside or on the circumference, x12 + y12 <= r2.A Naive approach can be for each query, traverse through all points and check the condition. This take O(n*Q) time complexity.An Efficient approach is to precompute x2 + y2 for each point coordinate and store them in an array p[]. Now, sort the array p[]. Then apply binary search on the array to find last index with condition p[i] <= r2 for each query.Below is the implementation of this approach:
C++
Java
Python 3
C#
Javascript
// C++ program to find number of points lie inside or// on the circumference of circle for Q queries.#include <bits/stdc++.h>using namespace std; // Computing the x^2 + y^2 for each given points// and sorting them.void preprocess(int p[], int x[], int y[], int n){ for (int i = 0; i < n; i++) p[i] = x[i] * x[i] + y[i] * y[i]; sort(p, p + n);} // Return count of points lie inside or on circumference// of circle using binary search on p[0..n-1]int query(int p[], int n, int rad){ int start = 0, end = n - 1; while ((end - start) > 1) { int mid = (start + end) / 2; double tp = sqrt(p[mid]); if (tp > (rad * 1.0)) end = mid - 1; else start = mid; } double tp1 = sqrt(p[start]), tp2 = sqrt(p[end]); if (tp1 > (rad * 1.0)) return 0; else if (tp2 <= (rad * 1.0)) return end + 1; else return start + 1;} // Driven Programint main(){ int x[] = { 1, 2, 3, -1, 4 }; int y[] = { 1, 2, 3, -1, 4 }; int n = sizeof(x) / sizeof(x[0]); // Compute distances of all points and keep // the distances sorted so that query can // work in O(logn) using Binary Search. int p[n]; preprocess(p, x, y, n); // Print number of points in a circle of radius 3. cout << query(p, n, 3) << endl; // Print number of points in a circle of radius 32. cout << query(p, n, 32) << endl; return 0;}
// JAVA Code for Queries on count of// points lie inside a circleimport java.util.*; class GFG { // Computing the x^2 + y^2 for each given points // and sorting them. public static void preprocess(int p[], int x[], int y[], int n) { for (int i = 0; i < n; i++) p[i] = x[i] * x[i] + y[i] * y[i]; Arrays.sort(p); } // Return count of points lie inside or on // circumference of circle using binary // search on p[0..n-1] public static int query(int p[], int n, int rad) { int start = 0, end = n - 1; while ((end - start) > 1) { int mid = (start + end) / 2; double tp = Math.sqrt(p[mid]); if (tp > (rad * 1.0)) end = mid - 1; else start = mid; } double tp1 = Math.sqrt(p[start]); double tp2 = Math.sqrt(p[end]); if (tp1 > (rad * 1.0)) return 0; else if (tp2 <= (rad * 1.0)) return end + 1; else return start + 1; } /* Driver program to test above function */ public static void main(String[] args) { int x[] = { 1, 2, 3, -1, 4 }; int y[] = { 1, 2, 3, -1, 4 }; int n = x.length; // Compute distances of all points and keep // the distances sorted so that query can // work in O(logn) using Binary Search. int p[] = new int[n]; preprocess(p, x, y, n); // Print number of points in a circle of // radius 3. System.out.println(query(p, n, 3)); // Print number of points in a circle of // radius 32. System.out.println(query(p, n, 32)); }}// This code is contributed by Arnav Kr. Mandal.
# Python 3 program to find number of# points lie inside or on the circumference# of circle for Q queries.import math # Computing the x^2 + y^2 for each# given points and sorting them.def preprocess(p, x, y, n): for i in range(n): p[i] = x[i] * x[i] + y[i] * y[i] p.sort() # Return count of points lie inside# or on circumference of circle using# binary search on p[0..n-1]def query(p, n, rad): start = 0 end = n - 1 while ((end - start) > 1): mid = (start + end) // 2 tp = math.sqrt(p[mid]) if (tp > (rad * 1.0)): end = mid - 1 else: start = mid tp1 = math.sqrt(p[start]) tp2 = math.sqrt(p[end]) if (tp1 > (rad * 1.0)): return 0 else if (tp2 <= (rad * 1.0)): return end + 1 else: return start + 1 # Driver Codeif __name__ == "__main__": x = [ 1, 2, 3, -1, 4 ] y = [ 1, 2, 3, -1, 4 ] n = len(x) # Compute distances of all points and keep # the distances sorted so that query can # work in O(logn) using Binary Search. p = [0] * n preprocess(p, x, y, n) # Print number of points in a # circle of radius 3. print(query(p, n, 3)) # Print number of points in a # circle of radius 32. print(query(p, n, 32)) # This code is contributed by ita_c
// C# Code for Queries on count of// points lie inside a circleusing System; class GFG { // Computing the x^2 + y^2 for each // given points and sorting them. public static void preprocess(int[] p, int[] x, int[] y, int n) { for (int i = 0; i < n; i++) p[i] = x[i] * x[i] + y[i] * y[i]; Array.Sort(p); } // Return count of points lie inside or on // circumference of circle using binary // search on p[0..n-1] public static int query(int[] p, int n, int rad) { int start = 0, end = n - 1; while ((end - start) > 1) { int mid = (start + end) / 2; double tp = Math.Sqrt(p[mid]); if (tp > (rad * 1.0)) end = mid - 1; else start = mid; } double tp1 = Math.Sqrt(p[start]); double tp2 = Math.Sqrt(p[end]); if (tp1 > (rad * 1.0)) return 0; else if (tp2 <= (rad * 1.0)) return end + 1; else return start + 1; } /* Driver program to test above function */ public static void Main() { int[] x = { 1, 2, 3, -1, 4 }; int[] y = { 1, 2, 3, -1, 4 }; int n = x.Length; // Compute distances of all points and keep // the distances sorted so that query can // work in O(logn) using Binary Search. int[] p = new int[n]; preprocess(p, x, y, n); // Print number of points in a circle of // radius 3. Console.WriteLine(query(p, n, 3)); // Print number of points in a circle of // radius 32. Console.WriteLine(query(p, n, 32)); }} // This code is contributed by vt_m.
<script> // Javascript Code for Queries on count of// points lie inside a circle // Computing the x^2 + y^2 for each given points // and sorting them. function preprocess(p,x,y,n) { for (let i = 0; i < n; i++) p[i] = x[i] * x[i] + y[i] * y[i]; p.sort(function(a,b){return a-b;}); } // Return count of points lie inside or on // circumference of circle using binary // search on p[0..n-1] function query(p,n,rad) { let start = 0, end = n - 1; while ((end - start) > 1) { let mid = Math.floor((start + end) / 2); let tp = Math.sqrt(p[mid]); if (tp > (rad * 1.0)) end = mid - 1; else start = mid; } let tp1 = Math.sqrt(p[start]); let tp2 = Math.sqrt(p[end]); if (tp1 > (rad * 1.0)) return 0; else if (tp2 <= (rad * 1.0)) return end + 1; else return start + 1; } /* Driver program to test above function */ let x=[1, 2, 3, -1, 4 ]; let y=[1, 2, 3, -1, 4]; let n = x.length; // Compute distances of all points and keep // the distances sorted so that query can // work in O(logn) using Binary Search. let p=new Array(n); for(let i=0;i<n;i++) { p[i]=0; } preprocess(p, x, y, n); // Print number of points in a circle of // radius 3. document.write(query(p, n, 3)+"<br>"); // Print number of points in a circle of // radius 32. document.write(query(p, n, 32)+"<br>"); // This code is contributed by rag2127 </script>
Output:
3
5
Time Complexity: O(n log n) for preprocessing and O(Q Log n) for Q queries.Auxiliary Space: O(1)
This article is contributed by Aarti_Rathi and Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
ukasp
rag2127
surindertarika1234
surinderdawra388
codewithrathi
Binary Search
Geometric
Geometric
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 300,
"s": 54,
"text": "Given n coordinate (x, y) of points on 2D plane and Q queries. Each query contains an integer r, the task is to count the number of points lying inside or on the circumference of the circle having radius r and centered at the origin.Examples : "
},
{
"code": null,
"e": 643,
"s": 300,
"text": "Input : n = 5\nCoordinates: \n1 1\n2 2\n3 3\n-1 -1\n4 4\n\nQuery 1: 3\nQuery 2: 32\n\nOutput :\n3\n5\nFor first query radius = 3, number of points lie\ninside or on the circumference are (1, 1), (-1, -1),\n(2, 2). There are only 3 points lie inside or on \nthe circumference of the circle.\nFor second query radius = 32, all five points are\ninside the circle. "
},
{
"code": null,
"e": 1223,
"s": 645,
"text": "The equation for the circle centered at origin (0, 0) with radius r, x2 + y2 = r2. And condition for a point at (x1, y1) to lie inside or on the circumference, x12 + y12 <= r2.A Naive approach can be for each query, traverse through all points and check the condition. This take O(n*Q) time complexity.An Efficient approach is to precompute x2 + y2 for each point coordinate and store them in an array p[]. Now, sort the array p[]. Then apply binary search on the array to find last index with condition p[i] <= r2 for each query.Below is the implementation of this approach: "
},
{
"code": null,
"e": 1227,
"s": 1223,
"text": "C++"
},
{
"code": null,
"e": 1232,
"s": 1227,
"text": "Java"
},
{
"code": null,
"e": 1241,
"s": 1232,
"text": "Python 3"
},
{
"code": null,
"e": 1244,
"s": 1241,
"text": "C#"
},
{
"code": null,
"e": 1255,
"s": 1244,
"text": "Javascript"
},
{
"code": "// C++ program to find number of points lie inside or// on the circumference of circle for Q queries.#include <bits/stdc++.h>using namespace std; // Computing the x^2 + y^2 for each given points// and sorting them.void preprocess(int p[], int x[], int y[], int n){ for (int i = 0; i < n; i++) p[i] = x[i] * x[i] + y[i] * y[i]; sort(p, p + n);} // Return count of points lie inside or on circumference// of circle using binary search on p[0..n-1]int query(int p[], int n, int rad){ int start = 0, end = n - 1; while ((end - start) > 1) { int mid = (start + end) / 2; double tp = sqrt(p[mid]); if (tp > (rad * 1.0)) end = mid - 1; else start = mid; } double tp1 = sqrt(p[start]), tp2 = sqrt(p[end]); if (tp1 > (rad * 1.0)) return 0; else if (tp2 <= (rad * 1.0)) return end + 1; else return start + 1;} // Driven Programint main(){ int x[] = { 1, 2, 3, -1, 4 }; int y[] = { 1, 2, 3, -1, 4 }; int n = sizeof(x) / sizeof(x[0]); // Compute distances of all points and keep // the distances sorted so that query can // work in O(logn) using Binary Search. int p[n]; preprocess(p, x, y, n); // Print number of points in a circle of radius 3. cout << query(p, n, 3) << endl; // Print number of points in a circle of radius 32. cout << query(p, n, 32) << endl; return 0;}",
"e": 2668,
"s": 1255,
"text": null
},
{
"code": "// JAVA Code for Queries on count of// points lie inside a circleimport java.util.*; class GFG { // Computing the x^2 + y^2 for each given points // and sorting them. public static void preprocess(int p[], int x[], int y[], int n) { for (int i = 0; i < n; i++) p[i] = x[i] * x[i] + y[i] * y[i]; Arrays.sort(p); } // Return count of points lie inside or on // circumference of circle using binary // search on p[0..n-1] public static int query(int p[], int n, int rad) { int start = 0, end = n - 1; while ((end - start) > 1) { int mid = (start + end) / 2; double tp = Math.sqrt(p[mid]); if (tp > (rad * 1.0)) end = mid - 1; else start = mid; } double tp1 = Math.sqrt(p[start]); double tp2 = Math.sqrt(p[end]); if (tp1 > (rad * 1.0)) return 0; else if (tp2 <= (rad * 1.0)) return end + 1; else return start + 1; } /* Driver program to test above function */ public static void main(String[] args) { int x[] = { 1, 2, 3, -1, 4 }; int y[] = { 1, 2, 3, -1, 4 }; int n = x.length; // Compute distances of all points and keep // the distances sorted so that query can // work in O(logn) using Binary Search. int p[] = new int[n]; preprocess(p, x, y, n); // Print number of points in a circle of // radius 3. System.out.println(query(p, n, 3)); // Print number of points in a circle of // radius 32. System.out.println(query(p, n, 32)); }}// This code is contributed by Arnav Kr. Mandal.",
"e": 4422,
"s": 2668,
"text": null
},
{
"code": "# Python 3 program to find number of# points lie inside or on the circumference# of circle for Q queries.import math # Computing the x^2 + y^2 for each# given points and sorting them.def preprocess(p, x, y, n): for i in range(n): p[i] = x[i] * x[i] + y[i] * y[i] p.sort() # Return count of points lie inside# or on circumference of circle using# binary search on p[0..n-1]def query(p, n, rad): start = 0 end = n - 1 while ((end - start) > 1): mid = (start + end) // 2 tp = math.sqrt(p[mid]) if (tp > (rad * 1.0)): end = mid - 1 else: start = mid tp1 = math.sqrt(p[start]) tp2 = math.sqrt(p[end]) if (tp1 > (rad * 1.0)): return 0 else if (tp2 <= (rad * 1.0)): return end + 1 else: return start + 1 # Driver Codeif __name__ == \"__main__\": x = [ 1, 2, 3, -1, 4 ] y = [ 1, 2, 3, -1, 4 ] n = len(x) # Compute distances of all points and keep # the distances sorted so that query can # work in O(logn) using Binary Search. p = [0] * n preprocess(p, x, y, n) # Print number of points in a # circle of radius 3. print(query(p, n, 3)) # Print number of points in a # circle of radius 32. print(query(p, n, 32)) # This code is contributed by ita_c",
"e": 5723,
"s": 4422,
"text": null
},
{
"code": "// C# Code for Queries on count of// points lie inside a circleusing System; class GFG { // Computing the x^2 + y^2 for each // given points and sorting them. public static void preprocess(int[] p, int[] x, int[] y, int n) { for (int i = 0; i < n; i++) p[i] = x[i] * x[i] + y[i] * y[i]; Array.Sort(p); } // Return count of points lie inside or on // circumference of circle using binary // search on p[0..n-1] public static int query(int[] p, int n, int rad) { int start = 0, end = n - 1; while ((end - start) > 1) { int mid = (start + end) / 2; double tp = Math.Sqrt(p[mid]); if (tp > (rad * 1.0)) end = mid - 1; else start = mid; } double tp1 = Math.Sqrt(p[start]); double tp2 = Math.Sqrt(p[end]); if (tp1 > (rad * 1.0)) return 0; else if (tp2 <= (rad * 1.0)) return end + 1; else return start + 1; } /* Driver program to test above function */ public static void Main() { int[] x = { 1, 2, 3, -1, 4 }; int[] y = { 1, 2, 3, -1, 4 }; int n = x.Length; // Compute distances of all points and keep // the distances sorted so that query can // work in O(logn) using Binary Search. int[] p = new int[n]; preprocess(p, x, y, n); // Print number of points in a circle of // radius 3. Console.WriteLine(query(p, n, 3)); // Print number of points in a circle of // radius 32. Console.WriteLine(query(p, n, 32)); }} // This code is contributed by vt_m.",
"e": 7444,
"s": 5723,
"text": null
},
{
"code": "<script> // Javascript Code for Queries on count of// points lie inside a circle // Computing the x^2 + y^2 for each given points // and sorting them. function preprocess(p,x,y,n) { for (let i = 0; i < n; i++) p[i] = x[i] * x[i] + y[i] * y[i]; p.sort(function(a,b){return a-b;}); } // Return count of points lie inside or on // circumference of circle using binary // search on p[0..n-1] function query(p,n,rad) { let start = 0, end = n - 1; while ((end - start) > 1) { let mid = Math.floor((start + end) / 2); let tp = Math.sqrt(p[mid]); if (tp > (rad * 1.0)) end = mid - 1; else start = mid; } let tp1 = Math.sqrt(p[start]); let tp2 = Math.sqrt(p[end]); if (tp1 > (rad * 1.0)) return 0; else if (tp2 <= (rad * 1.0)) return end + 1; else return start + 1; } /* Driver program to test above function */ let x=[1, 2, 3, -1, 4 ]; let y=[1, 2, 3, -1, 4]; let n = x.length; // Compute distances of all points and keep // the distances sorted so that query can // work in O(logn) using Binary Search. let p=new Array(n); for(let i=0;i<n;i++) { p[i]=0; } preprocess(p, x, y, n); // Print number of points in a circle of // radius 3. document.write(query(p, n, 3)+\"<br>\"); // Print number of points in a circle of // radius 32. document.write(query(p, n, 32)+\"<br>\"); // This code is contributed by rag2127 </script>",
"e": 9097,
"s": 7444,
"text": null
},
{
"code": null,
"e": 9106,
"s": 9097,
"text": "Output: "
},
{
"code": null,
"e": 9110,
"s": 9106,
"text": "3\n5"
},
{
"code": null,
"e": 9207,
"s": 9110,
"text": "Time Complexity: O(n log n) for preprocessing and O(Q Log n) for Q queries.Auxiliary Space: O(1)"
},
{
"code": null,
"e": 9644,
"s": 9207,
"text": "This article is contributed by Aarti_Rathi and Anuj Chauhan. 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": 9649,
"s": 9644,
"text": "vt_m"
},
{
"code": null,
"e": 9655,
"s": 9649,
"text": "ukasp"
},
{
"code": null,
"e": 9663,
"s": 9655,
"text": "rag2127"
},
{
"code": null,
"e": 9682,
"s": 9663,
"text": "surindertarika1234"
},
{
"code": null,
"e": 9699,
"s": 9682,
"text": "surinderdawra388"
},
{
"code": null,
"e": 9713,
"s": 9699,
"text": "codewithrathi"
},
{
"code": null,
"e": 9727,
"s": 9713,
"text": "Binary Search"
},
{
"code": null,
"e": 9737,
"s": 9727,
"text": "Geometric"
},
{
"code": null,
"e": 9747,
"s": 9737,
"text": "Geometric"
},
{
"code": null,
"e": 9761,
"s": 9747,
"text": "Binary Search"
}
] |
Spring Boot | How to consume JSON messages using Apache Kafka
|
24 Jan, 2022
Apache Kafka is a stream processing system which lets you send messages between processes, applications, and servers. In this article, we will see how to publish JSON messages on the console of a Spring boot application using Apache Kafka.
In order to learn how to create a Spring boot project, refer to this article.
Working Steps:
Go to Spring initializer and create a starter project with following dependency: Spring for Apache KafkaOpen the project in an IDE and sync the dependencies. In this article, we would be creating a student model where we would be posting the student details. Therefore, create a model class Student. Add data members and create constructor and override the toString method to see the messages in JSON format. The following is the implementation of the student class:
Go to Spring initializer and create a starter project with following dependency: Spring for Apache Kafka
Spring for Apache Kafka
Open the project in an IDE and sync the dependencies. In this article, we would be creating a student model where we would be posting the student details. Therefore, create a model class Student. Add data members and create constructor and override the toString method to see the messages in JSON format. The following is the implementation of the student class:
Student Model
// Java program to implement a// student class // Creating a student classpublic class Student { // Data members of the class int id; String firstName; String lastName; // Constructor of the student // class public Student() { } // Parameterized constructor of // the student class public Student(int id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return "Student{" + "id = " + id + ", firstName = '" + firstName + "'" + ", lastName = '" + lastName + "'" + "}"; }}
Create a new class Config and add annotations @Configuration and @EnableKafka. Now create beans ConsumerFactory and ConcurrentKafkaListenerContainerFactory with Student class object.
Create a new class Config and add annotations @Configuration and @EnableKafka. Now create beans ConsumerFactory and ConcurrentKafkaListenerContainerFactory with Student class object.
Config clas
@EnableKafka@Configurationpublic class Config { // Function to establish a connection // between Spring application // and Kafka server @Bean public ConsumerFactory<String, Student> studentConsumer() { // HashMap to store the configurations Map<String, Object> map = new HashMap<>(); // put the host IP in the map map.put(ConsumerConfig .BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092"); // put the group ID of consumer in the map map.put(ConsumerConfig .GROUP_ID_CONFIG, "id"); map.put(ConsumerConfig .KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); map.put(ConsumerConfig .VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); // return message in JSON formate return new DefaultKafkaConsumerFactory<>( map, new StringDeserializer(), new JsonDeserializer<>(Student.class)); } @Bean public ConcurrentKafkaListenerContainerFactory<String, Student> studentListner() { ConcurrentKafkaListenerContainerFactory<String, Student> factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(studentConsumer()); return factory; }}
Create a class KafkaService with @Service annotation. This class will contain the listener method to publish the message on the console.
Create a class KafkaService with @Service annotation. This class will contain the listener method to publish the message on the console.
KafkaService Class
@Servicepublic class KafkaService { // Annotation required to listen // the message from Kafka server @KafkaListener(topics = "JsonTopic", groupId = "id", containerFactory = "studentListner") public void publish(Student student) { System.out.println("New Entry: " + student); }}
Start zookeeper and Kafka server. Now we need to create a new topic with the name JsonTopic. To do so, open a new command prompt window and change directory to the Kafka directory.Now create a new topic using the command given below:
Start zookeeper and Kafka server. Now we need to create a new topic with the name JsonTopic. To do so, open a new command prompt window and change directory to the Kafka directory.
Now create a new topic using the command given below:
bin/Kafka-topics.sh –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic topic_name // for mac and linux.\bin\windows\Kafka-topics.bat –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic topic_name // for windows
Now to run Kafka producer console, use the command below:
Now to run Kafka producer console, use the command below:
bin/Kafka-console-producer.sh –broker-list localhost:9092 –topic Kafka_Example // for mac and linux.\bin\windows\Kafka-console-producer.bat –broker-list localhost:9092 –topic Kafka_Example // for windows
Run the application and and type message on Kafka producer and press enter.
Run the application and and type message on Kafka producer and press enter.
simmytarika5
surinderdawra388
Apache
java-advanced
Java-Spring
JSON
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 268,
"s": 28,
"text": "Apache Kafka is a stream processing system which lets you send messages between processes, applications, and servers. In this article, we will see how to publish JSON messages on the console of a Spring boot application using Apache Kafka."
},
{
"code": null,
"e": 346,
"s": 268,
"text": "In order to learn how to create a Spring boot project, refer to this article."
},
{
"code": null,
"e": 363,
"s": 346,
"text": "Working Steps: "
},
{
"code": null,
"e": 831,
"s": 363,
"text": "Go to Spring initializer and create a starter project with following dependency: Spring for Apache KafkaOpen the project in an IDE and sync the dependencies. In this article, we would be creating a student model where we would be posting the student details. Therefore, create a model class Student. Add data members and create constructor and override the toString method to see the messages in JSON format. The following is the implementation of the student class: "
},
{
"code": null,
"e": 936,
"s": 831,
"text": "Go to Spring initializer and create a starter project with following dependency: Spring for Apache Kafka"
},
{
"code": null,
"e": 960,
"s": 936,
"text": "Spring for Apache Kafka"
},
{
"code": null,
"e": 1324,
"s": 960,
"text": "Open the project in an IDE and sync the dependencies. In this article, we would be creating a student model where we would be posting the student details. Therefore, create a model class Student. Add data members and create constructor and override the toString method to see the messages in JSON format. The following is the implementation of the student class: "
},
{
"code": null,
"e": 1338,
"s": 1324,
"text": "Student Model"
},
{
"code": "// Java program to implement a// student class // Creating a student classpublic class Student { // Data members of the class int id; String firstName; String lastName; // Constructor of the student // class public Student() { } // Parameterized constructor of // the student class public Student(int id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return \"Student{\" + \"id = \" + id + \", firstName = '\" + firstName + \"'\" + \", lastName = '\" + lastName + \"'\" + \"}\"; }}",
"e": 2052,
"s": 1338,
"text": null
},
{
"code": null,
"e": 2237,
"s": 2052,
"text": " Create a new class Config and add annotations @Configuration and @EnableKafka. Now create beans ConsumerFactory and ConcurrentKafkaListenerContainerFactory with Student class object. "
},
{
"code": null,
"e": 2423,
"s": 2239,
"text": "Create a new class Config and add annotations @Configuration and @EnableKafka. Now create beans ConsumerFactory and ConcurrentKafkaListenerContainerFactory with Student class object. "
},
{
"code": null,
"e": 2435,
"s": 2423,
"text": "Config clas"
},
{
"code": "@EnableKafka@Configurationpublic class Config { // Function to establish a connection // between Spring application // and Kafka server @Bean public ConsumerFactory<String, Student> studentConsumer() { // HashMap to store the configurations Map<String, Object> map = new HashMap<>(); // put the host IP in the map map.put(ConsumerConfig .BOOTSTRAP_SERVERS_CONFIG, \"127.0.0.1:9092\"); // put the group ID of consumer in the map map.put(ConsumerConfig .GROUP_ID_CONFIG, \"id\"); map.put(ConsumerConfig .KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); map.put(ConsumerConfig .VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); // return message in JSON formate return new DefaultKafkaConsumerFactory<>( map, new StringDeserializer(), new JsonDeserializer<>(Student.class)); } @Bean public ConcurrentKafkaListenerContainerFactory<String, Student> studentListner() { ConcurrentKafkaListenerContainerFactory<String, Student> factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(studentConsumer()); return factory; }}",
"e": 3917,
"s": 2435,
"text": null
},
{
"code": null,
"e": 4056,
"s": 3917,
"text": " Create a class KafkaService with @Service annotation. This class will contain the listener method to publish the message on the console. "
},
{
"code": null,
"e": 4196,
"s": 4058,
"text": "Create a class KafkaService with @Service annotation. This class will contain the listener method to publish the message on the console. "
},
{
"code": null,
"e": 4215,
"s": 4196,
"text": "KafkaService Class"
},
{
"code": "@Servicepublic class KafkaService { // Annotation required to listen // the message from Kafka server @KafkaListener(topics = \"JsonTopic\", groupId = \"id\", containerFactory = \"studentListner\") public void publish(Student student) { System.out.println(\"New Entry: \" + student); }}",
"e": 4601,
"s": 4215,
"text": null
},
{
"code": null,
"e": 4837,
"s": 4601,
"text": " Start zookeeper and Kafka server. Now we need to create a new topic with the name JsonTopic. To do so, open a new command prompt window and change directory to the Kafka directory.Now create a new topic using the command given below: "
},
{
"code": null,
"e": 5020,
"s": 4839,
"text": "Start zookeeper and Kafka server. Now we need to create a new topic with the name JsonTopic. To do so, open a new command prompt window and change directory to the Kafka directory."
},
{
"code": null,
"e": 5075,
"s": 5020,
"text": "Now create a new topic using the command given below: "
},
{
"code": null,
"e": 5339,
"s": 5075,
"text": "bin/Kafka-topics.sh –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic topic_name // for mac and linux.\\bin\\windows\\Kafka-topics.bat –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic topic_name // for windows "
},
{
"code": null,
"e": 5399,
"s": 5339,
"text": " Now to run Kafka producer console, use the command below: "
},
{
"code": null,
"e": 5460,
"s": 5401,
"text": "Now to run Kafka producer console, use the command below: "
},
{
"code": null,
"e": 5666,
"s": 5460,
"text": "bin/Kafka-console-producer.sh –broker-list localhost:9092 –topic Kafka_Example // for mac and linux.\\bin\\windows\\Kafka-console-producer.bat –broker-list localhost:9092 –topic Kafka_Example // for windows "
},
{
"code": null,
"e": 5743,
"s": 5666,
"text": " Run the application and and type message on Kafka producer and press enter."
},
{
"code": null,
"e": 5821,
"s": 5745,
"text": "Run the application and and type message on Kafka producer and press enter."
},
{
"code": null,
"e": 5834,
"s": 5821,
"text": "simmytarika5"
},
{
"code": null,
"e": 5851,
"s": 5834,
"text": "surinderdawra388"
},
{
"code": null,
"e": 5858,
"s": 5851,
"text": "Apache"
},
{
"code": null,
"e": 5872,
"s": 5858,
"text": "java-advanced"
},
{
"code": null,
"e": 5884,
"s": 5872,
"text": "Java-Spring"
},
{
"code": null,
"e": 5889,
"s": 5884,
"text": "JSON"
},
{
"code": null,
"e": 5894,
"s": 5889,
"text": "Java"
},
{
"code": null,
"e": 5899,
"s": 5894,
"text": "Java"
}
] |
JSON Formatting in Python
|
06 Jun, 2018
Javascript Object Notation abbreviated as JSON is a light-weight data interchange format. It Encode Python objects as JSON strings, and decode JSON strings into Python objects .
Many of the APIs like Github. send their results in this format. JSON is probably most widely used for communicating between the web server and client in an AJAX application, but is not limited to that problem domain.
For example, if you are trying to build an exciting project like this, we need to format the JSON output to render necessary results. So lets dive into json module which Python offers for formatting JSON output.
Functions
json.dump(obj, fileObj): Serializes obj as a JSON formatted stream to fileObj.
json.dumps(obj) : Serializes obj as JSON formatted string.
json.load(JSONfile) : De-serializes JSONfile to a Python object.
json.loads(JSONfile) : De-serializes JSONfile(type: string) to a Python object.
Classes
JSONEncoder: An encoder class to convert Python objects to JSON format.
JSONDecoder: A decoder class to convert JSON format file into Python obj.
The conversions are based on this conversion table.
Implementation
EncodingWe will be using dump(), dumps() and JSON.Encoder class.
#Code will run in Python 3 from io import StringIOimport json fileObj = StringIO()json.dump(["Hello", "Geeks"], fileObj)print("Using json.dump(): "+str(fileObj.getvalue())) class TypeEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, type): return str(obj) print("Using json.dumps(): "+str(json.dumps(type(str), cls=TypeEncoder)))print("Using json.JSONEncoder().encode"+ str(TypeEncoder().encode(type(list))))print("Using json.JSONEncoder().iterencode"+ str(list(TypeEncoder().iterencode(type(dict)))))
Output:
Using json.dump(): ["Hello", "Geeks"]
Using json.dumps(): ""
Using json.JSONEncoder().encode""
Using json.JSONEncoder().iterencode['""']
DecodingWe will be using load(), loads() and JSON.Decoder class.
#Code will run in Python 3 from io import StringIOimport json fileObj = StringIO('["Geeks for Geeks"]')print("Using json.load(): "+str(json.load(fileObj)))print("Using json.loads(): "+str(json.loads('{"Geeks": 1, "for": 2, "Geeks": 3}')))print("Using json.JSONDecoder().decode(): " + str(json.JSONDecoder().decode('{"Geeks": 1, "for": 2, "Geeks": 3}')))print("Using json.JSONDecoder().raw_decode(): " + str(json.JSONDecoder().raw_decode('{"Geeks": 1, "for": 2, "Geeks": 3}')))
Output:
Using json.load(): ['Geeks for Geeks']
Using json.loads(): {'for': 2, 'Geeks': 3}
Using json.JSONDecoder().decode(): {'for': 2, 'Geeks': 3}
Using json.JSONDecoder().raw_decode(): ({'for': 2, 'Geeks': 3}, 34)
Reference:
https://docs.python.org/3/library/json.html
This article is contributed by Sri Sanketh Uppalapati. 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.
JSON
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jun, 2018"
},
{
"code": null,
"e": 230,
"s": 52,
"text": "Javascript Object Notation abbreviated as JSON is a light-weight data interchange format. It Encode Python objects as JSON strings, and decode JSON strings into Python objects ."
},
{
"code": null,
"e": 448,
"s": 230,
"text": "Many of the APIs like Github. send their results in this format. JSON is probably most widely used for communicating between the web server and client in an AJAX application, but is not limited to that problem domain."
},
{
"code": null,
"e": 660,
"s": 448,
"text": "For example, if you are trying to build an exciting project like this, we need to format the JSON output to render necessary results. So lets dive into json module which Python offers for formatting JSON output."
},
{
"code": null,
"e": 670,
"s": 660,
"text": "Functions"
},
{
"code": null,
"e": 749,
"s": 670,
"text": "json.dump(obj, fileObj): Serializes obj as a JSON formatted stream to fileObj."
},
{
"code": null,
"e": 808,
"s": 749,
"text": "json.dumps(obj) : Serializes obj as JSON formatted string."
},
{
"code": null,
"e": 873,
"s": 808,
"text": "json.load(JSONfile) : De-serializes JSONfile to a Python object."
},
{
"code": null,
"e": 953,
"s": 873,
"text": "json.loads(JSONfile) : De-serializes JSONfile(type: string) to a Python object."
},
{
"code": null,
"e": 961,
"s": 953,
"text": "Classes"
},
{
"code": null,
"e": 1033,
"s": 961,
"text": "JSONEncoder: An encoder class to convert Python objects to JSON format."
},
{
"code": null,
"e": 1107,
"s": 1033,
"text": "JSONDecoder: A decoder class to convert JSON format file into Python obj."
},
{
"code": null,
"e": 1159,
"s": 1107,
"text": "The conversions are based on this conversion table."
},
{
"code": null,
"e": 1174,
"s": 1159,
"text": "Implementation"
},
{
"code": null,
"e": 1239,
"s": 1174,
"text": "EncodingWe will be using dump(), dumps() and JSON.Encoder class."
},
{
"code": "#Code will run in Python 3 from io import StringIOimport json fileObj = StringIO()json.dump([\"Hello\", \"Geeks\"], fileObj)print(\"Using json.dump(): \"+str(fileObj.getvalue())) class TypeEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, type): return str(obj) print(\"Using json.dumps(): \"+str(json.dumps(type(str), cls=TypeEncoder)))print(\"Using json.JSONEncoder().encode\"+ str(TypeEncoder().encode(type(list))))print(\"Using json.JSONEncoder().iterencode\"+ str(list(TypeEncoder().iterencode(type(dict)))))",
"e": 1796,
"s": 1239,
"text": null
},
{
"code": null,
"e": 1804,
"s": 1796,
"text": "Output:"
},
{
"code": null,
"e": 1942,
"s": 1804,
"text": "Using json.dump(): [\"Hello\", \"Geeks\"]\nUsing json.dumps(): \"\"\nUsing json.JSONEncoder().encode\"\"\nUsing json.JSONEncoder().iterencode['\"\"']\n"
},
{
"code": null,
"e": 2007,
"s": 1942,
"text": "DecodingWe will be using load(), loads() and JSON.Decoder class."
},
{
"code": "#Code will run in Python 3 from io import StringIOimport json fileObj = StringIO('[\"Geeks for Geeks\"]')print(\"Using json.load(): \"+str(json.load(fileObj)))print(\"Using json.loads(): \"+str(json.loads('{\"Geeks\": 1, \"for\": 2, \"Geeks\": 3}')))print(\"Using json.JSONDecoder().decode(): \" + str(json.JSONDecoder().decode('{\"Geeks\": 1, \"for\": 2, \"Geeks\": 3}')))print(\"Using json.JSONDecoder().raw_decode(): \" + str(json.JSONDecoder().raw_decode('{\"Geeks\": 1, \"for\": 2, \"Geeks\": 3}')))",
"e": 2492,
"s": 2007,
"text": null
},
{
"code": null,
"e": 2500,
"s": 2492,
"text": "Output:"
},
{
"code": null,
"e": 2710,
"s": 2500,
"text": "Using json.load(): ['Geeks for Geeks']\nUsing json.loads(): {'for': 2, 'Geeks': 3}\nUsing json.JSONDecoder().decode(): {'for': 2, 'Geeks': 3}\nUsing json.JSONDecoder().raw_decode(): ({'for': 2, 'Geeks': 3}, 34)\n\n"
},
{
"code": null,
"e": 2721,
"s": 2710,
"text": "Reference:"
},
{
"code": null,
"e": 2765,
"s": 2721,
"text": "https://docs.python.org/3/library/json.html"
},
{
"code": null,
"e": 3075,
"s": 2765,
"text": "This article is contributed by Sri Sanketh Uppalapati. 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": 3200,
"s": 3075,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3205,
"s": 3200,
"text": "JSON"
},
{
"code": null,
"e": 3212,
"s": 3205,
"text": "Python"
}
] |
Materialize - Colors
|
Materialize supports a rich set of color classes. These color classes are inspired and developed considering the colors used in marketing, road signs, and sticky notes.
red
pink
purple
deep-purple
indigo
blue
light-blue
cyan
teal
green
light-green
lime
yellow
amber
orange
deep-orange
brown
grey
blue-grey
black
white
transparent
Following is the list of lightness/darkness classes, which can be used to vary the color applied.
lighten-1
lighten-2
lighten-3
lighten-4
lighten-5
darken-1
darken-2
darken-3
darken-4
accent-1
accent-2
accent-3
accent-4
The following example demonstrates how to use the above classes to render the background or to change the color of the text. In case of background, add the classes as such and in case of text, suffix '-text' to color class and prefix 'text-' to lightning class.
<!DOCTYPE html>
<html>
<head>
<title>The Materialize Colors Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>
</head>
<body>
<h2>Color Theme Demo</h2>
<hr/>
<div class="card-panel">
<div class="card-panel red lighten-2">
<h1>Red Colored Theme</h1>
</div>
<span class="red-text text-darken-2">
<h2>Red Colored Text</h2>
</span>
<ul>
<li class="red lighten-5"><p>Using red lighten-5</p></li>
<li class="red lighten-4"><p>Using red lighten-4</p></li>
<li class="red lighten-3"><p>Using red lighten-3</p></li>
<li class="red lighten-2"><p>Using red lighten-2</p></li>
<li class="red lighten-1"><p>Using red lighten-1</p></li>
<li class="red"><p>Using red</p></li>
<li class="red darken-1"><p>Using red darken-1</p></li>
<li class="red darken-2"><p>Using red darken-2</p></li>
<li class="red darken-3"><p>Using red darken-3</p></li>
<li class="red darken-4"><p>Using red darken-4</p></li>
<li class="red accent-1"><p>Using red accent-1</p></li>
<li class="red accent-2"><p>Using red accent-2</p></li>
<li class="red accent-3"><p>Using red accent-3</p></li>
<li class="red accent-4"><p>Using red accent-4</p></li>
</ul>
</div>
</body>
</html>
Verify the output.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2356,
"s": 2187,
"text": "Materialize supports a rich set of color classes. These color classes are inspired and developed considering the colors used in marketing, road signs, and sticky notes."
},
{
"code": null,
"e": 2360,
"s": 2356,
"text": "red"
},
{
"code": null,
"e": 2365,
"s": 2360,
"text": "pink"
},
{
"code": null,
"e": 2372,
"s": 2365,
"text": "purple"
},
{
"code": null,
"e": 2384,
"s": 2372,
"text": "deep-purple"
},
{
"code": null,
"e": 2391,
"s": 2384,
"text": "indigo"
},
{
"code": null,
"e": 2396,
"s": 2391,
"text": "blue"
},
{
"code": null,
"e": 2407,
"s": 2396,
"text": "light-blue"
},
{
"code": null,
"e": 2412,
"s": 2407,
"text": "cyan"
},
{
"code": null,
"e": 2417,
"s": 2412,
"text": "teal"
},
{
"code": null,
"e": 2423,
"s": 2417,
"text": "green"
},
{
"code": null,
"e": 2435,
"s": 2423,
"text": "light-green"
},
{
"code": null,
"e": 2440,
"s": 2435,
"text": "lime"
},
{
"code": null,
"e": 2447,
"s": 2440,
"text": "yellow"
},
{
"code": null,
"e": 2453,
"s": 2447,
"text": "amber"
},
{
"code": null,
"e": 2460,
"s": 2453,
"text": "orange"
},
{
"code": null,
"e": 2472,
"s": 2460,
"text": "deep-orange"
},
{
"code": null,
"e": 2478,
"s": 2472,
"text": "brown"
},
{
"code": null,
"e": 2483,
"s": 2478,
"text": "grey"
},
{
"code": null,
"e": 2493,
"s": 2483,
"text": "blue-grey"
},
{
"code": null,
"e": 2499,
"s": 2493,
"text": "black"
},
{
"code": null,
"e": 2505,
"s": 2499,
"text": "white"
},
{
"code": null,
"e": 2517,
"s": 2505,
"text": "transparent"
},
{
"code": null,
"e": 2615,
"s": 2517,
"text": "Following is the list of lightness/darkness classes, which can be used to vary the color applied."
},
{
"code": null,
"e": 2625,
"s": 2615,
"text": "lighten-1"
},
{
"code": null,
"e": 2635,
"s": 2625,
"text": "lighten-2"
},
{
"code": null,
"e": 2645,
"s": 2635,
"text": "lighten-3"
},
{
"code": null,
"e": 2655,
"s": 2645,
"text": "lighten-4"
},
{
"code": null,
"e": 2665,
"s": 2655,
"text": "lighten-5"
},
{
"code": null,
"e": 2674,
"s": 2665,
"text": "darken-1"
},
{
"code": null,
"e": 2683,
"s": 2674,
"text": "darken-2"
},
{
"code": null,
"e": 2692,
"s": 2683,
"text": "darken-3"
},
{
"code": null,
"e": 2701,
"s": 2692,
"text": "darken-4"
},
{
"code": null,
"e": 2710,
"s": 2701,
"text": "accent-1"
},
{
"code": null,
"e": 2719,
"s": 2710,
"text": "accent-2"
},
{
"code": null,
"e": 2728,
"s": 2719,
"text": "accent-3"
},
{
"code": null,
"e": 2737,
"s": 2728,
"text": "accent-4"
},
{
"code": null,
"e": 2999,
"s": 2737,
"text": "The following example demonstrates how to use the above classes to render the background or to change the color of the text. In case of background, add the classes as such and in case of text, suffix '-text' to color class and prefix 'text-' to lightning class."
},
{
"code": null,
"e": 4901,
"s": 2999,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>The Materialize Colors Example</title>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/icon?family=Material+Icons\">\n <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css\">\n <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"></script>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js\"></script>\n </head>\n <body>\n <h2>Color Theme Demo</h2>\n <hr/>\n <div class=\"card-panel\">\n <div class=\"card-panel red lighten-2\">\n <h1>Red Colored Theme</h1>\n </div>\n <span class=\"red-text text-darken-2\">\n <h2>Red Colored Text</h2>\n </span>\n <ul>\n <li class=\"red lighten-5\"><p>Using red lighten-5</p></li>\n <li class=\"red lighten-4\"><p>Using red lighten-4</p></li>\n <li class=\"red lighten-3\"><p>Using red lighten-3</p></li>\n <li class=\"red lighten-2\"><p>Using red lighten-2</p></li>\n <li class=\"red lighten-1\"><p>Using red lighten-1</p></li>\n <li class=\"red\"><p>Using red</p></li>\n <li class=\"red darken-1\"><p>Using red darken-1</p></li>\n <li class=\"red darken-2\"><p>Using red darken-2</p></li>\n <li class=\"red darken-3\"><p>Using red darken-3</p></li>\n <li class=\"red darken-4\"><p>Using red darken-4</p></li>\n <li class=\"red accent-1\"><p>Using red accent-1</p></li>\n <li class=\"red accent-2\"><p>Using red accent-2</p></li>\n <li class=\"red accent-3\"><p>Using red accent-3</p></li>\n <li class=\"red accent-4\"><p>Using red accent-4</p></li>\n </ul>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 4920,
"s": 4901,
"text": "Verify the output."
},
{
"code": null,
"e": 4927,
"s": 4920,
"text": " Print"
},
{
"code": null,
"e": 4938,
"s": 4927,
"text": " Add Notes"
}
] |
PostgreSQL - Functions
|
PostgreSQL functions, also known as Stored Procedures, allow you to carry out operations that would normally take several queries and round trips in a single function within the database. Functions allow database reuse as other applications can interact directly with your stored procedures instead of a middle-tier or duplicating code.
Functions can be created in a language of your choice like SQL, PL/pgSQL, C, Python, etc.
The basic syntax to create a function is as follows −
CREATE [OR REPLACE] FUNCTION function_name (arguments)
RETURNS return_datatype AS $variable_name$
DECLARE
declaration;
[...]
BEGIN
< function_body >
[...]
RETURN { variable_name | value }
END; LANGUAGE plpgsql;
Where,
function-name specifies the name of the function.
function-name specifies the name of the function.
[OR REPLACE] option allows modifying an existing function.
[OR REPLACE] option allows modifying an existing function.
The function must contain a return statement.
The function must contain a return statement.
RETURN clause specifies that data type you are going to return from the function. The return_datatype can be a base, composite, or domain type, or can reference the type of a table column.
RETURN clause specifies that data type you are going to return from the function. The return_datatype can be a base, composite, or domain type, or can reference the type of a table column.
function-body contains the executable part.
function-body contains the executable part.
The AS keyword is used for creating a standalone function.
The AS keyword is used for creating a standalone function.
plpgsql is the name of the language that the function is implemented in. Here, we use this option for PostgreSQL, it Can be SQL, C, internal, or the name of a user-defined procedural language. For backward compatibility, the name can be enclosed by single quotes.
plpgsql is the name of the language that the function is implemented in. Here, we use this option for PostgreSQL, it Can be SQL, C, internal, or the name of a user-defined procedural language. For backward compatibility, the name can be enclosed by single quotes.
The following example illustrates creating and calling a standalone function. This function returns the total number of records in the COMPANY table. We will use the COMPANY table, which has the following records −
testdb# select * from COMPANY;
id | name | age | address | salary
----+-------+-----+-----------+--------
1 | Paul | 32 | California| 20000
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
6 | Kim | 22 | South-Hall| 45000
7 | James | 24 | Houston | 10000
(7 rows)
Function totalRecords() is as follows −
CREATE OR REPLACE FUNCTION totalRecords ()
RETURNS integer AS $total$
declare
total integer;
BEGIN
SELECT count(*) into total FROM COMPANY;
RETURN total;
END;
$total$ LANGUAGE plpgsql;
When the above query is executed, the result would be −
testdb# CREATE FUNCTION
Now, let us execute a call to this function and check the records in the COMPANY table
testdb=# select totalRecords();
When the above query is executed, the result would be −
totalrecords
--------------
7
(1 row)
23 Lectures
1.5 hours
John Elder
49 Lectures
3.5 hours
Niyazi Erdogan
126 Lectures
10.5 hours
Abhishek And Pukhraj
35 Lectures
5 hours
Karthikeya T
5 Lectures
51 mins
Vinay Kumar
5 Lectures
52 mins
Vinay Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3162,
"s": 2825,
"text": "PostgreSQL functions, also known as Stored Procedures, allow you to carry out operations that would normally take several queries and round trips in a single function within the database. Functions allow database reuse as other applications can interact directly with your stored procedures instead of a middle-tier or duplicating code."
},
{
"code": null,
"e": 3252,
"s": 3162,
"text": "Functions can be created in a language of your choice like SQL, PL/pgSQL, C, Python, etc."
},
{
"code": null,
"e": 3306,
"s": 3252,
"text": "The basic syntax to create a function is as follows −"
},
{
"code": null,
"e": 3558,
"s": 3306,
"text": "CREATE [OR REPLACE] FUNCTION function_name (arguments) \nRETURNS return_datatype AS $variable_name$\n DECLARE\n declaration;\n [...]\n BEGIN\n < function_body >\n [...]\n RETURN { variable_name | value }\n END; LANGUAGE plpgsql;\n"
},
{
"code": null,
"e": 3565,
"s": 3558,
"text": "Where,"
},
{
"code": null,
"e": 3615,
"s": 3565,
"text": "function-name specifies the name of the function."
},
{
"code": null,
"e": 3665,
"s": 3615,
"text": "function-name specifies the name of the function."
},
{
"code": null,
"e": 3724,
"s": 3665,
"text": "[OR REPLACE] option allows modifying an existing function."
},
{
"code": null,
"e": 3783,
"s": 3724,
"text": "[OR REPLACE] option allows modifying an existing function."
},
{
"code": null,
"e": 3829,
"s": 3783,
"text": "The function must contain a return statement."
},
{
"code": null,
"e": 3875,
"s": 3829,
"text": "The function must contain a return statement."
},
{
"code": null,
"e": 4065,
"s": 3875,
"text": "RETURN clause specifies that data type you are going to return from the function. The return_datatype can be a base, composite, or domain type, or can reference the type of a table column."
},
{
"code": null,
"e": 4255,
"s": 4065,
"text": "RETURN clause specifies that data type you are going to return from the function. The return_datatype can be a base, composite, or domain type, or can reference the type of a table column."
},
{
"code": null,
"e": 4299,
"s": 4255,
"text": "function-body contains the executable part."
},
{
"code": null,
"e": 4343,
"s": 4299,
"text": "function-body contains the executable part."
},
{
"code": null,
"e": 4402,
"s": 4343,
"text": "The AS keyword is used for creating a standalone function."
},
{
"code": null,
"e": 4461,
"s": 4402,
"text": "The AS keyword is used for creating a standalone function."
},
{
"code": null,
"e": 4725,
"s": 4461,
"text": "plpgsql is the name of the language that the function is implemented in. Here, we use this option for PostgreSQL, it Can be SQL, C, internal, or the name of a user-defined procedural language. For backward compatibility, the name can be enclosed by single quotes."
},
{
"code": null,
"e": 4989,
"s": 4725,
"text": "plpgsql is the name of the language that the function is implemented in. Here, we use this option for PostgreSQL, it Can be SQL, C, internal, or the name of a user-defined procedural language. For backward compatibility, the name can be enclosed by single quotes."
},
{
"code": null,
"e": 5204,
"s": 4989,
"text": "The following example illustrates creating and calling a standalone function. This function returns the total number of records in the COMPANY table. We will use the COMPANY table, which has the following records −"
},
{
"code": null,
"e": 5596,
"s": 5204,
"text": "testdb# select * from COMPANY;\n id | name | age | address | salary\n----+-------+-----+-----------+--------\n 1 | Paul | 32 | California| 20000\n 2 | Allen | 25 | Texas | 15000\n 3 | Teddy | 23 | Norway | 20000\n 4 | Mark | 25 | Rich-Mond | 65000\n 5 | David | 27 | Texas | 85000\n 6 | Kim | 22 | South-Hall| 45000\n 7 | James | 24 | Houston | 10000\n(7 rows)"
},
{
"code": null,
"e": 5636,
"s": 5596,
"text": "Function totalRecords() is as follows −"
},
{
"code": null,
"e": 5828,
"s": 5636,
"text": "CREATE OR REPLACE FUNCTION totalRecords ()\nRETURNS integer AS $total$\ndeclare\n\ttotal integer;\nBEGIN\n SELECT count(*) into total FROM COMPANY;\n RETURN total;\nEND;\n$total$ LANGUAGE plpgsql;"
},
{
"code": null,
"e": 5884,
"s": 5828,
"text": "When the above query is executed, the result would be −"
},
{
"code": null,
"e": 5909,
"s": 5884,
"text": "testdb# CREATE FUNCTION\n"
},
{
"code": null,
"e": 5996,
"s": 5909,
"text": "Now, let us execute a call to this function and check the records in the COMPANY table"
},
{
"code": null,
"e": 6028,
"s": 5996,
"text": "testdb=# select totalRecords();"
},
{
"code": null,
"e": 6084,
"s": 6028,
"text": "When the above query is executed, the result would be −"
},
{
"code": null,
"e": 6130,
"s": 6084,
"text": " totalrecords\n--------------\n 7\n(1 row)\n"
},
{
"code": null,
"e": 6165,
"s": 6130,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6177,
"s": 6165,
"text": " John Elder"
},
{
"code": null,
"e": 6212,
"s": 6177,
"text": "\n 49 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6228,
"s": 6212,
"text": " Niyazi Erdogan"
},
{
"code": null,
"e": 6265,
"s": 6228,
"text": "\n 126 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 6287,
"s": 6265,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 6320,
"s": 6287,
"text": "\n 35 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6334,
"s": 6320,
"text": " Karthikeya T"
},
{
"code": null,
"e": 6365,
"s": 6334,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 6378,
"s": 6365,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 6409,
"s": 6378,
"text": "\n 5 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 6422,
"s": 6409,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 6429,
"s": 6422,
"text": " Print"
},
{
"code": null,
"e": 6440,
"s": 6429,
"text": " Add Notes"
}
] |
Find three prime numbers with given sum - GeeksforGeeks
|
05 Jan, 2021
Given an integer N, the task is to find three prime numbers X, Y, and Z such that the sum of these three numbers is equal to N i.e. X + Y + Z = N.
Examples:
Input: N = 20 Output: 2 5 13
Input: N = 34 Output: 2 3 29
Approach:
Generate prime numbers using Sieve of Eratosthenes
Start from the first prime number.
Take another number from the generated list.
Subtract first number and second number from the original number to obtain the third number.
Check if the third number is a prime number.
If the third number is a prime number then output the three numbers.
Otherwise, repeat the process for the second number and consequently the first number
If the answer does not exist then print -1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ implementation of the approach #include <bits/stdc++.h>using namespace std; const int MAX = 100001; // The vector primes holds// the prime numbersvector<int> primes; // Function to generate prime numbersvoid initialize(){ // Initialize the array elements to 0s bool numbers[MAX] = {}; int n = MAX; for (int i = 2; i * i <= n; i++) if (!numbers[i]) for (int j = i * i; j <= n; j += i) // Set the non-primes to true numbers[j] = true; // Fill the vector primes with prime // numbers which are marked as false // in the numbers array for (int i = 2; i <= n; i++) if (numbers[i] == false) primes.push_back(i);} // Function to print three prime numbers// which sum up to the number Nvoid findNums(int num){ bool ans = false; int first = -1, second = -1, third = -1; for (int i = 0; i < num; i++) { // Take the first prime number first = primes[i]; for (int j = 0; j < num; j++) { // Take the second prime number second = primes[j]; // Subtract the two prime numbers // from the N to obtain the third number third = num - first - second; // If the third number is prime if (binary_search(primes.begin(), primes.end(), third)) { ans = true; break; } } if (ans) break; } // Print the three prime numbers // if the solution exists if (ans) cout << first << " " << second << " " << third << endl; else cout << -1 << endl;} // Driver codeint main(){ int n = 101; // Function for generating prime numbers // using Sieve of Eratosthenes initialize(); // Function to print the three prime // numbers whose sum is equal to N findNums(n); return 0;}
// Java implementation of the approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ static int MAX = 100001; // The vector primes holds// the prime numbersstatic ArrayList<Integer> primes; // Function to generate prime numbersstatic void initialize(){ // Initialize the array elements to 0s boolean[] numbers = new boolean[MAX + 1]; int n = MAX; for(int i = 2; i * i <= n; i++) if (!numbers[i]) for(int j = i * i; j <= n; j += i) // Set the non-primes to true numbers[j] = true; // Fill the vector primes with prime // numbers which are marked as false // in the numbers array for(int i = 2; i <= n; i++) if (numbers[i] == false) primes.add(i);} // Function to print three prime numbers// which sum up to the number Nstatic void findNums(int num){ boolean ans = false; int first = -1, second = -1, third = -1; for(int i = 0; i < num; i++) { // Take the first prime number first = primes.get(i); for(int j = 0; j < num; j++) { // Take the second prime number second = primes.get(j); // Subtract the two prime numbers // from the N to obtain the third number third = num - first - second; // If the third number is prime if (Collections.binarySearch( primes, third) >= 0) { ans = true; break; } } if (ans) break; } // Print the three prime numbers // if the solution exists if (ans) System.out.println(first + " " + second + " " + third); else System.out.println(-1 );} // Driver codepublic static void main (String[] args){ int n = 101; primes = new ArrayList<>(); // Function for generating prime numbers // using Sieve of Eratosthenes initialize(); // Function to print the three prime // numbers whose sum is equal to N findNums(n);}} // This code is contributed by offbeat
# Python3 implementation of the approachfrom math import sqrt MAX = 100001; # The vector primes holds# the prime numbersprimes = []; # Function to generate prime numbersdef initialize() : # Initialize the array elements to 0s numbers = [0]*(MAX + 1); n = MAX; for i in range(2, int(sqrt(n)) + 1) : if (not numbers[i]) : for j in range( i * i , n + 1, i) : # Set the non-primes to true numbers[j] = True; # Fill the vector primes with prime # numbers which are marked as false # in the numbers array for i in range(2, n + 1) : if (numbers[i] == False) : primes.append(i); # Function to print three prime numbers# which sum up to the number Ndef findNums(num) : ans = False; first = -1; second = -1; third = -1; for i in range(num) : # Take the first prime number first = primes[i]; for j in range(num) : # Take the second prime number second = primes[j]; # Subtract the two prime numbers # from the N to obtain the third number third = num - first - second; # If the third number is prime if (third in primes) : ans = True; break; if (ans) : break; # Print the three prime numbers # if the solution exists if (ans) : print(first , second , third); else : print(-1); # Driver codeif __name__ == "__main__" : n = 101; # Function for generating prime numbers # using Sieve of Eratosthenes initialize(); # Function to print the three prime # numbers whose sum is equal to N findNums(n); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System;using System.Collections.Generic;class GFG{ static int MAX = 100001; // The vector primes holds // the prime numbers static List<int> primes = new List<int>(); // Function to generate prime numbers static void initialize() { // Initialize the array elements to 0s bool[] numbers = new bool[MAX + 1]; int n = MAX; for (int i = 2; i * i <= n; i++) if (!numbers[i]) for (int j = i * i; j <= n; j += i) // Set the non-primes to true numbers[j] = true; // Fill the vector primes with prime // numbers which are marked as false // in the numbers array for (int i = 2; i <= n; i++) if (numbers[i] == false) primes.Add(i); } // Function to print three prime numbers // which sum up to the number N static void findNums(int num) { bool ans = false; int first = -1, second = -1, third = -1; for (int i = 0; i < num; i++) { // Take the first prime number first = primes[i]; for (int j = 0; j < num; j++) { // Take the second prime number second = primes[j]; // Subtract the two prime numbers // from the N to obtain the third number third = num - first - second; // If the third number is prime if (Array.BinarySearch(primes.ToArray(), third) >= 0) { ans = true; break; } } if (ans) break; } // Print the three prime numbers // if the solution exists if (ans) Console.WriteLine(first + " " + second + " " + third); else Console.WriteLine(-1); } // Driver code static void Main() { int n = 101; // Function for generating prime numbers // using Sieve of Eratosthenes initialize(); // Function to print the three prime // numbers whose sum is equal to N findNums(n); }} // This code is contributed by divyesh072019
2 2 97
ankthon
offbeat
divyesh072019
Prime Number
Mathematical
Mathematical
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Modulo Operator (%) in C/C++ with Examples
Merge two sorted arrays
Prime Numbers
Program to find sum of elements in a given array
Program for factorial of a number
Operators in C / C++
Euclidean algorithms (Basic and Extended)
Program for Decimal to Binary Conversion
Algorithm to solve Rubik's Cube
Minimum number of jumps to reach end
|
[
{
"code": null,
"e": 25094,
"s": 25066,
"text": "\n05 Jan, 2021"
},
{
"code": null,
"e": 25241,
"s": 25094,
"text": "Given an integer N, the task is to find three prime numbers X, Y, and Z such that the sum of these three numbers is equal to N i.e. X + Y + Z = N."
},
{
"code": null,
"e": 25253,
"s": 25241,
"text": "Examples: "
},
{
"code": null,
"e": 25282,
"s": 25253,
"text": "Input: N = 20 Output: 2 5 13"
},
{
"code": null,
"e": 25312,
"s": 25282,
"text": "Input: N = 34 Output: 2 3 29 "
},
{
"code": null,
"e": 25324,
"s": 25312,
"text": "Approach: "
},
{
"code": null,
"e": 25375,
"s": 25324,
"text": "Generate prime numbers using Sieve of Eratosthenes"
},
{
"code": null,
"e": 25410,
"s": 25375,
"text": "Start from the first prime number."
},
{
"code": null,
"e": 25455,
"s": 25410,
"text": "Take another number from the generated list."
},
{
"code": null,
"e": 25548,
"s": 25455,
"text": "Subtract first number and second number from the original number to obtain the third number."
},
{
"code": null,
"e": 25593,
"s": 25548,
"text": "Check if the third number is a prime number."
},
{
"code": null,
"e": 25662,
"s": 25593,
"text": "If the third number is a prime number then output the three numbers."
},
{
"code": null,
"e": 25748,
"s": 25662,
"text": "Otherwise, repeat the process for the second number and consequently the first number"
},
{
"code": null,
"e": 25792,
"s": 25748,
"text": "If the answer does not exist then print -1."
},
{
"code": null,
"e": 25845,
"s": 25792,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25849,
"s": 25845,
"text": "C++"
},
{
"code": null,
"e": 25854,
"s": 25849,
"text": "Java"
},
{
"code": null,
"e": 25862,
"s": 25854,
"text": "Python3"
},
{
"code": null,
"e": 25865,
"s": 25862,
"text": "C#"
},
{
"code": "// C++ implementation of the approach #include <bits/stdc++.h>using namespace std; const int MAX = 100001; // The vector primes holds// the prime numbersvector<int> primes; // Function to generate prime numbersvoid initialize(){ // Initialize the array elements to 0s bool numbers[MAX] = {}; int n = MAX; for (int i = 2; i * i <= n; i++) if (!numbers[i]) for (int j = i * i; j <= n; j += i) // Set the non-primes to true numbers[j] = true; // Fill the vector primes with prime // numbers which are marked as false // in the numbers array for (int i = 2; i <= n; i++) if (numbers[i] == false) primes.push_back(i);} // Function to print three prime numbers// which sum up to the number Nvoid findNums(int num){ bool ans = false; int first = -1, second = -1, third = -1; for (int i = 0; i < num; i++) { // Take the first prime number first = primes[i]; for (int j = 0; j < num; j++) { // Take the second prime number second = primes[j]; // Subtract the two prime numbers // from the N to obtain the third number third = num - first - second; // If the third number is prime if (binary_search(primes.begin(), primes.end(), third)) { ans = true; break; } } if (ans) break; } // Print the three prime numbers // if the solution exists if (ans) cout << first << \" \" << second << \" \" << third << endl; else cout << -1 << endl;} // Driver codeint main(){ int n = 101; // Function for generating prime numbers // using Sieve of Eratosthenes initialize(); // Function to print the three prime // numbers whose sum is equal to N findNums(n); return 0;}",
"e": 27774,
"s": 25865,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ static int MAX = 100001; // The vector primes holds// the prime numbersstatic ArrayList<Integer> primes; // Function to generate prime numbersstatic void initialize(){ // Initialize the array elements to 0s boolean[] numbers = new boolean[MAX + 1]; int n = MAX; for(int i = 2; i * i <= n; i++) if (!numbers[i]) for(int j = i * i; j <= n; j += i) // Set the non-primes to true numbers[j] = true; // Fill the vector primes with prime // numbers which are marked as false // in the numbers array for(int i = 2; i <= n; i++) if (numbers[i] == false) primes.add(i);} // Function to print three prime numbers// which sum up to the number Nstatic void findNums(int num){ boolean ans = false; int first = -1, second = -1, third = -1; for(int i = 0; i < num; i++) { // Take the first prime number first = primes.get(i); for(int j = 0; j < num; j++) { // Take the second prime number second = primes.get(j); // Subtract the two prime numbers // from the N to obtain the third number third = num - first - second; // If the third number is prime if (Collections.binarySearch( primes, third) >= 0) { ans = true; break; } } if (ans) break; } // Print the three prime numbers // if the solution exists if (ans) System.out.println(first + \" \" + second + \" \" + third); else System.out.println(-1 );} // Driver codepublic static void main (String[] args){ int n = 101; primes = new ArrayList<>(); // Function for generating prime numbers // using Sieve of Eratosthenes initialize(); // Function to print the three prime // numbers whose sum is equal to N findNums(n);}} // This code is contributed by offbeat",
"e": 29961,
"s": 27774,
"text": null
},
{
"code": "# Python3 implementation of the approachfrom math import sqrt MAX = 100001; # The vector primes holds# the prime numbersprimes = []; # Function to generate prime numbersdef initialize() : # Initialize the array elements to 0s numbers = [0]*(MAX + 1); n = MAX; for i in range(2, int(sqrt(n)) + 1) : if (not numbers[i]) : for j in range( i * i , n + 1, i) : # Set the non-primes to true numbers[j] = True; # Fill the vector primes with prime # numbers which are marked as false # in the numbers array for i in range(2, n + 1) : if (numbers[i] == False) : primes.append(i); # Function to print three prime numbers# which sum up to the number Ndef findNums(num) : ans = False; first = -1; second = -1; third = -1; for i in range(num) : # Take the first prime number first = primes[i]; for j in range(num) : # Take the second prime number second = primes[j]; # Subtract the two prime numbers # from the N to obtain the third number third = num - first - second; # If the third number is prime if (third in primes) : ans = True; break; if (ans) : break; # Print the three prime numbers # if the solution exists if (ans) : print(first , second , third); else : print(-1); # Driver codeif __name__ == \"__main__\" : n = 101; # Function for generating prime numbers # using Sieve of Eratosthenes initialize(); # Function to print the three prime # numbers whose sum is equal to N findNums(n); # This code is contributed by AnkitRai01",
"e": 31703,
"s": 29961,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic;class GFG{ static int MAX = 100001; // The vector primes holds // the prime numbers static List<int> primes = new List<int>(); // Function to generate prime numbers static void initialize() { // Initialize the array elements to 0s bool[] numbers = new bool[MAX + 1]; int n = MAX; for (int i = 2; i * i <= n; i++) if (!numbers[i]) for (int j = i * i; j <= n; j += i) // Set the non-primes to true numbers[j] = true; // Fill the vector primes with prime // numbers which are marked as false // in the numbers array for (int i = 2; i <= n; i++) if (numbers[i] == false) primes.Add(i); } // Function to print three prime numbers // which sum up to the number N static void findNums(int num) { bool ans = false; int first = -1, second = -1, third = -1; for (int i = 0; i < num; i++) { // Take the first prime number first = primes[i]; for (int j = 0; j < num; j++) { // Take the second prime number second = primes[j]; // Subtract the two prime numbers // from the N to obtain the third number third = num - first - second; // If the third number is prime if (Array.BinarySearch(primes.ToArray(), third) >= 0) { ans = true; break; } } if (ans) break; } // Print the three prime numbers // if the solution exists if (ans) Console.WriteLine(first + \" \" + second + \" \" + third); else Console.WriteLine(-1); } // Driver code static void Main() { int n = 101; // Function for generating prime numbers // using Sieve of Eratosthenes initialize(); // Function to print the three prime // numbers whose sum is equal to N findNums(n); }} // This code is contributed by divyesh072019",
"e": 33630,
"s": 31703,
"text": null
},
{
"code": null,
"e": 33637,
"s": 33630,
"text": "2 2 97"
},
{
"code": null,
"e": 33649,
"s": 33641,
"text": "ankthon"
},
{
"code": null,
"e": 33657,
"s": 33649,
"text": "offbeat"
},
{
"code": null,
"e": 33671,
"s": 33657,
"text": "divyesh072019"
},
{
"code": null,
"e": 33684,
"s": 33671,
"text": "Prime Number"
},
{
"code": null,
"e": 33697,
"s": 33684,
"text": "Mathematical"
},
{
"code": null,
"e": 33710,
"s": 33697,
"text": "Mathematical"
},
{
"code": null,
"e": 33723,
"s": 33710,
"text": "Prime Number"
},
{
"code": null,
"e": 33821,
"s": 33723,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33830,
"s": 33821,
"text": "Comments"
},
{
"code": null,
"e": 33843,
"s": 33830,
"text": "Old Comments"
},
{
"code": null,
"e": 33886,
"s": 33843,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 33910,
"s": 33886,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 33924,
"s": 33910,
"text": "Prime Numbers"
},
{
"code": null,
"e": 33973,
"s": 33924,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 34007,
"s": 33973,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 34028,
"s": 34007,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 34070,
"s": 34028,
"text": "Euclidean algorithms (Basic and Extended)"
},
{
"code": null,
"e": 34111,
"s": 34070,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 34143,
"s": 34111,
"text": "Algorithm to solve Rubik's Cube"
}
] |
Ruby on Rails - Scaffolding
|
While you're developing Rails applications, especially those which are mainly providing you with a simple interface to data in a database, it can often be useful to use the scaffold method.
Scaffolding provides more than cheap demo thrills. Here are some benefits −
You can quickly get code in front of your users for feedback.
You can quickly get code in front of your users for feedback.
You are motivated by faster success.
You are motivated by faster success.
You can learn how Rails works by looking at the generated code.
You can learn how Rails works by looking at the generated code.
You can use scaffolding as a foundation to jump start your development.
You can use scaffolding as a foundation to jump start your development.
To understand scaffolding, let's create a database called cookbook and a table called recipes.
Open a command window and navigate to where you want to create this cookbook web application. So, run the following command to create a complete directory structure.
tp> rails new cookbook
Here is the way to create a database −
mysql> create database cookbook;
Query OK, 1 row affected (0.01 sec)
mysql> grant all privileges on cookbook.*
to 'root'@'localhost' identified by 'password';
Query OK, 0 rows affected (0.00 sec)
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)
To instruct Rails how to find the database, edit the configuration file cookbook\config\database.yml and change the database name to cookbook. Leave the password empty. When you finish, it should look as follows −
development:
adapter: mysql
database: cookbook
username: root
password: [password]
host: localhost
test:
adapter: mysql
database: cookbook
username: root
password: [password]
host: localhost
production:
adapter: mysql
database: cookbook
username: root
password: [password]
host: localhost
Rails lets you run in the development mode, test mode, or production mode, using different databases. This application uses the same database for each.
With the scaffold action, Rails generates all the code it needs dynamically. By running scaffold as a script, we can get all the code written to disk, where we can investigate it and then start tailoring it to our requirements.
So now, let's start once again to generate Scaffold code manually by using the scaffold helper script −
cookbook> rails generate scaffold recipe
It generates auto-files as shown below −
Let's look at the code behind the controller. This code is generated by the scaffold generator. If you open app/controllers/recipes_controller.rb, then you will find something as follows −
class RecipesController < ApplicationController
before_action :set_recipe, only: [:show, :edit, :update, :destroy]
# GET /recipes
# GET /recipes.json
def index
@recipes = Recipe.all
end
# GET /recipes/1
# GET /recipes/1.json
def show
end
# GET /recipes/new
def new
@recipe = Recipe.new
end
# GET /recipes/1/edit
def edit
end
# POST /recipes
# POST /recipes.json
def create
@recipe = Recipe.new(recipe_params)
respond_to do |format|
if @recipe.save
format.html { redirect_to @recipe, notice: 'Recipe was successfully created.' }
format.json { render :show, status: :created, location: @recipe }
else
format.html { render :new }
format.json { render json: @recipe.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /recipes/1
# PATCH/PUT /recipes/1.json
def update
respond_to do |format|
if @recipe.update(recipe_params)
format.html { redirect_to @recipe, notice: 'Recipe was successfully updated.' }
format.json { render :show, status: :ok, location: @recipe }
else
format.html { render :edit }
format.json { render json: @recipe.errors, status: :unprocessable_entity }
end
end
end
# DELETE /recipes/1
# DELETE /recipes/1.json
def destroy
@recipe.destroy
respond_to do |format|
format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_recipe
@recipe = Recipe.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def recipe_params
params.require(:recipe).permit(:tittle, :instructions)
end
end
When the user of a Rails application selects an action, e.g. "Show" - the controller will execute any code in the appropriate section - "def show" - and then by default will render a template of the same name - "show.html.erb". This default behavior can be overwritten.
The controller uses ActiveRecord methods such as find, find_all, new, save, update_attributes, and destroy to move data to and from the database tables. Note that you do not have to write any SQL statements, rails will take care of it automatically.
This single line of code will bring the database table to life. It will provide with a simple interface to your data, and ways of −
Creating new entries
Editing current entries
Viewing current entries
Destroying current entries
When creating or editing an entry, scaffold will do all the hard work like form generation and handling for you, and will even provide clever form generation, supporting the following types of inputs −
Simple text strings
Text areas (or large blocks of text)
Date selectors
Date-time selectors
You can use Rails Migrations to create and maintain tables.
rake db:migrate RAILS_ENV=development
Now, go to the cookbook directory and run the Web Server using the following command −
cookbook> rails server
Now, open a browser and navigate to http://127.0.0.1:3000/recipe/new. This will provide you a screen to create new entries in the recipes table. A screenshot is shown below −
Once you press the Create button to create a new recipe, your record is added into the recipes table and it shows the following result −
You can see the option to edit, show, and destroy the records. So, play around with these options.
You can also list down all the recipes available in the recipes table using the URL http://127.0.0.1:3000/recipe/list.
Rails gives you a lot of error handling for free. To understand this, add some validation rules to the empty recipe model −
Modify app/models/recipe.rb as follows and then test your application −
class Recipe < ActiveRecord::Base
validates_length_of :title, :within => 1..20
validates_uniqueness_of :title, :message => "already exists"
end
These entries will give automatic checking.
validates_length_of − the field is not blank and not too long.
validates_length_of − the field is not blank and not too long.
validates_uniqueness_of − duplicate values are trapped. Instead of the default Rails error message, we have given a custom message here.
validates_uniqueness_of − duplicate values are trapped. Instead of the default Rails error message, we have given a custom message here.
Create an application as shown above and The Generated Scaffold Code as shown below
rails g scaffold Recipe tittle:string instructions:text
Above code generates the auto files with data base by using with sqlite3 with tittle and instruction column as shown below an image.
we need to migrate the data base by using below syntax.
$ rake db:migrate RAILS_ENV=development
Finally run the application by using the following command line −
rails server
It will generate the result as shown above output images.
All the views and corresponding all the controller methods are created by scaffold command and they are available in the app/views/recipes directory.
If you have gone through the previous chapters, then you must have seen that we had created methods to list, show, delete and create data etc., but scaffolding does that job automatically.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2293,
"s": 2103,
"text": "While you're developing Rails applications, especially those which are mainly providing you with a simple interface to data in a database, it can often be useful to use the scaffold method."
},
{
"code": null,
"e": 2369,
"s": 2293,
"text": "Scaffolding provides more than cheap demo thrills. Here are some benefits −"
},
{
"code": null,
"e": 2431,
"s": 2369,
"text": "You can quickly get code in front of your users for feedback."
},
{
"code": null,
"e": 2493,
"s": 2431,
"text": "You can quickly get code in front of your users for feedback."
},
{
"code": null,
"e": 2530,
"s": 2493,
"text": "You are motivated by faster success."
},
{
"code": null,
"e": 2567,
"s": 2530,
"text": "You are motivated by faster success."
},
{
"code": null,
"e": 2631,
"s": 2567,
"text": "You can learn how Rails works by looking at the generated code."
},
{
"code": null,
"e": 2695,
"s": 2631,
"text": "You can learn how Rails works by looking at the generated code."
},
{
"code": null,
"e": 2767,
"s": 2695,
"text": "You can use scaffolding as a foundation to jump start your development."
},
{
"code": null,
"e": 2839,
"s": 2767,
"text": "You can use scaffolding as a foundation to jump start your development."
},
{
"code": null,
"e": 2934,
"s": 2839,
"text": "To understand scaffolding, let's create a database called cookbook and a table called recipes."
},
{
"code": null,
"e": 3100,
"s": 2934,
"text": "Open a command window and navigate to where you want to create this cookbook web application. So, run the following command to create a complete directory structure."
},
{
"code": null,
"e": 3124,
"s": 3100,
"text": "tp> rails new cookbook\n"
},
{
"code": null,
"e": 3163,
"s": 3124,
"text": "Here is the way to create a database −"
},
{
"code": null,
"e": 3424,
"s": 3163,
"text": "mysql> create database cookbook;\nQuery OK, 1 row affected (0.01 sec)\n\nmysql> grant all privileges on cookbook.*\nto 'root'@'localhost' identified by 'password';\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> FLUSH PRIVILEGES;\nQuery OK, 0 rows affected (0.00 sec)\n"
},
{
"code": null,
"e": 3638,
"s": 3424,
"text": "To instruct Rails how to find the database, edit the configuration file cookbook\\config\\database.yml and change the database name to cookbook. Leave the password empty. When you finish, it should look as follows −"
},
{
"code": null,
"e": 3977,
"s": 3638,
"text": "development:\n adapter: mysql\n database: cookbook\n username: root\n password: [password]\n host: localhost\n\t\ntest:\n adapter: mysql\n database: cookbook\n username: root\n password: [password]\n host: localhost\n\t\nproduction:\n adapter: mysql\n database: cookbook\n username: root\n password: [password]\n host: localhost\n"
},
{
"code": null,
"e": 4129,
"s": 3977,
"text": "Rails lets you run in the development mode, test mode, or production mode, using different databases. This application uses the same database for each."
},
{
"code": null,
"e": 4357,
"s": 4129,
"text": "With the scaffold action, Rails generates all the code it needs dynamically. By running scaffold as a script, we can get all the code written to disk, where we can investigate it and then start tailoring it to our requirements."
},
{
"code": null,
"e": 4461,
"s": 4357,
"text": "So now, let's start once again to generate Scaffold code manually by using the scaffold helper script −"
},
{
"code": null,
"e": 4503,
"s": 4461,
"text": "cookbook> rails generate scaffold recipe\n"
},
{
"code": null,
"e": 4544,
"s": 4503,
"text": "It generates auto-files as shown below −"
},
{
"code": null,
"e": 4733,
"s": 4544,
"text": "Let's look at the code behind the controller. This code is generated by the scaffold generator. If you open app/controllers/recipes_controller.rb, then you will find something as follows −"
},
{
"code": null,
"e": 6754,
"s": 4733,
"text": "class RecipesController < ApplicationController\n before_action :set_recipe, only: [:show, :edit, :update, :destroy]\n \n # GET /recipes\n # GET /recipes.json\n def index\n @recipes = Recipe.all\n end\n \n # GET /recipes/1\n # GET /recipes/1.json\n def show\n end\n \n # GET /recipes/new\n def new\n @recipe = Recipe.new\n end\n \n # GET /recipes/1/edit\n def edit\n end\n \n # POST /recipes\n # POST /recipes.json\n def create\n @recipe = Recipe.new(recipe_params)\n \n respond_to do |format|\n if @recipe.save\n format.html { redirect_to @recipe, notice: 'Recipe was successfully created.' }\n format.json { render :show, status: :created, location: @recipe }\n else\n format.html { render :new }\n format.json { render json: @recipe.errors, status: :unprocessable_entity }\n end\n end\n \n end\n \n # PATCH/PUT /recipes/1\n # PATCH/PUT /recipes/1.json\n def update\n respond_to do |format|\n if @recipe.update(recipe_params)\n format.html { redirect_to @recipe, notice: 'Recipe was successfully updated.' }\n format.json { render :show, status: :ok, location: @recipe }\n else\n format.html { render :edit }\n format.json { render json: @recipe.errors, status: :unprocessable_entity }\n end\n end\n \n end\n \n # DELETE /recipes/1\n # DELETE /recipes/1.json\n def destroy\n @recipe.destroy\n respond_to do |format|\n format.html { redirect_to recipes_url, notice: 'Recipe was successfully destroyed.' }\n format.json { head :no_content }\n end\n end\n \n private\n \n # Use callbacks to share common setup or constraints between actions.\n def set_recipe\n @recipe = Recipe.find(params[:id])\n end\n \n # Never trust parameters from the scary internet, only allow the white list through.\n def recipe_params\n params.require(:recipe).permit(:tittle, :instructions)\n end\nend"
},
{
"code": null,
"e": 7024,
"s": 6754,
"text": "When the user of a Rails application selects an action, e.g. \"Show\" - the controller will execute any code in the appropriate section - \"def show\" - and then by default will render a template of the same name - \"show.html.erb\". This default behavior can be overwritten."
},
{
"code": null,
"e": 7274,
"s": 7024,
"text": "The controller uses ActiveRecord methods such as find, find_all, new, save, update_attributes, and destroy to move data to and from the database tables. Note that you do not have to write any SQL statements, rails will take care of it automatically."
},
{
"code": null,
"e": 7406,
"s": 7274,
"text": "This single line of code will bring the database table to life. It will provide with a simple interface to your data, and ways of −"
},
{
"code": null,
"e": 7427,
"s": 7406,
"text": "Creating new entries"
},
{
"code": null,
"e": 7451,
"s": 7427,
"text": "Editing current entries"
},
{
"code": null,
"e": 7475,
"s": 7451,
"text": "Viewing current entries"
},
{
"code": null,
"e": 7502,
"s": 7475,
"text": "Destroying current entries"
},
{
"code": null,
"e": 7704,
"s": 7502,
"text": "When creating or editing an entry, scaffold will do all the hard work like form generation and handling for you, and will even provide clever form generation, supporting the following types of inputs −"
},
{
"code": null,
"e": 7724,
"s": 7704,
"text": "Simple text strings"
},
{
"code": null,
"e": 7761,
"s": 7724,
"text": "Text areas (or large blocks of text)"
},
{
"code": null,
"e": 7776,
"s": 7761,
"text": "Date selectors"
},
{
"code": null,
"e": 7796,
"s": 7776,
"text": "Date-time selectors"
},
{
"code": null,
"e": 7856,
"s": 7796,
"text": "You can use Rails Migrations to create and maintain tables."
},
{
"code": null,
"e": 7895,
"s": 7856,
"text": "rake db:migrate RAILS_ENV=development\n"
},
{
"code": null,
"e": 7982,
"s": 7895,
"text": "Now, go to the cookbook directory and run the Web Server using the following command −"
},
{
"code": null,
"e": 8006,
"s": 7982,
"text": "cookbook> rails server\n"
},
{
"code": null,
"e": 8181,
"s": 8006,
"text": "Now, open a browser and navigate to http://127.0.0.1:3000/recipe/new. This will provide you a screen to create new entries in the recipes table. A screenshot is shown below −"
},
{
"code": null,
"e": 8318,
"s": 8181,
"text": "Once you press the Create button to create a new recipe, your record is added into the recipes table and it shows the following result −"
},
{
"code": null,
"e": 8417,
"s": 8318,
"text": "You can see the option to edit, show, and destroy the records. So, play around with these options."
},
{
"code": null,
"e": 8536,
"s": 8417,
"text": "You can also list down all the recipes available in the recipes table using the URL http://127.0.0.1:3000/recipe/list."
},
{
"code": null,
"e": 8661,
"s": 8536,
"text": "Rails gives you a lot of error handling for free. To understand this, add some validation rules to the empty recipe model −"
},
{
"code": null,
"e": 8733,
"s": 8661,
"text": "Modify app/models/recipe.rb as follows and then test your application −"
},
{
"code": null,
"e": 8884,
"s": 8733,
"text": "class Recipe < ActiveRecord::Base\n validates_length_of :title, :within => 1..20\n validates_uniqueness_of :title, :message => \"already exists\"\nend\n"
},
{
"code": null,
"e": 8928,
"s": 8884,
"text": "These entries will give automatic checking."
},
{
"code": null,
"e": 8991,
"s": 8928,
"text": "validates_length_of − the field is not blank and not too long."
},
{
"code": null,
"e": 9054,
"s": 8991,
"text": "validates_length_of − the field is not blank and not too long."
},
{
"code": null,
"e": 9191,
"s": 9054,
"text": "validates_uniqueness_of − duplicate values are trapped. Instead of the default Rails error message, we have given a custom message here."
},
{
"code": null,
"e": 9328,
"s": 9191,
"text": "validates_uniqueness_of − duplicate values are trapped. Instead of the default Rails error message, we have given a custom message here."
},
{
"code": null,
"e": 9412,
"s": 9328,
"text": "Create an application as shown above and The Generated Scaffold Code as shown below"
},
{
"code": null,
"e": 9469,
"s": 9412,
"text": "rails g scaffold Recipe tittle:string instructions:text\n"
},
{
"code": null,
"e": 9602,
"s": 9469,
"text": "Above code generates the auto files with data base by using with sqlite3 with tittle and instruction column as shown below an image."
},
{
"code": null,
"e": 9658,
"s": 9602,
"text": "we need to migrate the data base by using below syntax."
},
{
"code": null,
"e": 9699,
"s": 9658,
"text": "$ rake db:migrate RAILS_ENV=development\n"
},
{
"code": null,
"e": 9765,
"s": 9699,
"text": "Finally run the application by using the following command line −"
},
{
"code": null,
"e": 9779,
"s": 9765,
"text": "rails server\n"
},
{
"code": null,
"e": 9837,
"s": 9779,
"text": "It will generate the result as shown above output images."
},
{
"code": null,
"e": 9987,
"s": 9837,
"text": "All the views and corresponding all the controller methods are created by scaffold command and they are available in the app/views/recipes directory."
},
{
"code": null,
"e": 10176,
"s": 9987,
"text": "If you have gone through the previous chapters, then you must have seen that we had created methods to list, show, delete and create data etc., but scaffolding does that job automatically."
},
{
"code": null,
"e": 10183,
"s": 10176,
"text": " Print"
},
{
"code": null,
"e": 10194,
"s": 10183,
"text": " Add Notes"
}
] |
Angular Google Charts - Combination Chart
|
Combination chart helps in rendering each series as a different marker type from the following list: line, area, bars, candlesticks, and stepped area. To assign a default marker type for series, use the seriesType property. Series property is to be used to specify properties of each series individually. Following is an example of a Column Chart showing differences.
We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a Column Chart showing differences.
We've used ComboChart class to show a Combination Chart.
type='ComboChart';
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Fruits distribution';
type = 'ComboChart';
data = [
["Apples", 3, 2, 2.5],
["Oranges",2, 3, 2.5],
["Pears", 1, 5, 3],
["Bananas", 3, 9, 6],
["Plums", 4, 2, 3]
];
columnNames = ['Fruits', 'Jane','Jone','Average'];
options = {
hAxis: {
title: 'Person'
},
vAxis:{
title: 'Fruits'
},
seriesType: 'bars',
series: {2: {type: 'line'}}
};
width = 550;
height = 400;
}
Verify the result.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2164,
"s": 1796,
"text": "Combination chart helps in rendering each series as a different marker type from the following list: line, area, bars, candlesticks, and stepped area. To assign a default marker type for series, use the seriesType property. Series property is to be used to specify properties of each series individually. Following is an example of a Column Chart showing differences."
},
{
"code": null,
"e": 2338,
"s": 2164,
"text": "We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a Column Chart showing differences."
},
{
"code": null,
"e": 2395,
"s": 2338,
"text": "We've used ComboChart class to show a Combination Chart."
},
{
"code": null,
"e": 2415,
"s": 2395,
"text": "type='ComboChart';\n"
},
{
"code": null,
"e": 2432,
"s": 2415,
"text": "app.component.ts"
},
{
"code": null,
"e": 3105,
"s": 2432,
"text": "import { Component } from '@angular/core';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Fruits distribution';\n type = 'ComboChart';\n data = [\n [\"Apples\", 3, 2, 2.5],\n [\"Oranges\",2, 3, 2.5],\n [\"Pears\", 1, 5, 3],\n [\"Bananas\", 3, 9, 6],\n [\"Plums\", 4, 2, 3]\n ];\n columnNames = ['Fruits', 'Jane','Jone','Average'];\n options = { \n hAxis: {\n title: 'Person'\n },\n vAxis:{\n title: 'Fruits'\n },\n seriesType: 'bars',\n series: {2: {type: 'line'}}\n };\n width = 550;\n height = 400;\n}"
},
{
"code": null,
"e": 3124,
"s": 3105,
"text": "Verify the result."
},
{
"code": null,
"e": 3159,
"s": 3124,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3173,
"s": 3159,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3208,
"s": 3173,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3222,
"s": 3208,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3257,
"s": 3222,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 3277,
"s": 3257,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 3312,
"s": 3277,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3329,
"s": 3312,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3362,
"s": 3329,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3374,
"s": 3362,
"text": " Senol Atac"
},
{
"code": null,
"e": 3409,
"s": 3374,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3421,
"s": 3409,
"text": " Senol Atac"
},
{
"code": null,
"e": 3428,
"s": 3421,
"text": " Print"
},
{
"code": null,
"e": 3439,
"s": 3428,
"text": " Add Notes"
}
] |
How to create a plot of empirical distribution in R?
|
The empirical distribution can be found by using the function ecdf and if we want to create a plot of empirical distribution then plot function will be used.
For example, if we have a vector called X then plot of empirical distribution can be created by using the below command −
plot(ecdf(X))
To create a plot of empirical distribution in R, use the code given below −
x<-rnorm(100)
plot(ecdf(x))
If you execute the above given code, it generates the following output −
To create a plot of empirical distribution in R, use the code given below −
y<-rpois(10000,2)
plot(ecdf(y))
If you execute the above given code, it generates the following output −
|
[
{
"code": null,
"e": 1220,
"s": 1062,
"text": "The empirical distribution can be found by using the function ecdf and if we want to create a plot of empirical distribution then plot function will be used."
},
{
"code": null,
"e": 1342,
"s": 1220,
"text": "For example, if we have a vector called X then plot of empirical distribution can be created by using the below command −"
},
{
"code": null,
"e": 1356,
"s": 1342,
"text": "plot(ecdf(X))"
},
{
"code": null,
"e": 1432,
"s": 1356,
"text": "To create a plot of empirical distribution in R, use the code given below −"
},
{
"code": null,
"e": 1460,
"s": 1432,
"text": "x<-rnorm(100)\nplot(ecdf(x))"
},
{
"code": null,
"e": 1533,
"s": 1460,
"text": "If you execute the above given code, it generates the following output −"
},
{
"code": null,
"e": 1609,
"s": 1533,
"text": "To create a plot of empirical distribution in R, use the code given below −"
},
{
"code": null,
"e": 1641,
"s": 1609,
"text": "y<-rpois(10000,2)\nplot(ecdf(y))"
},
{
"code": null,
"e": 1714,
"s": 1641,
"text": "If you execute the above given code, it generates the following output −"
}
] |
Maximum consecutive repeating character in string - GeeksforGeeks
|
10 May, 2021
Given a string, the task is to find the maximum consecutive repeating character in a string.Note: We do not need to consider the overall count, but the count of repeating that appears in one place.Examples:
Input : str = "geeekk"
Output : e
Input : str = "aaaabbcbbb"
Output : a
The simple solution to this problem is to use two for loops. The outer loop considers the current character, the inner loop counts occurrences of the current character. If the count goes beyond the current maximum count, we update the result.
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to find the maximum consecutive// repeating character in given string#include<bits/stdc++.h>using namespace std; // function to find out the maximum repeating// character in given stringchar maxRepeating(string str){ int len = str.length(); int count = 0; // Find the maximum repeating character // starting from str[i] char res = str[0]; for (int i=0; i<len; i++) { int cur_count = 1; for (int j=i+1; j<len; j++) { if (str[i] != str[j]) break; cur_count++; } // Update result if required if (cur_count > count) { count = cur_count; res = str[i]; } } return res;} // Driver codeint main(){ string str = "aaaabbaaccde"; cout << maxRepeating(str); return 0;}
// Java program to find the maximum consecutive// repeating character in given stringpublic class GFG { // function to find out the maximum repeating // character in given string static char maxRepeating(String str) { int len = str.length(); int count = 0; // Find the maximum repeating character // starting from str[i] char res = str.charAt(0); for (int i=0; i<len; i++) { int cur_count = 1; for (int j=i+1; j<len; j++) { if (str.charAt(i) != str.charAt(j)) break; cur_count++; } // Update result if required if (cur_count > count) { count = cur_count; res = str.charAt(i); } } return res; } // Driver code public static void main(String args[]) { String str = "aaaabbaaccde"; System.out.println(maxRepeating(str)); }}// This code is contributed by Sumit Ghosh
# Python 3 program to find the# maximum consecutive repeating# character in given string # function to find out the maximum# repeating character in given stringdef maxRepeating(str): l = len(str) count = 0 # Find the maximum repeating # character starting from str[i] res = str[0] for i in range(l): cur_count = 1 for j in range(i + 1, l): if (str[i] != str[j]): break cur_count += 1 # Update result if required if cur_count > count : count = cur_count res = str[i] return res # Driver codeif __name__ == "__main__": str = "aaaabbaaccde" print(maxRepeating(str)) # This code is contributed# by ChitraNayal
// C# program to find the maximum// consecutive repeating character// in given stringusing System; class GFG{ // function to find out the maximum// repeating character in given stringstatic char maxRepeating(string str){ int len = str.Length; int count = 0; char res = str[0]; // Find the maximum repeating // character starting from str[i] for (int i = 0; i < len; i++) { int cur_count = 1; for (int j = i + 1; j < len; j++) { if (str[i] != str[j]) break; cur_count++; } // Update result if required if (cur_count > count) { count = cur_count; res = str[i]; } } return res;} // Driver codepublic static void Main(){ string str = "aaaabbaaccde"; Console.Write(maxRepeating(str));}} // This code is contributed// by ChitraNayal
<?php//PHP program to find the maximum consecutive// repeating character in given string // function to find out the maximum repeating// character in given stringfunction maxRepeating( $str){ $len = strlen($str); $count = 0; // Find the maximum repeating character // starting from str[i] $res = $str[0]; for ($i = 0; $i < $len; $i++) { $cur_count = 1; for ($j = $i+1; $j < $len; $j++) { if ($str[$i] != $str[$j]) break; $cur_count++; } // Update result if required if ($cur_count > $count) { $count = $cur_count; $res = $str[$i]; } } return $res;} // Driver code $str = "aaaabbaaccde"; echo maxRepeating($str); // This code is contributed by ajit?>
<script> // Javascript program to find the maximum consecutive// repeating character in given string // function to find out the maximum repeating // character in given string function maxRepeating(str) { let len = str.length; let count = 0; // Find the maximum repeating character // starting from str[i] let res = str[0]; for (let i=0; i<len; i++) { let cur_count = 1; for (let j=i+1; j<len; j++) { if (str[i] != str[j]) break; cur_count++; } // Update result if required if (cur_count > count) { count = cur_count; res = str[i]; } } return res; } // Driver code let str = "aaaabbaaccde"; document.write(maxRepeating(str)); // This code is contributed by rag2127 </script>
Output:
a
Time Complexity : O(n^2) Space Complexity : O(1)An efficient solution is to run only one loop. The idea is to reset the count as 1 as soon as we find a character not matching with the previous.
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to find the maximum consecutive// repeating character in given string#include<bits/stdc++.h>using namespace std; // Returns the maximum repeating character in a// given stringchar maxRepeating(string str){ int n = str.length(); int count = 0; char res = str[0]; int cur_count = 1; // Traverse string except last character for (int i=0; i<n; i++) { // If current character matches with next if (i < n-1 && str[i] == str[i+1]) cur_count++; // If doesn't match, update result // (if required) and reset count else { if (cur_count > count) { count = cur_count; res = str[i]; } cur_count = 1; } } return res;} // Driver codeint main(){ string str = "aaaabbaaccde"; cout << maxRepeating(str); return 0;}
// Java program to find the maximum consecutive// repeating character in given stringclass GFG { // function to find out the maximum repeating // character in given string static char maxRepeating(String str) { int n = str.length(); int count = 0; char res = str.charAt(0); int cur_count = 1; // Traverse string except last character for (int i = 0; i < n; i++) { // If current character matches with next if (i < n - 1 && str.charAt(i) == str.charAt(i + 1)) cur_count++; // If doesn't match, update result // (if required) and reset count else { if (cur_count > count) { count = cur_count; res = str.charAt(i); } cur_count = 1; } } return res; } // Driver code public static void main(String args[]) { String str = "aaaabbaaccde"; System.out.println(maxRepeating(str)); }} // This code is contributed by Sudeep Mukherjee
# Python 3 program to find the# maximum consecutive repeating# character in given string # Returns the maximum repeating# character in a given stringdef maxRepeating(str): n = len(str) count = 0 res = str[0] cur_count = 1 # Traverse string except # last character for i in range(n): # If current character # matches with next if (i < n - 1 and str[i] == str[i + 1]): cur_count += 1 # If doesn't match, update result # (if required) and reset count else: if cur_count > count: count = cur_count res = str[i] cur_count = 1 return res # Driver codeif __name__ == "__main__": str = "aaaabbaaccde" print(maxRepeating(str)) # This code is contributed# by ChitraNayal
// C# program to find the maximum// consecutive repeating character// in given stringusing System; class GFG{ // function to find out the// maximum repeating character// in given stringstatic char maxRepeating(string str){ int n = str.Length; int count = 0; char res = str[0]; int cur_count = 1; // Traverse string except // last character for (int i = 0; i < n; i++) { // If current character // matches with next if (i < n - 1 && str[i] == str[i + 1]) cur_count++; // If doesn't match, update result // (if required) and reset count else { if (cur_count > count) { count = cur_count; res = str[i]; } cur_count = 1; } } return res;} // Driver codepublic static void Main(){ string str = "aaaabbaaccde"; Console.Write(maxRepeating(str));}} // This code is contributed// by ChitraNayal
<?php// PHP program to find the maximum// consecutive repeating character// in given string // Returns the maximum repeating// character in a given stringfunction maxRepeating($str){ $n = strlen($str); $count = 0; $res = $str[0]; $cur_count = 1; // Traverse string except // last character for ($i = 0; $i < $n; $i++) { // If current character // matches with next if ($i < $n - 1 && $str[$i] == $str[$i + 1]) $cur_count++; // If doesn't match, update result // (if required) and reset count else { if ($cur_count > $count) { $count = $cur_count; $res = $str[$i]; } $cur_count = 1; } } return $res;} // Driver code$str = "aaaabbaaccde";echo maxRepeating($str); // This code is contributed// by ChitraNayal?>
<script> // JavaScript program to find the maximum consecutive// repeating character in given string // function to find out the maximum repeating // character in given stringfunction maxRepeating( str){ var n = str.length; var count = 0; var res = str[0]; var cur_count = 1; // Traverse string except last character for (var i=0; i<n; i++) { // If current character matches with next if (i < n-1 && str[i] == str[i+1]) cur_count++; // If doesn't match, update result // (if required) and reset count else { if (cur_count > count) { count = cur_count; res = str[i]; } cur_count = 1; } } return res;} var str = "aaaabbaaccde"; document.write( maxRepeating(str)); </script>
Output:
a
Time Complexity : O(n) Space Complexity : O(1)This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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.
jit_t
sudeepmukherjee
ukasp
rag2127
akshitsaxenaa09
Amazon
Strings
Amazon
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert string to char array in C++
Array of Strings in C++ (5 Different Ways to Create)
Longest Palindromic Substring | Set 1
Reverse words in a given string
Caesar Cipher in Cryptography
Length of the longest substring without repeating characters
Check whether two strings are anagram of each other
How to split a string in C/C++, Python and Java?
Remove duplicates from a given string
Top 50 String Coding Problems for Interviews
|
[
{
"code": null,
"e": 24797,
"s": 24769,
"text": "\n10 May, 2021"
},
{
"code": null,
"e": 25006,
"s": 24797,
"text": "Given a string, the task is to find the maximum consecutive repeating character in a string.Note: We do not need to consider the overall count, but the count of repeating that appears in one place.Examples: "
},
{
"code": null,
"e": 25079,
"s": 25006,
"text": "Input : str = \"geeekk\"\nOutput : e\n\nInput : str = \"aaaabbcbbb\"\nOutput : a"
},
{
"code": null,
"e": 25326,
"s": 25081,
"text": "The simple solution to this problem is to use two for loops. The outer loop considers the current character, the inner loop counts occurrences of the current character. If the count goes beyond the current maximum count, we update the result. "
},
{
"code": null,
"e": 25330,
"s": 25326,
"text": "C++"
},
{
"code": null,
"e": 25335,
"s": 25330,
"text": "Java"
},
{
"code": null,
"e": 25344,
"s": 25335,
"text": "Python 3"
},
{
"code": null,
"e": 25347,
"s": 25344,
"text": "C#"
},
{
"code": null,
"e": 25351,
"s": 25347,
"text": "PHP"
},
{
"code": null,
"e": 25362,
"s": 25351,
"text": "Javascript"
},
{
"code": "// C++ program to find the maximum consecutive// repeating character in given string#include<bits/stdc++.h>using namespace std; // function to find out the maximum repeating// character in given stringchar maxRepeating(string str){ int len = str.length(); int count = 0; // Find the maximum repeating character // starting from str[i] char res = str[0]; for (int i=0; i<len; i++) { int cur_count = 1; for (int j=i+1; j<len; j++) { if (str[i] != str[j]) break; cur_count++; } // Update result if required if (cur_count > count) { count = cur_count; res = str[i]; } } return res;} // Driver codeint main(){ string str = \"aaaabbaaccde\"; cout << maxRepeating(str); return 0;}",
"e": 26188,
"s": 25362,
"text": null
},
{
"code": "// Java program to find the maximum consecutive// repeating character in given stringpublic class GFG { // function to find out the maximum repeating // character in given string static char maxRepeating(String str) { int len = str.length(); int count = 0; // Find the maximum repeating character // starting from str[i] char res = str.charAt(0); for (int i=0; i<len; i++) { int cur_count = 1; for (int j=i+1; j<len; j++) { if (str.charAt(i) != str.charAt(j)) break; cur_count++; } // Update result if required if (cur_count > count) { count = cur_count; res = str.charAt(i); } } return res; } // Driver code public static void main(String args[]) { String str = \"aaaabbaaccde\"; System.out.println(maxRepeating(str)); }}// This code is contributed by Sumit Ghosh",
"e": 27231,
"s": 26188,
"text": null
},
{
"code": "# Python 3 program to find the# maximum consecutive repeating# character in given string # function to find out the maximum# repeating character in given stringdef maxRepeating(str): l = len(str) count = 0 # Find the maximum repeating # character starting from str[i] res = str[0] for i in range(l): cur_count = 1 for j in range(i + 1, l): if (str[i] != str[j]): break cur_count += 1 # Update result if required if cur_count > count : count = cur_count res = str[i] return res # Driver codeif __name__ == \"__main__\": str = \"aaaabbaaccde\" print(maxRepeating(str)) # This code is contributed# by ChitraNayal",
"e": 27969,
"s": 27231,
"text": null
},
{
"code": "// C# program to find the maximum// consecutive repeating character// in given stringusing System; class GFG{ // function to find out the maximum// repeating character in given stringstatic char maxRepeating(string str){ int len = str.Length; int count = 0; char res = str[0]; // Find the maximum repeating // character starting from str[i] for (int i = 0; i < len; i++) { int cur_count = 1; for (int j = i + 1; j < len; j++) { if (str[i] != str[j]) break; cur_count++; } // Update result if required if (cur_count > count) { count = cur_count; res = str[i]; } } return res;} // Driver codepublic static void Main(){ string str = \"aaaabbaaccde\"; Console.Write(maxRepeating(str));}} // This code is contributed// by ChitraNayal",
"e": 28850,
"s": 27969,
"text": null
},
{
"code": "<?php//PHP program to find the maximum consecutive// repeating character in given string // function to find out the maximum repeating// character in given stringfunction maxRepeating( $str){ $len = strlen($str); $count = 0; // Find the maximum repeating character // starting from str[i] $res = $str[0]; for ($i = 0; $i < $len; $i++) { $cur_count = 1; for ($j = $i+1; $j < $len; $j++) { if ($str[$i] != $str[$j]) break; $cur_count++; } // Update result if required if ($cur_count > $count) { $count = $cur_count; $res = $str[$i]; } } return $res;} // Driver code $str = \"aaaabbaaccde\"; echo maxRepeating($str); // This code is contributed by ajit?>",
"e": 29660,
"s": 28850,
"text": null
},
{
"code": "<script> // Javascript program to find the maximum consecutive// repeating character in given string // function to find out the maximum repeating // character in given string function maxRepeating(str) { let len = str.length; let count = 0; // Find the maximum repeating character // starting from str[i] let res = str[0]; for (let i=0; i<len; i++) { let cur_count = 1; for (let j=i+1; j<len; j++) { if (str[i] != str[j]) break; cur_count++; } // Update result if required if (cur_count > count) { count = cur_count; res = str[i]; } } return res; } // Driver code let str = \"aaaabbaaccde\"; document.write(maxRepeating(str)); // This code is contributed by rag2127 </script>",
"e": 30613,
"s": 29660,
"text": null
},
{
"code": null,
"e": 30622,
"s": 30613,
"text": "Output: "
},
{
"code": null,
"e": 30624,
"s": 30622,
"text": "a"
},
{
"code": null,
"e": 30820,
"s": 30624,
"text": "Time Complexity : O(n^2) Space Complexity : O(1)An efficient solution is to run only one loop. The idea is to reset the count as 1 as soon as we find a character not matching with the previous. "
},
{
"code": null,
"e": 30824,
"s": 30820,
"text": "C++"
},
{
"code": null,
"e": 30829,
"s": 30824,
"text": "Java"
},
{
"code": null,
"e": 30838,
"s": 30829,
"text": "Python 3"
},
{
"code": null,
"e": 30841,
"s": 30838,
"text": "C#"
},
{
"code": null,
"e": 30845,
"s": 30841,
"text": "PHP"
},
{
"code": null,
"e": 30856,
"s": 30845,
"text": "Javascript"
},
{
"code": "// C++ program to find the maximum consecutive// repeating character in given string#include<bits/stdc++.h>using namespace std; // Returns the maximum repeating character in a// given stringchar maxRepeating(string str){ int n = str.length(); int count = 0; char res = str[0]; int cur_count = 1; // Traverse string except last character for (int i=0; i<n; i++) { // If current character matches with next if (i < n-1 && str[i] == str[i+1]) cur_count++; // If doesn't match, update result // (if required) and reset count else { if (cur_count > count) { count = cur_count; res = str[i]; } cur_count = 1; } } return res;} // Driver codeint main(){ string str = \"aaaabbaaccde\"; cout << maxRepeating(str); return 0;}",
"e": 31742,
"s": 30856,
"text": null
},
{
"code": "// Java program to find the maximum consecutive// repeating character in given stringclass GFG { // function to find out the maximum repeating // character in given string static char maxRepeating(String str) { int n = str.length(); int count = 0; char res = str.charAt(0); int cur_count = 1; // Traverse string except last character for (int i = 0; i < n; i++) { // If current character matches with next if (i < n - 1 && str.charAt(i) == str.charAt(i + 1)) cur_count++; // If doesn't match, update result // (if required) and reset count else { if (cur_count > count) { count = cur_count; res = str.charAt(i); } cur_count = 1; } } return res; } // Driver code public static void main(String args[]) { String str = \"aaaabbaaccde\"; System.out.println(maxRepeating(str)); }} // This code is contributed by Sudeep Mukherjee",
"e": 32866,
"s": 31742,
"text": null
},
{
"code": "# Python 3 program to find the# maximum consecutive repeating# character in given string # Returns the maximum repeating# character in a given stringdef maxRepeating(str): n = len(str) count = 0 res = str[0] cur_count = 1 # Traverse string except # last character for i in range(n): # If current character # matches with next if (i < n - 1 and str[i] == str[i + 1]): cur_count += 1 # If doesn't match, update result # (if required) and reset count else: if cur_count > count: count = cur_count res = str[i] cur_count = 1 return res # Driver codeif __name__ == \"__main__\": str = \"aaaabbaaccde\" print(maxRepeating(str)) # This code is contributed# by ChitraNayal",
"e": 33685,
"s": 32866,
"text": null
},
{
"code": "// C# program to find the maximum// consecutive repeating character// in given stringusing System; class GFG{ // function to find out the// maximum repeating character// in given stringstatic char maxRepeating(string str){ int n = str.Length; int count = 0; char res = str[0]; int cur_count = 1; // Traverse string except // last character for (int i = 0; i < n; i++) { // If current character // matches with next if (i < n - 1 && str[i] == str[i + 1]) cur_count++; // If doesn't match, update result // (if required) and reset count else { if (cur_count > count) { count = cur_count; res = str[i]; } cur_count = 1; } } return res;} // Driver codepublic static void Main(){ string str = \"aaaabbaaccde\"; Console.Write(maxRepeating(str));}} // This code is contributed// by ChitraNayal",
"e": 34660,
"s": 33685,
"text": null
},
{
"code": "<?php// PHP program to find the maximum// consecutive repeating character// in given string // Returns the maximum repeating// character in a given stringfunction maxRepeating($str){ $n = strlen($str); $count = 0; $res = $str[0]; $cur_count = 1; // Traverse string except // last character for ($i = 0; $i < $n; $i++) { // If current character // matches with next if ($i < $n - 1 && $str[$i] == $str[$i + 1]) $cur_count++; // If doesn't match, update result // (if required) and reset count else { if ($cur_count > $count) { $count = $cur_count; $res = $str[$i]; } $cur_count = 1; } } return $res;} // Driver code$str = \"aaaabbaaccde\";echo maxRepeating($str); // This code is contributed// by ChitraNayal?>",
"e": 35553,
"s": 34660,
"text": null
},
{
"code": "<script> // JavaScript program to find the maximum consecutive// repeating character in given string // function to find out the maximum repeating // character in given stringfunction maxRepeating( str){ var n = str.length; var count = 0; var res = str[0]; var cur_count = 1; // Traverse string except last character for (var i=0; i<n; i++) { // If current character matches with next if (i < n-1 && str[i] == str[i+1]) cur_count++; // If doesn't match, update result // (if required) and reset count else { if (cur_count > count) { count = cur_count; res = str[i]; } cur_count = 1; } } return res;} var str = \"aaaabbaaccde\"; document.write( maxRepeating(str)); </script>",
"e": 36395,
"s": 35553,
"text": null
},
{
"code": null,
"e": 36405,
"s": 36395,
"text": "Output: "
},
{
"code": null,
"e": 36407,
"s": 36405,
"text": "a"
},
{
"code": null,
"e": 36873,
"s": 36407,
"text": "Time Complexity : O(n) Space Complexity : O(1)This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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. "
},
{
"code": null,
"e": 36879,
"s": 36873,
"text": "jit_t"
},
{
"code": null,
"e": 36895,
"s": 36879,
"text": "sudeepmukherjee"
},
{
"code": null,
"e": 36901,
"s": 36895,
"text": "ukasp"
},
{
"code": null,
"e": 36909,
"s": 36901,
"text": "rag2127"
},
{
"code": null,
"e": 36925,
"s": 36909,
"text": "akshitsaxenaa09"
},
{
"code": null,
"e": 36932,
"s": 36925,
"text": "Amazon"
},
{
"code": null,
"e": 36940,
"s": 36932,
"text": "Strings"
},
{
"code": null,
"e": 36947,
"s": 36940,
"text": "Amazon"
},
{
"code": null,
"e": 36955,
"s": 36947,
"text": "Strings"
},
{
"code": null,
"e": 37053,
"s": 36955,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37062,
"s": 37053,
"text": "Comments"
},
{
"code": null,
"e": 37075,
"s": 37062,
"text": "Old Comments"
},
{
"code": null,
"e": 37111,
"s": 37075,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 37164,
"s": 37111,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 37202,
"s": 37164,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 37234,
"s": 37202,
"text": "Reverse words in a given string"
},
{
"code": null,
"e": 37264,
"s": 37234,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 37325,
"s": 37264,
"text": "Length of the longest substring without repeating characters"
},
{
"code": null,
"e": 37377,
"s": 37325,
"text": "Check whether two strings are anagram of each other"
},
{
"code": null,
"e": 37426,
"s": 37377,
"text": "How to split a string in C/C++, Python and Java?"
},
{
"code": null,
"e": 37464,
"s": 37426,
"text": "Remove duplicates from a given string"
}
] |
Mockito - Varying Calls
|
Mockito provides the following additional methods to vary the expected call counts.
atLeast (int min) − expects min calls.
atLeast (int min) − expects min calls.
atLeastOnce () − expects at least one call.
atLeastOnce () − expects at least one call.
atMost (int max) − expects max calls.
atMost (int max) − expects max calls.
Step 1 − Create an interface CalculatorService to provide mathematical functions
File: CalculatorService.java
public interface CalculatorService {
public double add(double input1, double input2);
public double subtract(double input1, double input2);
public double multiply(double input1, double input2);
public double divide(double input1, double input2);
}
Step 2 − Create a JAVA class to represent MathApplication
File: MathApplication.java
public class MathApplication {
private CalculatorService calcService;
public void setCalculatorService(CalculatorService calcService){
this.calcService = calcService;
}
public double add(double input1, double input2){
return calcService.add(input1, input2);
}
public double subtract(double input1, double input2){
return calcService.subtract(input1, input2);
}
public double multiply(double input1, double input2){
return calcService.multiply(input1, input2);
}
public double divide(double input1, double input2){
return calcService.divide(input1, input2);
}
}
Step 3 − Test the MathApplication class
Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by Mockito.
File: MathApplicationTester.java
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atMost;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
// @RunWith attaches a runner with the test class to initialize the test data
@RunWith(MockitoJUnitRunner.class)
public class MathApplicationTester {
//@InjectMocks annotation is used to create and inject the mock object
@InjectMocks
MathApplication mathApplication = new MathApplication();
//@Mock annotation is used to create the mock object to be injected
@Mock
CalculatorService calcService;
@Test
public void testAdd(){
//add the behavior of calc service to add two numbers
when(calcService.add(10.0,20.0)).thenReturn(30.00);
//add the behavior of calc service to subtract two numbers
when(calcService.subtract(20.0,10.0)).thenReturn(10.00);
//test the add functionality
Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);
Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);
Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);
//test the subtract functionality
Assert.assertEquals(mathApplication.subtract(20.0, 10.0),10.0,0.0);
//check a minimum 1 call count
verify(calcService, atLeastOnce()).subtract(20.0, 10.0);
//check if add function is called minimum 2 times
verify(calcService, atLeast(2)).add(10.0, 20.0);
//check if add function is called maximum 3 times
verify(calcService, atMost(3)).add(10.0,20.0);
}
}
Step 4 − Execute test cases
Create a java class file named TestRunner in C:\> Mockito_WORKSPACE to execute Test case(s)
File: TestRunner.java
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(MathApplicationTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Step 5 − Verify the Result
Compile the classes using javac compiler as follows −
C:\Mockito_WORKSPACE>javac CalculatorService.java MathApplication.
java MathApplicationTester.java TestRunner.java
Now run the Test Runner to see the result −
C:\Mockito_WORKSPACE>java TestRunner
Verify the output.
true
31 Lectures
43 mins
Abhinav Manchanda
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2064,
"s": 1980,
"text": "Mockito provides the following additional methods to vary the expected call counts."
},
{
"code": null,
"e": 2104,
"s": 2064,
"text": "atLeast (int min) − expects min calls."
},
{
"code": null,
"e": 2144,
"s": 2104,
"text": "atLeast (int min) − expects min calls."
},
{
"code": null,
"e": 2188,
"s": 2144,
"text": "atLeastOnce () − expects at least one call."
},
{
"code": null,
"e": 2232,
"s": 2188,
"text": "atLeastOnce () − expects at least one call."
},
{
"code": null,
"e": 2270,
"s": 2232,
"text": "atMost (int max) − expects max calls."
},
{
"code": null,
"e": 2308,
"s": 2270,
"text": "atMost (int max) − expects max calls."
},
{
"code": null,
"e": 2389,
"s": 2308,
"text": "Step 1 − Create an interface CalculatorService to provide mathematical functions"
},
{
"code": null,
"e": 2418,
"s": 2389,
"text": "File: CalculatorService.java"
},
{
"code": null,
"e": 2678,
"s": 2418,
"text": "public interface CalculatorService {\n public double add(double input1, double input2);\n public double subtract(double input1, double input2);\n public double multiply(double input1, double input2);\n public double divide(double input1, double input2);\n}"
},
{
"code": null,
"e": 2736,
"s": 2678,
"text": "Step 2 − Create a JAVA class to represent MathApplication"
},
{
"code": null,
"e": 2763,
"s": 2736,
"text": "File: MathApplication.java"
},
{
"code": null,
"e": 3406,
"s": 2763,
"text": "public class MathApplication {\n private CalculatorService calcService;\n\n public void setCalculatorService(CalculatorService calcService){\n this.calcService = calcService;\n }\n \n public double add(double input1, double input2){\n return calcService.add(input1, input2);\t\t\n }\n \n public double subtract(double input1, double input2){\n return calcService.subtract(input1, input2);\n }\n \n public double multiply(double input1, double input2){\n return calcService.multiply(input1, input2);\n }\n \n public double divide(double input1, double input2){\n return calcService.divide(input1, input2);\n }\n}"
},
{
"code": null,
"e": 3446,
"s": 3406,
"text": "Step 3 − Test the MathApplication class"
},
{
"code": null,
"e": 3565,
"s": 3446,
"text": "Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by Mockito."
},
{
"code": null,
"e": 3598,
"s": 3565,
"text": "File: MathApplicationTester.java"
},
{
"code": null,
"e": 5420,
"s": 3598,
"text": "import static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\nimport static org.mockito.Mockito.atLeastOnce;\nimport static org.mockito.Mockito.atLeast;\nimport static org.mockito.Mockito.atMost;\n\nimport org.junit.Assert;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.InjectMocks;\nimport org.mockito.Mock;\nimport org.mockito.runners.MockitoJUnitRunner;\n\n// @RunWith attaches a runner with the test class to initialize the test data\n@RunWith(MockitoJUnitRunner.class)\npublic class MathApplicationTester {\n\t\n //@InjectMocks annotation is used to create and inject the mock object\n @InjectMocks \n MathApplication mathApplication = new MathApplication();\n\n //@Mock annotation is used to create the mock object to be injected\n @Mock\n CalculatorService calcService;\n\n @Test\n public void testAdd(){\n //add the behavior of calc service to add two numbers\n when(calcService.add(10.0,20.0)).thenReturn(30.00);\n\t\t\n //add the behavior of calc service to subtract two numbers\n when(calcService.subtract(20.0,10.0)).thenReturn(10.00);\n \n //test the add functionality\n Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);\n Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);\n Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);\n \n //test the subtract functionality\n Assert.assertEquals(mathApplication.subtract(20.0, 10.0),10.0,0.0);\n \n //check a minimum 1 call count\n verify(calcService, atLeastOnce()).subtract(20.0, 10.0);\n \n //check if add function is called minimum 2 times\n verify(calcService, atLeast(2)).add(10.0, 20.0);\n \n //check if add function is called maximum 3 times\n verify(calcService, atMost(3)).add(10.0,20.0); \n }\n}\n"
},
{
"code": null,
"e": 5448,
"s": 5420,
"text": "Step 4 − Execute test cases"
},
{
"code": null,
"e": 5540,
"s": 5448,
"text": "Create a java class file named TestRunner in C:\\> Mockito_WORKSPACE to execute Test case(s)"
},
{
"code": null,
"e": 5562,
"s": 5540,
"text": "File: TestRunner.java"
},
{
"code": null,
"e": 6003,
"s": 5562,
"text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(MathApplicationTester.class);\n \n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n \n System.out.println(result.wasSuccessful());\n }\n} \t"
},
{
"code": null,
"e": 6030,
"s": 6003,
"text": "Step 5 − Verify the Result"
},
{
"code": null,
"e": 6084,
"s": 6030,
"text": "Compile the classes using javac compiler as follows −"
},
{
"code": null,
"e": 6203,
"s": 6084,
"text": "C:\\Mockito_WORKSPACE>javac CalculatorService.java MathApplication.\n java MathApplicationTester.java TestRunner.java\n"
},
{
"code": null,
"e": 6247,
"s": 6203,
"text": "Now run the Test Runner to see the result −"
},
{
"code": null,
"e": 6285,
"s": 6247,
"text": "C:\\Mockito_WORKSPACE>java TestRunner\n"
},
{
"code": null,
"e": 6304,
"s": 6285,
"text": "Verify the output."
},
{
"code": null,
"e": 6310,
"s": 6304,
"text": "true\n"
},
{
"code": null,
"e": 6342,
"s": 6310,
"text": "\n 31 Lectures \n 43 mins\n"
},
{
"code": null,
"e": 6361,
"s": 6342,
"text": " Abhinav Manchanda"
},
{
"code": null,
"e": 6368,
"s": 6361,
"text": " Print"
},
{
"code": null,
"e": 6379,
"s": 6368,
"text": " Add Notes"
}
] |
Difference between x++ and x=x+1 in Java - GeeksforGeeks
|
23 Nov, 2017
In x++, it increase the value of x by 1 and in x=x+1 it also increase the value of x by 1. But the question is that both are same or there is any difference between them. We should aware with the fact that whenever we are trying to apply any arithmetic operator between two variables a and b, the result type is always max ( int, type of a, type of b). Let’s see now see difference between both of them :
Internal Typecasting of data: In the below example, we are doing arithmetic operation i.e. addition on b and 1. Here b is of byte type and 1 is of int type. Therefore, the result should be of int type i.e max(int,type of b i.e. byte,type of 1 i.e. int). We are assigning int type to byte type in the above program that’s why we are getting compile time error saying “possible loss precision”. Here typecasting is required to perform addition.Using x = x + 1// Java program to illustrate// how arithmetic operations performed// depends on data typespublic class Test { public static void main(String[] args) { byte b = 10; // Using b = b+1 b = b + 1; System.out.println(b); /* Using typecasting will work b=(byte)b+1; System.out.println(b);*/ }}Output:error: incompatible types: possible lossy conversion from int to byte
Using Typecasting, output will be11Using x++In the next example, we are doing increment but internally we are doing operation like b++. The result should be of int type i.e max(int,type of b i.e. byte,type of 1 i.e. int) and we are getting the result as 11 because implicit typecasting is done by compiler like byte b=(byte)(b+1) here.// Java program to understand the // operations of ++ operatorpublic class Test { public static void main(String[] args) { byte b = 10; b++; System.out.println(b); }}Output:11
From the above example we can understand that in the increment/Decrement operator compiler automatically do type-casting whenever required. But how this happens? Let try to understand:Suppose We have to perform increment then we use ++ operator:i++;is just a shortcut for:i = i + 1;But what if we take values for i and j like this:byte i = 1;
Then i = i + 1;will not compile because we are assigning int value to byte type and there is no typecasting in that statement but i++; will compile fine.It means that in fact i++; is a shortcut for something like thisi = (type of i)(i + 1);Different compiler instructions for both : They are different operators, and use different JVM instructions in bytecode.x + 1 uses iadd instruction,
whereas x++ uses iinc instruction internallyAlthough this is compiler dependent. A compiler is free to use a different set of instructions for a particular operation.
Internal Typecasting of data: In the below example, we are doing arithmetic operation i.e. addition on b and 1. Here b is of byte type and 1 is of int type. Therefore, the result should be of int type i.e max(int,type of b i.e. byte,type of 1 i.e. int). We are assigning int type to byte type in the above program that’s why we are getting compile time error saying “possible loss precision”. Here typecasting is required to perform addition.Using x = x + 1// Java program to illustrate// how arithmetic operations performed// depends on data typespublic class Test { public static void main(String[] args) { byte b = 10; // Using b = b+1 b = b + 1; System.out.println(b); /* Using typecasting will work b=(byte)b+1; System.out.println(b);*/ }}Output:error: incompatible types: possible lossy conversion from int to byte
Using Typecasting, output will be11Using x++In the next example, we are doing increment but internally we are doing operation like b++. The result should be of int type i.e max(int,type of b i.e. byte,type of 1 i.e. int) and we are getting the result as 11 because implicit typecasting is done by compiler like byte b=(byte)(b+1) here.// Java program to understand the // operations of ++ operatorpublic class Test { public static void main(String[] args) { byte b = 10; b++; System.out.println(b); }}Output:11
From the above example we can understand that in the increment/Decrement operator compiler automatically do type-casting whenever required. But how this happens? Let try to understand:Suppose We have to perform increment then we use ++ operator:i++;is just a shortcut for:i = i + 1;But what if we take values for i and j like this:byte i = 1;
Then i = i + 1;will not compile because we are assigning int value to byte type and there is no typecasting in that statement but i++; will compile fine.It means that in fact i++; is a shortcut for something like thisi = (type of i)(i + 1);
Using x = x + 1
// Java program to illustrate// how arithmetic operations performed// depends on data typespublic class Test { public static void main(String[] args) { byte b = 10; // Using b = b+1 b = b + 1; System.out.println(b); /* Using typecasting will work b=(byte)b+1; System.out.println(b);*/ }}
Output:
error: incompatible types: possible lossy conversion from int to byte
Using Typecasting, output will be
11
Using x++
In the next example, we are doing increment but internally we are doing operation like b++. The result should be of int type i.e max(int,type of b i.e. byte,type of 1 i.e. int) and we are getting the result as 11 because implicit typecasting is done by compiler like byte b=(byte)(b+1) here.
// Java program to understand the // operations of ++ operatorpublic class Test { public static void main(String[] args) { byte b = 10; b++; System.out.println(b); }}
Output:
11
From the above example we can understand that in the increment/Decrement operator compiler automatically do type-casting whenever required. But how this happens? Let try to understand:Suppose We have to perform increment then we use ++ operator:
i++;
is just a shortcut for:
i = i + 1;
But what if we take values for i and j like this:
byte i = 1;
Then i = i + 1;
will not compile because we are assigning int value to byte type and there is no typecasting in that statement but i++; will compile fine.It means that in fact i++; is a shortcut for something like this
i = (type of i)(i + 1);
Different compiler instructions for both : They are different operators, and use different JVM instructions in bytecode.x + 1 uses iadd instruction,
whereas x++ uses iinc instruction internallyAlthough this is compiler dependent. A compiler is free to use a different set of instructions for a particular operation.
x + 1 uses iadd instruction,
whereas x++ uses iinc instruction internally
Although this is compiler dependent. A compiler is free to use a different set of instructions for a particular operation.
This article is contributed by Bishal Kumar Dubey. 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.
java-basics
java-puzzle
Difference Between
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Stack vs Heap Memory Allocation
Difference between Process and Thread
Difference Between Method Overloading and Method Overriding in Java
Difference between Clustered and Non-clustered index
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
|
[
{
"code": null,
"e": 24414,
"s": 24386,
"text": "\n23 Nov, 2017"
},
{
"code": null,
"e": 24819,
"s": 24414,
"text": "In x++, it increase the value of x by 1 and in x=x+1 it also increase the value of x by 1. But the question is that both are same or there is any difference between them. We should aware with the fact that whenever we are trying to apply any arithmetic operator between two variables a and b, the result type is always max ( int, type of a, type of b). Let’s see now see difference between both of them :"
},
{
"code": null,
"e": 27147,
"s": 24819,
"text": "Internal Typecasting of data: In the below example, we are doing arithmetic operation i.e. addition on b and 1. Here b is of byte type and 1 is of int type. Therefore, the result should be of int type i.e max(int,type of b i.e. byte,type of 1 i.e. int). We are assigning int type to byte type in the above program that’s why we are getting compile time error saying “possible loss precision”. Here typecasting is required to perform addition.Using x = x + 1// Java program to illustrate// how arithmetic operations performed// depends on data typespublic class Test { public static void main(String[] args) { byte b = 10; // Using b = b+1 b = b + 1; System.out.println(b); /* Using typecasting will work b=(byte)b+1; System.out.println(b);*/ }}Output:error: incompatible types: possible lossy conversion from int to byte\nUsing Typecasting, output will be11Using x++In the next example, we are doing increment but internally we are doing operation like b++. The result should be of int type i.e max(int,type of b i.e. byte,type of 1 i.e. int) and we are getting the result as 11 because implicit typecasting is done by compiler like byte b=(byte)(b+1) here.// Java program to understand the // operations of ++ operatorpublic class Test { public static void main(String[] args) { byte b = 10; b++; System.out.println(b); }}Output:11\nFrom the above example we can understand that in the increment/Decrement operator compiler automatically do type-casting whenever required. But how this happens? Let try to understand:Suppose We have to perform increment then we use ++ operator:i++;is just a shortcut for:i = i + 1;But what if we take values for i and j like this:byte i = 1;\nThen i = i + 1;will not compile because we are assigning int value to byte type and there is no typecasting in that statement but i++; will compile fine.It means that in fact i++; is a shortcut for something like thisi = (type of i)(i + 1);Different compiler instructions for both : They are different operators, and use different JVM instructions in bytecode.x + 1 uses iadd instruction, \nwhereas x++ uses iinc instruction internallyAlthough this is compiler dependent. A compiler is free to use a different set of instructions for a particular operation."
},
{
"code": null,
"e": 29159,
"s": 27147,
"text": "Internal Typecasting of data: In the below example, we are doing arithmetic operation i.e. addition on b and 1. Here b is of byte type and 1 is of int type. Therefore, the result should be of int type i.e max(int,type of b i.e. byte,type of 1 i.e. int). We are assigning int type to byte type in the above program that’s why we are getting compile time error saying “possible loss precision”. Here typecasting is required to perform addition.Using x = x + 1// Java program to illustrate// how arithmetic operations performed// depends on data typespublic class Test { public static void main(String[] args) { byte b = 10; // Using b = b+1 b = b + 1; System.out.println(b); /* Using typecasting will work b=(byte)b+1; System.out.println(b);*/ }}Output:error: incompatible types: possible lossy conversion from int to byte\nUsing Typecasting, output will be11Using x++In the next example, we are doing increment but internally we are doing operation like b++. The result should be of int type i.e max(int,type of b i.e. byte,type of 1 i.e. int) and we are getting the result as 11 because implicit typecasting is done by compiler like byte b=(byte)(b+1) here.// Java program to understand the // operations of ++ operatorpublic class Test { public static void main(String[] args) { byte b = 10; b++; System.out.println(b); }}Output:11\nFrom the above example we can understand that in the increment/Decrement operator compiler automatically do type-casting whenever required. But how this happens? Let try to understand:Suppose We have to perform increment then we use ++ operator:i++;is just a shortcut for:i = i + 1;But what if we take values for i and j like this:byte i = 1;\nThen i = i + 1;will not compile because we are assigning int value to byte type and there is no typecasting in that statement but i++; will compile fine.It means that in fact i++; is a shortcut for something like thisi = (type of i)(i + 1);"
},
{
"code": null,
"e": 29175,
"s": 29159,
"text": "Using x = x + 1"
},
{
"code": "// Java program to illustrate// how arithmetic operations performed// depends on data typespublic class Test { public static void main(String[] args) { byte b = 10; // Using b = b+1 b = b + 1; System.out.println(b); /* Using typecasting will work b=(byte)b+1; System.out.println(b);*/ }}",
"e": 29541,
"s": 29175,
"text": null
},
{
"code": null,
"e": 29549,
"s": 29541,
"text": "Output:"
},
{
"code": null,
"e": 29620,
"s": 29549,
"text": "error: incompatible types: possible lossy conversion from int to byte\n"
},
{
"code": null,
"e": 29654,
"s": 29620,
"text": "Using Typecasting, output will be"
},
{
"code": null,
"e": 29657,
"s": 29654,
"text": "11"
},
{
"code": null,
"e": 29667,
"s": 29657,
"text": "Using x++"
},
{
"code": null,
"e": 29959,
"s": 29667,
"text": "In the next example, we are doing increment but internally we are doing operation like b++. The result should be of int type i.e max(int,type of b i.e. byte,type of 1 i.e. int) and we are getting the result as 11 because implicit typecasting is done by compiler like byte b=(byte)(b+1) here."
},
{
"code": "// Java program to understand the // operations of ++ operatorpublic class Test { public static void main(String[] args) { byte b = 10; b++; System.out.println(b); }}",
"e": 30144,
"s": 29959,
"text": null
},
{
"code": null,
"e": 30152,
"s": 30144,
"text": "Output:"
},
{
"code": null,
"e": 30156,
"s": 30152,
"text": "11\n"
},
{
"code": null,
"e": 30402,
"s": 30156,
"text": "From the above example we can understand that in the increment/Decrement operator compiler automatically do type-casting whenever required. But how this happens? Let try to understand:Suppose We have to perform increment then we use ++ operator:"
},
{
"code": null,
"e": 30407,
"s": 30402,
"text": "i++;"
},
{
"code": null,
"e": 30431,
"s": 30407,
"text": "is just a shortcut for:"
},
{
"code": null,
"e": 30442,
"s": 30431,
"text": "i = i + 1;"
},
{
"code": null,
"e": 30492,
"s": 30442,
"text": "But what if we take values for i and j like this:"
},
{
"code": null,
"e": 30520,
"s": 30492,
"text": "byte i = 1;\nThen i = i + 1;"
},
{
"code": null,
"e": 30723,
"s": 30520,
"text": "will not compile because we are assigning int value to byte type and there is no typecasting in that statement but i++; will compile fine.It means that in fact i++; is a shortcut for something like this"
},
{
"code": null,
"e": 30747,
"s": 30723,
"text": "i = (type of i)(i + 1);"
},
{
"code": null,
"e": 31064,
"s": 30747,
"text": "Different compiler instructions for both : They are different operators, and use different JVM instructions in bytecode.x + 1 uses iadd instruction, \nwhereas x++ uses iinc instruction internallyAlthough this is compiler dependent. A compiler is free to use a different set of instructions for a particular operation."
},
{
"code": null,
"e": 31139,
"s": 31064,
"text": "x + 1 uses iadd instruction, \nwhereas x++ uses iinc instruction internally"
},
{
"code": null,
"e": 31262,
"s": 31139,
"text": "Although this is compiler dependent. A compiler is free to use a different set of instructions for a particular operation."
},
{
"code": null,
"e": 31568,
"s": 31262,
"text": "This article is contributed by Bishal Kumar Dubey. 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": 31693,
"s": 31568,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 31705,
"s": 31693,
"text": "java-basics"
},
{
"code": null,
"e": 31717,
"s": 31705,
"text": "java-puzzle"
},
{
"code": null,
"e": 31736,
"s": 31717,
"text": "Difference Between"
},
{
"code": null,
"e": 31741,
"s": 31736,
"text": "Java"
},
{
"code": null,
"e": 31746,
"s": 31741,
"text": "Java"
},
{
"code": null,
"e": 31844,
"s": 31746,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31853,
"s": 31844,
"text": "Comments"
},
{
"code": null,
"e": 31866,
"s": 31853,
"text": "Old Comments"
},
{
"code": null,
"e": 31927,
"s": 31866,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 31959,
"s": 31927,
"text": "Stack vs Heap Memory Allocation"
},
{
"code": null,
"e": 31997,
"s": 31959,
"text": "Difference between Process and Thread"
},
{
"code": null,
"e": 32065,
"s": 31997,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 32118,
"s": 32065,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 32133,
"s": 32118,
"text": "Arrays in Java"
},
{
"code": null,
"e": 32177,
"s": 32133,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 32199,
"s": 32177,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 32235,
"s": 32199,
"text": "Arrays.sort() in Java with examples"
}
] |
Draw a line in C++ graphics - GeeksforGeeks
|
25 Jan, 2018
graphics.h library is used to include and facilitate graphical operations in program. graphics.h functions can be used to draw different shapes, display text in different fonts, change colors and many more. Using functions of graphics.h you can make graphics programs, animations, projects and games. You can draw circles, lines, rectangles, bars and many other geometrical figures. You can change their colors using the available functions and fill them.
Examples:
For line 1, Input : x1 = 150, y1 = 150, x2 = 450, y2 = 150
For line 2, Input : x1 = 150, y1 = 200, x2 = 450, y2 = 200
For line 2, Input : x1 = 150, y1 = 250, x2 = 450, y2 = 250
Output :
Explanation :The header file graphics.h contains line() function which is described below :
Declaration : void line(int x1, int y1, int x2, int y2);
line function is used to draw a line from a point(x1,y1) to point(x2,y2) i.e. (x1,y1) and (x2,y2) are end points of the line.The code given below draws a line.
// C++ Implementation for drawing line#include <graphics.h> // driver codeint main(){ // gm is Graphics mode which is a computer display // mode that generates image using pixels. // DETECT is a macro defined in "graphics.h" header file int gd = DETECT, gm; // initgraph initializes the graphics system // by loading a graphics driver from disk initgraph(&gd, &gm, ""); // line for x1, y1, x2, y2 line(150, 150, 450, 150); // line for x1, y1, x2, y2 line(150, 200, 450, 200); // line for x1, y1, x2, y2 line(150, 250, 450, 250); getch(); // closegraph function closes the graphics // mode and deallocates all memory allocated // by graphics system . closegraph();}
Output:
computer-graphics
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Operator Overloading in C++
Socket Programming in C/C++
Bitwise Operators in C/C++
Virtual Function in C++
Constructors in C++
Templates in C++ with Examples
Object Oriented Programming in C++
|
[
{
"code": null,
"e": 24556,
"s": 24528,
"text": "\n25 Jan, 2018"
},
{
"code": null,
"e": 25012,
"s": 24556,
"text": "graphics.h library is used to include and facilitate graphical operations in program. graphics.h functions can be used to draw different shapes, display text in different fonts, change colors and many more. Using functions of graphics.h you can make graphics programs, animations, projects and games. You can draw circles, lines, rectangles, bars and many other geometrical figures. You can change their colors using the available functions and fill them."
},
{
"code": null,
"e": 25022,
"s": 25012,
"text": "Examples:"
},
{
"code": null,
"e": 25211,
"s": 25022,
"text": "For line 1, Input : x1 = 150, y1 = 150, x2 = 450, y2 = 150\nFor line 2, Input : x1 = 150, y1 = 200, x2 = 450, y2 = 200\nFor line 2, Input : x1 = 150, y1 = 250, x2 = 450, y2 = 250\nOutput :\n\n\n"
},
{
"code": null,
"e": 25303,
"s": 25211,
"text": "Explanation :The header file graphics.h contains line() function which is described below :"
},
{
"code": null,
"e": 25360,
"s": 25303,
"text": "Declaration : void line(int x1, int y1, int x2, int y2);"
},
{
"code": null,
"e": 25520,
"s": 25360,
"text": "line function is used to draw a line from a point(x1,y1) to point(x2,y2) i.e. (x1,y1) and (x2,y2) are end points of the line.The code given below draws a line."
},
{
"code": "// C++ Implementation for drawing line#include <graphics.h> // driver codeint main(){ // gm is Graphics mode which is a computer display // mode that generates image using pixels. // DETECT is a macro defined in \"graphics.h\" header file int gd = DETECT, gm; // initgraph initializes the graphics system // by loading a graphics driver from disk initgraph(&gd, &gm, \"\"); // line for x1, y1, x2, y2 line(150, 150, 450, 150); // line for x1, y1, x2, y2 line(150, 200, 450, 200); // line for x1, y1, x2, y2 line(150, 250, 450, 250); getch(); // closegraph function closes the graphics // mode and deallocates all memory allocated // by graphics system . closegraph();}",
"e": 26252,
"s": 25520,
"text": null
},
{
"code": null,
"e": 26260,
"s": 26252,
"text": "Output:"
},
{
"code": null,
"e": 26280,
"s": 26262,
"text": "computer-graphics"
},
{
"code": null,
"e": 26284,
"s": 26280,
"text": "C++"
},
{
"code": null,
"e": 26288,
"s": 26284,
"text": "CPP"
},
{
"code": null,
"e": 26386,
"s": 26288,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26395,
"s": 26386,
"text": "Comments"
},
{
"code": null,
"e": 26408,
"s": 26395,
"text": "Old Comments"
},
{
"code": null,
"e": 26427,
"s": 26408,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 26470,
"s": 26427,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26494,
"s": 26470,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 26522,
"s": 26494,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26550,
"s": 26522,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 26577,
"s": 26550,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 26601,
"s": 26577,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 26621,
"s": 26601,
"text": "Constructors in C++"
},
{
"code": null,
"e": 26652,
"s": 26621,
"text": "Templates in C++ with Examples"
}
] |
How to show numpy 2D array as grayscale image in Jupyter Notebook?
|
To show a 2D array as a grayscale image in Jupyter Notebook, we can take the following steps
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create a random data using numpy.
Create a random data using numpy.
Display the data as an image, i.e., on a 2D regular raster, with gray colormap.
Display the data as an image, i.e., on a 2D regular raster, with gray colormap.
To display the figure, use Show() method.
To display the figure, use Show() method.
from matplotlib import pyplot as plt
import numpy as np
# Set the figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
# Random data points
data = np.random.rand(5, 5)
# Plot the data using imshow with gray colormap
plt.imshow(data, cmap='gray')
# Display the plot
plt.show()
It will produce the following output −
|
[
{
"code": null,
"e": 1155,
"s": 1062,
"text": "To show a 2D array as a grayscale image in Jupyter Notebook, we can take the following steps"
},
{
"code": null,
"e": 1231,
"s": 1155,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1307,
"s": 1231,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1341,
"s": 1307,
"text": "Create a random data using numpy."
},
{
"code": null,
"e": 1375,
"s": 1341,
"text": "Create a random data using numpy."
},
{
"code": null,
"e": 1455,
"s": 1375,
"text": "Display the data as an image, i.e., on a 2D regular raster, with gray colormap."
},
{
"code": null,
"e": 1535,
"s": 1455,
"text": "Display the data as an image, i.e., on a 2D regular raster, with gray colormap."
},
{
"code": null,
"e": 1577,
"s": 1535,
"text": "To display the figure, use Show() method."
},
{
"code": null,
"e": 1619,
"s": 1577,
"text": "To display the figure, use Show() method."
},
{
"code": null,
"e": 1945,
"s": 1619,
"text": "from matplotlib import pyplot as plt\nimport numpy as np\n\n# Set the figure size\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\n# Random data points\ndata = np.random.rand(5, 5)\n\n# Plot the data using imshow with gray colormap\nplt.imshow(data, cmap='gray')\n\n# Display the plot\nplt.show()"
},
{
"code": null,
"e": 1984,
"s": 1945,
"text": "It will produce the following output −"
}
] |
How Attractive Are You in the Eyes of Deep Neural Network? | by Dima Shulga | Towards Data Science
|
A couple of months ago, South China University published a paper and a dataset about “Facial Beauty Prediction”. You can find it here. The data set includes 5500 people that have a score of 1 through 5 of how attractive they are. Here are some examples from the paper:
There are also several famous people in the set. This Julia Robert’s photo got an average score of 3.78:
This photo of a famous Israeli model Bar Refaeli got a score of 3.7:
These may look like low scores, but a score of 3.7 means that bar is more attractive than ~80% of the people in the dataset.
Along with the dataset, the authors trained multiple models that trying to predict attractiveness of a person based on the picture of the face.
In this post, I want to reproduce their result and check how attractive am I.
The original paper implemented a bunch of different models, including classic ML models with handcrafted features and 3 deep learning models: AlexNet, ResNet18, and ResNext50.I want to keep my work as simple as possible (I don’t want to implement and train the whole resnet network from scratch), I want to fine tune some existing model that will do the job. In keras, there’s a module called applications, which is a collection of different pre-trained models. One of them is resnet50. Unfortunately, there’s no ResNet18 or ResNext50 in keras.applications so I won’t be able to reproduce exactly the same work, but I should be close enough with resnet50.
from keras.applications import ResNet50
ResNet is a Deep Convolutional network that was developed by Microsoft and won the 2015 ImageNet competition, which is an image classification task.When we initiate the resnet50 model in keras, we create a model with the ResNet50 architecture and also we download the trained weights as were trained on the ImageNet dataset.
The authors of the paper didn’t mention how exactly they trained the models, so I’ll try to do my best.I want to remove the last layer (the “softmax” layer) and add a Dense layer with no activation function to perform regression.
resnet = ResNet50(include_top=False, pooling=’avg’)model = Sequential()model.add(resnet)model.add(Dense(1))model.layers[0].trainable = Falseprint model.summary()# Output: Layer (type) Output Shape Param # ================================================================= resnet50 (Model) (None, 2048) 23587712 _________________________________________________________________ dense_1 (Dense) (None, 1) 2049 ================================================================= Total params: 23,589,761 Trainable params: 23,536,641 Non-trainable params: 53,120
You can see that I made the first layer (the resnet model) non-trainable, so I have only 2,049 trainable params instead of 23,589,761.
My plan is to train the final Dense layer, and then, train the whole network with a smaller learning rate.
model.compile(loss='mean_squared_error', optimizer=Adam())model.fit(batch_size=32, x=train_X, y=train_Y, epochs=30)
After that, I change the first layer to trainable, compile and fit the model for another 30 epochs.
Here train_X are the photos, i.e,numpy arrays of shape (350, 350, 3), and train_Y are the scores of the images as were tagged.
The paper trained the models using 2 techniques: 5-fold cross validation, and a 60%-40% train test split. They measured their results using Pearson Correlation (PC), Mean Absolute Error (MAE), and Root Mean Square Error (RMSE). These are the results they got using the 5-fold cross validation:
And these are the results they got using the 60%-40% train-test split:
I‘ll’ do a 80%-20% train-test split, so it is similar to perform 1 fold of their cross validation part.
I got the following results:
RMSE: 0.301799791952313 MAE: 0.2333630505619627 PC: 0.9012570266136678
Pretty good. Also, it is always nice to look at the scatter plot and the histograms of the scores:
Original scores distribution (normalized):
Predicted scores distribution (normalized):
The results look pretty good. Now let’s see what this Deep Neural Network says about me. I used this photo at first:
I got 2.85, which means that I’m more attractive than 52% of people in this dataset. I have to say that I’m bit disappointed, I hoped that I’ll be better than that. So I tried to improve my situation.
I took a lot of photos and eventually with this one I got a score of 3.15, which means that I’m more attractive than 64% of the people in the dataset.
This is much better, I have to be honest and say that I hoped for better :)
One final note, I built and fine-tuned this model using the Google Colaboratory, in short, it gives you a python notebook that uses a GPU for free!
Hope you enjoyed the post.
|
[
{
"code": null,
"e": 316,
"s": 47,
"text": "A couple of months ago, South China University published a paper and a dataset about “Facial Beauty Prediction”. You can find it here. The data set includes 5500 people that have a score of 1 through 5 of how attractive they are. Here are some examples from the paper:"
},
{
"code": null,
"e": 421,
"s": 316,
"text": "There are also several famous people in the set. This Julia Robert’s photo got an average score of 3.78:"
},
{
"code": null,
"e": 490,
"s": 421,
"text": "This photo of a famous Israeli model Bar Refaeli got a score of 3.7:"
},
{
"code": null,
"e": 615,
"s": 490,
"text": "These may look like low scores, but a score of 3.7 means that bar is more attractive than ~80% of the people in the dataset."
},
{
"code": null,
"e": 759,
"s": 615,
"text": "Along with the dataset, the authors trained multiple models that trying to predict attractiveness of a person based on the picture of the face."
},
{
"code": null,
"e": 837,
"s": 759,
"text": "In this post, I want to reproduce their result and check how attractive am I."
},
{
"code": null,
"e": 1493,
"s": 837,
"text": "The original paper implemented a bunch of different models, including classic ML models with handcrafted features and 3 deep learning models: AlexNet, ResNet18, and ResNext50.I want to keep my work as simple as possible (I don’t want to implement and train the whole resnet network from scratch), I want to fine tune some existing model that will do the job. In keras, there’s a module called applications, which is a collection of different pre-trained models. One of them is resnet50. Unfortunately, there’s no ResNet18 or ResNext50 in keras.applications so I won’t be able to reproduce exactly the same work, but I should be close enough with resnet50."
},
{
"code": null,
"e": 1533,
"s": 1493,
"text": "from keras.applications import ResNet50"
},
{
"code": null,
"e": 1858,
"s": 1533,
"text": "ResNet is a Deep Convolutional network that was developed by Microsoft and won the 2015 ImageNet competition, which is an image classification task.When we initiate the resnet50 model in keras, we create a model with the ResNet50 architecture and also we download the trained weights as were trained on the ImageNet dataset."
},
{
"code": null,
"e": 2088,
"s": 1858,
"text": "The authors of the paper didn’t mention how exactly they trained the models, so I’ll try to do my best.I want to remove the last layer (the “softmax” layer) and add a Dense layer with no activation function to perform regression."
},
{
"code": null,
"e": 2739,
"s": 2088,
"text": "resnet = ResNet50(include_top=False, pooling=’avg’)model = Sequential()model.add(resnet)model.add(Dense(1))model.layers[0].trainable = Falseprint model.summary()# Output: Layer (type) Output Shape Param # ================================================================= resnet50 (Model) (None, 2048) 23587712 _________________________________________________________________ dense_1 (Dense) (None, 1) 2049 ================================================================= Total params: 23,589,761 Trainable params: 23,536,641 Non-trainable params: 53,120"
},
{
"code": null,
"e": 2874,
"s": 2739,
"text": "You can see that I made the first layer (the resnet model) non-trainable, so I have only 2,049 trainable params instead of 23,589,761."
},
{
"code": null,
"e": 2981,
"s": 2874,
"text": "My plan is to train the final Dense layer, and then, train the whole network with a smaller learning rate."
},
{
"code": null,
"e": 3097,
"s": 2981,
"text": "model.compile(loss='mean_squared_error', optimizer=Adam())model.fit(batch_size=32, x=train_X, y=train_Y, epochs=30)"
},
{
"code": null,
"e": 3197,
"s": 3097,
"text": "After that, I change the first layer to trainable, compile and fit the model for another 30 epochs."
},
{
"code": null,
"e": 3324,
"s": 3197,
"text": "Here train_X are the photos, i.e,numpy arrays of shape (350, 350, 3), and train_Y are the scores of the images as were tagged."
},
{
"code": null,
"e": 3618,
"s": 3324,
"text": "The paper trained the models using 2 techniques: 5-fold cross validation, and a 60%-40% train test split. They measured their results using Pearson Correlation (PC), Mean Absolute Error (MAE), and Root Mean Square Error (RMSE). These are the results they got using the 5-fold cross validation:"
},
{
"code": null,
"e": 3689,
"s": 3618,
"text": "And these are the results they got using the 60%-40% train-test split:"
},
{
"code": null,
"e": 3793,
"s": 3689,
"text": "I‘ll’ do a 80%-20% train-test split, so it is similar to perform 1 fold of their cross validation part."
},
{
"code": null,
"e": 3822,
"s": 3793,
"text": "I got the following results:"
},
{
"code": null,
"e": 3893,
"s": 3822,
"text": "RMSE: 0.301799791952313 MAE: 0.2333630505619627 PC: 0.9012570266136678"
},
{
"code": null,
"e": 3992,
"s": 3893,
"text": "Pretty good. Also, it is always nice to look at the scatter plot and the histograms of the scores:"
},
{
"code": null,
"e": 4035,
"s": 3992,
"text": "Original scores distribution (normalized):"
},
{
"code": null,
"e": 4079,
"s": 4035,
"text": "Predicted scores distribution (normalized):"
},
{
"code": null,
"e": 4196,
"s": 4079,
"text": "The results look pretty good. Now let’s see what this Deep Neural Network says about me. I used this photo at first:"
},
{
"code": null,
"e": 4397,
"s": 4196,
"text": "I got 2.85, which means that I’m more attractive than 52% of people in this dataset. I have to say that I’m bit disappointed, I hoped that I’ll be better than that. So I tried to improve my situation."
},
{
"code": null,
"e": 4548,
"s": 4397,
"text": "I took a lot of photos and eventually with this one I got a score of 3.15, which means that I’m more attractive than 64% of the people in the dataset."
},
{
"code": null,
"e": 4624,
"s": 4548,
"text": "This is much better, I have to be honest and say that I hoped for better :)"
},
{
"code": null,
"e": 4772,
"s": 4624,
"text": "One final note, I built and fine-tuned this model using the Google Colaboratory, in short, it gives you a python notebook that uses a GPU for free!"
}
] |
3D Streamtube Plots using Plotly in Python - GeeksforGeeks
|
05 Sep, 2020
Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
In plotly, the streamtube plot, parameter includes X, Y, and Z, which set the coordinates with vector fields. U, V, and W which set X, Y, and Z component of vector fields. A streamtube is a tubular region surrounded by streamlines that form a closed loop.
Syntax: plotly.graph_objects.Streamtube(arg=None, hoverinfo=None, showscale=None, u=None, v=None, w=None, x=None, y=None, z=None, **kwargs)
Parameters:
arg: dict of properties compatible with this constructor or an instance of plotly.graph_objects.Streamtube
hoverinfo: Determines which trace information appear on hover. If none or skip are set, no information is displayed upon hovering. But, if none is set, click and hover events are still fired.
showscale: Determines whether or not a colorbar is displayed for this trace.
u: Sets the x components of the vector field.
v: Sets the y components of the vector field.
w: Sets the z components of the vector field.
x: Sets the x coordinates of the vector field.
y: Sets the y coordinates of the vector field.
z: Sets the z coordinates of the vector field.
Example:
Python3
import plotly.graph_objects as go fig = go.Figure(data=go.Streamtube(x=[1, 1, 1], y=[1, 1, 2], z=[0, 0, 0], u=[0, 0, 0], v=[1, 1, 1], w=[0, 0, 0]))fig.show()
Output:
The diameter of tubes can be determined by local divergence of the vector field. The norms are proportionate but the direction of the vector is different and it result in different divergence field.
Example:
Python3
import plotly.graph_objects as goimport numpy as np x, y, z = np.mgrid[0:20, 0:20, 0:20]x = x.flatten()y = y.flatten()z = z.flatten() u = np.zeros_like(x)v = np.zeros_like(y)w = z**2 fig = go.Figure(data=go.Streamtube(x=x, y=y, z=z, u=u, v=v, w=w))fig.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
|
[
{
"code": null,
"e": 24242,
"s": 24214,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 24544,
"s": 24242,
"text": "Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library."
},
{
"code": null,
"e": 24800,
"s": 24544,
"text": "In plotly, the streamtube plot, parameter includes X, Y, and Z, which set the coordinates with vector fields. U, V, and W which set X, Y, and Z component of vector fields. A streamtube is a tubular region surrounded by streamlines that form a closed loop."
},
{
"code": null,
"e": 24940,
"s": 24800,
"text": "Syntax: plotly.graph_objects.Streamtube(arg=None, hoverinfo=None, showscale=None, u=None, v=None, w=None, x=None, y=None, z=None, **kwargs)"
},
{
"code": null,
"e": 24952,
"s": 24940,
"text": "Parameters:"
},
{
"code": null,
"e": 25059,
"s": 24952,
"text": "arg: dict of properties compatible with this constructor or an instance of plotly.graph_objects.Streamtube"
},
{
"code": null,
"e": 25251,
"s": 25059,
"text": "hoverinfo: Determines which trace information appear on hover. If none or skip are set, no information is displayed upon hovering. But, if none is set, click and hover events are still fired."
},
{
"code": null,
"e": 25328,
"s": 25251,
"text": "showscale: Determines whether or not a colorbar is displayed for this trace."
},
{
"code": null,
"e": 25374,
"s": 25328,
"text": "u: Sets the x components of the vector field."
},
{
"code": null,
"e": 25420,
"s": 25374,
"text": "v: Sets the y components of the vector field."
},
{
"code": null,
"e": 25466,
"s": 25420,
"text": "w: Sets the z components of the vector field."
},
{
"code": null,
"e": 25513,
"s": 25466,
"text": "x: Sets the x coordinates of the vector field."
},
{
"code": null,
"e": 25560,
"s": 25513,
"text": "y: Sets the y coordinates of the vector field."
},
{
"code": null,
"e": 25607,
"s": 25560,
"text": "z: Sets the z coordinates of the vector field."
},
{
"code": null,
"e": 25616,
"s": 25607,
"text": "Example:"
},
{
"code": null,
"e": 25624,
"s": 25616,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as go fig = go.Figure(data=go.Streamtube(x=[1, 1, 1], y=[1, 1, 2], z=[0, 0, 0], u=[0, 0, 0], v=[1, 1, 1], w=[0, 0, 0]))fig.show()",
"e": 25852,
"s": 25624,
"text": null
},
{
"code": null,
"e": 25860,
"s": 25852,
"text": "Output:"
},
{
"code": null,
"e": 26059,
"s": 25860,
"text": "The diameter of tubes can be determined by local divergence of the vector field. The norms are proportionate but the direction of the vector is different and it result in different divergence field."
},
{
"code": null,
"e": 26068,
"s": 26059,
"text": "Example:"
},
{
"code": null,
"e": 26076,
"s": 26068,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as goimport numpy as np x, y, z = np.mgrid[0:20, 0:20, 0:20]x = x.flatten()y = y.flatten()z = z.flatten() u = np.zeros_like(x)v = np.zeros_like(y)w = z**2 fig = go.Figure(data=go.Streamtube(x=x, y=y, z=z, u=u, v=v, w=w))fig.show()",
"e": 26338,
"s": 26076,
"text": null
},
{
"code": null,
"e": 26346,
"s": 26338,
"text": "Output:"
},
{
"code": null,
"e": 26360,
"s": 26346,
"text": "Python-Plotly"
},
{
"code": null,
"e": 26367,
"s": 26360,
"text": "Python"
},
{
"code": null,
"e": 26465,
"s": 26367,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26500,
"s": 26465,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26522,
"s": 26500,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26554,
"s": 26522,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26584,
"s": 26554,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26626,
"s": 26584,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26652,
"s": 26626,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26689,
"s": 26652,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26732,
"s": 26689,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26776,
"s": 26732,
"text": "Reading and Writing to text files in Python"
}
] |
How to get the values of an object in JavaScript?
|
There are some methods such as Object.values() to get the values of an object. But through those methods, the process to find out the values is lengthy. To alleviate this, Underscore.js a library of javascript has provided a method called _.values(). This method requires no for loop to execute the values. It is a direct method to execute the values of an object.
In the following example, the values of an object were executed using the Object.values() method. This method requires a for-loop to execute the values.
Live Demo
<html>
<body>
<script>
var user = {
name: "Rahim",
designation: "content developer"
};
for (let value of Object.values(user)) {
document.write(value + "</br>");
}
</script>
</body>
</html>
Rahim
content developer
In the following example, the values of an object were executed using _.values() method. Here no for-loop is required. It's a straight forward method.
Live Demo
<html>
<body>
<script
src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
</head>
<body>
<script>
var res = JSON.stringify(_.values({"name": 'ElonMusk',age: 47, "Organization":'Spacex' }));
document.write((res));
</script>
</body>
</html>
["ElonMusk",47,"Spacex"]
|
[
{
"code": null,
"e": 1428,
"s": 1062,
"text": "There are some methods such as Object.values() to get the values of an object. But through those methods, the process to find out the values is lengthy. To alleviate this, Underscore.js a library of javascript has provided a method called _.values(). This method requires no for loop to execute the values. It is a direct method to execute the values of an object. "
},
{
"code": null,
"e": 1581,
"s": 1428,
"text": "In the following example, the values of an object were executed using the Object.values() method. This method requires a for-loop to execute the values."
},
{
"code": null,
"e": 1591,
"s": 1581,
"text": "Live Demo"
},
{
"code": null,
"e": 1810,
"s": 1591,
"text": "<html>\n<body>\n<script>\n var user = {\n name: \"Rahim\",\n designation: \"content developer\"\n };\n for (let value of Object.values(user)) {\n document.write(value + \"</br>\");\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 1834,
"s": 1810,
"text": "Rahim\ncontent developer"
},
{
"code": null,
"e": 1985,
"s": 1834,
"text": "In the following example, the values of an object were executed using _.values() method. Here no for-loop is required. It's a straight forward method."
},
{
"code": null,
"e": 1995,
"s": 1985,
"text": "Live Demo"
},
{
"code": null,
"e": 2280,
"s": 1995,
"text": "<html>\n<body>\n<script\nsrc=\"//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js\"></script>\n</head>\n<body>\n <script>\n var res = JSON.stringify(_.values({\"name\": 'ElonMusk',age: 47, \"Organization\":'Spacex' }));\n document.write((res));\n </script>\n</body>\n</html>"
},
{
"code": null,
"e": 2305,
"s": 2280,
"text": "[\"ElonMusk\",47,\"Spacex\"]"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.