title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
D Programming - File I/O
Files are represented by the File struct of the std.stdio module. A file represents a sequence of bytes, does not matter if it is a text file or binary file. D programming language provides access on high level functions as well as low level (OS level) calls to handle file on your storage devices. The standard input and output streams stdin and stdout are already open when programs start running. They are ready to be used. On the other hand, files must first be opened by specifying the name of the file and the access rights that are needed. File file = File(filepath, "mode"); Here, filename is string literal, which you use to name the file and access mode can have one of the following values − r Opens an existing text file for reading purpose. w Opens a text file for writing, if it does not exist then a new file is created. Here your program will start writing content from the beginning of the file. a Opens a text file for writing in appending mode, if it does not exist then a new file is created. Here your program will start appending content in the existing file content. r+ Opens a text file for reading and writing both. w+ Opens a text file for reading and writing both. It first truncate the file to zero length if it exists otherwise create the file if it does not exist. a+ Opens a text file for reading and writing both. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended. To close a file, use the file.close() function where file holds the file reference. The prototype of this function is − file.close(); Any file that has been opened by a program must be closed when the program finishes using that file. In most cases the files need not be closed explicitly; they are closed automatically when File objects are terminated. file.writeln is used to write to an open file. file.writeln("hello"); import std.stdio; import std.file; void main() { File file = File("test.txt", "w"); file.writeln("hello"); file.close(); } When the above code is compiled and executed, it creates a new file test.txt in the directory that it has been started under (in the program working directory). The following method reads a single line from a file − string s = file.readln(); A complete example of read and write is shown below. import std.stdio; import std.file; void main() { File file = File("test.txt", "w"); file.writeln("hello"); file.close(); file = File("test.txt", "r"); string s = file.readln(); writeln(s); file.close(); } When the above code is compiled and executed, it reads the file created in previous section and produces the following result − hello Here is another example for reading file till end of file. import std.stdio; import std.string; void main() { File file = File("test.txt", "w"); file.writeln("hello"); file.writeln("world"); file.close(); file = File("test.txt", "r"); while (!file.eof()) { string line = chomp(file.readln()); writeln("line -", line); } } When the above code is compiled and executed, it reads the file created in previous section and produces the following result − line -hello line -world line - You can see in the above example an empty third line since writeln takes it to next line once it is executed. 10 Lectures 1.5 hours Nishant Malik 42 Lectures 1.5 hours Ravi Kiran 46 Lectures 7.5 hours Aditya Dua 32 Lectures 3.5 hours Sharad Kumar 14 Lectures 1 hours Mahesh Kumar 18 Lectures 49 mins Rushi Panchal Print Add Notes Bookmark this page
[ { "code": null, "e": 2762, "s": 2604, "text": "Files are represented by the File struct of the std.stdio module. A file represents a sequence of bytes, does not matter if it is a text file or binary file." }, { "code": null, "e": 2903, "s": 2762, "text": "D programming language provides access on high level functions as well as low level (OS level) calls to handle file on your storage devices." }, { "code": null, "e": 3151, "s": 2903, "text": "The standard input and output streams stdin and stdout are already open when programs start running. They are ready to be used. On the other hand, files must first be opened by specifying the name of the file and the access rights that are needed." }, { "code": null, "e": 3188, "s": 3151, "text": "File file = File(filepath, \"mode\");\n" }, { "code": null, "e": 3308, "s": 3188, "text": "Here, filename is string literal, which you use to name the file and access mode can have one of the following values −" }, { "code": null, "e": 3310, "s": 3308, "text": "r" }, { "code": null, "e": 3359, "s": 3310, "text": "Opens an existing text file for reading purpose." }, { "code": null, "e": 3361, "s": 3359, "text": "w" }, { "code": null, "e": 3518, "s": 3361, "text": "Opens a text file for writing, if it does not exist then a new file is created. Here your program will start writing content from the beginning of the file." }, { "code": null, "e": 3520, "s": 3518, "text": "a" }, { "code": null, "e": 3695, "s": 3520, "text": "Opens a text file for writing in appending mode, if it does not exist then a new file is created. Here your program will start appending content in the existing file content." }, { "code": null, "e": 3698, "s": 3695, "text": "r+" }, { "code": null, "e": 3746, "s": 3698, "text": "Opens a text file for reading and writing both." }, { "code": null, "e": 3749, "s": 3746, "text": "w+" }, { "code": null, "e": 3900, "s": 3749, "text": "Opens a text file for reading and writing both. It first truncate the file to zero length if it exists otherwise create the file if it does not exist." }, { "code": null, "e": 3903, "s": 3900, "text": "a+" }, { "code": null, "e": 4069, "s": 3903, "text": "Opens a text file for reading and writing both. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended." }, { "code": null, "e": 4189, "s": 4069, "text": "To close a file, use the file.close() function where file holds the file reference. The prototype of this function is −" }, { "code": null, "e": 4204, "s": 4189, "text": "file.close();\n" }, { "code": null, "e": 4424, "s": 4204, "text": "Any file that has been opened by a program must be closed when the program finishes using that file. In most cases the files need not be closed explicitly; they are closed automatically when File objects are terminated." }, { "code": null, "e": 4471, "s": 4424, "text": "file.writeln is used to write to an open file." }, { "code": null, "e": 4496, "s": 4471, "text": "file.writeln(\"hello\"); \n" }, { "code": null, "e": 4635, "s": 4496, "text": "import std.stdio; \nimport std.file;\n \nvoid main() { \n File file = File(\"test.txt\", \"w\"); \n file.writeln(\"hello\");\n file.close(); \n}" }, { "code": null, "e": 4796, "s": 4635, "text": "When the above code is compiled and executed, it creates a new file test.txt in the directory that it has been started under (in the program working directory)." }, { "code": null, "e": 4851, "s": 4796, "text": "The following method reads a single line from a file −" }, { "code": null, "e": 4878, "s": 4851, "text": "string s = file.readln();\n" }, { "code": null, "e": 4931, "s": 4878, "text": "A complete example of read and write is shown below." }, { "code": null, "e": 5177, "s": 4931, "text": "import std.stdio; \nimport std.file; \n \nvoid main() { \n File file = File(\"test.txt\", \"w\");\n file.writeln(\"hello\"); \n file.close(); \n file = File(\"test.txt\", \"r\"); \n \n string s = file.readln(); \n writeln(s);\n \n file.close(); \n} " }, { "code": null, "e": 5305, "s": 5177, "text": "When the above code is compiled and executed, it reads the file created in previous section and produces the following result −" }, { "code": null, "e": 5312, "s": 5305, "text": "hello\n" }, { "code": null, "e": 5371, "s": 5312, "text": "Here is another example for reading file till end of file." }, { "code": null, "e": 5686, "s": 5371, "text": "import std.stdio;\nimport std.string;\n\nvoid main() { \n File file = File(\"test.txt\", \"w\"); \n file.writeln(\"hello\"); \n file.writeln(\"world\"); \n file.close(); \n file = File(\"test.txt\", \"r\"); \n \n while (!file.eof()) { \n string line = chomp(file.readln()); \n writeln(\"line -\", line); \n }\n} " }, { "code": null, "e": 5814, "s": 5686, "text": "When the above code is compiled and executed, it reads the file created in previous section and produces the following result −" }, { "code": null, "e": 5848, "s": 5814, "text": "line -hello \nline -world \nline -\n" }, { "code": null, "e": 5958, "s": 5848, "text": "You can see in the above example an empty third line since writeln takes it to next line once it is executed." }, { "code": null, "e": 5993, "s": 5958, "text": "\n 10 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6008, "s": 5993, "text": " Nishant Malik" }, { "code": null, "e": 6043, "s": 6008, "text": "\n 42 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6055, "s": 6043, "text": " Ravi Kiran" }, { "code": null, "e": 6090, "s": 6055, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6102, "s": 6090, "text": " Aditya Dua" }, { "code": null, "e": 6137, "s": 6102, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6151, "s": 6137, "text": " Sharad Kumar" }, { "code": null, "e": 6184, "s": 6151, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 6198, "s": 6184, "text": " Mahesh Kumar" }, { "code": null, "e": 6230, "s": 6198, "text": "\n 18 Lectures \n 49 mins\n" }, { "code": null, "e": 6245, "s": 6230, "text": " Rushi Panchal" }, { "code": null, "e": 6252, "s": 6245, "text": " Print" }, { "code": null, "e": 6263, "s": 6252, "text": " Add Notes" } ]
How to do Web API versioning with URI in C# ASP.NET WebAPI?
Once a Web API service is made public, different client applications start using our Web API services. As the business grows and requirements change, we may have to change the services as well, but the changes to the services should be done in way that does not break any existing client applications. This is when Web API versioning helps. We keep the existing services as is, so we are not breaking the existing client applications, and develop a new version of the service that new client applications can start using. One of the option to implement versioning is by using URI. Below is an example on how to implement the same. Let us consider a version 1 (V1) of sudent controller which has the following action methods. Student Model V1 − namespace DemoWebApplication.Models{ public class StudentV1{ public int Id { get; set; } public string Name { get; set; } } } Student Controller V1 − using DemoWebApplication.Models; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace DemoWebApplication.Controllers{ public class StudentV1Controller : ApiController{ List<StudentV1> students = new List<StudentV1>{ new StudentV1{ Id = 1, Name = "Mark" }, new StudentV1{ Id = 2, Name = "John" } }; [Route("api/v1/students")] public IEnumerable<StudentV1> Get(){ return students; } [Route("api/v1/students/{id}")] public StudentV1 Get(int id){ var studentForId = students.FirstOrDefault(x => x.Id == id); return studentForId; } } } In the above example we have used Attribute Routing to implement the versioning. The output of the above example is shown below − Now let us say in the student controller, business has proposed a new change only for the new users and the existing users should still use the Version 1. So in this case we have to introduce Version 2 (V2). Student Model V2 − namespace DemoWebApplication.Models{ public class StudentV2{ public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } } Student Controller V2 − using DemoWebApplication.Models; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace DemoWebApplication.Controllers{ public class StudentV2Controller : ApiController{ List<StudentV2> students = new List<StudentV2>{ new StudentV2{ Id = 1, FirstName = "Roger", LastName = "Federer" }, new StudentV2{ Id = 2, FirstName = "Tom", LastName = "Bruce" } }; [Route("api/v2/students")] public IEnumerable<StudentV2> Get(){ return students; } [Route("api/v2/students/{id}")] public StudentV2 Get(int id){ var studentForId = students.FirstOrDefault(x => x.Id == id); return studentForId; } } } The output of the above example is shown below.
[ { "code": null, "e": 1364, "s": 1062, "text": "Once a Web API service is made public, different client applications start using our\nWeb API services. As the business grows and requirements change, we may have to\nchange the services as well, but the changes to the services should be done in way\nthat does not break any existing client applications." }, { "code": null, "e": 1584, "s": 1364, "text": "This is when Web API versioning helps. We keep the existing services as is, so we\nare not breaking the existing client applications, and develop a new version of the\nservice that new client applications can start using." }, { "code": null, "e": 1693, "s": 1584, "text": "One of the option to implement versioning is by using URI. Below is an example on\nhow to implement the same." }, { "code": null, "e": 1787, "s": 1693, "text": "Let us consider a version 1 (V1) of sudent controller which has the following action\nmethods." }, { "code": null, "e": 1806, "s": 1787, "text": "Student Model V1 −" }, { "code": null, "e": 1950, "s": 1806, "text": "namespace DemoWebApplication.Models{\n public class StudentV1{\n public int Id { get; set; }\n public string Name { get; set; }\n }\n}" }, { "code": null, "e": 1974, "s": 1950, "text": "Student Controller V1 −" }, { "code": null, "e": 2703, "s": 1974, "text": "using DemoWebApplication.Models;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Http;\nnamespace DemoWebApplication.Controllers{\n public class StudentV1Controller : ApiController{\n List<StudentV1> students = new List<StudentV1>{\n new StudentV1{\n Id = 1,\n Name = \"Mark\"\n },\n new StudentV1{\n Id = 2,\n Name = \"John\"\n }\n };\n [Route(\"api/v1/students\")]\n public IEnumerable<StudentV1> Get(){\n return students;\n }\n [Route(\"api/v1/students/{id}\")]\n public StudentV1 Get(int id){\n var studentForId = students.FirstOrDefault(x => x.Id == id);\n return studentForId;\n }\n }\n}" }, { "code": null, "e": 2833, "s": 2703, "text": "In the above example we have used Attribute Routing to implement the versioning.\nThe output of the above example is shown below −" }, { "code": null, "e": 3041, "s": 2833, "text": "Now let us say in the student controller, business has proposed a new change only for\nthe new users and the existing users should still use the Version 1. So in this case we\nhave to introduce Version 2 (V2)." }, { "code": null, "e": 3060, "s": 3041, "text": "Student Model V2 −" }, { "code": null, "e": 3252, "s": 3060, "text": "namespace DemoWebApplication.Models{\n public class StudentV2{\n public int Id { get; set; }\n public string FirstName { get; set; }\n public string LastName { get; set; }\n }\n}" }, { "code": null, "e": 3276, "s": 3252, "text": "Student Controller V2 −" }, { "code": null, "e": 4081, "s": 3276, "text": "using DemoWebApplication.Models;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Http;\nnamespace DemoWebApplication.Controllers{\n public class StudentV2Controller : ApiController{\n List<StudentV2> students = new List<StudentV2>{\n new StudentV2{\n Id = 1,\n FirstName = \"Roger\",\n LastName = \"Federer\"\n },\n new StudentV2{\n Id = 2,\n FirstName = \"Tom\",\n LastName = \"Bruce\"\n }\n };\n [Route(\"api/v2/students\")]\n public IEnumerable<StudentV2> Get(){\n return students;\n }\n [Route(\"api/v2/students/{id}\")]\n public StudentV2 Get(int id){\n var studentForId = students.FirstOrDefault(x => x.Id == id);\n return studentForId;\n }\n }\n}" }, { "code": null, "e": 4129, "s": 4081, "text": "The output of the above example is shown below." } ]
PostgreSQL - PRIVILEGES
Whenever an object is created in a database, an owner is assigned to it. The owner is usually the one who executed the creation statement. For most kinds of objects, the initial state is that only the owner (or a superuser) can modify or delete the object. To allow other roles or users to use it, privileges or permission must be granted. Different kinds of privileges in PostgreSQL are − SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER, CREATE, CONNECT, TEMPORARY, EXECUTE, and USAGE Depending on the type of the object (table, function, etc.,), privileges are applied to the object. To assign privileges to the users, the GRANT command is used. Basic syntax for GRANT command is as follows − GRANT privilege [, ...] ON object [, ...] TO { PUBLIC | GROUP group | username } privilege − values could be: SELECT, INSERT, UPDATE, DELETE, RULE, ALL. privilege − values could be: SELECT, INSERT, UPDATE, DELETE, RULE, ALL. object − The name of an object to which to grant access. The possible objects are: table, view, sequence object − The name of an object to which to grant access. The possible objects are: table, view, sequence PUBLIC − A short form representing all users. PUBLIC − A short form representing all users. GROUP group − A group to whom to grant privileges. GROUP group − A group to whom to grant privileges. username − The name of a user to whom to grant privileges. PUBLIC is a short form representing all users. username − The name of a user to whom to grant privileges. PUBLIC is a short form representing all users. The privileges can be revoked using the REVOKE command. Basic syntax for REVOKE command is as follows − REVOKE privilege [, ...] ON object [, ...] FROM { PUBLIC | GROUP groupname | username } privilege − values could be: SELECT, INSERT, UPDATE, DELETE, RULE, ALL. privilege − values could be: SELECT, INSERT, UPDATE, DELETE, RULE, ALL. object − The name of an object to which to grant access. The possible objects are: table, view, sequence object − The name of an object to which to grant access. The possible objects are: table, view, sequence PUBLIC − A short form representing all users. PUBLIC − A short form representing all users. GROUP group − A group to whom to grant privileges. GROUP group − A group to whom to grant privileges. username − The name of a user to whom to grant privileges. PUBLIC is a short form representing all users. username − The name of a user to whom to grant privileges. PUBLIC is a short form representing all users. To understand the privileges, let us first create a USER as follows − testdb=# CREATE USER manisha WITH PASSWORD 'password'; CREATE ROLE The message CREATE ROLE indicates that the USER "manisha" is created. Consider the table COMPANY having records as follows − 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) Next, let us grant all privileges on a table COMPANY to the user "manisha" as follows − testdb=# GRANT ALL ON COMPANY TO manisha; GRANT The message GRANT indicates that all privileges are assigned to the USER. Next, let us revoke the privileges from the USER "manisha" as follows − testdb=# REVOKE ALL ON COMPANY FROM manisha; REVOKE The message REVOKE indicates that all privileges are revoked from the USER. You can even delete the user as follows − testdb=# DROP USER manisha; DROP ROLE The message DROP ROLE indicates USER ‘Manisha’ is deleted from the database. 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": 3165, "s": 2825, "text": "Whenever an object is created in a database, an owner is assigned to it. The owner is usually the one who executed the creation statement. For most kinds of objects, the initial state is that only the owner (or a superuser) can modify or delete the object. To allow other roles or users to use it, privileges or permission must be granted." }, { "code": null, "e": 3215, "s": 3165, "text": "Different kinds of privileges in PostgreSQL are −" }, { "code": null, "e": 3223, "s": 3215, "text": "SELECT," }, { "code": null, "e": 3231, "s": 3223, "text": "INSERT," }, { "code": null, "e": 3239, "s": 3231, "text": "UPDATE," }, { "code": null, "e": 3247, "s": 3239, "text": "DELETE," }, { "code": null, "e": 3257, "s": 3247, "text": "TRUNCATE," }, { "code": null, "e": 3269, "s": 3257, "text": "REFERENCES," }, { "code": null, "e": 3278, "s": 3269, "text": "TRIGGER," }, { "code": null, "e": 3286, "s": 3278, "text": "CREATE," }, { "code": null, "e": 3295, "s": 3286, "text": "CONNECT," }, { "code": null, "e": 3306, "s": 3295, "text": "TEMPORARY," }, { "code": null, "e": 3319, "s": 3306, "text": "EXECUTE, and" }, { "code": null, "e": 3325, "s": 3319, "text": "USAGE" }, { "code": null, "e": 3487, "s": 3325, "text": "Depending on the type of the object (table, function, etc.,), privileges are applied to the object. To assign privileges to the users, the GRANT command is used." }, { "code": null, "e": 3534, "s": 3487, "text": "Basic syntax for GRANT command is as follows −" }, { "code": null, "e": 3616, "s": 3534, "text": "GRANT privilege [, ...]\nON object [, ...]\nTO { PUBLIC | GROUP group | username }\n" }, { "code": null, "e": 3688, "s": 3616, "text": "privilege − values could be: SELECT, INSERT, UPDATE, DELETE, RULE, ALL." }, { "code": null, "e": 3760, "s": 3688, "text": "privilege − values could be: SELECT, INSERT, UPDATE, DELETE, RULE, ALL." }, { "code": null, "e": 3865, "s": 3760, "text": "object − The name of an object to which to grant access. The possible objects are: table, view, sequence" }, { "code": null, "e": 3970, "s": 3865, "text": "object − The name of an object to which to grant access. The possible objects are: table, view, sequence" }, { "code": null, "e": 4016, "s": 3970, "text": "PUBLIC − A short form representing all users." }, { "code": null, "e": 4062, "s": 4016, "text": "PUBLIC − A short form representing all users." }, { "code": null, "e": 4113, "s": 4062, "text": "GROUP group − A group to whom to grant privileges." }, { "code": null, "e": 4164, "s": 4113, "text": "GROUP group − A group to whom to grant privileges." }, { "code": null, "e": 4270, "s": 4164, "text": "username − The name of a user to whom to grant privileges. PUBLIC is a short form representing all users." }, { "code": null, "e": 4376, "s": 4270, "text": "username − The name of a user to whom to grant privileges. PUBLIC is a short form representing all users." }, { "code": null, "e": 4432, "s": 4376, "text": "The privileges can be revoked using the REVOKE command." }, { "code": null, "e": 4480, "s": 4432, "text": "Basic syntax for REVOKE command is as follows −" }, { "code": null, "e": 4569, "s": 4480, "text": "REVOKE privilege [, ...]\nON object [, ...]\nFROM { PUBLIC | GROUP groupname | username }\n" }, { "code": null, "e": 4641, "s": 4569, "text": "privilege − values could be: SELECT, INSERT, UPDATE, DELETE, RULE, ALL." }, { "code": null, "e": 4713, "s": 4641, "text": "privilege − values could be: SELECT, INSERT, UPDATE, DELETE, RULE, ALL." }, { "code": null, "e": 4818, "s": 4713, "text": "object − The name of an object to which to grant access. The possible objects are: table, view, sequence" }, { "code": null, "e": 4923, "s": 4818, "text": "object − The name of an object to which to grant access. The possible objects are: table, view, sequence" }, { "code": null, "e": 4969, "s": 4923, "text": "PUBLIC − A short form representing all users." }, { "code": null, "e": 5015, "s": 4969, "text": "PUBLIC − A short form representing all users." }, { "code": null, "e": 5066, "s": 5015, "text": "GROUP group − A group to whom to grant privileges." }, { "code": null, "e": 5117, "s": 5066, "text": "GROUP group − A group to whom to grant privileges." }, { "code": null, "e": 5223, "s": 5117, "text": "username − The name of a user to whom to grant privileges. PUBLIC is a short form representing all users." }, { "code": null, "e": 5329, "s": 5223, "text": "username − The name of a user to whom to grant privileges. PUBLIC is a short form representing all users." }, { "code": null, "e": 5399, "s": 5329, "text": "To understand the privileges, let us first create a USER as follows −" }, { "code": null, "e": 5466, "s": 5399, "text": "testdb=# CREATE USER manisha WITH PASSWORD 'password';\nCREATE ROLE" }, { "code": null, "e": 5536, "s": 5466, "text": "The message CREATE ROLE indicates that the USER \"manisha\" is created." }, { "code": null, "e": 5591, "s": 5536, "text": "Consider the table COMPANY having records as follows −" }, { "code": null, "e": 5983, "s": 5591, "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": 6071, "s": 5983, "text": "Next, let us grant all privileges on a table COMPANY to the user \"manisha\" as follows −" }, { "code": null, "e": 6119, "s": 6071, "text": "testdb=# GRANT ALL ON COMPANY TO manisha;\nGRANT" }, { "code": null, "e": 6193, "s": 6119, "text": "The message GRANT indicates that all privileges are assigned to the USER." }, { "code": null, "e": 6265, "s": 6193, "text": "Next, let us revoke the privileges from the USER \"manisha\" as follows −" }, { "code": null, "e": 6317, "s": 6265, "text": "testdb=# REVOKE ALL ON COMPANY FROM manisha;\nREVOKE" }, { "code": null, "e": 6393, "s": 6317, "text": "The message REVOKE indicates that all privileges are revoked from the USER." }, { "code": null, "e": 6435, "s": 6393, "text": "You can even delete the user as follows −" }, { "code": null, "e": 6473, "s": 6435, "text": "testdb=# DROP USER manisha;\nDROP ROLE" }, { "code": null, "e": 6550, "s": 6473, "text": "The message DROP ROLE indicates USER ‘Manisha’ is deleted from the database." }, { "code": null, "e": 6585, "s": 6550, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6597, "s": 6585, "text": " John Elder" }, { "code": null, "e": 6632, "s": 6597, "text": "\n 49 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6648, "s": 6632, "text": " Niyazi Erdogan" }, { "code": null, "e": 6685, "s": 6648, "text": "\n 126 Lectures \n 10.5 hours \n" }, { "code": null, "e": 6707, "s": 6685, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 6740, "s": 6707, "text": "\n 35 Lectures \n 5 hours \n" }, { "code": null, "e": 6754, "s": 6740, "text": " Karthikeya T" }, { "code": null, "e": 6785, "s": 6754, "text": "\n 5 Lectures \n 51 mins\n" }, { "code": null, "e": 6798, "s": 6785, "text": " Vinay Kumar" }, { "code": null, "e": 6829, "s": 6798, "text": "\n 5 Lectures \n 52 mins\n" }, { "code": null, "e": 6842, "s": 6829, "text": " Vinay Kumar" }, { "code": null, "e": 6849, "s": 6842, "text": " Print" }, { "code": null, "e": 6860, "s": 6849, "text": " Add Notes" } ]
Find the Number of subarrays having sum less than K using C++
In this article, we will find out the number of subarrays having a sum less than K using C++. In this problem, we have an array arr[] and an integer K. So now we have to find subarrays that have a sum less than K. Here is the example − Input : arr[] = {1, 11, 2, 3, 15} K = 10 Output : 4 {1}, {2}, {3} and {2, 3} Now we will use two different methods to solve the given problem − In this approach, we will iterate through all the subarrays and calculate their sum and compare with k if the sum is less than k to increment our answer. #include <bits/stdc++.h> using namespace std; int main(){ int arr[] = {1, 11, 2, 3, 15}; // given array int k = 10; // given k int size = sizeof(arr) / sizeof(int); // size of our array. int ans = 0; // counter variable. for(int i = 0; i < size; i++){ // outer loop. int sum = 0; for(int j = i; j < size; j++){ // inner loop. sum = sum + arr[j]; if(sum < k) // comparing with k. ans++; // incrementing our ans if sum is less than k. } } cout << ans << "\n"; return 0; } 4 However, this approach is not very good as it's the time complexity is very high O(N*N), where n is the size of our array. We'll look at an alternative solution using the Sliding Window method(That will help us decrease the time complexity of the program). Unlike Brute Force, we will not be going through all the subarrays. Instead, we will traverse only when the sum of a subarray exceeds k and moves our left border till our right border and keeps repeating until the whole array is traversed. #include <bits/stdc++.h> using namespace std; int main(){ int arr[] = {1, 11, 2, 3, 15}; // given array int k = 10; // given k int size = sizeof(arr) / sizeof(int); // size of our array. int ans = 0; // counter variable. int start = 0; // left border. int end = 0; // right border. int sum = 0; while(end < size && start < size){ // till the whole array is traversed. while(sum >= k && start < end){ sum = sum - arr[start]; start++; } if(end >= start) ans = ans + end - start; sum += arr[end]; end++; } cout << ans << "\n"; return 0; } 4 We use the Sliding Window Technique to make our program faster or time-efficient to run for bigger constraints in this approach. In this approach, we are normally traversing till our sum is less than k and incrementing our answer according to it is now the crucial change in the code that occurs when the sum becomes greater or equal to k. In this situation, we start to increment our left border smaller to our right border or till the sum is greater or equal to k. As we process further, it traverses through other subarrays that can be formed. These new subarrays whose sum is less than k are added to our answer, so our answer is incremented. This approach is very efficient compared to the earlier Brute Force we applied as its time complexity is O(N), where N is the size of our array. In this article, we solve a problem to find the Number of subarrays with a sum less than k using the Sliding Window Technique. We also learned the C++ program for this problem and the complete approach ( Normal and efficient ) by which we solved this problem. We can write the same program in other languages such as C, java, python, and other languages. Hope you find this article helpful.
[ { "code": null, "e": 1298, "s": 1062, "text": "In this article, we will find out the number of subarrays having a sum less than K using C++. In this problem, we have an array arr[] and an integer K. So now we have to find subarrays that have a sum less than K. Here is the example −" }, { "code": null, "e": 1375, "s": 1298, "text": "Input : arr[] = {1, 11, 2, 3, 15}\nK = 10\nOutput : 4\n{1}, {2}, {3} and {2, 3}" }, { "code": null, "e": 1442, "s": 1375, "text": "Now we will use two different methods to solve the given problem −" }, { "code": null, "e": 1596, "s": 1442, "text": "In this approach, we will iterate through all the subarrays and calculate their sum and compare with k if the sum is less than k to increment our answer." }, { "code": null, "e": 2161, "s": 1596, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n int arr[] = {1, 11, 2, 3, 15}; // given array\n int k = 10; // given k\n int size = sizeof(arr) / sizeof(int); // size of our array.\n int ans = 0; // counter variable.\n for(int i = 0; i < size; i++){ // outer loop.\n int sum = 0;\n for(int j = i; j < size; j++){ // inner loop.\n sum = sum + arr[j];\n if(sum < k) // comparing with k.\n ans++; // incrementing our ans if sum is less than k.\n }\n }\n cout << ans << \"\\n\";\n return 0;\n}" }, { "code": null, "e": 2163, "s": 2161, "text": "4" }, { "code": null, "e": 2286, "s": 2163, "text": "However, this approach is not very good as it's the time complexity is very high O(N*N), where n is the size of our array." }, { "code": null, "e": 2420, "s": 2286, "text": "We'll look at an alternative solution using the Sliding Window method(That will help us decrease the time complexity of the program)." }, { "code": null, "e": 2660, "s": 2420, "text": "Unlike Brute Force, we will not be going through all the subarrays. Instead, we will traverse only when the sum of a subarray exceeds k and moves our left border till our right border and keeps repeating until the whole array is traversed." }, { "code": null, "e": 3313, "s": 2660, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n int arr[] = {1, 11, 2, 3, 15}; // given array\n int k = 10; // given k\n int size = sizeof(arr) / sizeof(int); // size of our array.\n int ans = 0; // counter variable.\n int start = 0; // left border.\n int end = 0; // right border.\n int sum = 0;\n while(end < size && start < size){ // till the whole array is traversed.\n while(sum >= k && start < end){\n sum = sum - arr[start];\n start++;\n }\n if(end >= start)\n ans = ans + end - start;\n sum += arr[end];\n end++;\n }\n cout << ans << \"\\n\";\n return 0;\n}" }, { "code": null, "e": 3315, "s": 3313, "text": "4" }, { "code": null, "e": 3444, "s": 3315, "text": "We use the Sliding Window Technique to make our program faster or time-efficient to run for bigger constraints in this approach." }, { "code": null, "e": 3962, "s": 3444, "text": "In this approach, we are normally traversing till our sum is less than k and incrementing our answer according to it is now the crucial change in the code that occurs when the sum becomes greater or equal to k. In this situation, we start to increment our left border smaller to our right border or till the sum is greater or equal to k. As we process further, it traverses through other subarrays that can be formed. These new subarrays whose sum is less than k are added to our answer, so our answer is incremented." }, { "code": null, "e": 4107, "s": 3962, "text": "This approach is very efficient compared to the earlier Brute Force we applied as its time complexity is O(N), where N is the size of our array." }, { "code": null, "e": 4498, "s": 4107, "text": "In this article, we solve a problem to find the Number of subarrays with a sum less than k using the Sliding Window Technique. We also learned the C++ program for this problem and the complete approach ( Normal and efficient ) by which we solved this problem. We can write the same program in other languages such as C, java, python, and other languages. Hope you find this article helpful." } ]
How to delete last element from a set in C++
06 Dec, 2018 Given a Set, the task is to remove the last element from this Set in C++. Examples: Input: set = [10 20 30 70 80 90 100 40 50 60] Output: 10 20 30 40 50 60 70 80 90 Input: set = [1 2 3 4 5] Output: 1 2 3 4 Sets are a type of associative containers in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. The last element of the Set can be deleted by by passing its iterator. Syntax: iterator erase (const_iterator positionOfElementToBeDeleted); Approach: One can easily delete the last element by passing its iterator to the erase function. To reach the iterator which points to the last element, there are two ways: Method 1:prev(setInt.end())Below is the implementation of the above approach:Program 1:// C++ program to delete last element// of a Set by passing its iterator #include <iostream>#include <set>using namespace std; // Function to print the setvoid printSet(set<int> myset){ // Get the iterator set<int>::iterator it; // printing all the elements of the set for (it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; cout << '\n';} // Function to delete last element of set// using method 1void deleteByMethod1(set<int> myset){ // printing all the elements of the set cout << "\nSet originally: "; printSet(myset); // Get the iterator set<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 1 it = prev(myset.end()); // Erase the last element // currently pointed by the iterator myset.erase(it); // printing all the elements of the set cout << "Set after deletion: "; printSet(myset);} // Driver codeint main(){ set<int> myset; // Get the set for (int i = 1; i < 10; i++) myset.insert(i * 10); // Method 1 to get positionOfElementToBeDeleted deleteByMethod1(myset); return 0;}Output:Set originally: 10 20 30 40 50 60 70 80 90 Set after deletion: 10 20 30 40 50 60 70 80 Method 2:set::iterator it = setInt.end(); --it; Below is the implementation of the above approach:Program 2:// C++ program to delete last element// of a Set by passing its iterator #include <iostream>#include <set>using namespace std; // Function to print the setvoid printSet(set<int> myset){ // Get the iterator set<int>::iterator it; // printing all the elements of the set for (it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; cout << '\n';} // Function to delete last element of set// using method 2void deleteByMethod2(set<int> myset){ // printing all the elements of the set cout << "\nSet originally: "; printSet(myset); // Get the iterator set<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 2 it = --myset.end(); // Erase the last element // currently pointed by the iterator myset.erase(it); // printing all the elements of the set cout << "Set after deletion: "; printSet(myset);} // Driver codeint main(){ set<int> myset; // Get the set for (int i = 1; i < 10; i++) myset.insert(i * 10); // Method 2 to get positionOfElementToBeDeleted deleteByMethod2(myset); return 0;}Output:Set originally: 10 20 30 40 50 60 70 80 90 Set after deletion: 10 20 30 40 50 60 70 80 Method 1:prev(setInt.end())Below is the implementation of the above approach:Program 1:// C++ program to delete last element// of a Set by passing its iterator #include <iostream>#include <set>using namespace std; // Function to print the setvoid printSet(set<int> myset){ // Get the iterator set<int>::iterator it; // printing all the elements of the set for (it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; cout << '\n';} // Function to delete last element of set// using method 1void deleteByMethod1(set<int> myset){ // printing all the elements of the set cout << "\nSet originally: "; printSet(myset); // Get the iterator set<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 1 it = prev(myset.end()); // Erase the last element // currently pointed by the iterator myset.erase(it); // printing all the elements of the set cout << "Set after deletion: "; printSet(myset);} // Driver codeint main(){ set<int> myset; // Get the set for (int i = 1; i < 10; i++) myset.insert(i * 10); // Method 1 to get positionOfElementToBeDeleted deleteByMethod1(myset); return 0;}Output:Set originally: 10 20 30 40 50 60 70 80 90 Set after deletion: 10 20 30 40 50 60 70 80 prev(setInt.end()) Below is the implementation of the above approach: Program 1: // C++ program to delete last element// of a Set by passing its iterator #include <iostream>#include <set>using namespace std; // Function to print the setvoid printSet(set<int> myset){ // Get the iterator set<int>::iterator it; // printing all the elements of the set for (it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; cout << '\n';} // Function to delete last element of set// using method 1void deleteByMethod1(set<int> myset){ // printing all the elements of the set cout << "\nSet originally: "; printSet(myset); // Get the iterator set<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 1 it = prev(myset.end()); // Erase the last element // currently pointed by the iterator myset.erase(it); // printing all the elements of the set cout << "Set after deletion: "; printSet(myset);} // Driver codeint main(){ set<int> myset; // Get the set for (int i = 1; i < 10; i++) myset.insert(i * 10); // Method 1 to get positionOfElementToBeDeleted deleteByMethod1(myset); return 0;} Set originally: 10 20 30 40 50 60 70 80 90 Set after deletion: 10 20 30 40 50 60 70 80 Method 2:set::iterator it = setInt.end(); --it; Below is the implementation of the above approach:Program 2:// C++ program to delete last element// of a Set by passing its iterator #include <iostream>#include <set>using namespace std; // Function to print the setvoid printSet(set<int> myset){ // Get the iterator set<int>::iterator it; // printing all the elements of the set for (it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; cout << '\n';} // Function to delete last element of set// using method 2void deleteByMethod2(set<int> myset){ // printing all the elements of the set cout << "\nSet originally: "; printSet(myset); // Get the iterator set<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 2 it = --myset.end(); // Erase the last element // currently pointed by the iterator myset.erase(it); // printing all the elements of the set cout << "Set after deletion: "; printSet(myset);} // Driver codeint main(){ set<int> myset; // Get the set for (int i = 1; i < 10; i++) myset.insert(i * 10); // Method 2 to get positionOfElementToBeDeleted deleteByMethod2(myset); return 0;}Output:Set originally: 10 20 30 40 50 60 70 80 90 Set after deletion: 10 20 30 40 50 60 70 80 set::iterator it = setInt.end(); --it; Below is the implementation of the above approach: Program 2: // C++ program to delete last element// of a Set by passing its iterator #include <iostream>#include <set>using namespace std; // Function to print the setvoid printSet(set<int> myset){ // Get the iterator set<int>::iterator it; // printing all the elements of the set for (it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; cout << '\n';} // Function to delete last element of set// using method 2void deleteByMethod2(set<int> myset){ // printing all the elements of the set cout << "\nSet originally: "; printSet(myset); // Get the iterator set<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 2 it = --myset.end(); // Erase the last element // currently pointed by the iterator myset.erase(it); // printing all the elements of the set cout << "Set after deletion: "; printSet(myset);} // Driver codeint main(){ set<int> myset; // Get the set for (int i = 1; i < 10; i++) myset.insert(i * 10); // Method 2 to get positionOfElementToBeDeleted deleteByMethod2(myset); return 0;} Set originally: 10 20 30 40 50 60 70 80 90 Set after deletion: 10 20 30 40 50 60 70 80 cpp-set STL Technical Scripter 2018 C++ Programs Technical Scripter STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Const keyword in C++ Program to implement Singly Linked List in C++ using class cout in C++ Different ways to print elements of vector Why it is important to write "using namespace std" in C++ program? Dynamic _Cast in C++ string::npos in C++ with Examples Maximum value of long long int in C++ How to convert a Vector to Set in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Dec, 2018" }, { "code": null, "e": 128, "s": 54, "text": "Given a Set, the task is to remove the last element from this Set in C++." }, { "code": null, "e": 138, "s": 128, "text": "Examples:" }, { "code": null, "e": 262, "s": 138, "text": "Input: set = [10 20 30 70 80 90 100 40 50 60]\nOutput: 10 20 30 40 50 60 70 80 90\n\nInput: set = [1 2 3 4 5]\nOutput: 1 2 3 4\n" }, { "code": null, "e": 540, "s": 262, "text": "Sets are a type of associative containers in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element." }, { "code": null, "e": 611, "s": 540, "text": "The last element of the Set can be deleted by by passing its iterator." }, { "code": null, "e": 619, "s": 611, "text": "Syntax:" }, { "code": null, "e": 682, "s": 619, "text": "iterator erase (const_iterator positionOfElementToBeDeleted);\n" }, { "code": null, "e": 854, "s": 682, "text": "Approach: One can easily delete the last element by passing its iterator to the erase function. To reach the iterator which points to the last element, there are two ways:" }, { "code": null, "e": 3509, "s": 854, "text": "Method 1:prev(setInt.end())Below is the implementation of the above approach:Program 1:// C++ program to delete last element// of a Set by passing its iterator #include <iostream>#include <set>using namespace std; // Function to print the setvoid printSet(set<int> myset){ // Get the iterator set<int>::iterator it; // printing all the elements of the set for (it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; cout << '\\n';} // Function to delete last element of set// using method 1void deleteByMethod1(set<int> myset){ // printing all the elements of the set cout << \"\\nSet originally: \"; printSet(myset); // Get the iterator set<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 1 it = prev(myset.end()); // Erase the last element // currently pointed by the iterator myset.erase(it); // printing all the elements of the set cout << \"Set after deletion: \"; printSet(myset);} // Driver codeint main(){ set<int> myset; // Get the set for (int i = 1; i < 10; i++) myset.insert(i * 10); // Method 1 to get positionOfElementToBeDeleted deleteByMethod1(myset); return 0;}Output:Set originally: 10 20 30 40 50 60 70 80 90\nSet after deletion: 10 20 30 40 50 60 70 80\nMethod 2:set::iterator it = setInt.end(); \n--it;\nBelow is the implementation of the above approach:Program 2:// C++ program to delete last element// of a Set by passing its iterator #include <iostream>#include <set>using namespace std; // Function to print the setvoid printSet(set<int> myset){ // Get the iterator set<int>::iterator it; // printing all the elements of the set for (it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; cout << '\\n';} // Function to delete last element of set// using method 2void deleteByMethod2(set<int> myset){ // printing all the elements of the set cout << \"\\nSet originally: \"; printSet(myset); // Get the iterator set<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 2 it = --myset.end(); // Erase the last element // currently pointed by the iterator myset.erase(it); // printing all the elements of the set cout << \"Set after deletion: \"; printSet(myset);} // Driver codeint main(){ set<int> myset; // Get the set for (int i = 1; i < 10; i++) myset.insert(i * 10); // Method 2 to get positionOfElementToBeDeleted deleteByMethod2(myset); return 0;}Output:Set originally: 10 20 30 40 50 60 70 80 90\nSet after deletion: 10 20 30 40 50 60 70 80\n" }, { "code": null, "e": 4828, "s": 3509, "text": "Method 1:prev(setInt.end())Below is the implementation of the above approach:Program 1:// C++ program to delete last element// of a Set by passing its iterator #include <iostream>#include <set>using namespace std; // Function to print the setvoid printSet(set<int> myset){ // Get the iterator set<int>::iterator it; // printing all the elements of the set for (it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; cout << '\\n';} // Function to delete last element of set// using method 1void deleteByMethod1(set<int> myset){ // printing all the elements of the set cout << \"\\nSet originally: \"; printSet(myset); // Get the iterator set<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 1 it = prev(myset.end()); // Erase the last element // currently pointed by the iterator myset.erase(it); // printing all the elements of the set cout << \"Set after deletion: \"; printSet(myset);} // Driver codeint main(){ set<int> myset; // Get the set for (int i = 1; i < 10; i++) myset.insert(i * 10); // Method 1 to get positionOfElementToBeDeleted deleteByMethod1(myset); return 0;}Output:Set originally: 10 20 30 40 50 60 70 80 90\nSet after deletion: 10 20 30 40 50 60 70 80\n" }, { "code": null, "e": 4847, "s": 4828, "text": "prev(setInt.end())" }, { "code": null, "e": 4898, "s": 4847, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 4909, "s": 4898, "text": "Program 1:" }, { "code": "// C++ program to delete last element// of a Set by passing its iterator #include <iostream>#include <set>using namespace std; // Function to print the setvoid printSet(set<int> myset){ // Get the iterator set<int>::iterator it; // printing all the elements of the set for (it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; cout << '\\n';} // Function to delete last element of set// using method 1void deleteByMethod1(set<int> myset){ // printing all the elements of the set cout << \"\\nSet originally: \"; printSet(myset); // Get the iterator set<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 1 it = prev(myset.end()); // Erase the last element // currently pointed by the iterator myset.erase(it); // printing all the elements of the set cout << \"Set after deletion: \"; printSet(myset);} // Driver codeint main(){ set<int> myset; // Get the set for (int i = 1; i < 10; i++) myset.insert(i * 10); // Method 1 to get positionOfElementToBeDeleted deleteByMethod1(myset); return 0;}", "e": 6045, "s": 4909, "text": null }, { "code": null, "e": 6135, "s": 6045, "text": "Set originally: 10 20 30 40 50 60 70 80 90\nSet after deletion: 10 20 30 40 50 60 70 80\n" }, { "code": null, "e": 7472, "s": 6135, "text": "Method 2:set::iterator it = setInt.end(); \n--it;\nBelow is the implementation of the above approach:Program 2:// C++ program to delete last element// of a Set by passing its iterator #include <iostream>#include <set>using namespace std; // Function to print the setvoid printSet(set<int> myset){ // Get the iterator set<int>::iterator it; // printing all the elements of the set for (it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; cout << '\\n';} // Function to delete last element of set// using method 2void deleteByMethod2(set<int> myset){ // printing all the elements of the set cout << \"\\nSet originally: \"; printSet(myset); // Get the iterator set<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 2 it = --myset.end(); // Erase the last element // currently pointed by the iterator myset.erase(it); // printing all the elements of the set cout << \"Set after deletion: \"; printSet(myset);} // Driver codeint main(){ set<int> myset; // Get the set for (int i = 1; i < 10; i++) myset.insert(i * 10); // Method 2 to get positionOfElementToBeDeleted deleteByMethod2(myset); return 0;}Output:Set originally: 10 20 30 40 50 60 70 80 90\nSet after deletion: 10 20 30 40 50 60 70 80\n" }, { "code": null, "e": 7513, "s": 7472, "text": "set::iterator it = setInt.end(); \n--it;\n" }, { "code": null, "e": 7564, "s": 7513, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 7575, "s": 7564, "text": "Program 2:" }, { "code": "// C++ program to delete last element// of a Set by passing its iterator #include <iostream>#include <set>using namespace std; // Function to print the setvoid printSet(set<int> myset){ // Get the iterator set<int>::iterator it; // printing all the elements of the set for (it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; cout << '\\n';} // Function to delete last element of set// using method 2void deleteByMethod2(set<int> myset){ // printing all the elements of the set cout << \"\\nSet originally: \"; printSet(myset); // Get the iterator set<int>::iterator it; // Get the positionOfElementToBeDeleted // using method 2 it = --myset.end(); // Erase the last element // currently pointed by the iterator myset.erase(it); // printing all the elements of the set cout << \"Set after deletion: \"; printSet(myset);} // Driver codeint main(){ set<int> myset; // Get the set for (int i = 1; i < 10; i++) myset.insert(i * 10); // Method 2 to get positionOfElementToBeDeleted deleteByMethod2(myset); return 0;}", "e": 8707, "s": 7575, "text": null }, { "code": null, "e": 8797, "s": 8707, "text": "Set originally: 10 20 30 40 50 60 70 80 90\nSet after deletion: 10 20 30 40 50 60 70 80\n" }, { "code": null, "e": 8805, "s": 8797, "text": "cpp-set" }, { "code": null, "e": 8809, "s": 8805, "text": "STL" }, { "code": null, "e": 8833, "s": 8809, "text": "Technical Scripter 2018" }, { "code": null, "e": 8846, "s": 8833, "text": "C++ Programs" }, { "code": null, "e": 8865, "s": 8846, "text": "Technical Scripter" }, { "code": null, "e": 8869, "s": 8865, "text": "STL" }, { "code": null, "e": 8967, "s": 8869, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9008, "s": 8967, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 9029, "s": 9008, "text": "Const keyword in C++" }, { "code": null, "e": 9088, "s": 9029, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 9100, "s": 9088, "text": "cout in C++" }, { "code": null, "e": 9143, "s": 9100, "text": "Different ways to print elements of vector" }, { "code": null, "e": 9210, "s": 9143, "text": "Why it is important to write \"using namespace std\" in C++ program?" }, { "code": null, "e": 9231, "s": 9210, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 9265, "s": 9231, "text": "string::npos in C++ with Examples" }, { "code": null, "e": 9303, "s": 9265, "text": "Maximum value of long long int in C++" } ]
How to Create a Bootstrap Spinner and Display on Screen till the data from the API loads ?
10 Jun, 2020 The task is to display a spinner on the page until the data response from the API comes. We have taken bootstrap spinner to show the example. Pre-requisite: You will need some knowledge about JavaScript fetch API. You will need a mock API for getting data. Approach: Create necessary HTML, CSS, and JavaScript file for the task. In HTML file, link bootstrap in head section.<link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css” integrity=”sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh” crossorigin=”anonymous”> <link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css” integrity=”sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh” crossorigin=”anonymous”> Now take any spinner from “https://getbootstrap.com/docs/4.4/components/spinners/“, The spinner I had taken for the example is:<div class="spinner-border text-primary" id="spinner"role="status"> <span class="sr-only">Loading...</span> </div> <div class="spinner-border text-primary" id="spinner"role="status"> <span class="sr-only">Loading...</span> </div> Now, spinner will have to be stopped once the data from the API loads. So, get the data from API by Fetch() API method. Store the data in a response variable. There is an if statement that checks if Response from API came or not. If Response came then there is a function hideSpinner() called. In that hideSpinner() function by using DOM manipulation, we set display of Spinner element to none. HTML file: <!DOCTYPE html><html> <head> <script src="script.js"></script> <title>Spinner</title> <link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"></head> <body> <div class="spinner-border text-primary" id="spinner" role="status"> <span class="sr-only">Loading...</span> </div> <div id="data"></div></body> </html> JavaScript file: // API url const api_url ="https://mygfgapi.free.beeceptor.com/my/api/path"; // Defining async function async function getapi(url) { // Storing response const response = await fetch(url); // Storing data in form of JSON var apidata = await response.json(); console.log(apidata); if (response) { hideSpinner(); } document.getElementById("data").innerHTML = `<h1>${apidata.data}</h1>`;} // Calling that async function getapi(api_url); // Function to hide the Spinnerfunction hideSpinner() { document.getElementById('spinner') .style.display = 'none';} Output: You can see in output window, spinner loads till the Data from API comes. API link: “https://mygfgapi.free.beeceptor.com/my/api/path” Bootstrap-Misc HTML-Misc JavaScript-Misc Bootstrap HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jun, 2020" }, { "code": null, "e": 170, "s": 28, "text": "The task is to display a spinner on the page until the data response from the API comes. We have taken bootstrap spinner to show the example." }, { "code": null, "e": 186, "s": 170, "text": "Pre-requisite: " }, { "code": null, "e": 243, "s": 186, "text": "You will need some knowledge about JavaScript fetch API." }, { "code": null, "e": 286, "s": 243, "text": "You will need a mock API for getting data." }, { "code": null, "e": 296, "s": 286, "text": "Approach:" }, { "code": null, "e": 358, "s": 296, "text": "Create necessary HTML, CSS, and JavaScript file for the task." }, { "code": null, "e": 615, "s": 358, "text": "In HTML file, link bootstrap in head section.<link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css” integrity=”sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh” crossorigin=”anonymous”>" }, { "code": null, "e": 827, "s": 615, "text": "<link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css” integrity=”sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh” crossorigin=”anonymous”>" }, { "code": null, "e": 1079, "s": 827, "text": "Now take any spinner from “https://getbootstrap.com/docs/4.4/components/spinners/“, The spinner I had taken for the example is:<div class=\"spinner-border text-primary\" \n id=\"spinner\"role=\"status\">\n <span class=\"sr-only\">Loading...</span>\n</div>\n" }, { "code": null, "e": 1204, "s": 1079, "text": "<div class=\"spinner-border text-primary\" \n id=\"spinner\"role=\"status\">\n <span class=\"sr-only\">Loading...</span>\n</div>\n" }, { "code": null, "e": 1275, "s": 1204, "text": "Now, spinner will have to be stopped once the data from the API loads." }, { "code": null, "e": 1324, "s": 1275, "text": "So, get the data from API by Fetch() API method." }, { "code": null, "e": 1363, "s": 1324, "text": "Store the data in a response variable." }, { "code": null, "e": 1434, "s": 1363, "text": "There is an if statement that checks if Response from API came or not." }, { "code": null, "e": 1498, "s": 1434, "text": "If Response came then there is a function hideSpinner() called." }, { "code": null, "e": 1599, "s": 1498, "text": "In that hideSpinner() function by using DOM manipulation, we set display of Spinner element to none." }, { "code": null, "e": 1610, "s": 1599, "text": "HTML file:" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"script.js\"></script> <title>Spinner</title> <link rel=\"stylesheet\" href=\"style.css\"> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\" integrity=\"sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh\" crossorigin=\"anonymous\"></head> <body> <div class=\"spinner-border text-primary\" id=\"spinner\" role=\"status\"> <span class=\"sr-only\">Loading...</span> </div> <div id=\"data\"></div></body> </html>", "e": 2169, "s": 1610, "text": null }, { "code": null, "e": 2186, "s": 2169, "text": "JavaScript file:" }, { "code": "// API url const api_url =\"https://mygfgapi.free.beeceptor.com/my/api/path\"; // Defining async function async function getapi(url) { // Storing response const response = await fetch(url); // Storing data in form of JSON var apidata = await response.json(); console.log(apidata); if (response) { hideSpinner(); } document.getElementById(\"data\").innerHTML = `<h1>${apidata.data}</h1>`;} // Calling that async function getapi(api_url); // Function to hide the Spinnerfunction hideSpinner() { document.getElementById('spinner') .style.display = 'none';} ", "e": 2798, "s": 2186, "text": null }, { "code": null, "e": 2806, "s": 2798, "text": "Output:" }, { "code": null, "e": 2880, "s": 2806, "text": "You can see in output window, spinner loads till the Data from API comes." }, { "code": null, "e": 2940, "s": 2880, "text": "API link: “https://mygfgapi.free.beeceptor.com/my/api/path”" }, { "code": null, "e": 2955, "s": 2940, "text": "Bootstrap-Misc" }, { "code": null, "e": 2965, "s": 2955, "text": "HTML-Misc" }, { "code": null, "e": 2981, "s": 2965, "text": "JavaScript-Misc" }, { "code": null, "e": 2991, "s": 2981, "text": "Bootstrap" }, { "code": null, "e": 2996, "s": 2991, "text": "HTML" }, { "code": null, "e": 3007, "s": 2996, "text": "JavaScript" }, { "code": null, "e": 3024, "s": 3007, "text": "Web Technologies" }, { "code": null, "e": 3029, "s": 3024, "text": "HTML" } ]
SQL Query to Calculate Total Number of Weeks Between Two Specific Dates
23 Apr, 2021 Here we will see, how to calculate the number of weeks between the two given dates with the help of SQL query using DATEDIFF() function. For the purpose of demonstration, we will be creating a demo_orders table in a database called “geeks“. Use the below SQL statement to create a database called geeks: CREATE DATABASE geeks; Use the below SQL statement to switch the database context to geeks: USE geeks; We have the following demo table in our geeks database. CREATE TABLE demo_orders( ORDER_ID INT IDENTITY(1,1) PRIMARY KEY, ITEM_NAME VARCHAR(30) NOT NULL, ORDER_DATE DATE NOT NULL ); You can use the below statement to query the description of the created table: EXEC SP_COLUMNS demo_orders; Use the below statement to add data to the demo_orders table: INSERT INTO demo_orders --no need to mention columns explicitly as we are inserting --into all columns and ID gets --automatically incremented. VALUES ('Maserati', '2007-10-03'), ('BMW', '2010-07-23'), ('Mercedes Benz', '2012-11-12'), ('Ferrari', '2016-05-09'), ('Lamborghini', '2020-10-20'); To verify the contents of the table use the below statement: SELECT * FROM demo_orders; Now let’s find the number of weeks between the dates of the order of ‘Maserati’ and ‘Ferrari’ in the table using DATEDIFF() function. Below is the syntax for the DATEDIFF() function to find the no. of weeks between two given dates. Syntax: DATEDIFF(week or ww or wk, <start_date>, <end_date>); Example: DECLARE @start VARCHAR(10) = ( SELECT order_date FROM demo_orders WHERE item_name = 'Maserati'), @end VARCHAR(10) = ( SELECT order_date FROM demo_orders WHERE item_name = 'Ferrari') --@start variable holds the start date(i.e date of Maserati being purchased). --@end variable holds the end date (i.e date of Ferrari being purchased). SELECT DATEDIFF(ww, @start, @end) AS number_of_weeks; Output: Picked SQL-Query 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? Window functions in SQL What is Temporary Table in SQL? SQL using Python SQL | Sub queries in From Clause SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter RANK() Function in SQL Server SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates SQL | DROP, TRUNCATE
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Apr, 2021" }, { "code": null, "e": 165, "s": 28, "text": "Here we will see, how to calculate the number of weeks between the two given dates with the help of SQL query using DATEDIFF() function." }, { "code": null, "e": 269, "s": 165, "text": "For the purpose of demonstration, we will be creating a demo_orders table in a database called “geeks“." }, { "code": null, "e": 332, "s": 269, "text": "Use the below SQL statement to create a database called geeks:" }, { "code": null, "e": 355, "s": 332, "text": "CREATE DATABASE geeks;" }, { "code": null, "e": 424, "s": 355, "text": "Use the below SQL statement to switch the database context to geeks:" }, { "code": null, "e": 435, "s": 424, "text": "USE geeks;" }, { "code": null, "e": 491, "s": 435, "text": "We have the following demo table in our geeks database." }, { "code": null, "e": 617, "s": 491, "text": "CREATE TABLE demo_orders(\nORDER_ID INT IDENTITY(1,1) PRIMARY KEY,\nITEM_NAME VARCHAR(30) NOT NULL,\nORDER_DATE DATE NOT NULL\n);" }, { "code": null, "e": 696, "s": 617, "text": "You can use the below statement to query the description of the created table:" }, { "code": null, "e": 725, "s": 696, "text": "EXEC SP_COLUMNS demo_orders;" }, { "code": null, "e": 787, "s": 725, "text": "Use the below statement to add data to the demo_orders table:" }, { "code": null, "e": 1130, "s": 787, "text": "INSERT INTO demo_orders --no need to mention columns explicitly as we are inserting\n --into all columns and ID gets\n --automatically incremented.\nVALUES\n('Maserati', '2007-10-03'),\n('BMW', '2010-07-23'),\n('Mercedes Benz', '2012-11-12'),\n('Ferrari', '2016-05-09'),\n('Lamborghini', '2020-10-20');" }, { "code": null, "e": 1191, "s": 1130, "text": "To verify the contents of the table use the below statement:" }, { "code": null, "e": 1218, "s": 1191, "text": "SELECT * FROM demo_orders;" }, { "code": null, "e": 1352, "s": 1218, "text": "Now let’s find the number of weeks between the dates of the order of ‘Maserati’ and ‘Ferrari’ in the table using DATEDIFF() function." }, { "code": null, "e": 1450, "s": 1352, "text": "Below is the syntax for the DATEDIFF() function to find the no. of weeks between two given dates." }, { "code": null, "e": 1512, "s": 1450, "text": "Syntax: DATEDIFF(week or ww or wk, <start_date>, <end_date>);" }, { "code": null, "e": 1522, "s": 1512, "text": "Example: " }, { "code": null, "e": 1925, "s": 1522, "text": "DECLARE \n@start VARCHAR(10) = (\n SELECT order_date FROM demo_orders\n WHERE item_name = 'Maserati'),\n@end VARCHAR(10) = (\n SELECT order_date FROM demo_orders\n WHERE item_name = 'Ferrari')\n \n\n--@start variable holds the start date(i.e date of Maserati being purchased).\n\n--@end variable holds the end date (i.e date of Ferrari being purchased).\n\nSELECT DATEDIFF(ww, @start, @end) AS number_of_weeks;" }, { "code": null, "e": 1933, "s": 1925, "text": "Output:" }, { "code": null, "e": 1940, "s": 1933, "text": "Picked" }, { "code": null, "e": 1950, "s": 1940, "text": "SQL-Query" }, { "code": null, "e": 1954, "s": 1950, "text": "SQL" }, { "code": null, "e": 1958, "s": 1954, "text": "SQL" }, { "code": null, "e": 2056, "s": 1958, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2122, "s": 2056, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 2146, "s": 2122, "text": "Window functions in SQL" }, { "code": null, "e": 2178, "s": 2146, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 2195, "s": 2178, "text": "SQL using Python" }, { "code": null, "e": 2228, "s": 2195, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 2306, "s": 2228, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 2336, "s": 2306, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 2372, "s": 2336, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 2403, "s": 2372, "text": "SQL Query to Compare Two Dates" } ]
Draw a Polygon in Java Applet
08 May, 2018 Polygon is a closed figure with finite set of line segments joining one vertex to the other. The polygon comprises of set of (x, y) coordinate pairs where each pair is the vertex of the polygon. The side of the polygon is the line drawn between two successive coordinate pairs and a line segment is drawn from the first pair to the last pair. We can draw Polygon in java applet by three ways : drawPolygon(int[] x, int[] y, int numberofpoints) : draws a polygon with the given set of x and y points.// Java program to draw polygon using// drawPolygon(int[] x, int[] y, int numberofpoints)// functionimport java.awt.*;import javax.swing.*; public class poly extends JApplet { // called when applet is started public void init() { // set the size of applet to 300, 300 setSize(200, 200); show(); } // invoked when applet is started public void start() { } // invoked when applet is closed public void stop() { } public void paint(Graphics g) { // x coordinates of vertices int x[] = { 10, 30, 40, 50, 110, 140 }; // y coordinates of vertices int y[] = { 140, 110, 50, 40, 30, 10 }; // number of vertices int numberofpoints = 6; // set the color of line drawn to blue g.setColor(Color.blue); // draw the polygon using drawPolygon function g.drawPolygon(x, y, numberofpoints); }}Output :drawPolygon(Polygon p) : draws a polygon with the given object of Polygon class.// Java program to draw polygon// using drawPolygon(Polygon p)// functionimport java.awt.*;import javax.swing.*; public class poly extends JApplet { // called when applet is started public void init() { // set the size of applet to 300, 300 setSize(200, 200); show(); } // invoked when applet is started public void start() { } // invoked when applet is closed public void stop() { } public void paint(Graphics g) { // x coordinates of vertices int x[] = { 10, 30, 40, 50, 110, 140 }; // y coordinates of vertices int y[] = { 140, 110, 50, 40, 30, 10 }; // number of vertices int numberofpoints = 6; // create a polygon with given x, y coordinates Polygon p = new Polygon(x, y, numberofpoints); // set the color of line drawn to blue g.setColor(Color.blue); // draw the polygon using drawPolygon // function using object of polygon class g.drawPolygon(p); }}Output :drawLine(int x, int y, int x1, int y1) : In this method we would connect adjacent vertices with a line segment and also connect the first and last vertex.// Java code to draw a polygon// using drawLine(int x, int y, int x1, int y1)// functionimport java.awt.*;import javax.swing.*; public class poly extends JApplet { // called when applet is started public void init() { // set the size of applet to 300, 300 setSize(200, 200); show(); } // invoked when applet is started public void start() { } // invoked when applet is closed public void stop() { } public void paint(Graphics g) { // x coordinates of vertices int x[] = { 10, 30, 40, 50, 110, 140 }; // y coordinates of vertices int y[] = { 140, 110, 50, 40, 30, 10 }; // number of vertices int numberofpoints = 6; // set the color of line drawn to blue g.setColor(Color.blue); // join the adjacent vertices for (int i = 0; i < numberofpoints - 1; i++) g.drawLine(x[i], y[i], x[i + 1], y[i + 1]); // join the first and last vertex g.drawLine(x[0], y[0], x[numberofpoints - 1], y[numberofpoints - 1]); }}Output : drawPolygon(int[] x, int[] y, int numberofpoints) : draws a polygon with the given set of x and y points.// Java program to draw polygon using// drawPolygon(int[] x, int[] y, int numberofpoints)// functionimport java.awt.*;import javax.swing.*; public class poly extends JApplet { // called when applet is started public void init() { // set the size of applet to 300, 300 setSize(200, 200); show(); } // invoked when applet is started public void start() { } // invoked when applet is closed public void stop() { } public void paint(Graphics g) { // x coordinates of vertices int x[] = { 10, 30, 40, 50, 110, 140 }; // y coordinates of vertices int y[] = { 140, 110, 50, 40, 30, 10 }; // number of vertices int numberofpoints = 6; // set the color of line drawn to blue g.setColor(Color.blue); // draw the polygon using drawPolygon function g.drawPolygon(x, y, numberofpoints); }}Output : // Java program to draw polygon using// drawPolygon(int[] x, int[] y, int numberofpoints)// functionimport java.awt.*;import javax.swing.*; public class poly extends JApplet { // called when applet is started public void init() { // set the size of applet to 300, 300 setSize(200, 200); show(); } // invoked when applet is started public void start() { } // invoked when applet is closed public void stop() { } public void paint(Graphics g) { // x coordinates of vertices int x[] = { 10, 30, 40, 50, 110, 140 }; // y coordinates of vertices int y[] = { 140, 110, 50, 40, 30, 10 }; // number of vertices int numberofpoints = 6; // set the color of line drawn to blue g.setColor(Color.blue); // draw the polygon using drawPolygon function g.drawPolygon(x, y, numberofpoints); }} Output : drawPolygon(Polygon p) : draws a polygon with the given object of Polygon class.// Java program to draw polygon// using drawPolygon(Polygon p)// functionimport java.awt.*;import javax.swing.*; public class poly extends JApplet { // called when applet is started public void init() { // set the size of applet to 300, 300 setSize(200, 200); show(); } // invoked when applet is started public void start() { } // invoked when applet is closed public void stop() { } public void paint(Graphics g) { // x coordinates of vertices int x[] = { 10, 30, 40, 50, 110, 140 }; // y coordinates of vertices int y[] = { 140, 110, 50, 40, 30, 10 }; // number of vertices int numberofpoints = 6; // create a polygon with given x, y coordinates Polygon p = new Polygon(x, y, numberofpoints); // set the color of line drawn to blue g.setColor(Color.blue); // draw the polygon using drawPolygon // function using object of polygon class g.drawPolygon(p); }}Output : // Java program to draw polygon// using drawPolygon(Polygon p)// functionimport java.awt.*;import javax.swing.*; public class poly extends JApplet { // called when applet is started public void init() { // set the size of applet to 300, 300 setSize(200, 200); show(); } // invoked when applet is started public void start() { } // invoked when applet is closed public void stop() { } public void paint(Graphics g) { // x coordinates of vertices int x[] = { 10, 30, 40, 50, 110, 140 }; // y coordinates of vertices int y[] = { 140, 110, 50, 40, 30, 10 }; // number of vertices int numberofpoints = 6; // create a polygon with given x, y coordinates Polygon p = new Polygon(x, y, numberofpoints); // set the color of line drawn to blue g.setColor(Color.blue); // draw the polygon using drawPolygon // function using object of polygon class g.drawPolygon(p); }} Output : drawLine(int x, int y, int x1, int y1) : In this method we would connect adjacent vertices with a line segment and also connect the first and last vertex.// Java code to draw a polygon// using drawLine(int x, int y, int x1, int y1)// functionimport java.awt.*;import javax.swing.*; public class poly extends JApplet { // called when applet is started public void init() { // set the size of applet to 300, 300 setSize(200, 200); show(); } // invoked when applet is started public void start() { } // invoked when applet is closed public void stop() { } public void paint(Graphics g) { // x coordinates of vertices int x[] = { 10, 30, 40, 50, 110, 140 }; // y coordinates of vertices int y[] = { 140, 110, 50, 40, 30, 10 }; // number of vertices int numberofpoints = 6; // set the color of line drawn to blue g.setColor(Color.blue); // join the adjacent vertices for (int i = 0; i < numberofpoints - 1; i++) g.drawLine(x[i], y[i], x[i + 1], y[i + 1]); // join the first and last vertex g.drawLine(x[0], y[0], x[numberofpoints - 1], y[numberofpoints - 1]); }}Output : // Java code to draw a polygon// using drawLine(int x, int y, int x1, int y1)// functionimport java.awt.*;import javax.swing.*; public class poly extends JApplet { // called when applet is started public void init() { // set the size of applet to 300, 300 setSize(200, 200); show(); } // invoked when applet is started public void start() { } // invoked when applet is closed public void stop() { } public void paint(Graphics g) { // x coordinates of vertices int x[] = { 10, 30, 40, 50, 110, 140 }; // y coordinates of vertices int y[] = { 140, 110, 50, 40, 30, 10 }; // number of vertices int numberofpoints = 6; // set the color of line drawn to blue g.setColor(Color.blue); // join the adjacent vertices for (int i = 0; i < numberofpoints - 1; i++) g.drawLine(x[i], y[i], x[i + 1], y[i + 1]); // join the first and last vertex g.drawLine(x[0], y[0], x[numberofpoints - 1], y[numberofpoints - 1]); }} Output : Note: The above function are a part of java.awt package and belongs to java.awt.Graphics class. Also, these codes might not run in an online compiler please use an offline compiler. The x and y coordinates can be changed by the programmer according to their need java-swing Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 May, 2018" }, { "code": null, "e": 395, "s": 52, "text": "Polygon is a closed figure with finite set of line segments joining one vertex to the other. The polygon comprises of set of (x, y) coordinate pairs where each pair is the vertex of the polygon. The side of the polygon is the line drawn between two successive coordinate pairs and a line segment is drawn from the first pair to the last pair." }, { "code": null, "e": 446, "s": 395, "text": "We can draw Polygon in java applet by three ways :" }, { "code": null, "e": 3857, "s": 446, "text": "drawPolygon(int[] x, int[] y, int numberofpoints) : draws a polygon with the given set of x and y points.// Java program to draw polygon using// drawPolygon(int[] x, int[] y, int numberofpoints)// functionimport java.awt.*;import javax.swing.*; public class poly extends JApplet { // called when applet is started public void init() { // set the size of applet to 300, 300 setSize(200, 200); show(); } // invoked when applet is started public void start() { } // invoked when applet is closed public void stop() { } public void paint(Graphics g) { // x coordinates of vertices int x[] = { 10, 30, 40, 50, 110, 140 }; // y coordinates of vertices int y[] = { 140, 110, 50, 40, 30, 10 }; // number of vertices int numberofpoints = 6; // set the color of line drawn to blue g.setColor(Color.blue); // draw the polygon using drawPolygon function g.drawPolygon(x, y, numberofpoints); }}Output :drawPolygon(Polygon p) : draws a polygon with the given object of Polygon class.// Java program to draw polygon// using drawPolygon(Polygon p)// functionimport java.awt.*;import javax.swing.*; public class poly extends JApplet { // called when applet is started public void init() { // set the size of applet to 300, 300 setSize(200, 200); show(); } // invoked when applet is started public void start() { } // invoked when applet is closed public void stop() { } public void paint(Graphics g) { // x coordinates of vertices int x[] = { 10, 30, 40, 50, 110, 140 }; // y coordinates of vertices int y[] = { 140, 110, 50, 40, 30, 10 }; // number of vertices int numberofpoints = 6; // create a polygon with given x, y coordinates Polygon p = new Polygon(x, y, numberofpoints); // set the color of line drawn to blue g.setColor(Color.blue); // draw the polygon using drawPolygon // function using object of polygon class g.drawPolygon(p); }}Output :drawLine(int x, int y, int x1, int y1) : In this method we would connect adjacent vertices with a line segment and also connect the first and last vertex.// Java code to draw a polygon// using drawLine(int x, int y, int x1, int y1)// functionimport java.awt.*;import javax.swing.*; public class poly extends JApplet { // called when applet is started public void init() { // set the size of applet to 300, 300 setSize(200, 200); show(); } // invoked when applet is started public void start() { } // invoked when applet is closed public void stop() { } public void paint(Graphics g) { // x coordinates of vertices int x[] = { 10, 30, 40, 50, 110, 140 }; // y coordinates of vertices int y[] = { 140, 110, 50, 40, 30, 10 }; // number of vertices int numberofpoints = 6; // set the color of line drawn to blue g.setColor(Color.blue); // join the adjacent vertices for (int i = 0; i < numberofpoints - 1; i++) g.drawLine(x[i], y[i], x[i + 1], y[i + 1]); // join the first and last vertex g.drawLine(x[0], y[0], x[numberofpoints - 1], y[numberofpoints - 1]); }}Output :" }, { "code": null, "e": 4900, "s": 3857, "text": "drawPolygon(int[] x, int[] y, int numberofpoints) : draws a polygon with the given set of x and y points.// Java program to draw polygon using// drawPolygon(int[] x, int[] y, int numberofpoints)// functionimport java.awt.*;import javax.swing.*; public class poly extends JApplet { // called when applet is started public void init() { // set the size of applet to 300, 300 setSize(200, 200); show(); } // invoked when applet is started public void start() { } // invoked when applet is closed public void stop() { } public void paint(Graphics g) { // x coordinates of vertices int x[] = { 10, 30, 40, 50, 110, 140 }; // y coordinates of vertices int y[] = { 140, 110, 50, 40, 30, 10 }; // number of vertices int numberofpoints = 6; // set the color of line drawn to blue g.setColor(Color.blue); // draw the polygon using drawPolygon function g.drawPolygon(x, y, numberofpoints); }}Output :" }, { "code": "// Java program to draw polygon using// drawPolygon(int[] x, int[] y, int numberofpoints)// functionimport java.awt.*;import javax.swing.*; public class poly extends JApplet { // called when applet is started public void init() { // set the size of applet to 300, 300 setSize(200, 200); show(); } // invoked when applet is started public void start() { } // invoked when applet is closed public void stop() { } public void paint(Graphics g) { // x coordinates of vertices int x[] = { 10, 30, 40, 50, 110, 140 }; // y coordinates of vertices int y[] = { 140, 110, 50, 40, 30, 10 }; // number of vertices int numberofpoints = 6; // set the color of line drawn to blue g.setColor(Color.blue); // draw the polygon using drawPolygon function g.drawPolygon(x, y, numberofpoints); }}", "e": 5830, "s": 4900, "text": null }, { "code": null, "e": 5839, "s": 5830, "text": "Output :" }, { "code": null, "e": 6962, "s": 5839, "text": "drawPolygon(Polygon p) : draws a polygon with the given object of Polygon class.// Java program to draw polygon// using drawPolygon(Polygon p)// functionimport java.awt.*;import javax.swing.*; public class poly extends JApplet { // called when applet is started public void init() { // set the size of applet to 300, 300 setSize(200, 200); show(); } // invoked when applet is started public void start() { } // invoked when applet is closed public void stop() { } public void paint(Graphics g) { // x coordinates of vertices int x[] = { 10, 30, 40, 50, 110, 140 }; // y coordinates of vertices int y[] = { 140, 110, 50, 40, 30, 10 }; // number of vertices int numberofpoints = 6; // create a polygon with given x, y coordinates Polygon p = new Polygon(x, y, numberofpoints); // set the color of line drawn to blue g.setColor(Color.blue); // draw the polygon using drawPolygon // function using object of polygon class g.drawPolygon(p); }}Output :" }, { "code": "// Java program to draw polygon// using drawPolygon(Polygon p)// functionimport java.awt.*;import javax.swing.*; public class poly extends JApplet { // called when applet is started public void init() { // set the size of applet to 300, 300 setSize(200, 200); show(); } // invoked when applet is started public void start() { } // invoked when applet is closed public void stop() { } public void paint(Graphics g) { // x coordinates of vertices int x[] = { 10, 30, 40, 50, 110, 140 }; // y coordinates of vertices int y[] = { 140, 110, 50, 40, 30, 10 }; // number of vertices int numberofpoints = 6; // create a polygon with given x, y coordinates Polygon p = new Polygon(x, y, numberofpoints); // set the color of line drawn to blue g.setColor(Color.blue); // draw the polygon using drawPolygon // function using object of polygon class g.drawPolygon(p); }}", "e": 7997, "s": 6962, "text": null }, { "code": null, "e": 8006, "s": 7997, "text": "Output :" }, { "code": null, "e": 9253, "s": 8006, "text": "drawLine(int x, int y, int x1, int y1) : In this method we would connect adjacent vertices with a line segment and also connect the first and last vertex.// Java code to draw a polygon// using drawLine(int x, int y, int x1, int y1)// functionimport java.awt.*;import javax.swing.*; public class poly extends JApplet { // called when applet is started public void init() { // set the size of applet to 300, 300 setSize(200, 200); show(); } // invoked when applet is started public void start() { } // invoked when applet is closed public void stop() { } public void paint(Graphics g) { // x coordinates of vertices int x[] = { 10, 30, 40, 50, 110, 140 }; // y coordinates of vertices int y[] = { 140, 110, 50, 40, 30, 10 }; // number of vertices int numberofpoints = 6; // set the color of line drawn to blue g.setColor(Color.blue); // join the adjacent vertices for (int i = 0; i < numberofpoints - 1; i++) g.drawLine(x[i], y[i], x[i + 1], y[i + 1]); // join the first and last vertex g.drawLine(x[0], y[0], x[numberofpoints - 1], y[numberofpoints - 1]); }}Output :" }, { "code": "// Java code to draw a polygon// using drawLine(int x, int y, int x1, int y1)// functionimport java.awt.*;import javax.swing.*; public class poly extends JApplet { // called when applet is started public void init() { // set the size of applet to 300, 300 setSize(200, 200); show(); } // invoked when applet is started public void start() { } // invoked when applet is closed public void stop() { } public void paint(Graphics g) { // x coordinates of vertices int x[] = { 10, 30, 40, 50, 110, 140 }; // y coordinates of vertices int y[] = { 140, 110, 50, 40, 30, 10 }; // number of vertices int numberofpoints = 6; // set the color of line drawn to blue g.setColor(Color.blue); // join the adjacent vertices for (int i = 0; i < numberofpoints - 1; i++) g.drawLine(x[i], y[i], x[i + 1], y[i + 1]); // join the first and last vertex g.drawLine(x[0], y[0], x[numberofpoints - 1], y[numberofpoints - 1]); }}", "e": 10338, "s": 9253, "text": null }, { "code": null, "e": 10347, "s": 10338, "text": "Output :" }, { "code": null, "e": 10610, "s": 10347, "text": "Note: The above function are a part of java.awt package and belongs to java.awt.Graphics class. Also, these codes might not run in an online compiler please use an offline compiler. The x and y coordinates can be changed by the programmer according to their need" }, { "code": null, "e": 10621, "s": 10610, "text": "java-swing" }, { "code": null, "e": 10626, "s": 10621, "text": "Java" }, { "code": null, "e": 10631, "s": 10626, "text": "Java" } ]
Matplotlib.pyplot.errorbar() in Python
21 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. The errorbar() function in pyplot module of matplotlib library is used to plot y versus x as lines and/or markers with attached errorbars. Syntax: matplotlib.pyplot.errorbar(x, y, yerr=None, xerr=None, fmt=”, ecolor=None, elinewidth=None, capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False, errorevery=1, capthick=None, \*, data=None, \*\*kwargs) Parameters: This method accept the following parameters that are described below: x, y: These parameter are the horizontal and vertical coordinates of the data points. fmt: This parameter is an optional parameter and it contains the string value. xerr, yerr: These parameter contains an array.And the error array should have positive values. ecolor: This parameter is an optional parameter. And it is the color of the errorbar lines with default value NONE. elinewidth: This parameter is also an optional parameter. And it is the linewidth of the errorbar lines with default value NONE. capsize: This parameter is also an optional parameter. And it is the length of the error bar caps in points with default value NONE. barsabove: This parameter is also an optional parameter. It contains boolean value True for plotting errorsbars above the plot symbols.Its default value is False. lolims, uplims, xlolims, xuplims: These parameter are also an optional parameter. They contain boolean values which is used to indicate that a value gives only upper/lower limits. errorevery: This parameter is also an optional parameter. They contain integer values which is used to draws error bars on a subset of the data. Returns: This returns the container and it is comprises of the following: plotline:This returns the Line2D instance of x, y plot markers and/or line. caplines:This returns the tuple of Line2D instances of the error bar caps. barlinecols:This returns the tuple of LineCollection with the horizontal and vertical error ranges. Below examples illustrate the matplotlib.pyplot.errorbar() function in matplotlib.pyplot: Example #1: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt # example dataxval = np.arange(0.1, 4, 0.5)yval = np.exp(-xval) plt.errorbar(xval, yval, xerr = 0.4, yerr = 0.5) plt.title('matplotlib.pyplot.errorbar() function Example')plt.show() Output: Example #2: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt fig = plt.figure()x = np.arange(10)y = 3 * np.sin(x / 20 * np.pi)yerr = np.linspace(0.05, 0.2, 10) plt.errorbar(x, y + 7, yerr = yerr, label ='Line1')plt.errorbar(x, y + 5, yerr = yerr, uplims = True, label ='Line2')plt.errorbar(x, y + 3, yerr = yerr, uplims = True, lolims = True, label ='Line3') upperlimits = [True, False] * 5lowerlimits = [False, True] * 5plt.errorbar(x, y, yerr = yerr, uplims = upperlimits, lolims = lowerlimits, label ='Line4') plt.legend(loc ='upper left') plt.title('matplotlib.pyplot.errorbar()\function Example')plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2020" }, { "code": null, "e": 223, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface." }, { "code": null, "e": 362, "s": 223, "text": "The errorbar() function in pyplot module of matplotlib library is used to plot y versus x as lines and/or markers with attached errorbars." }, { "code": null, "e": 607, "s": 362, "text": "Syntax: matplotlib.pyplot.errorbar(x, y, yerr=None, xerr=None, fmt=”, ecolor=None, elinewidth=None, capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False, errorevery=1, capthick=None, \\*, data=None, \\*\\*kwargs)" }, { "code": null, "e": 689, "s": 607, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 775, "s": 689, "text": "x, y: These parameter are the horizontal and vertical coordinates of the data points." }, { "code": null, "e": 854, "s": 775, "text": "fmt: This parameter is an optional parameter and it contains the string value." }, { "code": null, "e": 949, "s": 854, "text": "xerr, yerr: These parameter contains an array.And the error array should have positive values." }, { "code": null, "e": 1065, "s": 949, "text": "ecolor: This parameter is an optional parameter. And it is the color of the errorbar lines with default value NONE." }, { "code": null, "e": 1194, "s": 1065, "text": "elinewidth: This parameter is also an optional parameter. And it is the linewidth of the errorbar lines with default value NONE." }, { "code": null, "e": 1327, "s": 1194, "text": "capsize: This parameter is also an optional parameter. And it is the length of the error bar caps in points with default value NONE." }, { "code": null, "e": 1490, "s": 1327, "text": "barsabove: This parameter is also an optional parameter. It contains boolean value True for plotting errorsbars above the plot symbols.Its default value is False." }, { "code": null, "e": 1670, "s": 1490, "text": "lolims, uplims, xlolims, xuplims: These parameter are also an optional parameter. They contain boolean values which is used to indicate that a value gives only upper/lower limits." }, { "code": null, "e": 1815, "s": 1670, "text": "errorevery: This parameter is also an optional parameter. They contain integer values which is used to draws error bars on a subset of the data." }, { "code": null, "e": 1889, "s": 1815, "text": "Returns: This returns the container and it is comprises of the following:" }, { "code": null, "e": 1965, "s": 1889, "text": "plotline:This returns the Line2D instance of x, y plot markers and/or line." }, { "code": null, "e": 2040, "s": 1965, "text": "caplines:This returns the tuple of Line2D instances of the error bar caps." }, { "code": null, "e": 2140, "s": 2040, "text": "barlinecols:This returns the tuple of LineCollection with the horizontal and vertical error ranges." }, { "code": null, "e": 2230, "s": 2140, "text": "Below examples illustrate the matplotlib.pyplot.errorbar() function in matplotlib.pyplot:" }, { "code": null, "e": 2242, "s": 2230, "text": "Example #1:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt # example dataxval = np.arange(0.1, 4, 0.5)yval = np.exp(-xval) plt.errorbar(xval, yval, xerr = 0.4, yerr = 0.5) plt.title('matplotlib.pyplot.errorbar() function Example')plt.show()", "e": 2516, "s": 2242, "text": null }, { "code": null, "e": 2524, "s": 2516, "text": "Output:" }, { "code": null, "e": 2536, "s": 2524, "text": "Example #2:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt fig = plt.figure()x = np.arange(10)y = 3 * np.sin(x / 20 * np.pi)yerr = np.linspace(0.05, 0.2, 10) plt.errorbar(x, y + 7, yerr = yerr, label ='Line1')plt.errorbar(x, y + 5, yerr = yerr, uplims = True, label ='Line2')plt.errorbar(x, y + 3, yerr = yerr, uplims = True, lolims = True, label ='Line3') upperlimits = [True, False] * 5lowerlimits = [False, True] * 5plt.errorbar(x, y, yerr = yerr, uplims = upperlimits, lolims = lowerlimits, label ='Line4') plt.legend(loc ='upper left') plt.title('matplotlib.pyplot.errorbar()\\function Example')plt.show()", "e": 3296, "s": 2536, "text": null }, { "code": null, "e": 3304, "s": 3296, "text": "Output:" }, { "code": null, "e": 3322, "s": 3304, "text": "Python-matplotlib" }, { "code": null, "e": 3329, "s": 3322, "text": "Python" } ]
How to include quotes in comma separated column with MySQL?
Let us first create a − mysql> create table DemoTable1407 -> ( -> Name text -> ); Query OK, 0 rows affected (0.51 sec) Insert some records in the table using insert − mysql> insert into DemoTable1407 values('John,Bob'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable1407 values('Carol,David,Adam'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable1407 values('Mike,Sam,Chris'); Query OK, 1 row affected (0.19 sec) Display all records from the table using select − mysql> select * from DemoTable1407; This will produce the following output − +------------------+ | Name | +------------------+ | John,Bob | | Carol,David,Adam | | Mike,Sam,Chris | +------------------+ 3 rows in set (0.00 sec) Here is the query to include quotes in comma separated column with MySQL − mysql> select concat("'", replace(Name, ",", "','"), "'") AS IncludingQuotes from DemoTable1407; This will produce the following output − +------------------------+ | IncludingQuotes | +------------------------+ | 'John','Bob' | | 'Carol','David','Adam' | | 'Mike','Sam','Chris' | +------------------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1211, "s": 1187, "text": "Let us first create a −" }, { "code": null, "e": 1315, "s": 1211, "text": "mysql> create table DemoTable1407\n -> (\n -> Name text\n -> );\nQuery OK, 0 rows affected (0.51 sec)" }, { "code": null, "e": 1363, "s": 1315, "text": "Insert some records in the table using insert −" }, { "code": null, "e": 1644, "s": 1363, "text": "mysql> insert into DemoTable1407 values('John,Bob');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable1407 values('Carol,David,Adam');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable1407 values('Mike,Sam,Chris');\nQuery OK, 1 row affected (0.19 sec)" }, { "code": null, "e": 1694, "s": 1644, "text": "Display all records from the table using select −" }, { "code": null, "e": 1730, "s": 1694, "text": "mysql> select * from DemoTable1407;" }, { "code": null, "e": 1771, "s": 1730, "text": "This will produce the following output −" }, { "code": null, "e": 1943, "s": 1771, "text": "+------------------+\n| Name |\n+------------------+\n| John,Bob |\n| Carol,David,Adam |\n| Mike,Sam,Chris |\n+------------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2018, "s": 1943, "text": "Here is the query to include quotes in comma separated column with MySQL −" }, { "code": null, "e": 2115, "s": 2018, "text": "mysql> select concat(\"'\", replace(Name, \",\", \"','\"), \"'\") AS IncludingQuotes from DemoTable1407;" }, { "code": null, "e": 2156, "s": 2115, "text": "This will produce the following output −" }, { "code": null, "e": 2370, "s": 2156, "text": "+------------------------+\n| IncludingQuotes |\n+------------------------+\n| 'John','Bob' |\n| 'Carol','David','Adam' |\n| 'Mike','Sam','Chris' |\n+------------------------+\n3 rows in set (0.00 sec)" } ]
Wrapping C/C++ for Python using SWIG – Set 1
07 Jul, 2017 There is no doubt that C is faster than Python then how do Python library like Numpy perform huge number crunching job so fast and efficiently? Actually, libraries like Numpy are not completely written in Python instead, some parts of the library are written in C which provides performance boost. After writing code in C, we wrap them in Python code which acts like an interface for those C codes. We can then call C functions using Python syntax where actual processing is done in C behind the scene and the result is returned back as Python object. In this article, we will see how to create Python wrapper for our C program on Linux systems using a software called SWIG. What is SWIG In a nutshell, SWIG is a compiler that takes C/C++ declarations and creates a wrapper needed to access those declarations from other languages like Python, Tcl, Ruby etc.It normally required no changes in existing code and create an interface within a minute. Reasons for creating wrapper In many occasions we need wrappers, following are few of them – Building interpreted interface for existing C programs. Building high-performance C modules for scripting languages It’s huge pain to test huge C programs, so we write wrappers in some scripting languages like Python, where it’s very easy to write test. etc Installing SWIG For downloading SWIG directly from apt repository type following commands – sudo apt-get update sudo apt-get install swig Writing Wrapper using SWIG Consider this piece of C code, having two functions and one global variable – /* file : gfg.c */ #include <stdio.h>#include <math.h> //our header file#include "gfg.h"#define ll long long double myvar = 3.4; // calculate factorialll int fact(ll int n){ if(n <= 1) return 1; else return (n * fact(n-1));} //find modint my_mod(int n, int m){ return(n % m);} Here is our header file gfg.h – long long int fact(long long int n);int my_mod(int n, int m); First, we have to create a SWIG Interface file. This file contains ANSI C function prototypes and variable declaration. Here – The %module directive specifies the name of the module we will use in Python. %{ .. %} block provides a location to insert additional code such as C header files or additional C declaration into the generated wrapper code. %include directive let us include additional files like header files. /* file : gfg.i */ /* name of module to use*/%module gfg%{ /* Every thing in this file is being copied in wrapper file. We include the C header file necessary to compile the interface */ #include "gfg.h" /* variable declaration*/ double myvar;%} /* explicitly list functions and variables to be interfaced */double myvar;long long int fact(long long int n1);int my_mod(int m, int n); /* or if we want to interface all functions then we can simply include header file like this - %include "gfg.h"*/ Now we will create wrapper code using the command like $ swig -target_language interface_file.i $ swig -python gfg.i After executing this command a wrapper code with name “gfg_wrap.c” is created. This files contains a bloated version of our original C code with various error handling code etc. Another file “gfg.py” is generated which is the module we will import in our python script. After this, we have to generate position-independent code which will be used in shared library by compiling “gfg_wrap.c” and “gfg.c” using the following command – $ gcc -c -fpic gfg_wrap.c gfg.c -I/use/include/python2.7 Replace python2.7 with your Python version. This will generate two object files“gfg_wrap.o” and “gfg.o”. In above command – -fpic generate position-independent code (PIC) suitable for use in a shared library, if supported for the target machine. Such code accesses all constant addresses through a global offset table (GOT) Note: If you get error something like “... ‘Python.h’ file not found” then following might be possible causes – You might not have ‘Python.h’ file or You are providing wrong location of ‘Python.h’ file to compiler To get ‘Python.h’ You must install Python-dev using following command – $ sudo apt-get install python-dev To find the correct path of ‘Python.h’ execute following command – $ python-config --cflags This will output something like this –Now replace the path in compilation command with this one for python2.7 or change the version as python3.5 for Python 3.5. Now, at last, we have to link generated objects files together to create a shared object which is analogous to dll files in windows. Use the following command, this will generate a “_gfg.so” shared object file – $ gcc -shared gfg.o gfg_wrap.o -o _gfg.so Now we are ready to test out python wrapper by importing it. Make sure you are in directory having this wrapper file. >>> import gfg >>> res = fact(5) >>> res 120 >>> res = my_mod(5,2) >>> res 1 >>> gfg.cvar.myvar 3.4 Here C variables are accessed as module.cvar.var_name. Compiling and Linking using distutils Instead of typing in commands and figuring out what compilation options are needed to compile files, we can automate this using distutils. Create a setup.py as below – # File : setup.py from distutils.core import setup, Extension#name of modulename = "gfg" #version of moduleversion = "1.0" # specify the name of the extension and source files# required to compile thisext_modules = Extension(name='_gfg',sources=["gfg.i","gfg.c"]) setup(name=name, version=version, ext_modules=[ext_modules]) Now write following commands to compile and install module – $ python setup.py build_ext --inplace It should look something like this on terminal – Possible Alternatives Obviously, SWIG is not the only way for creating wrappers, one can consider following alternatives based on their requirements – Manual Wrapping pyrex ctypes (Built in module) SIP In next article, we will see how to create wrapper for C++ code (OPP) References http://www.swig.org/Doc3.0/Introduction.html This article is contributed by Atul Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. 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. Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jul, 2017" }, { "code": null, "e": 703, "s": 28, "text": "There is no doubt that C is faster than Python then how do Python library like Numpy perform huge number crunching job so fast and efficiently? Actually, libraries like Numpy are not completely written in Python instead, some parts of the library are written in C which provides performance boost. After writing code in C, we wrap them in Python code which acts like an interface for those C codes. We can then call C functions using Python syntax where actual processing is done in C behind the scene and the result is returned back as Python object. In this article, we will see how to create Python wrapper for our C program on Linux systems using a software called SWIG." }, { "code": null, "e": 716, "s": 703, "text": "What is SWIG" }, { "code": null, "e": 976, "s": 716, "text": "In a nutshell, SWIG is a compiler that takes C/C++ declarations and creates a wrapper needed to access those declarations from other languages like Python, Tcl, Ruby etc.It normally required no changes in existing code and create an interface within a minute." }, { "code": null, "e": 1005, "s": 976, "text": "Reasons for creating wrapper" }, { "code": null, "e": 1069, "s": 1005, "text": "In many occasions we need wrappers, following are few of them –" }, { "code": null, "e": 1125, "s": 1069, "text": "Building interpreted interface for existing C programs." }, { "code": null, "e": 1185, "s": 1125, "text": "Building high-performance C modules for scripting languages" }, { "code": null, "e": 1327, "s": 1185, "text": "It’s huge pain to test huge C programs, so we write wrappers in some scripting languages like Python, where it’s very easy to write test. etc" }, { "code": null, "e": 1343, "s": 1327, "text": "Installing SWIG" }, { "code": null, "e": 1419, "s": 1343, "text": "For downloading SWIG directly from apt repository type following commands –" }, { "code": null, "e": 1466, "s": 1419, "text": "sudo apt-get update\nsudo apt-get install swig\n" }, { "code": null, "e": 1493, "s": 1466, "text": "Writing Wrapper using SWIG" }, { "code": null, "e": 1571, "s": 1493, "text": "Consider this piece of C code, having two functions and one global variable –" }, { "code": "/* file : gfg.c */ #include <stdio.h>#include <math.h> //our header file#include \"gfg.h\"#define ll long long double myvar = 3.4; // calculate factorialll int fact(ll int n){ if(n <= 1) return 1; else return (n * fact(n-1));} //find modint my_mod(int n, int m){ return(n % m);}", "e": 1874, "s": 1571, "text": null }, { "code": null, "e": 1906, "s": 1874, "text": "Here is our header file gfg.h –" }, { "code": "long long int fact(long long int n);int my_mod(int n, int m);", "e": 1968, "s": 1906, "text": null }, { "code": null, "e": 2095, "s": 1968, "text": "First, we have to create a SWIG Interface file. This file contains ANSI C function prototypes and variable declaration. Here –" }, { "code": null, "e": 2173, "s": 2095, "text": "The %module directive specifies the name of the module we will use in Python." }, { "code": null, "e": 2318, "s": 2173, "text": "%{ .. %} block provides a location to insert additional code such as C header files or additional C declaration into the generated wrapper code." }, { "code": null, "e": 2388, "s": 2318, "text": "%include directive let us include additional files like header files." }, { "code": "/* file : gfg.i */ /* name of module to use*/%module gfg%{ /* Every thing in this file is being copied in wrapper file. We include the C header file necessary to compile the interface */ #include \"gfg.h\" /* variable declaration*/ double myvar;%} /* explicitly list functions and variables to be interfaced */double myvar;long long int fact(long long int n1);int my_mod(int m, int n); /* or if we want to interface all functions then we can simply include header file like this - %include \"gfg.h\"*/", "e": 2917, "s": 2388, "text": null }, { "code": null, "e": 3013, "s": 2917, "text": "Now we will create wrapper code using the command like $ swig -target_language interface_file.i" }, { "code": null, "e": 3035, "s": 3013, "text": "$ swig -python gfg.i\n" }, { "code": null, "e": 3305, "s": 3035, "text": "After executing this command a wrapper code with name “gfg_wrap.c” is created. This files contains a bloated version of our original C code with various error handling code etc. Another file “gfg.py” is generated which is the module we will import in our python script." }, { "code": null, "e": 3468, "s": 3305, "text": "After this, we have to generate position-independent code which will be used in shared library by compiling “gfg_wrap.c” and “gfg.c” using the following command –" }, { "code": null, "e": 3526, "s": 3468, "text": "$ gcc -c -fpic gfg_wrap.c gfg.c -I/use/include/python2.7\n" }, { "code": null, "e": 3650, "s": 3526, "text": "Replace python2.7 with your Python version. This will generate two object files“gfg_wrap.o” and “gfg.o”. In above command –" }, { "code": null, "e": 3850, "s": 3650, "text": "-fpic generate position-independent code (PIC) suitable for use in a shared library, if supported for the target machine. Such code accesses all constant addresses through a global offset table (GOT)" }, { "code": null, "e": 3962, "s": 3850, "text": "Note: If you get error something like “... ‘Python.h’ file not found” then following might be possible causes –" }, { "code": null, "e": 4000, "s": 3962, "text": "You might not have ‘Python.h’ file or" }, { "code": null, "e": 4064, "s": 4000, "text": "You are providing wrong location of ‘Python.h’ file to compiler" }, { "code": null, "e": 4136, "s": 4064, "text": "To get ‘Python.h’ You must install Python-dev using following command –" }, { "code": null, "e": 4171, "s": 4136, "text": "$ sudo apt-get install python-dev\n" }, { "code": null, "e": 4238, "s": 4171, "text": "To find the correct path of ‘Python.h’ execute following command –" }, { "code": null, "e": 4264, "s": 4238, "text": "$ python-config --cflags\n" }, { "code": null, "e": 4425, "s": 4264, "text": "This will output something like this –Now replace the path in compilation command with this one for python2.7 or change the version as python3.5 for Python 3.5." }, { "code": null, "e": 4637, "s": 4425, "text": "Now, at last, we have to link generated objects files together to create a shared object which is analogous to dll files in windows. Use the following command, this will generate a “_gfg.so” shared object file –" }, { "code": null, "e": 4680, "s": 4637, "text": "$ gcc -shared gfg.o gfg_wrap.o -o _gfg.so\n" }, { "code": null, "e": 4798, "s": 4680, "text": "Now we are ready to test out python wrapper by importing it. Make sure you are in directory having this wrapper file." }, { "code": null, "e": 4899, "s": 4798, "text": ">>> import gfg\n>>> res = fact(5)\n>>> res\n120\n>>> res = my_mod(5,2)\n>>> res\n1\n>>> gfg.cvar.myvar\n3.4\n" }, { "code": null, "e": 4954, "s": 4899, "text": "Here C variables are accessed as module.cvar.var_name." }, { "code": null, "e": 4992, "s": 4954, "text": "Compiling and Linking using distutils" }, { "code": null, "e": 5160, "s": 4992, "text": "Instead of typing in commands and figuring out what compilation options are needed to compile files, we can automate this using distutils. Create a setup.py as below –" }, { "code": "# File : setup.py from distutils.core import setup, Extension#name of modulename = \"gfg\" #version of moduleversion = \"1.0\" # specify the name of the extension and source files# required to compile thisext_modules = Extension(name='_gfg',sources=[\"gfg.i\",\"gfg.c\"]) setup(name=name, version=version, ext_modules=[ext_modules])", "e": 5500, "s": 5160, "text": null }, { "code": null, "e": 5561, "s": 5500, "text": "Now write following commands to compile and install module –" }, { "code": null, "e": 5600, "s": 5561, "text": "$ python setup.py build_ext --inplace\n" }, { "code": null, "e": 5649, "s": 5600, "text": "It should look something like this on terminal –" }, { "code": null, "e": 5671, "s": 5649, "text": "Possible Alternatives" }, { "code": null, "e": 5800, "s": 5671, "text": "Obviously, SWIG is not the only way for creating wrappers, one can consider following alternatives based on their requirements –" }, { "code": null, "e": 5816, "s": 5800, "text": "Manual Wrapping" }, { "code": null, "e": 5822, "s": 5816, "text": "pyrex" }, { "code": null, "e": 5847, "s": 5822, "text": "ctypes (Built in module)" }, { "code": null, "e": 5851, "s": 5847, "text": "SIP" }, { "code": null, "e": 5921, "s": 5851, "text": "In next article, we will see how to create wrapper for C++ code (OPP)" }, { "code": null, "e": 5932, "s": 5921, "text": "References" }, { "code": null, "e": 5977, "s": 5932, "text": "http://www.swig.org/Doc3.0/Introduction.html" }, { "code": null, "e": 6275, "s": 5977, "text": "This article is contributed by Atul Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 6400, "s": 6275, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 6407, "s": 6400, "text": "Python" } ]
Scala String toUpperCase() method with example
29 Oct, 2019 The toUpperCase() method is utilized to convert all the characters of the stated string to uppercase. Method Definition: String toUpperCase() Return Type: It returns the resultant string after converting its all the character to uppercase. Example: 1# // Scala program of toUpperCase()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying toUpperCase method val result = "GeeksforGeeks".toUpperCase() // Displays output println(result) }} GEEKSFORGEEKS Example: 2# // Scala program of toUpperCase()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying toUpperCase method val result = "nid#!".toUpperCase() // Displays output println(result) }} NID#! Scala Scala-Method Scala-Strings Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Class and Object in Scala Scala Tutorial – Learn Scala with Step By Step Guide Scala Lists Scala String substring() method with example Scala | Arrays Operators in Scala Scala Constructors Enumeration in Scala Lambda Expression in Scala How to Install Scala with VSCode?
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Oct, 2019" }, { "code": null, "e": 130, "s": 28, "text": "The toUpperCase() method is utilized to convert all the characters of the stated string to uppercase." }, { "code": null, "e": 170, "s": 130, "text": "Method Definition: String toUpperCase()" }, { "code": null, "e": 268, "s": 170, "text": "Return Type: It returns the resultant string after converting its all the character to uppercase." }, { "code": null, "e": 280, "s": 268, "text": "Example: 1#" }, { "code": "// Scala program of toUpperCase()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying toUpperCase method val result = \"GeeksforGeeks\".toUpperCase() // Displays output println(result) }} ", "e": 578, "s": 280, "text": null }, { "code": null, "e": 593, "s": 578, "text": "GEEKSFORGEEKS\n" }, { "code": null, "e": 605, "s": 593, "text": "Example: 2#" }, { "code": "// Scala program of toUpperCase()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying toUpperCase method val result = \"nid#!\".toUpperCase() // Displays output println(result) }} ", "e": 895, "s": 605, "text": null }, { "code": null, "e": 902, "s": 895, "text": "NID#!\n" }, { "code": null, "e": 908, "s": 902, "text": "Scala" }, { "code": null, "e": 921, "s": 908, "text": "Scala-Method" }, { "code": null, "e": 935, "s": 921, "text": "Scala-Strings" }, { "code": null, "e": 941, "s": 935, "text": "Scala" }, { "code": null, "e": 1039, "s": 941, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1065, "s": 1039, "text": "Class and Object in Scala" }, { "code": null, "e": 1118, "s": 1065, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 1130, "s": 1118, "text": "Scala Lists" }, { "code": null, "e": 1175, "s": 1130, "text": "Scala String substring() method with example" }, { "code": null, "e": 1190, "s": 1175, "text": "Scala | Arrays" }, { "code": null, "e": 1209, "s": 1190, "text": "Operators in Scala" }, { "code": null, "e": 1228, "s": 1209, "text": "Scala Constructors" }, { "code": null, "e": 1249, "s": 1228, "text": "Enumeration in Scala" }, { "code": null, "e": 1276, "s": 1249, "text": "Lambda Expression in Scala" } ]
How to Bind Multiple Commands to Tkinter Button?
26 Dec, 2020 The button widget in Tkinter provides a way to interact with the application. The user presses a button to perform certain actions that are attached to that button. In general, we user provides a single action to a button but what if the user wants to attach more than one action to a button. In this article, we are going to see how we can bind more than one action/command to a single button. To create a button in Tkinter please follow the below syntax. Syntax: Button(master, text=”Button”, command=function, options, ...) Parameters: master: refers to the top-level window in which button is placed text: Text to show button command: An action which will be called on button pressThere are other options as well but they are rarely used. compound: To show both image and text image: To show image pady: To provide vertical padding padx: To provide horizontal padding Method 1: By using the lambda function and list In this method, we are going to pass a list of functions to lambda, and then that lambda will be passed to command. Python3 # Import tkinter and Button Widgetfrom tkinter import Tkfrom tkinter.ttk import Button # Demo function 1def fun1(): print("Function 1") # Demo function 2def fun2(): print("Function 2") if __name__ == "__main__": # Creating top-level window master = Tk() # Setting window title master.title("Bind multiple function to Button") # Setting window Dimensions master.geometry("400x250") # Creating a button with more than one command using lambda button = Button(master, text="Button", command=lambda: [fun1(), fun2()]) # Attaching button to the top-level window # Always remember to attach your widgets to the top-level button.pack() # Mainloop that will run forever master.mainloop() Output: Method 2: By creating our own generic function that will call functions for us. Python3 # Import tkinter and Button Widgetfrom tkinter import Tkfrom tkinter.ttk import Button # funcs parameter will have the reference# of all the functions that are passed as arguments i.e "fun1" and "fun2"def combine_funcs(*funcs): # this function will call the passed functions # with the arguments that are passed to the functions def inner_combined_func(*args, **kwargs): for f in funcs: # Calling functions with arguments, if any f(*args, **kwargs) # returning the reference of inner_combined_func # this reference will have the called result of all # the functions that are passed to the combined_funcs return inner_combined_func # Demo function 1def fun1(): print("Function 1") # Demo function 2def fun2(): print("Function 2") if __name__ == "__main__": # Creating top-level window master = Tk() # Setting window title master.title("Bind multiple function to Button") # Setting window Dimensions master.geometry("400x250") # Creating a button with more than one # command our own generic function button = Button(master, text="Button", command=combine_funcs(fun1, fun2)) # Attaching button to the top-level window # Always remember to attach your widgets to the top-level button.pack() # Mainloop that will run forever master.mainloop() In the above method, you may be wondering how we are going to pass arguments to fun1 and fun2 because if we do the following combine_funcs(fun1(arguments), fun2(arguments)) It will immediately call the functions as soon as the application runs, but we want that these functions should be called only when the button is pressed. So the answer is simple if you want to pass arguments to fun1 or fun2 use the below syntax: combine_funcs(lambda: fun1(arguments), lambda: fun2(arguments)) Let see the below example where we actually have parameters to fun1 and fun2. Python3 # Import tkinter and Button Widgetfrom tkinter import Tkfrom tkinter.ttk import Button # funcs parameter will have the reference# of all the functions that are # passed as arguments i.e "fun1" and "fun2"def combine_funcs(*funcs): # this function will call the passed functions # with the arguments that are passed to the functions def inner_combined_func(*args, **kwargs): for f in funcs: # Calling functions with arguments, if any f(*args, **kwargs) # returning the reference of inner_combined_func # this reference will have the called result of all # the functions that are passed to the combined_funcs return inner_combined_func # Demo function 1 with paramsdef fun1(param): print("Function 1 {}".format(param)) # Demo function 2 with paramsdef fun2(param): print("Function 2 {}".format(param)) if __name__ == "__main__": # Creating top-level window master = Tk() # Setting window title master.title("Bind multiple function to Button") # Setting window Dimensions master.geometry("400x250") # Creating a button with more than # one command our own generic function button = Button(master, text="Button", # Passing arguments to "fun1" and "fun2" command=combine_funcs(lambda: fun1("Function 1 PARAM"), lambda: fun2("Function 2 PARAM"))) # Attaching button to the top-level window # Always remember to attach your widgets to the top-level button.pack() # Mainloop that will run forever master.mainloop() Output: Picked Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Dec, 2020" }, { "code": null, "e": 321, "s": 28, "text": "The button widget in Tkinter provides a way to interact with the application. The user presses a button to perform certain actions that are attached to that button. In general, we user provides a single action to a button but what if the user wants to attach more than one action to a button." }, { "code": null, "e": 423, "s": 321, "text": "In this article, we are going to see how we can bind more than one action/command to a single button." }, { "code": null, "e": 485, "s": 423, "text": "To create a button in Tkinter please follow the below syntax." }, { "code": null, "e": 555, "s": 485, "text": "Syntax: Button(master, text=”Button”, command=function, options, ...)" }, { "code": null, "e": 567, "s": 555, "text": "Parameters:" }, { "code": null, "e": 632, "s": 567, "text": "master: refers to the top-level window in which button is placed" }, { "code": null, "e": 658, "s": 632, "text": "text: Text to show button" }, { "code": null, "e": 771, "s": 658, "text": "command: An action which will be called on button pressThere are other options as well but they are rarely used." }, { "code": null, "e": 809, "s": 771, "text": "compound: To show both image and text" }, { "code": null, "e": 830, "s": 809, "text": "image: To show image" }, { "code": null, "e": 864, "s": 830, "text": "pady: To provide vertical padding" }, { "code": null, "e": 900, "s": 864, "text": "padx: To provide horizontal padding" }, { "code": null, "e": 948, "s": 900, "text": "Method 1: By using the lambda function and list" }, { "code": null, "e": 1064, "s": 948, "text": "In this method, we are going to pass a list of functions to lambda, and then that lambda will be passed to command." }, { "code": null, "e": 1072, "s": 1064, "text": "Python3" }, { "code": "# Import tkinter and Button Widgetfrom tkinter import Tkfrom tkinter.ttk import Button # Demo function 1def fun1(): print(\"Function 1\") # Demo function 2def fun2(): print(\"Function 2\") if __name__ == \"__main__\": # Creating top-level window master = Tk() # Setting window title master.title(\"Bind multiple function to Button\") # Setting window Dimensions master.geometry(\"400x250\") # Creating a button with more than one command using lambda button = Button(master, text=\"Button\", command=lambda: [fun1(), fun2()]) # Attaching button to the top-level window # Always remember to attach your widgets to the top-level button.pack() # Mainloop that will run forever master.mainloop()", "e": 1816, "s": 1072, "text": null }, { "code": null, "e": 1824, "s": 1816, "text": "Output:" }, { "code": null, "e": 1904, "s": 1824, "text": "Method 2: By creating our own generic function that will call functions for us." }, { "code": null, "e": 1912, "s": 1904, "text": "Python3" }, { "code": "# Import tkinter and Button Widgetfrom tkinter import Tkfrom tkinter.ttk import Button # funcs parameter will have the reference# of all the functions that are passed as arguments i.e \"fun1\" and \"fun2\"def combine_funcs(*funcs): # this function will call the passed functions # with the arguments that are passed to the functions def inner_combined_func(*args, **kwargs): for f in funcs: # Calling functions with arguments, if any f(*args, **kwargs) # returning the reference of inner_combined_func # this reference will have the called result of all # the functions that are passed to the combined_funcs return inner_combined_func # Demo function 1def fun1(): print(\"Function 1\") # Demo function 2def fun2(): print(\"Function 2\") if __name__ == \"__main__\": # Creating top-level window master = Tk() # Setting window title master.title(\"Bind multiple function to Button\") # Setting window Dimensions master.geometry(\"400x250\") # Creating a button with more than one # command our own generic function button = Button(master, text=\"Button\", command=combine_funcs(fun1, fun2)) # Attaching button to the top-level window # Always remember to attach your widgets to the top-level button.pack() # Mainloop that will run forever master.mainloop()", "e": 3289, "s": 1912, "text": null }, { "code": null, "e": 3414, "s": 3289, "text": "In the above method, you may be wondering how we are going to pass arguments to fun1 and fun2 because if we do the following" }, { "code": null, "e": 3462, "s": 3414, "text": "combine_funcs(fun1(arguments), fun2(arguments))" }, { "code": null, "e": 3709, "s": 3462, "text": "It will immediately call the functions as soon as the application runs, but we want that these functions should be called only when the button is pressed. So the answer is simple if you want to pass arguments to fun1 or fun2 use the below syntax:" }, { "code": null, "e": 3773, "s": 3709, "text": "combine_funcs(lambda: fun1(arguments), lambda: fun2(arguments))" }, { "code": null, "e": 3851, "s": 3773, "text": "Let see the below example where we actually have parameters to fun1 and fun2." }, { "code": null, "e": 3859, "s": 3851, "text": "Python3" }, { "code": "# Import tkinter and Button Widgetfrom tkinter import Tkfrom tkinter.ttk import Button # funcs parameter will have the reference# of all the functions that are # passed as arguments i.e \"fun1\" and \"fun2\"def combine_funcs(*funcs): # this function will call the passed functions # with the arguments that are passed to the functions def inner_combined_func(*args, **kwargs): for f in funcs: # Calling functions with arguments, if any f(*args, **kwargs) # returning the reference of inner_combined_func # this reference will have the called result of all # the functions that are passed to the combined_funcs return inner_combined_func # Demo function 1 with paramsdef fun1(param): print(\"Function 1 {}\".format(param)) # Demo function 2 with paramsdef fun2(param): print(\"Function 2 {}\".format(param)) if __name__ == \"__main__\": # Creating top-level window master = Tk() # Setting window title master.title(\"Bind multiple function to Button\") # Setting window Dimensions master.geometry(\"400x250\") # Creating a button with more than # one command our own generic function button = Button(master, text=\"Button\", # Passing arguments to \"fun1\" and \"fun2\" command=combine_funcs(lambda: fun1(\"Function 1 PARAM\"), lambda: fun2(\"Function 2 PARAM\"))) # Attaching button to the top-level window # Always remember to attach your widgets to the top-level button.pack() # Mainloop that will run forever master.mainloop()", "e": 5509, "s": 3859, "text": null }, { "code": null, "e": 5517, "s": 5509, "text": "Output:" }, { "code": null, "e": 5524, "s": 5517, "text": "Picked" }, { "code": null, "e": 5539, "s": 5524, "text": "Python-tkinter" }, { "code": null, "e": 5546, "s": 5539, "text": "Python" } ]
How to get the classes of all columns in a dataframe in R ?
16 May, 2021 In this article, we will discuss how to find all the classes of the dataframe in R Programming Language. There are two methods to find the classes of columns in the dataframe. Using str() function Using lapply() function Method1 : Using str() function This function will return the class and value of the input data. Syntax: str(dataframe_name) Example: R program to create a dataframe and apply str() function. R # create vector with integer # elementsa = c(7058, 7059, 7072, 7075) # create vector with floating# point elementsc = c(98.00, 92.56, 90.00, 95.00) # pass these vectors as inputs to# the dataframedata = data.frame( id = a, percentage = c)print(data) # apply str function to get columns # class of the dataframeprint(str(data)) Output: id percentage 1 7058 98.00 2 7059 92.56 3 7072 90.00 4 7075 95.00 'data.frame': 4 obs. of 2 variables: $ id : num 7058 7059 7072 7075 $ percentage: num 98 92.6 90 95 NULL Method 2: Using lapply() function lapply() function will result only the class of the dataframe column Syntax: lapply(data_frame_name,class) where: data_frame_name is the dataframe. R program to create the dataframe and use lapply() function to find a class. R # create vector with integer # elementsa = c(7058, 7059, 7072, 7075) # create vector with string elementsb = c("sravan", "jyothika", "harsha", "deepika") # create vector with floating point# elementsc = c(98.00, 92.56, 90.00, 95.00) # pass these vectors as inputs to # the dataframedata = data.frame(id = a, names = b, percentage = c)print(data) # lapply function to get columns class # of the dataframeprint(lapply(data, class)) Output: id names percentage 1 7058 sravan 98.00 2 7059 jyothika 92.56 3 7072 harsha 90.00 4 7075 deepika 95.00 $id [1] "numeric" $names [1] "factor" $percentage [1] "numeric" Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 May, 2021" }, { "code": null, "e": 133, "s": 28, "text": "In this article, we will discuss how to find all the classes of the dataframe in R Programming Language." }, { "code": null, "e": 204, "s": 133, "text": "There are two methods to find the classes of columns in the dataframe." }, { "code": null, "e": 225, "s": 204, "text": "Using str() function" }, { "code": null, "e": 249, "s": 225, "text": "Using lapply() function" }, { "code": null, "e": 280, "s": 249, "text": "Method1 : Using str() function" }, { "code": null, "e": 345, "s": 280, "text": "This function will return the class and value of the input data." }, { "code": null, "e": 373, "s": 345, "text": "Syntax: str(dataframe_name)" }, { "code": null, "e": 440, "s": 373, "text": "Example: R program to create a dataframe and apply str() function." }, { "code": null, "e": 442, "s": 440, "text": "R" }, { "code": "# create vector with integer # elementsa = c(7058, 7059, 7072, 7075) # create vector with floating# point elementsc = c(98.00, 92.56, 90.00, 95.00) # pass these vectors as inputs to# the dataframedata = data.frame( id = a, percentage = c)print(data) # apply str function to get columns # class of the dataframeprint(str(data))", "e": 772, "s": 442, "text": null }, { "code": null, "e": 780, "s": 772, "text": "Output:" }, { "code": null, "e": 990, "s": 780, "text": " id percentage\n1 7058 98.00\n2 7059 92.56\n3 7072 90.00\n4 7075 95.00\n'data.frame': 4 obs. of 2 variables:\n $ id : num 7058 7059 7072 7075\n $ percentage: num 98 92.6 90 95\nNULL" }, { "code": null, "e": 1024, "s": 990, "text": "Method 2: Using lapply() function" }, { "code": null, "e": 1093, "s": 1024, "text": "lapply() function will result only the class of the dataframe column" }, { "code": null, "e": 1131, "s": 1093, "text": "Syntax: lapply(data_frame_name,class)" }, { "code": null, "e": 1172, "s": 1131, "text": "where: data_frame_name is the dataframe." }, { "code": null, "e": 1249, "s": 1172, "text": "R program to create the dataframe and use lapply() function to find a class." }, { "code": null, "e": 1251, "s": 1249, "text": "R" }, { "code": "# create vector with integer # elementsa = c(7058, 7059, 7072, 7075) # create vector with string elementsb = c(\"sravan\", \"jyothika\", \"harsha\", \"deepika\") # create vector with floating point# elementsc = c(98.00, 92.56, 90.00, 95.00) # pass these vectors as inputs to # the dataframedata = data.frame(id = a, names = b, percentage = c)print(data) # lapply function to get columns class # of the dataframeprint(lapply(data, class))", "e": 1685, "s": 1251, "text": null }, { "code": null, "e": 1693, "s": 1685, "text": "Output:" }, { "code": null, "e": 1894, "s": 1693, "text": " id names percentage\n1 7058 sravan 98.00\n2 7059 jyothika 92.56\n3 7072 harsha 90.00\n4 7075 deepika 95.00\n$id\n[1] \"numeric\"\n\n$names\n[1] \"factor\"\n\n$percentage\n[1] \"numeric\"" }, { "code": null, "e": 1901, "s": 1894, "text": "Picked" }, { "code": null, "e": 1922, "s": 1901, "text": "R DataFrame-Programs" }, { "code": null, "e": 1934, "s": 1922, "text": "R-DataFrame" }, { "code": null, "e": 1945, "s": 1934, "text": "R Language" }, { "code": null, "e": 1956, "s": 1945, "text": "R Programs" } ]
How to convert an HTML element or document into image ?
18 Jul, 2019 This article is going to tell and guide the users to convert a div element into an image using AngularJS. The user will be generating an image from the webpage and also be able to convert a particular part of the HTML page into the picture. Also, the user needs an HTML tag and html2canvas JavaScript library. By using this, we can create the pictures i.e. converting the HTML page to an image in PNG or JPEG formats. Also handling the ul, li and the required div tag to the image format. To summarize it, the html2canvas library will be rendering the HTML page to the preferred image format that is mentioned by the user. It means that the user will be able to create the screenshot of the div or any element of the WebPage. Approach: There are two buttons in the web-page, one used for preview the image of web-page and other button is used to download the image of web-page. Convert an html page into image using html2canvas JavaScript library. When user click on preview button, the html2canvas() function called and this function also call another function which append the preview of canvas image. When user click on Download button, then first change the document into image format and then start downloading it instead of displaying the image. Example: <!DOCTYPE html><html> <head> <title> How to convert an HTML element or document into image ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"> </script> <script src="https://files.codepedia.info/files/uploads/iScripts/html2canvas.js"> </script></head> <body> <center> <h2 style="color:green"> GeeksForGeeks </h2> <h2 style="color:purple"> Convert div to image </h2> <div id="html-content-holder" style="background-color: #F0F0F1; color: #00cc65; width: 500px;padding-left: 25px; padding-top: 10px;"> <strong> GeeksForGeeks </strong> <hr/> <h3 style="color: #3e4b51;"> ABOUT US </h3> <p style="color: #3e4b51;"> <b>GeeksForGeeks</b> is a portal and a forum for many tutorials focusing on Programming ASP.Net, C#, jQuery, AngularJs, Gridview, MVC, Ajax, Javascript, XML, MS SQL-Server, NodeJs, Web Design, Software and much more </p> <p style="color: #3e4b51;"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. </p> </div> <input id="btn-Preview-Image" type="button" value="Preview" /> <a id="btn-Convert-Html2Image" href="#"> Download </a> <br/> <h3>Preview :</h3> <div id="previewImage"></div> <script> $(document).ready(function() { // Global variable var element = $("#html-content-holder"); // Global variable var getCanvas; $("#btn-Preview-Image").on('click', function() { html2canvas(element, { onrendered: function(canvas) { $("#previewImage").append(canvas); getCanvas = canvas; } }); }); $("#btn-Convert-Html2Image").on('click', function() { var imgageData = getCanvas.toDataURL("image/png"); // Now browser starts downloading // it instead of just showing it var newData = imgageData.replace( /^data:image\/png/, "data:application/octet-stream"); $("#btn-Convert-Html2Image").attr( "download", "GeeksForGeeks.png").attr( "href", newData); }); }); </script> </center></body> </html> Output: HTML-Misc Picked Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Jul, 2019" }, { "code": null, "e": 778, "s": 52, "text": "This article is going to tell and guide the users to convert a div element into an image using AngularJS. The user will be generating an image from the webpage and also be able to convert a particular part of the HTML page into the picture. Also, the user needs an HTML tag and html2canvas JavaScript library. By using this, we can create the pictures i.e. converting the HTML page to an image in PNG or JPEG formats. Also handling the ul, li and the required div tag to the image format. To summarize it, the html2canvas library will be rendering the HTML page to the preferred image format that is mentioned by the user. It means that the user will be able to create the screenshot of the div or any element of the WebPage." }, { "code": null, "e": 788, "s": 778, "text": "Approach:" }, { "code": null, "e": 930, "s": 788, "text": "There are two buttons in the web-page, one used for preview the image of web-page and other button is used to download the image of web-page." }, { "code": null, "e": 1000, "s": 930, "text": "Convert an html page into image using html2canvas JavaScript library." }, { "code": null, "e": 1156, "s": 1000, "text": "When user click on preview button, the html2canvas() function called and this function also call another function which append the preview of canvas image." }, { "code": null, "e": 1304, "s": 1156, "text": "When user click on Download button, then first change the document into image format and then start downloading it instead of displaying the image." }, { "code": null, "e": 1313, "s": 1304, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to convert an HTML element or document into image ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js\"> </script> <script src=\"https://files.codepedia.info/files/uploads/iScripts/html2canvas.js\"> </script></head> <body> <center> <h2 style=\"color:green\"> GeeksForGeeks </h2> <h2 style=\"color:purple\"> Convert div to image </h2> <div id=\"html-content-holder\" style=\"background-color: #F0F0F1; color: #00cc65; width: 500px;padding-left: 25px; padding-top: 10px;\"> <strong> GeeksForGeeks </strong> <hr/> <h3 style=\"color: #3e4b51;\"> ABOUT US </h3> <p style=\"color: #3e4b51;\"> <b>GeeksForGeeks</b> is a portal and a forum for many tutorials focusing on Programming ASP.Net, C#, jQuery, AngularJs, Gridview, MVC, Ajax, Javascript, XML, MS SQL-Server, NodeJs, Web Design, Software and much more </p> <p style=\"color: #3e4b51;\"> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. </p> </div> <input id=\"btn-Preview-Image\" type=\"button\" value=\"Preview\" /> <a id=\"btn-Convert-Html2Image\" href=\"#\"> Download </a> <br/> <h3>Preview :</h3> <div id=\"previewImage\"></div> <script> $(document).ready(function() { // Global variable var element = $(\"#html-content-holder\"); // Global variable var getCanvas; $(\"#btn-Preview-Image\").on('click', function() { html2canvas(element, { onrendered: function(canvas) { $(\"#previewImage\").append(canvas); getCanvas = canvas; } }); }); $(\"#btn-Convert-Html2Image\").on('click', function() { var imgageData = getCanvas.toDataURL(\"image/png\"); // Now browser starts downloading // it instead of just showing it var newData = imgageData.replace( /^data:image\\/png/, \"data:application/octet-stream\"); $(\"#btn-Convert-Html2Image\").attr( \"download\", \"GeeksForGeeks.png\").attr( \"href\", newData); }); }); </script> </center></body> </html> ", "e": 4280, "s": 1313, "text": null }, { "code": null, "e": 4288, "s": 4280, "text": "Output:" }, { "code": null, "e": 4298, "s": 4288, "text": "HTML-Misc" }, { "code": null, "e": 4305, "s": 4298, "text": "Picked" }, { "code": null, "e": 4322, "s": 4305, "text": "Web Technologies" }, { "code": null, "e": 4349, "s": 4322, "text": "Web technologies Questions" } ]
ctype.h(<cctype>) library in C/C++ with Examples
16 Dec, 2019 As string.h header file contains inbuilt functions to handle Strings in C/C++, the ctype.h/<cctype> contains inbuilt functions to handle characters in C/C++ respectively. Characters are of two types: Printable Characters: The characters that are displayed on the terminal.Control Characters: The characters that are initiated to perform a specific operation. Printable Characters: The characters that are displayed on the terminal. Control Characters: The characters that are initiated to perform a specific operation. The arguments passed to character functions should be of integer type. If we pass characters instead of an integer, the characters are typecasted into integers(corresponding ASCII values) and those integers are passed as arguments. The below functions under ctype.h/<cctype> header file are applied on normal characters. Wide character functions are used for the characters of type wchar_t. Below are examples to implement some of the above functions: Example 1: The following program identifies the number of alphabets, digits:#include <stdio.h> // Header file containing character functions#include <ctype.h> void identify_alpha_numeric(char a[]){ int count_alpha = 0, count_digit = 0; for (int i = 0; a[i] != '\0'; i++) { // To check the character is alphabet if (isalpha(a[i])) count_alpha++; // To check the character is a digit if (isdigit(a[i])) count_digit++; } printf("The number of alphabets are %d\n", count_alpha); printf("The number of digits are %d", count_digit);} int main(){ // String Initialization char a[] = "Hi 1234, " " Welcome to GeeksForGeeks"; identify_alpha_numeric(a);}Output:The number of alphabets are 24 The number of digits are 4 #include <stdio.h> // Header file containing character functions#include <ctype.h> void identify_alpha_numeric(char a[]){ int count_alpha = 0, count_digit = 0; for (int i = 0; a[i] != '\0'; i++) { // To check the character is alphabet if (isalpha(a[i])) count_alpha++; // To check the character is a digit if (isdigit(a[i])) count_digit++; } printf("The number of alphabets are %d\n", count_alpha); printf("The number of digits are %d", count_digit);} int main(){ // String Initialization char a[] = "Hi 1234, " " Welcome to GeeksForGeeks"; identify_alpha_numeric(a);} The number of alphabets are 24 The number of digits are 4 Example 2: The following program identifies the number of uppercase and lowercase alphabets and converts the uppercase to lowercase:#include <stdio.h> // Header file containing character functions#include <ctype.h> char* identify_convert_ul(char a[]){ int count_upper = 0, count_lower = 0; for (int i = 0; a[i] != '\0'; i++) { // To check the uppercase characters if (isupper(a[i])) { count_upper++; a[i] = tolower(a[i]); } // To check the lowercase characters else if (islower(a[i])) { count_lower++; a[i] = toupper(a[i]); } } printf("No. of uppercase characters are %d\n", count_upper); printf("No. of lowercase characters are %d", count_lower); return a;} int main(){ // String Initialization char a[] = "Hi, Welcome to GeeksForGeeks"; char* p; p = identify_convert_ul(a); printf("%s", p);}Output:No. of uppercase alphabets are 5 No. of lowercase alphabets are 19 hI, wELCOME TO gEEKSfORgEEKS #include <stdio.h> // Header file containing character functions#include <ctype.h> char* identify_convert_ul(char a[]){ int count_upper = 0, count_lower = 0; for (int i = 0; a[i] != '\0'; i++) { // To check the uppercase characters if (isupper(a[i])) { count_upper++; a[i] = tolower(a[i]); } // To check the lowercase characters else if (islower(a[i])) { count_lower++; a[i] = toupper(a[i]); } } printf("No. of uppercase characters are %d\n", count_upper); printf("No. of lowercase characters are %d", count_lower); return a;} int main(){ // String Initialization char a[] = "Hi, Welcome to GeeksForGeeks"; char* p; p = identify_convert_ul(a); printf("%s", p);} No. of uppercase alphabets are 5 No. of lowercase alphabets are 19 hI, wELCOME TO gEEKSfORgEEKS Example 3: The following program prints each word in a new line:#include <stdio.h> // Header file containing character functions#include <ctype.h> char* print_word(char a[]){ for (int i = 0; a[i] != '\0'; i++) { // Space is replaced // with control character '\n' if (isblank(a[i])) a[i] = '\n'; } return a;}int main(){ // String Initialization char a[] = "Hello Everyone." " Welcome to GeeksForGeeks portal. "; char* p; p = print_word(a); printf("%s", p);}Output:Hello Everyone. Welcome to GeeksForGeeks portal. #include <stdio.h> // Header file containing character functions#include <ctype.h> char* print_word(char a[]){ for (int i = 0; a[i] != '\0'; i++) { // Space is replaced // with control character '\n' if (isblank(a[i])) a[i] = '\n'; } return a;}int main(){ // String Initialization char a[] = "Hello Everyone." " Welcome to GeeksForGeeks portal. "; char* p; p = print_word(a); printf("%s", p);} Hello Everyone. Welcome to GeeksForGeeks portal. C-Functions C-String C Language Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n16 Dec, 2019" }, { "code": null, "e": 224, "s": 53, "text": "As string.h header file contains inbuilt functions to handle Strings in C/C++, the ctype.h/<cctype> contains inbuilt functions to handle characters in C/C++ respectively." }, { "code": null, "e": 253, "s": 224, "text": "Characters are of two types:" }, { "code": null, "e": 412, "s": 253, "text": "Printable Characters: The characters that are displayed on the terminal.Control Characters: The characters that are initiated to perform a specific operation." }, { "code": null, "e": 485, "s": 412, "text": "Printable Characters: The characters that are displayed on the terminal." }, { "code": null, "e": 572, "s": 485, "text": "Control Characters: The characters that are initiated to perform a specific operation." }, { "code": null, "e": 804, "s": 572, "text": "The arguments passed to character functions should be of integer type. If we pass characters instead of an integer, the characters are typecasted into integers(corresponding ASCII values) and those integers are passed as arguments." }, { "code": null, "e": 963, "s": 804, "text": "The below functions under ctype.h/<cctype> header file are applied on normal characters. Wide character functions are used for the characters of type wchar_t." }, { "code": null, "e": 1024, "s": 963, "text": "Below are examples to implement some of the above functions:" }, { "code": null, "e": 1849, "s": 1024, "text": "Example 1: The following program identifies the number of alphabets, digits:#include <stdio.h> // Header file containing character functions#include <ctype.h> void identify_alpha_numeric(char a[]){ int count_alpha = 0, count_digit = 0; for (int i = 0; a[i] != '\\0'; i++) { // To check the character is alphabet if (isalpha(a[i])) count_alpha++; // To check the character is a digit if (isdigit(a[i])) count_digit++; } printf(\"The number of alphabets are %d\\n\", count_alpha); printf(\"The number of digits are %d\", count_digit);} int main(){ // String Initialization char a[] = \"Hi 1234, \" \" Welcome to GeeksForGeeks\"; identify_alpha_numeric(a);}Output:The number of alphabets are 24\nThe number of digits are 4\n" }, { "code": "#include <stdio.h> // Header file containing character functions#include <ctype.h> void identify_alpha_numeric(char a[]){ int count_alpha = 0, count_digit = 0; for (int i = 0; a[i] != '\\0'; i++) { // To check the character is alphabet if (isalpha(a[i])) count_alpha++; // To check the character is a digit if (isdigit(a[i])) count_digit++; } printf(\"The number of alphabets are %d\\n\", count_alpha); printf(\"The number of digits are %d\", count_digit);} int main(){ // String Initialization char a[] = \"Hi 1234, \" \" Welcome to GeeksForGeeks\"; identify_alpha_numeric(a);}", "e": 2533, "s": 1849, "text": null }, { "code": null, "e": 2592, "s": 2533, "text": "The number of alphabets are 24\nThe number of digits are 4\n" }, { "code": null, "e": 3635, "s": 2592, "text": "Example 2: The following program identifies the number of uppercase and lowercase alphabets and converts the uppercase to lowercase:#include <stdio.h> // Header file containing character functions#include <ctype.h> char* identify_convert_ul(char a[]){ int count_upper = 0, count_lower = 0; for (int i = 0; a[i] != '\\0'; i++) { // To check the uppercase characters if (isupper(a[i])) { count_upper++; a[i] = tolower(a[i]); } // To check the lowercase characters else if (islower(a[i])) { count_lower++; a[i] = toupper(a[i]); } } printf(\"No. of uppercase characters are %d\\n\", count_upper); printf(\"No. of lowercase characters are %d\", count_lower); return a;} int main(){ // String Initialization char a[] = \"Hi, Welcome to GeeksForGeeks\"; char* p; p = identify_convert_ul(a); printf(\"%s\", p);}Output:No. of uppercase alphabets are 5\nNo. of lowercase alphabets are 19\nhI, wELCOME TO gEEKSfORgEEKS\n" }, { "code": "#include <stdio.h> // Header file containing character functions#include <ctype.h> char* identify_convert_ul(char a[]){ int count_upper = 0, count_lower = 0; for (int i = 0; a[i] != '\\0'; i++) { // To check the uppercase characters if (isupper(a[i])) { count_upper++; a[i] = tolower(a[i]); } // To check the lowercase characters else if (islower(a[i])) { count_lower++; a[i] = toupper(a[i]); } } printf(\"No. of uppercase characters are %d\\n\", count_upper); printf(\"No. of lowercase characters are %d\", count_lower); return a;} int main(){ // String Initialization char a[] = \"Hi, Welcome to GeeksForGeeks\"; char* p; p = identify_convert_ul(a); printf(\"%s\", p);}", "e": 4443, "s": 3635, "text": null }, { "code": null, "e": 4540, "s": 4443, "text": "No. of uppercase alphabets are 5\nNo. of lowercase alphabets are 19\nhI, wELCOME TO gEEKSfORgEEKS\n" }, { "code": null, "e": 5128, "s": 4540, "text": "Example 3: The following program prints each word in a new line:#include <stdio.h> // Header file containing character functions#include <ctype.h> char* print_word(char a[]){ for (int i = 0; a[i] != '\\0'; i++) { // Space is replaced // with control character '\\n' if (isblank(a[i])) a[i] = '\\n'; } return a;}int main(){ // String Initialization char a[] = \"Hello Everyone.\" \" Welcome to GeeksForGeeks portal. \"; char* p; p = print_word(a); printf(\"%s\", p);}Output:Hello\nEveryone.\nWelcome\nto\nGeeksForGeeks\nportal.\n" }, { "code": "#include <stdio.h> // Header file containing character functions#include <ctype.h> char* print_word(char a[]){ for (int i = 0; a[i] != '\\0'; i++) { // Space is replaced // with control character '\\n' if (isblank(a[i])) a[i] = '\\n'; } return a;}int main(){ // String Initialization char a[] = \"Hello Everyone.\" \" Welcome to GeeksForGeeks portal. \"; char* p; p = print_word(a); printf(\"%s\", p);}", "e": 5596, "s": 5128, "text": null }, { "code": null, "e": 5646, "s": 5596, "text": "Hello\nEveryone.\nWelcome\nto\nGeeksForGeeks\nportal.\n" }, { "code": null, "e": 5658, "s": 5646, "text": "C-Functions" }, { "code": null, "e": 5667, "s": 5658, "text": "C-String" }, { "code": null, "e": 5678, "s": 5667, "text": "C Language" }, { "code": null, "e": 5686, "s": 5678, "text": "Strings" }, { "code": null, "e": 5694, "s": 5686, "text": "Strings" } ]
How to sort an array elements in android?
This example demonstrate about How to sort an array elements in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:gravity="center" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"> <TextView android:id="@+id/text" android:layout_width="match_parent" android:layout_height="wrap_content"></TextView> </LinearLayout> In the above code, we have taken text view to sorted array. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.TextView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { TextView text; int temp; int[] arr = {12, 10, 5, 4, 2, 20, 6, 1, 0, 2}; ArrayList<String> arrayList; @RequiresApi(api = Build.VERSION_CODES.P) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text = findViewById(R.id.text); for (int i = 0; i < arr.length; i++) { for (int j = i + 1; j < arr.length; j++) { if (arr[i] > arr[j]) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } StringBuffer buff = new StringBuffer(); for (int i = 0; i < arr.length; i++) { buff.append(String.valueOf(arr[i] + " , ")); Log.d("sai", String.valueOf(arr[i])); } text.setText(buff); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code
[ { "code": null, "e": 1260, "s": 1187, "text": "This example demonstrate about How to sort an array elements in android." }, { "code": null, "e": 1389, "s": 1260, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1454, "s": 1389, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2001, "s": 1454, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:gravity=\"center\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\"\n android:orientation=\"vertical\">\n <TextView\n android:id=\"@+id/text\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"></TextView>\n</LinearLayout>" }, { "code": null, "e": 2061, "s": 2001, "text": "In the above code, we have taken text view to sorted array." }, { "code": null, "e": 2118, "s": 2061, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3286, "s": 2118, "text": "package com.example.myapplication;\n\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.Log;\nimport android.widget.TextView;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends AppCompatActivity {\n TextView text;\n int temp;\n int[] arr = {12, 10, 5, 4, 2, 20, 6, 1, 0, 2};\n ArrayList<String> arrayList;\n\n @RequiresApi(api = Build.VERSION_CODES.P)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n text = findViewById(R.id.text);\n for (int i = 0; i < arr.length; i++) {\n for (int j = i + 1; j < arr.length; j++) {\n if (arr[i] > arr[j]) {\n temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n }\n }\n StringBuffer buff = new StringBuffer();\n for (int i = 0; i < arr.length; i++) {\n buff.append(String.valueOf(arr[i] + \" , \"));\n Log.d(\"sai\", String.valueOf(arr[i]));\n }\n text.setText(buff);\n }\n}" }, { "code": null, "e": 3633, "s": 3286, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 3673, "s": 3633, "text": "Click here to download the project code" } ]
Stack push() and pop() in C++ STL
16 Jun, 2022 Stacks are a type of container adaptors that follow LIFO(Last In First Out) property, where a new element is added at one end and an element(at the top) is removed from that end only. Basically, the insertion and deletion happen on the top of the stack itself. push() function is used to insert or ‘push’ an element at the top of the stack. This is an inbuilt function from C++ Standard Template Library(STL). This function belongs to the <stack> header file. The element is added to the stack container and the size of the stack is increased by 1.Syntax: stackname.push(value) Parameters: The value of the element to be inserted is passed as the parameter.Result: Adds an element of value the same as that of the parameter passed at the top of the stack. Examples: Input : mystack mystack.push(6); Output : 6 Input : mystack mystack.push(0); mystack.push(1); Output : 0, 1 Errors and Exceptions: Shows an error if the value passed doesn’t match the stack type. Shows no exception throw guarantee if the parameter doesn’t throw any exception. CPP // CPP program to illustrate// Implementation of push() function #include <iostream>#include <stack>using namespace std; int main(){ // Empty stack stack<int> mystack; mystack.push(0); mystack.push(1); mystack.push(2); // Printing content of stack while (!mystack.empty()) { cout << ' ' << mystack.top(); mystack.pop(); }} 2 1 0 NOTE: Here, output is printed on the basis of LIFO property. The pop() function is used to remove or ‘pop’ an element from the top of the stack(newest or the topmost element in the stack). This is an inbuilt function from C++ Standard Template Library(STL). This function belongs to the <stack> header file. The element is removed from the stack container and the size of the stack is decreased by 1.Syntax: stackname.pop() Parameters: No parameters are passed. Result: Removes the newest element in the stack or basically the top element. Examples: Input : mystack = 0, 1, 2 mystack.pop(); Output : 0, 1 Input : mystack = 0, 1, 2, 3, 4, 5 mystack.pop(); Output : 0, 1, 2, 3, 4 Errors and Exceptions: Shows error if a parameter is passed. Shows no exception throw guarantee. CPP // CPP program to illustrate// Implementation of pop() function #include <iostream>#include <stack>using namespace std; int main(){ stack<int> mystack; mystack.push(1); mystack.push(2); mystack.push(3); mystack.push(4); // Stack becomes 1, 2, 3, 4 mystack.pop(); mystack.pop(); // Stack becomes 1, 2 while (!mystack.empty()) { cout << ' ' << mystack.top(); mystack.pop(); }} 2 1 Note: Here, output is printed on the basis of LIFO property. Application: Given a number of integers, add them to the stack and find the size of the stack without using the size function. Input : 5, 13, 0, 9, 4 Output: 5 Approach: We can keep a counter variable that will keep track of the size of the stack. Whenever we push (add) elements into the stack then increment the counter that indicates the size of the stack has increased now and whenever we pop (remove) elements from the stack then decrement the counter that indicates decrement in size of the stack. Algorithm: Push the given elements to the stack container one by one. Keep popping the elements of the stack until it becomes empty, and increment the counter variable. Print the counter variable. CPP // CPP program to illustrate// Application of push()// and pop() function #include <iostream>#include <stack>using namespace std; int main(){ int c = 0; // Empty stack stack<int> mystack; mystack.push(5); mystack.push(13); mystack.push(0); mystack.push(9); mystack.push(4); // stack becomes 5, 13, 0, 9, 4 // Counting number of elements in queue while (!mystack.empty()) { mystack.pop(); c++; } cout << c;} 5 Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. anshikajain26 divyanshmishra101010 cpp-containers-library CPP-Library cpp-stack cpp-stack-functions STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ std::string class in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL) Unordered Sets in C++ Standard Template Library List in C++ Standard Template Library (STL) std::find in C++ Inline Functions in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jun, 2022" }, { "code": null, "e": 313, "s": 52, "text": "Stacks are a type of container adaptors that follow LIFO(Last In First Out) property, where a new element is added at one end and an element(at the top) is removed from that end only. Basically, the insertion and deletion happen on the top of the stack itself." }, { "code": null, "e": 608, "s": 313, "text": "push() function is used to insert or ‘push’ an element at the top of the stack. This is an inbuilt function from C++ Standard Template Library(STL). This function belongs to the <stack> header file. The element is added to the stack container and the size of the stack is increased by 1.Syntax:" }, { "code": null, "e": 630, "s": 608, "text": "stackname.push(value)" }, { "code": null, "e": 808, "s": 630, "text": "Parameters: The value of the element to be inserted is passed as the parameter.Result: Adds an element of value the same as that of the parameter passed at the top of the stack." }, { "code": null, "e": 819, "s": 808, "text": "Examples: " }, { "code": null, "e": 965, "s": 819, "text": "Input : mystack\n mystack.push(6);\nOutput : 6\n \nInput : mystack\n mystack.push(0);\n mystack.push(1);\nOutput : 0, 1" }, { "code": null, "e": 988, "s": 965, "text": "Errors and Exceptions:" }, { "code": null, "e": 1054, "s": 988, "text": "Shows an error if the value passed doesn’t match the stack type. " }, { "code": null, "e": 1135, "s": 1054, "text": "Shows no exception throw guarantee if the parameter doesn’t throw any exception." }, { "code": null, "e": 1139, "s": 1135, "text": "CPP" }, { "code": "// CPP program to illustrate// Implementation of push() function #include <iostream>#include <stack>using namespace std; int main(){ // Empty stack stack<int> mystack; mystack.push(0); mystack.push(1); mystack.push(2); // Printing content of stack while (!mystack.empty()) { cout << ' ' << mystack.top(); mystack.pop(); }}", "e": 1501, "s": 1139, "text": null }, { "code": null, "e": 1508, "s": 1501, "text": " 2 1 0" }, { "code": null, "e": 1569, "s": 1508, "text": "NOTE: Here, output is printed on the basis of LIFO property." }, { "code": null, "e": 1916, "s": 1569, "text": "The pop() function is used to remove or ‘pop’ an element from the top of the stack(newest or the topmost element in the stack). This is an inbuilt function from C++ Standard Template Library(STL). This function belongs to the <stack> header file. The element is removed from the stack container and the size of the stack is decreased by 1.Syntax:" }, { "code": null, "e": 1932, "s": 1916, "text": "stackname.pop()" }, { "code": null, "e": 1970, "s": 1932, "text": "Parameters: No parameters are passed." }, { "code": null, "e": 2048, "s": 1970, "text": "Result: Removes the newest element in the stack or basically the top element." }, { "code": null, "e": 2059, "s": 2048, "text": "Examples: " }, { "code": null, "e": 2215, "s": 2059, "text": "Input : mystack = 0, 1, 2\n mystack.pop();\nOutput : 0, 1\n \nInput : mystack = 0, 1, 2, 3, 4, 5\n mystack.pop();\nOutput : 0, 1, 2, 3, 4" }, { "code": null, "e": 2238, "s": 2215, "text": "Errors and Exceptions:" }, { "code": null, "e": 2277, "s": 2238, "text": "Shows error if a parameter is passed. " }, { "code": null, "e": 2313, "s": 2277, "text": "Shows no exception throw guarantee." }, { "code": null, "e": 2317, "s": 2313, "text": "CPP" }, { "code": "// CPP program to illustrate// Implementation of pop() function #include <iostream>#include <stack>using namespace std; int main(){ stack<int> mystack; mystack.push(1); mystack.push(2); mystack.push(3); mystack.push(4); // Stack becomes 1, 2, 3, 4 mystack.pop(); mystack.pop(); // Stack becomes 1, 2 while (!mystack.empty()) { cout << ' ' << mystack.top(); mystack.pop(); }}", "e": 2745, "s": 2317, "text": null }, { "code": null, "e": 2750, "s": 2745, "text": " 2 1" }, { "code": null, "e": 2811, "s": 2750, "text": "Note: Here, output is printed on the basis of LIFO property." }, { "code": null, "e": 2939, "s": 2811, "text": "Application: Given a number of integers, add them to the stack and find the size of the stack without using the size function. " }, { "code": null, "e": 2972, "s": 2939, "text": "Input : 5, 13, 0, 9, 4\nOutput: 5" }, { "code": null, "e": 3316, "s": 2972, "text": "Approach: We can keep a counter variable that will keep track of the size of the stack. Whenever we push (add) elements into the stack then increment the counter that indicates the size of the stack has increased now and whenever we pop (remove) elements from the stack then decrement the counter that indicates decrement in size of the stack." }, { "code": null, "e": 3328, "s": 3316, "text": "Algorithm: " }, { "code": null, "e": 3388, "s": 3328, "text": "Push the given elements to the stack container one by one. " }, { "code": null, "e": 3488, "s": 3388, "text": "Keep popping the elements of the stack until it becomes empty, and increment the counter variable. " }, { "code": null, "e": 3516, "s": 3488, "text": "Print the counter variable." }, { "code": null, "e": 3520, "s": 3516, "text": "CPP" }, { "code": "// CPP program to illustrate// Application of push()// and pop() function #include <iostream>#include <stack>using namespace std; int main(){ int c = 0; // Empty stack stack<int> mystack; mystack.push(5); mystack.push(13); mystack.push(0); mystack.push(9); mystack.push(4); // stack becomes 5, 13, 0, 9, 4 // Counting number of elements in queue while (!mystack.empty()) { mystack.pop(); c++; } cout << c;}", "e": 3982, "s": 3520, "text": null }, { "code": null, "e": 3984, "s": 3982, "text": "5" }, { "code": null, "e": 4113, "s": 3984, "text": "Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. " }, { "code": null, "e": 4127, "s": 4113, "text": "anshikajain26" }, { "code": null, "e": 4148, "s": 4127, "text": "divyanshmishra101010" }, { "code": null, "e": 4171, "s": 4148, "text": "cpp-containers-library" }, { "code": null, "e": 4183, "s": 4171, "text": "CPP-Library" }, { "code": null, "e": 4193, "s": 4183, "text": "cpp-stack" }, { "code": null, "e": 4213, "s": 4193, "text": "cpp-stack-functions" }, { "code": null, "e": 4217, "s": 4213, "text": "STL" }, { "code": null, "e": 4221, "s": 4217, "text": "C++" }, { "code": null, "e": 4225, "s": 4221, "text": "STL" }, { "code": null, "e": 4229, "s": 4225, "text": "CPP" }, { "code": null, "e": 4327, "s": 4229, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4351, "s": 4327, "text": "Sorting a vector in C++" }, { "code": null, "e": 4371, "s": 4351, "text": "Polymorphism in C++" }, { "code": null, "e": 4396, "s": 4371, "text": "std::string class in C++" }, { "code": null, "e": 4429, "s": 4396, "text": "Friend class and function in C++" }, { "code": null, "e": 4473, "s": 4429, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 4518, "s": 4473, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 4566, "s": 4518, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 4610, "s": 4566, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 4627, "s": 4610, "text": "std::find in C++" } ]
Find the first maximum length even word from a string
21 Apr, 2021 Given a string of words separated by spaces. The task is to find the first maximum length even word from the string. Eg: “You are given an array of n numbers” The answer would be “an” and not “of” because “an” comes before “of”.Examples: Input: "this is a test string" Output: string Even length words are this, is, test, string. Even maximum length word is string. Input: "geeksforgeeks is a platform for geeks" Output: platform Only even length word is platform. Approach: The idea is to traverse the input string and find length of each word. Check if the length of word is even or not. If even, then compare length with maximum length found so far. If length is strictly greater than maximum length then store current word as required string.Below is the implementation of above approach: C++ Java Python 3 C# Javascript // C++ program to find maximum length even word #include <bits/stdc++.h>using namespace std; // Function to find maximum length even wordstring findMaxLenEven(string str){ int n = str.length(); int i = 0; // To store length of current word. int currlen = 0; // To store length of maximum length word. int maxlen = 0; // To store starting index of maximum // length word. int st = -1; while (i < n) { // If current character is space then // word has ended. Check if it is even // length word or not. If yes then // compare length with maximum length // found so far. if (str[i] == ' ') { if (currlen % 2 == 0) { if (maxlen < currlen) { maxlen = currlen; st = i - currlen; } } // Set currlen to zero for next word. currlen = 0; } else { // Update length of current word. currlen++; } i++; } // Check length of last word. if (currlen % 2 == 0) { if (maxlen < currlen) { maxlen = currlen; st = i - currlen; } } // If no even length word is present // then return -1. if (st == -1) return "-1"; return str.substr(st, maxlen);} // Driver codeint main(){ string str = "this is a test string"; cout << findMaxLenEven(str); return 0;} // Java program to find maximum length even wordclass GFG{ // Function to find maximum length even wordstatic String findMaxLenEven(String str){ int n = str.length(); int i = 0; // To store length of current word. int currlen = 0; // To store length of maximum length word. int maxlen = 0; // To store starting index of maximum // length word. int st = -1; while (i < n) { // If current character is space then // word has ended. Check if it is even // length word or not. If yes then // compare length with maximum length // found so far. if (str.charAt(i) == ' ') { if (currlen % 2 == 0) { if (maxlen < currlen) { maxlen = currlen; st = i - currlen; } } // Set currlen to zero for next word. currlen = 0; } else { // Update length of current word. currlen++; } i++; } // Check length of last word. if (currlen % 2 == 0) { if (maxlen < currlen) { maxlen = currlen; st = i - currlen; } } // If no even length word is present // then return -1. if (st == -1) return "-1"; return str.substring(st, st + maxlen);} // Driver codepublic static void main(String args[]){ String str = "this is a test string"; System.out.println( findMaxLenEven(str));}} // This code is contributed by Arnab Kundu # Python3 program to find maximum# length even word # Function to find maximum length# even worddef findMaxLenEven(str): n = len(str) i = 0 # To store length of current word. currlen = 0 # To store length of maximum length word. maxlen = 0 # To store starting index of maximum # length word. st = -1 while (i < n): # If current character is space then # word has ended. Check if it is even # length word or not. If yes then # compare length with maximum length # found so far. if (str[i] == ' '): if (currlen % 2 == 0): if (maxlen < currlen): maxlen = currlen st = i - currlen # Set currlen to zero for next word. currlen = 0 else : # Update length of current word. currlen += 1 i += 1 # Check length of last word. if (currlen % 2 == 0): if (maxlen < currlen): maxlen = currlen st = i - currlen # If no even length word is present # then return -1. if (st == -1): print("trie") return "-1" return str[st: st + maxlen] # Driver codeif __name__ == "__main__": str = "this is a test string" print(findMaxLenEven(str)) # This code is contributed by Ita_c // C# program to find maximum length even word using System; class GFG{ // Function to find maximum length even word static String findMaxLenEven(string str) { int n = str.Length; int i = 0; // To store length of current word. int currlen = 0; // To store length of maximum length word. int maxlen = 0; // To store starting index of maximum // length word. int st = -1; while (i < n) { // If current character is space then // word has ended. Check if it is even // length word or not. If yes then // compare length with maximum length // found so far. if (str[i] == ' ') { if (currlen % 2 == 0) { if (maxlen < currlen) { maxlen = currlen; st = i - currlen; } } // Set currlen to zero for next word. currlen = 0; } else { // Update length of current word. currlen++; } i++; } // Check length of last word. if (currlen % 2 == 0) { if (maxlen < currlen) { maxlen = currlen; st = i - currlen; } } // If no even length word is present // then return -1. if (st == -1) return "-1"; return str.Substring(st, maxlen); } // Driver code public static void Main() { string str = "this is a test string"; Console.WriteLine(findMaxLenEven(str)); } // This code is contributed by Ryuga} <script> // Javascript program to find maximum length even word // Function to find maximum length even wordfunction findMaxLenEven(str){ var n = str.length; var i = 0; // To store length of current word. var currlen = 0; // To store length of maximum length word. var maxlen = 0; // To store starting index of maximum // length word. var st = -1; while (i < n) { // If current character is space then // word has ended. Check if it is even // length word or not. If yes then // compare length with maximum length // found so far. if (str[i] == ' ') { if (currlen % 2 == 0) { if (maxlen < currlen) { maxlen = currlen; st = i - currlen; } } // Set currlen to zero for next word. currlen = 0; } else { // Update length of current word. currlen++; } i++; } // Check length of last word. if (currlen % 2 == 0) { if (maxlen < currlen) { maxlen = currlen; st = i - currlen; } } // If no even length word is present // then return -1. if (st == -1) return "-1"; return str.substr(st, maxlen);} // Driver codevar str = "this is a test string";document.write( findMaxLenEven(str)); // This code is contributed by noob2000.</script> string Time Complexity: O(N), where N is the length of the string. Auxiliary Space: O(1) andrew1234 ankthon ukasp ManasChhabra2 noob2000 array-traversal-question Goldman Sachs Data Structures Strings Goldman Sachs Data Structures Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation What is Hashing | A Complete Tutorial Introduction to Data Structures Find if there is a path between two vertices in an undirected graph Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Different Methods to Reverse a String in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Apr, 2021" }, { "code": null, "e": 292, "s": 52, "text": "Given a string of words separated by spaces. The task is to find the first maximum length even word from the string. Eg: “You are given an array of n numbers” The answer would be “an” and not “of” because “an” comes before “of”.Examples: " }, { "code": null, "e": 524, "s": 292, "text": "Input: \"this is a test string\"\nOutput: string\nEven length words are this, is, test, string. Even\nmaximum length word is string.\n\nInput: \"geeksforgeeks is a platform for geeks\"\nOutput: platform\nOnly even length word is platform." }, { "code": null, "e": 856, "s": 526, "text": "Approach: The idea is to traverse the input string and find length of each word. Check if the length of word is even or not. If even, then compare length with maximum length found so far. If length is strictly greater than maximum length then store current word as required string.Below is the implementation of above approach: " }, { "code": null, "e": 860, "s": 856, "text": "C++" }, { "code": null, "e": 865, "s": 860, "text": "Java" }, { "code": null, "e": 874, "s": 865, "text": "Python 3" }, { "code": null, "e": 877, "s": 874, "text": "C#" }, { "code": null, "e": 888, "s": 877, "text": "Javascript" }, { "code": "// C++ program to find maximum length even word #include <bits/stdc++.h>using namespace std; // Function to find maximum length even wordstring findMaxLenEven(string str){ int n = str.length(); int i = 0; // To store length of current word. int currlen = 0; // To store length of maximum length word. int maxlen = 0; // To store starting index of maximum // length word. int st = -1; while (i < n) { // If current character is space then // word has ended. Check if it is even // length word or not. If yes then // compare length with maximum length // found so far. if (str[i] == ' ') { if (currlen % 2 == 0) { if (maxlen < currlen) { maxlen = currlen; st = i - currlen; } } // Set currlen to zero for next word. currlen = 0; } else { // Update length of current word. currlen++; } i++; } // Check length of last word. if (currlen % 2 == 0) { if (maxlen < currlen) { maxlen = currlen; st = i - currlen; } } // If no even length word is present // then return -1. if (st == -1) return \"-1\"; return str.substr(st, maxlen);} // Driver codeint main(){ string str = \"this is a test string\"; cout << findMaxLenEven(str); return 0;}", "e": 2338, "s": 888, "text": null }, { "code": "// Java program to find maximum length even wordclass GFG{ // Function to find maximum length even wordstatic String findMaxLenEven(String str){ int n = str.length(); int i = 0; // To store length of current word. int currlen = 0; // To store length of maximum length word. int maxlen = 0; // To store starting index of maximum // length word. int st = -1; while (i < n) { // If current character is space then // word has ended. Check if it is even // length word or not. If yes then // compare length with maximum length // found so far. if (str.charAt(i) == ' ') { if (currlen % 2 == 0) { if (maxlen < currlen) { maxlen = currlen; st = i - currlen; } } // Set currlen to zero for next word. currlen = 0; } else { // Update length of current word. currlen++; } i++; } // Check length of last word. if (currlen % 2 == 0) { if (maxlen < currlen) { maxlen = currlen; st = i - currlen; } } // If no even length word is present // then return -1. if (st == -1) return \"-1\"; return str.substring(st, st + maxlen);} // Driver codepublic static void main(String args[]){ String str = \"this is a test string\"; System.out.println( findMaxLenEven(str));}} // This code is contributed by Arnab Kundu", "e": 3904, "s": 2338, "text": null }, { "code": "# Python3 program to find maximum# length even word # Function to find maximum length# even worddef findMaxLenEven(str): n = len(str) i = 0 # To store length of current word. currlen = 0 # To store length of maximum length word. maxlen = 0 # To store starting index of maximum # length word. st = -1 while (i < n): # If current character is space then # word has ended. Check if it is even # length word or not. If yes then # compare length with maximum length # found so far. if (str[i] == ' '): if (currlen % 2 == 0): if (maxlen < currlen): maxlen = currlen st = i - currlen # Set currlen to zero for next word. currlen = 0 else : # Update length of current word. currlen += 1 i += 1 # Check length of last word. if (currlen % 2 == 0): if (maxlen < currlen): maxlen = currlen st = i - currlen # If no even length word is present # then return -1. if (st == -1): print(\"trie\") return \"-1\" return str[st: st + maxlen] # Driver codeif __name__ == \"__main__\": str = \"this is a test string\" print(findMaxLenEven(str)) # This code is contributed by Ita_c", "e": 5258, "s": 3904, "text": null }, { "code": "// C# program to find maximum length even word using System; class GFG{ // Function to find maximum length even word static String findMaxLenEven(string str) { int n = str.Length; int i = 0; // To store length of current word. int currlen = 0; // To store length of maximum length word. int maxlen = 0; // To store starting index of maximum // length word. int st = -1; while (i < n) { // If current character is space then // word has ended. Check if it is even // length word or not. If yes then // compare length with maximum length // found so far. if (str[i] == ' ') { if (currlen % 2 == 0) { if (maxlen < currlen) { maxlen = currlen; st = i - currlen; } } // Set currlen to zero for next word. currlen = 0; } else { // Update length of current word. currlen++; } i++; } // Check length of last word. if (currlen % 2 == 0) { if (maxlen < currlen) { maxlen = currlen; st = i - currlen; } } // If no even length word is present // then return -1. if (st == -1) return \"-1\"; return str.Substring(st, maxlen); } // Driver code public static void Main() { string str = \"this is a test string\"; Console.WriteLine(findMaxLenEven(str)); } // This code is contributed by Ryuga}", "e": 7093, "s": 5258, "text": null }, { "code": "<script> // Javascript program to find maximum length even word // Function to find maximum length even wordfunction findMaxLenEven(str){ var n = str.length; var i = 0; // To store length of current word. var currlen = 0; // To store length of maximum length word. var maxlen = 0; // To store starting index of maximum // length word. var st = -1; while (i < n) { // If current character is space then // word has ended. Check if it is even // length word or not. If yes then // compare length with maximum length // found so far. if (str[i] == ' ') { if (currlen % 2 == 0) { if (maxlen < currlen) { maxlen = currlen; st = i - currlen; } } // Set currlen to zero for next word. currlen = 0; } else { // Update length of current word. currlen++; } i++; } // Check length of last word. if (currlen % 2 == 0) { if (maxlen < currlen) { maxlen = currlen; st = i - currlen; } } // If no even length word is present // then return -1. if (st == -1) return \"-1\"; return str.substr(st, maxlen);} // Driver codevar str = \"this is a test string\";document.write( findMaxLenEven(str)); // This code is contributed by noob2000.</script>", "e": 8529, "s": 7093, "text": null }, { "code": null, "e": 8536, "s": 8529, "text": "string" }, { "code": null, "e": 8621, "s": 8538, "text": "Time Complexity: O(N), where N is the length of the string. Auxiliary Space: O(1) " }, { "code": null, "e": 8632, "s": 8621, "text": "andrew1234" }, { "code": null, "e": 8640, "s": 8632, "text": "ankthon" }, { "code": null, "e": 8646, "s": 8640, "text": "ukasp" }, { "code": null, "e": 8660, "s": 8646, "text": "ManasChhabra2" }, { "code": null, "e": 8669, "s": 8660, "text": "noob2000" }, { "code": null, "e": 8694, "s": 8669, "text": "array-traversal-question" }, { "code": null, "e": 8708, "s": 8694, "text": "Goldman Sachs" }, { "code": null, "e": 8724, "s": 8708, "text": "Data Structures" }, { "code": null, "e": 8732, "s": 8724, "text": "Strings" }, { "code": null, "e": 8746, "s": 8732, "text": "Goldman Sachs" }, { "code": null, "e": 8762, "s": 8746, "text": "Data Structures" }, { "code": null, "e": 8770, "s": 8762, "text": "Strings" }, { "code": null, "e": 8868, "s": 8770, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8893, "s": 8868, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 8942, "s": 8893, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 8980, "s": 8942, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 9012, "s": 8980, "text": "Introduction to Data Structures" }, { "code": null, "e": 9080, "s": 9012, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 9126, "s": 9080, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 9151, "s": 9126, "text": "Reverse a string in Java" }, { "code": null, "e": 9211, "s": 9151, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 9226, "s": 9211, "text": "C++ Data Types" } ]
TreeSet toString() method in Java with Example
27 Dec, 2018 The toString() method of Java TreeSet is used to return a string representation of the elements of the Collection. The String representation comprises a set representation of the elements of the Collection in the order they are picked by the iterator closed in square brackets[].This method is used mainly to display collections other than String type(for instance: Object, Integer)in a String Representation. Syntax: public String toString() Parameter The method does not take any parameters. Return This method returns a String representation of the collection. Below examples illustrate the toString() method: Example 1: // Java program to demonstrate// TreeSet toString() method import java.util.*; public class collection { public static void main(String args[]) { // Creating an Empty TreeSet TreeSet<String> abs = new TreeSet<String>(); // Use add() method // to add elements to the Collection abs.add("Welcome"); abs.add("To"); abs.add("Geeks"); abs.add("For"); abs.add("Geeks"); // Using toString() method System.out.println(abs.toString()); }} [For, Geeks, To, Welcome] Example 2: // Java program to demonstrate// TreeSet toString() method import java.util.*; public class collection { public static void main(String args[]) { // Creating an Empty TreeSet TreeSet<Integer> abs = new TreeSet<Integer>(); // Use add() method // to add elements to the Collection abs.add(10); abs.add(20); abs.add(30); abs.add(40); // Using toString() method System.out.println(abs.toString()); }} [10, 20, 30, 40] Java - util package Java-Collections Java-Functions java-treeset Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Dec, 2018" }, { "code": null, "e": 143, "s": 28, "text": "The toString() method of Java TreeSet is used to return a string representation of the elements of the Collection." }, { "code": null, "e": 438, "s": 143, "text": "The String representation comprises a set representation of the elements of the Collection in the order they are picked by the iterator closed in square brackets[].This method is used mainly to display collections other than String type(for instance: Object, Integer)in a String Representation." }, { "code": null, "e": 446, "s": 438, "text": "Syntax:" }, { "code": null, "e": 471, "s": 446, "text": "public String toString()" }, { "code": null, "e": 522, "s": 471, "text": "Parameter The method does not take any parameters." }, { "code": null, "e": 592, "s": 522, "text": "Return This method returns a String representation of the collection." }, { "code": null, "e": 641, "s": 592, "text": "Below examples illustrate the toString() method:" }, { "code": null, "e": 652, "s": 641, "text": "Example 1:" }, { "code": "// Java program to demonstrate// TreeSet toString() method import java.util.*; public class collection { public static void main(String args[]) { // Creating an Empty TreeSet TreeSet<String> abs = new TreeSet<String>(); // Use add() method // to add elements to the Collection abs.add(\"Welcome\"); abs.add(\"To\"); abs.add(\"Geeks\"); abs.add(\"For\"); abs.add(\"Geeks\"); // Using toString() method System.out.println(abs.toString()); }}", "e": 1185, "s": 652, "text": null }, { "code": null, "e": 1212, "s": 1185, "text": "[For, Geeks, To, Welcome]\n" }, { "code": null, "e": 1223, "s": 1212, "text": "Example 2:" }, { "code": "// Java program to demonstrate// TreeSet toString() method import java.util.*; public class collection { public static void main(String args[]) { // Creating an Empty TreeSet TreeSet<Integer> abs = new TreeSet<Integer>(); // Use add() method // to add elements to the Collection abs.add(10); abs.add(20); abs.add(30); abs.add(40); // Using toString() method System.out.println(abs.toString()); }}", "e": 1716, "s": 1223, "text": null }, { "code": null, "e": 1734, "s": 1716, "text": "[10, 20, 30, 40]\n" }, { "code": null, "e": 1754, "s": 1734, "text": "Java - util package" }, { "code": null, "e": 1771, "s": 1754, "text": "Java-Collections" }, { "code": null, "e": 1786, "s": 1771, "text": "Java-Functions" }, { "code": null, "e": 1799, "s": 1786, "text": "java-treeset" }, { "code": null, "e": 1804, "s": 1799, "text": "Java" }, { "code": null, "e": 1809, "s": 1804, "text": "Java" }, { "code": null, "e": 1826, "s": 1809, "text": "Java-Collections" } ]
Regular Expression to Extract SQL Query
29 Oct, 2021 Regular Expressions are the easier mechanism to search the data that matches the complex criteria. For example, from an alphanumeric value, extract only the alpha value or numeric value or check for the specific patterns of character matching and retrieve the records, etc. Let us see them one by one by taking some sample scenarios; Step 1: Creating Database Query: SELECT * FROM sys.databases WHERE name = 'GEEKSFORGEEKS' BEGIN CREATE DATABASE [GEEKSFORGEEKS] END Step 2: Using the database Query: USE GEEKSFORGEEKS Step 3: CREATING TABLE Country under GEEKSFORGEEKS and insert few records Query: INSERT INTO Country(CountryID,CountryName) VALUES (1,'United States'); INSERT INTO Country(CountryID,CountryName) VALUES (2,'United States'); INSERT INTO Country(CountryID,CountryName) VALUES (3,'United Kingdom'); INSERT INTO Country(CountryID,CountryName) VALUES (4,'Canada'); INSERT INTO Country(CountryID,CountryName) VALUES (5,'United Kingdom'); INSERT INTO Country(CountryID,CountryName) VALUES (6,'Canada'); INSERT INTO Country(CountryID,CountryName) VALUES (7,'United States'); INSERT INTO Country(CountryID,CountryName) VALUES (8,'Australia'); INSERT INTO Country(CountryID,CountryName) VALUES (9,'Canada'); INSERT INTO Country(CountryID,CountryName) VALUES (10,'United States'); SELECT * FROM Country Output : Example 1: To get the records starting between A – D and the second letter between U to Z and the rest of the letters can be anything. Query: --Find Country Names having: --First character should be A and D alphabets. --The second character should be from U and Z alphabet SELECT * FROM Country WHERE CountryName like '[A-D][U-Z]%' --regular expression is used here Output : If we need to specifically check for the first character alone and the rest of the characters can be anything, then Query: --Find Country Names having: --First character should be A and D alphabets. --Rest letters can be any character SELECT * FROM Country WHERE CountryName like '[A-D]%' --regular expression Output : By seeing the above two outputs, we can understand that just by giving different regular expressions, we are getting different outputs. Suppose if we want to find country names starting with ‘U’ alone then the query will be as follows: Query: --Find country names starting with 'U' alone SELECT * FROM Country WHERE CountryName like 'U%' --regular expression Output : Suppose if we want to find country names starting with ‘U’ and additional information then the query will be as follows: Query: --Find country names starting with -- U and additional condition is given SELECT * FROM Country WHERE CountryName like 'U% [S]%' --regular expression Output : ‘ While using with Like operator, we need to understand the below factors also We can use the regular expression in other functions also. Example 2: Let us check out PATINDEX function first. It is a function that accepts the search pattern and input string and returns the starting position of the character not matching the pattern. --pattern to check is A-Z or a-z(search pattern) -- in the input string and --position of the non-matching pattern -- It checks for numeric value position --and it is displaying position of the character SELECT 'GFGVersion1' as InputString, PATINDEX('%[^A-Za-z]%', 'GFGVersion1') as NumericCharacterPosition; Output : To get numbers only from an input string, we can use in below way also SELECT 'GFGVersion1' as InputString, PATINDEX('%[0-9]%', 'GFGVersion1') as NumericCharacterPosition; i.e. instead of using [^A-Za-z], used [0-9] and getting the same result as above -- 0 will indicate no numeric value present SELECT 'VERSION' as InputString, PATINDEX('%[^A-Za-z]%', 'VERSION') as NumericPosition; Output : If there are no numeric, 0 will be displayed for NumericPosition We can use this functionality of using a regular expression with functions like PATINDEX, we can solve to get only the characters alone from input string/numbers alone from input string etc., For that, let us see STUFF function also STUFF function --remove the integer from -- position 3 in the input string. /* As only one character need to be removed, we need to send params like this 1st Param -- Input string 2nd Param -- Start location 3rd Param -- Number of characters to be replaced 4th Param - Replacing value */ SELECT STUFF('GE098EKS9VER1', 3, 1, '' ); Output : Example 3 : By having PATINDEX and STUFF functions, we can get only the character values from an input string. We need to use a regular expression to get applied on PATINDEX Find out the numeric position and remove the numbers by using STUFF function Step 2 has to be repeated until there is no numeric value Query: DECLARE @inputData NVARCHAR(MAX) = 'GE098EKS9VER1' --input string DECLARE @intPosition INT --get the position of the integer from the input string SET @intPosition = PATINDEX('%[^A-Za-z]%', @inputData) print @intPosition --run loop until no integer is found in the input string WHILE @intPosition > 0 BEGIN --remove the integer from that position SET @inputData = STUFF(@inputData, @intPosition, 1, '' ) --PRINT @inputData SET @intPosition = PATINDEX('%[^A-Za-z]%', @inputData ) --Again get the position of the next integer in the input string --PRINT @intPosition END SELECT 'GE098EKS9VER1' as InputString, @inputData AS AlphabetsOnly Output : Similarly, we can use regular expression as the best search pattern practice. Throughout SQL, we can use a regular expression to extract different outputs to our needs. It can be used with other functions also and it will help to get only alphabets from an input string/numerals from an input string. anikakapoor varshagumber28 Picked SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? SQL Interview Questions Difference between DELETE, DROP and TRUNCATE Window functions in SQL MySQL | Group_CONCAT() Function Difference between DDL and DML in DBMS Difference between DELETE and TRUNCATE SQL Correlated Subqueries MySQL | Regular expressions (Regexp)
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Oct, 2021" }, { "code": null, "e": 302, "s": 28, "text": "Regular Expressions are the easier mechanism to search the data that matches the complex criteria. For example, from an alphanumeric value, extract only the alpha value or numeric value or check for the specific patterns of character matching and retrieve the records, etc." }, { "code": null, "e": 362, "s": 302, "text": "Let us see them one by one by taking some sample scenarios;" }, { "code": null, "e": 388, "s": 362, "text": "Step 1: Creating Database" }, { "code": null, "e": 395, "s": 388, "text": "Query:" }, { "code": null, "e": 506, "s": 395, "text": "SELECT * FROM sys.databases WHERE name = 'GEEKSFORGEEKS'\n BEGIN\n CREATE DATABASE [GEEKSFORGEEKS]\n END" }, { "code": null, "e": 533, "s": 506, "text": "Step 2: Using the database" }, { "code": null, "e": 540, "s": 533, "text": "Query:" }, { "code": null, "e": 558, "s": 540, "text": "USE GEEKSFORGEEKS" }, { "code": null, "e": 632, "s": 558, "text": "Step 3: CREATING TABLE Country under GEEKSFORGEEKS and insert few records" }, { "code": null, "e": 639, "s": 632, "text": "Query:" }, { "code": null, "e": 1350, "s": 639, "text": "INSERT INTO Country(CountryID,CountryName) VALUES (1,'United States');\nINSERT INTO Country(CountryID,CountryName) VALUES (2,'United States');\nINSERT INTO Country(CountryID,CountryName) VALUES (3,'United Kingdom');\nINSERT INTO Country(CountryID,CountryName) VALUES (4,'Canada');\nINSERT INTO Country(CountryID,CountryName) VALUES (5,'United Kingdom');\nINSERT INTO Country(CountryID,CountryName) VALUES (6,'Canada');\nINSERT INTO Country(CountryID,CountryName) VALUES (7,'United States');\nINSERT INTO Country(CountryID,CountryName) VALUES (8,'Australia');\nINSERT INTO Country(CountryID,CountryName) VALUES (9,'Canada');\nINSERT INTO Country(CountryID,CountryName) VALUES (10,'United States');\n\nSELECT * FROM Country" }, { "code": null, "e": 1359, "s": 1350, "text": "Output :" }, { "code": null, "e": 1371, "s": 1359, "text": "Example 1: " }, { "code": null, "e": 1496, "s": 1371, "text": "To get the records starting between A – D and the second letter between U to Z and the rest of the letters can be anything. " }, { "code": null, "e": 1503, "s": 1496, "text": "Query:" }, { "code": null, "e": 1730, "s": 1503, "text": "--Find Country Names having:\n--First character should be A and D alphabets. \n--The second character should be from U and Z alphabet\nSELECT * FROM Country\nWHERE CountryName like '[A-D][U-Z]%' \n--regular expression is used here" }, { "code": null, "e": 1739, "s": 1730, "text": "Output :" }, { "code": null, "e": 1856, "s": 1739, "text": "If we need to specifically check for the first character alone and the rest of the characters can be anything, then " }, { "code": null, "e": 1863, "s": 1856, "text": "Query:" }, { "code": null, "e": 2052, "s": 1863, "text": "--Find Country Names having:\n--First character should be A and D alphabets. \n--Rest letters can be any character\nSELECT * FROM Country\nWHERE CountryName like '[A-D]%' \n--regular expression" }, { "code": null, "e": 2061, "s": 2052, "text": "Output :" }, { "code": null, "e": 2197, "s": 2061, "text": "By seeing the above two outputs, we can understand that just by giving different regular expressions, we are getting different outputs." }, { "code": null, "e": 2297, "s": 2197, "text": "Suppose if we want to find country names starting with ‘U’ alone then the query will be as follows:" }, { "code": null, "e": 2304, "s": 2297, "text": "Query:" }, { "code": null, "e": 2422, "s": 2304, "text": "--Find country names starting with 'U' alone\nSELECT * FROM Country\nWHERE CountryName like 'U%' \n--regular expression" }, { "code": null, "e": 2431, "s": 2422, "text": "Output :" }, { "code": null, "e": 2553, "s": 2431, "text": "Suppose if we want to find country names starting with ‘U’ and additional information then the query will be as follows:" }, { "code": null, "e": 2560, "s": 2553, "text": "Query:" }, { "code": null, "e": 2710, "s": 2560, "text": "--Find country names starting with\n-- U and additional condition is given\nSELECT * FROM Country\nWHERE CountryName like 'U% [S]%'\n--regular expression" }, { "code": null, "e": 2719, "s": 2710, "text": "Output :" }, { "code": null, "e": 2721, "s": 2719, "text": "‘" }, { "code": null, "e": 2798, "s": 2721, "text": "While using with Like operator, we need to understand the below factors also" }, { "code": null, "e": 2857, "s": 2798, "text": "We can use the regular expression in other functions also." }, { "code": null, "e": 2868, "s": 2857, "text": "Example 2:" }, { "code": null, "e": 3054, "s": 2868, "text": "Let us check out PATINDEX function first. It is a function that accepts the search pattern and input string and returns the starting position of the character not matching the pattern." }, { "code": null, "e": 3365, "s": 3054, "text": "--pattern to check is A-Z or a-z(search pattern)\n-- in the input string and \n--position of the non-matching pattern\n-- It checks for numeric value position \n--and it is displaying position of the character\nSELECT 'GFGVersion1' as InputString,\nPATINDEX('%[^A-Za-z]%', 'GFGVersion1') as\nNumericCharacterPosition;" }, { "code": null, "e": 3374, "s": 3365, "text": "Output :" }, { "code": null, "e": 3445, "s": 3374, "text": "To get numbers only from an input string, we can use in below way also" }, { "code": null, "e": 3547, "s": 3445, "text": "SELECT 'GFGVersion1' as InputString, \nPATINDEX('%[0-9]%', 'GFGVersion1') as\nNumericCharacterPosition;" }, { "code": null, "e": 3628, "s": 3547, "text": "i.e. instead of using [^A-Za-z], used [0-9] and getting the same result as above" }, { "code": null, "e": 3763, "s": 3628, "text": "-- 0 will indicate no numeric value present\nSELECT 'VERSION' as InputString, \nPATINDEX('%[^A-Za-z]%', 'VERSION')\n as NumericPosition; " }, { "code": null, "e": 3772, "s": 3763, "text": "Output :" }, { "code": null, "e": 3837, "s": 3772, "text": "If there are no numeric, 0 will be displayed for NumericPosition" }, { "code": null, "e": 4029, "s": 3837, "text": "We can use this functionality of using a regular expression with functions like PATINDEX, we can solve to get only the characters alone from input string/numbers alone from input string etc.," }, { "code": null, "e": 4070, "s": 4029, "text": "For that, let us see STUFF function also" }, { "code": null, "e": 4085, "s": 4070, "text": "STUFF function" }, { "code": null, "e": 4416, "s": 4085, "text": " --remove the integer from\n -- position 3 in the input string. \n /* As only one character need to be removed, \n we need to send params like this\n 1st Param -- Input string\n 2nd Param -- Start location \n 3rd Param -- Number of characters to be replaced\n 4th Param - Replacing value\n */\nSELECT STUFF('GE098EKS9VER1', 3, 1, '' ); " }, { "code": null, "e": 4425, "s": 4416, "text": "Output :" }, { "code": null, "e": 4437, "s": 4425, "text": "Example 3 :" }, { "code": null, "e": 4536, "s": 4437, "text": "By having PATINDEX and STUFF functions, we can get only the character values from an input string." }, { "code": null, "e": 4599, "s": 4536, "text": "We need to use a regular expression to get applied on PATINDEX" }, { "code": null, "e": 4676, "s": 4599, "text": "Find out the numeric position and remove the numbers by using STUFF function" }, { "code": null, "e": 4734, "s": 4676, "text": "Step 2 has to be repeated until there is no numeric value" }, { "code": null, "e": 4741, "s": 4734, "text": "Query:" }, { "code": null, "e": 5470, "s": 4741, "text": "DECLARE @inputData NVARCHAR(MAX) = 'GE098EKS9VER1' \n--input string\nDECLARE @intPosition INT \n --get the position of the integer from the input string \nSET @intPosition = PATINDEX('%[^A-Za-z]%', @inputData) \nprint @intPosition\n\n--run loop until no integer is found in the input string\nWHILE @intPosition > 0 \n BEGIN \n --remove the integer from that position\n SET @inputData = STUFF(@inputData, @intPosition, 1, '' ) \n --PRINT @inputData \n SET @intPosition = PATINDEX('%[^A-Za-z]%', @inputData )\n --Again get the position of the next integer in the input string\n --PRINT @intPosition \nEND \nSELECT 'GE098EKS9VER1' as InputString, @inputData AS AlphabetsOnly" }, { "code": null, "e": 5479, "s": 5470, "text": "Output :" }, { "code": null, "e": 5557, "s": 5479, "text": "Similarly, we can use regular expression as the best search pattern practice." }, { "code": null, "e": 5780, "s": 5557, "text": "Throughout SQL, we can use a regular expression to extract different outputs to our needs. It can be used with other functions also and it will help to get only alphabets from an input string/numerals from an input string." }, { "code": null, "e": 5792, "s": 5780, "text": "anikakapoor" }, { "code": null, "e": 5807, "s": 5792, "text": "varshagumber28" }, { "code": null, "e": 5814, "s": 5807, "text": "Picked" }, { "code": null, "e": 5825, "s": 5814, "text": "SQL-Server" }, { "code": null, "e": 5829, "s": 5825, "text": "SQL" }, { "code": null, "e": 5833, "s": 5829, "text": "SQL" }, { "code": null, "e": 5931, "s": 5833, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5942, "s": 5931, "text": "CTE in SQL" }, { "code": null, "e": 6008, "s": 5942, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 6032, "s": 6008, "text": "SQL Interview Questions" }, { "code": null, "e": 6077, "s": 6032, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 6101, "s": 6077, "text": "Window functions in SQL" }, { "code": null, "e": 6133, "s": 6101, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 6172, "s": 6133, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 6211, "s": 6172, "text": "Difference between DELETE and TRUNCATE" }, { "code": null, "e": 6237, "s": 6211, "text": "SQL Correlated Subqueries" } ]
Difference between ExecutorService execute() and submit() method in Java
20 Jun, 2021 The ExecutorService interface extends Executor by adding methods that help manage and control the execution of threads. It is defined in java.util.concurrent package. It defines methods that execute the threads that return results, a set of threads and that determine the shutdown status. In this article, we will see the difference between the two such methods called execute() and submit(). In Java, in order to perform asynchronous tasks, the runnable interface is implemented. In order to do this, one such interface available is the Executor interface. The executor interface contains the execute() method. Apart from that, there is another interface available which is the ExecutorService interface which extends the executor interface. This method contains the submit() method. The following image illustrates the relationship between these two interfaces. Execute Method: This function executes the given command at some time in the future. The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of the Executor implementation. This method is a void method meaning it doesn’t return any function. Once the task is assigned in the execute() method, we won’t get any response and we can forget about the task. The following is an implementation of the execute method. Java // Java program to demonstrate// the behavior of the// execute() method import java.util.concurrent.*;public class GFG { public static void main(String[] args) throws Exception { // Creating the object of the // Executor Service ExecutorService executorService = Executors.newSingleThreadExecutor(); // execute() method cannot return // anything because it's return type // is void. // By using execute(), we are accepting // a Runnable task executorService.execute(new Runnable() { // Override the run method public void run() { System.out.println( "This is execute() " + "method example"); } }); // This method performs all the // previouslu submitted tasks // before termination executorService.shutdown(); }} Output: Submit Method: This function executes the given command at some time in the future. The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of the Executor implementation. Unlike the execute method, this method returns a future. In Java, the future represents the result of an asynchronous computation. The future object is used to handle the task after the execution has started. Therefore, when we need the result of the execution, then we can use the submit() method of the future object. In order to get the result, we can use the get() methods on the Future. The get() method returns an object if we call the get() method before the task has completed, it will block until the result is ready and may throw checked exception or if the task is completed, then the future object holds a result which is returned which can then be used later. The following is an implementation of the submit method: Java // Java program to demonstrate// the behavior of the// submit() method import java.util.concurrent.*;public class GFG { public static void main(String[] args) throws Exception { // Creating the object of the // Executor service interface ExecutorService executorService = Executors.newFixedThreadPool(1); // submit() method can return the // result of the computation // because it has a return type of Future. // By using submit(), we are // accepting a Callable task Future obj = executorService.submit(new Callable() { // Overriding the call method public Object call() { System.out.println( "This is submit() " + "method example"); return "Returning Callable " + "Task Result"; } }); // This method will return the result // if the task has finished perfectly. // The submit() method returns a // Java Future object which is // used to check when the Runnable // has completed. // As it implements Future, // get() method is called // to get the result System.out.println(obj.get()); executorService.shutdown(); }} Output: The following table demonstrates the difference between the execute method and the submit method: absoluteastha Java - util package Java-concurrent-package Difference Between Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Similarities and Difference between Java and C++ Difference between Internal and External fragmentation Difference between Compile-time and Run-time Polymorphism in Java Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n20 Jun, 2021" }, { "code": null, "e": 448, "s": 54, "text": "The ExecutorService interface extends Executor by adding methods that help manage and control the execution of threads. It is defined in java.util.concurrent package. It defines methods that execute the threads that return results, a set of threads and that determine the shutdown status. In this article, we will see the difference between the two such methods called execute() and submit(). " }, { "code": null, "e": 921, "s": 448, "text": "In Java, in order to perform asynchronous tasks, the runnable interface is implemented. In order to do this, one such interface available is the Executor interface. The executor interface contains the execute() method. Apart from that, there is another interface available which is the ExecutorService interface which extends the executor interface. This method contains the submit() method. The following image illustrates the relationship between these two interfaces. " }, { "code": null, "e": 1383, "s": 921, "text": "Execute Method: This function executes the given command at some time in the future. The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of the Executor implementation. This method is a void method meaning it doesn’t return any function. Once the task is assigned in the execute() method, we won’t get any response and we can forget about the task. The following is an implementation of the execute method. " }, { "code": null, "e": 1388, "s": 1383, "text": "Java" }, { "code": "// Java program to demonstrate// the behavior of the// execute() method import java.util.concurrent.*;public class GFG { public static void main(String[] args) throws Exception { // Creating the object of the // Executor Service ExecutorService executorService = Executors.newSingleThreadExecutor(); // execute() method cannot return // anything because it's return type // is void. // By using execute(), we are accepting // a Runnable task executorService.execute(new Runnable() { // Override the run method public void run() { System.out.println( \"This is execute() \" + \"method example\"); } }); // This method performs all the // previouslu submitted tasks // before termination executorService.shutdown(); }}", "e": 2329, "s": 1388, "text": null }, { "code": null, "e": 2338, "s": 2329, "text": "Output: " }, { "code": null, "e": 3290, "s": 2338, "text": "Submit Method: This function executes the given command at some time in the future. The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of the Executor implementation. Unlike the execute method, this method returns a future. In Java, the future represents the result of an asynchronous computation. The future object is used to handle the task after the execution has started. Therefore, when we need the result of the execution, then we can use the submit() method of the future object. In order to get the result, we can use the get() methods on the Future. The get() method returns an object if we call the get() method before the task has completed, it will block until the result is ready and may throw checked exception or if the task is completed, then the future object holds a result which is returned which can then be used later. The following is an implementation of the submit method: " }, { "code": null, "e": 3295, "s": 3290, "text": "Java" }, { "code": "// Java program to demonstrate// the behavior of the// submit() method import java.util.concurrent.*;public class GFG { public static void main(String[] args) throws Exception { // Creating the object of the // Executor service interface ExecutorService executorService = Executors.newFixedThreadPool(1); // submit() method can return the // result of the computation // because it has a return type of Future. // By using submit(), we are // accepting a Callable task Future obj = executorService.submit(new Callable() { // Overriding the call method public Object call() { System.out.println( \"This is submit() \" + \"method example\"); return \"Returning Callable \" + \"Task Result\"; } }); // This method will return the result // if the task has finished perfectly. // The submit() method returns a // Java Future object which is // used to check when the Runnable // has completed. // As it implements Future, // get() method is called // to get the result System.out.println(obj.get()); executorService.shutdown(); }}", "e": 4697, "s": 3295, "text": null }, { "code": null, "e": 4707, "s": 4697, "text": "Output: " }, { "code": null, "e": 4806, "s": 4707, "text": "The following table demonstrates the difference between the execute method and the submit method: " }, { "code": null, "e": 4820, "s": 4806, "text": "absoluteastha" }, { "code": null, "e": 4840, "s": 4820, "text": "Java - util package" }, { "code": null, "e": 4864, "s": 4840, "text": "Java-concurrent-package" }, { "code": null, "e": 4883, "s": 4864, "text": "Difference Between" }, { "code": null, "e": 4888, "s": 4883, "text": "Java" }, { "code": null, "e": 4893, "s": 4888, "text": "Java" }, { "code": null, "e": 4991, "s": 4893, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5052, "s": 4991, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5120, "s": 5052, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 5169, "s": 5120, "text": "Similarities and Difference between Java and C++" }, { "code": null, "e": 5224, "s": 5169, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 5290, "s": 5224, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 5305, "s": 5290, "text": "Arrays in Java" }, { "code": null, "e": 5349, "s": 5305, "text": "Split() String method in Java with examples" }, { "code": null, "e": 5385, "s": 5349, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 5436, "s": 5385, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
File canExecute() method in Java with Examples
28 Jan, 2019 The canExecute() function is a part of File class in Java. This function determines whether the program can execute the specified file denoted by the abstract pathname. If the file path exists and the application is allowed to execute the file, this method will return true. Else it will return false. Function signature: public boolean canExecute() Syntax: file.canExecute(); Parameters: This function does not accept any parameter. Return Value: This function returns a boolean value representing whether the specified file can be executed or not. Exceptions: This method throws Security Exception if the read access to the file is denied Below programs illustrates the use of canExecute() function: Example 1: The file “F:\\program.txt” is an existing file in F: directory and the program is allowed the permission to execute the file. // Java program to demonstrate// canExecute() method of File class import java.io.*; public class solution { // Driver Code public static void main(String args[]) { // Get the file to be executed File f = new File("F:\\program.txt"); // Check if this file // can be executed or not // using canExecute() method if (f.canExecute()) { // The file is can be executed // as true is returned System.out.println("Executable"); } else { // The file is cannot be executed // as false is returned System.out.println("Non Executable"); } }} Output: Executable Example 2: The file “F:\\program1.txt” does not exist we will try to check if the file is executable or not. // Java program to demonstrate// canExecute() method of File class import java.io.*; public class solution { // Driver Code public static void main(String args[]) { // Get the file to be executed File f = new File("F:\\program1.txt"); // Check if this file // can be executed or not // using canExecute() method if (f.canExecute()) { // The file is can be executed // as true is returned System.out.println("Executable"); } else { // The file is cannot be executed // as false is returned System.out.println("Non Executable"); } }} Output: Non Executable Note: The programs might not run in an online IDE. Please use an offline IDE and set the path of the file. Java-File Class Java-Functions Java-IO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jan, 2019" }, { "code": null, "e": 354, "s": 52, "text": "The canExecute() function is a part of File class in Java. This function determines whether the program can execute the specified file denoted by the abstract pathname. If the file path exists and the application is allowed to execute the file, this method will return true. Else it will return false." }, { "code": null, "e": 374, "s": 354, "text": "Function signature:" }, { "code": null, "e": 402, "s": 374, "text": "public boolean canExecute()" }, { "code": null, "e": 410, "s": 402, "text": "Syntax:" }, { "code": null, "e": 429, "s": 410, "text": "file.canExecute();" }, { "code": null, "e": 486, "s": 429, "text": "Parameters: This function does not accept any parameter." }, { "code": null, "e": 602, "s": 486, "text": "Return Value: This function returns a boolean value representing whether the specified file can be executed or not." }, { "code": null, "e": 693, "s": 602, "text": "Exceptions: This method throws Security Exception if the read access to the file is denied" }, { "code": null, "e": 754, "s": 693, "text": "Below programs illustrates the use of canExecute() function:" }, { "code": null, "e": 891, "s": 754, "text": "Example 1: The file “F:\\\\program.txt” is an existing file in F: directory and the program is allowed the permission to execute the file." }, { "code": "// Java program to demonstrate// canExecute() method of File class import java.io.*; public class solution { // Driver Code public static void main(String args[]) { // Get the file to be executed File f = new File(\"F:\\\\program.txt\"); // Check if this file // can be executed or not // using canExecute() method if (f.canExecute()) { // The file is can be executed // as true is returned System.out.println(\"Executable\"); } else { // The file is cannot be executed // as false is returned System.out.println(\"Non Executable\"); } }}", "e": 1575, "s": 891, "text": null }, { "code": null, "e": 1583, "s": 1575, "text": "Output:" }, { "code": null, "e": 1594, "s": 1583, "text": "Executable" }, { "code": null, "e": 1703, "s": 1594, "text": "Example 2: The file “F:\\\\program1.txt” does not exist we will try to check if the file is executable or not." }, { "code": "// Java program to demonstrate// canExecute() method of File class import java.io.*; public class solution { // Driver Code public static void main(String args[]) { // Get the file to be executed File f = new File(\"F:\\\\program1.txt\"); // Check if this file // can be executed or not // using canExecute() method if (f.canExecute()) { // The file is can be executed // as true is returned System.out.println(\"Executable\"); } else { // The file is cannot be executed // as false is returned System.out.println(\"Non Executable\"); } }}", "e": 2388, "s": 1703, "text": null }, { "code": null, "e": 2396, "s": 2388, "text": "Output:" }, { "code": null, "e": 2411, "s": 2396, "text": "Non Executable" }, { "code": null, "e": 2518, "s": 2411, "text": "Note: The programs might not run in an online IDE. Please use an offline IDE and set the path of the file." }, { "code": null, "e": 2534, "s": 2518, "text": "Java-File Class" }, { "code": null, "e": 2549, "s": 2534, "text": "Java-Functions" }, { "code": null, "e": 2565, "s": 2549, "text": "Java-IO package" }, { "code": null, "e": 2570, "s": 2565, "text": "Java" }, { "code": null, "e": 2575, "s": 2570, "text": "Java" }, { "code": null, "e": 2673, "s": 2575, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2688, "s": 2673, "text": "Stream In Java" }, { "code": null, "e": 2709, "s": 2688, "text": "Introduction to Java" }, { "code": null, "e": 2730, "s": 2709, "text": "Constructors in Java" }, { "code": null, "e": 2749, "s": 2730, "text": "Exceptions in Java" }, { "code": null, "e": 2766, "s": 2749, "text": "Generics in Java" }, { "code": null, "e": 2796, "s": 2766, "text": "Functional Interfaces in Java" }, { "code": null, "e": 2822, "s": 2796, "text": "Java Programming Examples" }, { "code": null, "e": 2838, "s": 2822, "text": "Strings in Java" }, { "code": null, "e": 2875, "s": 2838, "text": "Differences between JDK, JRE and JVM" } ]
Python Tkinter | Create different shapes using Canvas class
02 Nov, 2021 In Tkinter, Canvas class is used to create different shapes with the help of some functions which are defined under Canvas class. Any shape that Canvas class creates requires a canvas, so before creating any shapes a Canvas object is required and needs to be packed to the main window. Canvas Methods for shapes: Canvas.create_oval(x1, y1, x2, y2, options = ...): It is used to create a oval, pieslice and chord. Canvas.create_rectangle(x1, y1, x2, y2, options = ...): It is used to create rectangle and square. Canvas.create_arc(x1, y1, x2, y2, options = ...) This is used to create an arc. Canvas.create_polygon(coordinates, options = ...) THis is used to create any valid shapes. We are using a class to show the working of functions that helps to creates different shapes.Class parameters – Data members used: master, canvasMember functions used: create() methodWidgets used: CanvasTkinter method used: Canvas.create_oval() Canvas.create_rectangle() Canvas.create_arc() Canvas.create_polygon() pack() title() geometry() Below is the Python code – Python3 # Imports each and every method and class# of module tkinter and tkinter.ttkfrom tkinter import * from tkinter.ttk import * class Shape: def __init__(self, master = None): self.master = master # Calls create method of class Shape self.create() def create(self): # Creates a object of class canvas # with the help of this we can create different shapes self.canvas = Canvas(self.master) # Creates a circle of diameter 80 self.canvas.create_oval(10, 10, 80, 80, outline = "black", fill = "white", width = 2) # Creates an ellipse with horizontal diameter # of 210 and vertical diameter of 80 self.canvas.create_oval(110, 10, 210, 80, outline = "red", fill = "green", width = 2) # Creates a rectangle of 50x60 (heightxwidth) self.canvas.create_rectangle(230, 10, 290, 60, outline = "black", fill = "blue", width = 2) # Creates an arc of 210 deg self.canvas.create_arc(30, 200, 90, 100, start = 0, extent = 210, outline = "green", fill = "red", width = 2) points = [150, 100, 200, 120, 240, 180, 210, 200, 150, 150, 100, 200] # Creates a polygon self.canvas.create_polygon(points, outline = "blue", fill = "orange", width = 2) # Pack the canvas to the main window and make it expandable self.canvas.pack(fill = BOTH, expand = 1) if __name__ == "__main__": # object of class Tk, responsible for creating # a tkinter toplevel window master = Tk() shape = Shape(master) # Sets the title to Shapes master.title("Shapes") # Sets the geometry and position # of window on the screen master.geometry("330x220 + 300 + 300") # Infinite loop breaks only by interrupt mainloop() Output: kapoorsagar226 simmytarika5 Python-gui Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Nov, 2021" }, { "code": null, "e": 315, "s": 28, "text": "In Tkinter, Canvas class is used to create different shapes with the help of some functions which are defined under Canvas class. Any shape that Canvas class creates requires a canvas, so before creating any shapes a Canvas object is required and needs to be packed to the main window. " }, { "code": null, "e": 714, "s": 315, "text": "Canvas Methods for shapes: Canvas.create_oval(x1, y1, x2, y2, options = ...): It is used to create a oval, pieslice and chord. Canvas.create_rectangle(x1, y1, x2, y2, options = ...): It is used to create rectangle and square. Canvas.create_arc(x1, y1, x2, y2, options = ...) This is used to create an arc. Canvas.create_polygon(coordinates, options = ...) THis is used to create any valid shapes. " }, { "code": null, "e": 828, "s": 714, "text": "We are using a class to show the working of functions that helps to creates different shapes.Class parameters – " }, { "code": null, "e": 1059, "s": 828, "text": "Data members used: master, canvasMember functions used: create() methodWidgets used: CanvasTkinter method used: Canvas.create_oval() Canvas.create_rectangle() Canvas.create_arc() Canvas.create_polygon() pack() title() geometry() " }, { "code": null, "e": 1087, "s": 1059, "text": "Below is the Python code – " }, { "code": null, "e": 1095, "s": 1087, "text": "Python3" }, { "code": "# Imports each and every method and class# of module tkinter and tkinter.ttkfrom tkinter import * from tkinter.ttk import * class Shape: def __init__(self, master = None): self.master = master # Calls create method of class Shape self.create() def create(self): # Creates a object of class canvas # with the help of this we can create different shapes self.canvas = Canvas(self.master) # Creates a circle of diameter 80 self.canvas.create_oval(10, 10, 80, 80, outline = \"black\", fill = \"white\", width = 2) # Creates an ellipse with horizontal diameter # of 210 and vertical diameter of 80 self.canvas.create_oval(110, 10, 210, 80, outline = \"red\", fill = \"green\", width = 2) # Creates a rectangle of 50x60 (heightxwidth) self.canvas.create_rectangle(230, 10, 290, 60, outline = \"black\", fill = \"blue\", width = 2) # Creates an arc of 210 deg self.canvas.create_arc(30, 200, 90, 100, start = 0, extent = 210, outline = \"green\", fill = \"red\", width = 2) points = [150, 100, 200, 120, 240, 180, 210, 200, 150, 150, 100, 200] # Creates a polygon self.canvas.create_polygon(points, outline = \"blue\", fill = \"orange\", width = 2) # Pack the canvas to the main window and make it expandable self.canvas.pack(fill = BOTH, expand = 1) if __name__ == \"__main__\": # object of class Tk, responsible for creating # a tkinter toplevel window master = Tk() shape = Shape(master) # Sets the title to Shapes master.title(\"Shapes\") # Sets the geometry and position # of window on the screen master.geometry(\"330x220 + 300 + 300\") # Infinite loop breaks only by interrupt mainloop()", "e": 3179, "s": 1095, "text": null }, { "code": null, "e": 3189, "s": 3179, "text": "Output: " }, { "code": null, "e": 3206, "s": 3191, "text": "kapoorsagar226" }, { "code": null, "e": 3219, "s": 3206, "text": "simmytarika5" }, { "code": null, "e": 3230, "s": 3219, "text": "Python-gui" }, { "code": null, "e": 3245, "s": 3230, "text": "Python-tkinter" }, { "code": null, "e": 3252, "s": 3245, "text": "Python" }, { "code": null, "e": 3350, "s": 3252, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3368, "s": 3350, "text": "Python Dictionary" }, { "code": null, "e": 3410, "s": 3368, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3432, "s": 3410, "text": "Enumerate() in Python" }, { "code": null, "e": 3467, "s": 3432, "text": "Read a file line by line in Python" }, { "code": null, "e": 3493, "s": 3467, "text": "Python String | replace()" }, { "code": null, "e": 3525, "s": 3493, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3554, "s": 3525, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3584, "s": 3554, "text": "Iterate over a list in Python" }, { "code": null, "e": 3611, "s": 3584, "text": "Python Classes and Objects" } ]
strings.Fields() Function in Golang With Examples
19 Apr, 2020 strings.Fields() Function in Golang is used to splits the given string around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of substrings of str or an empty slice if str contains only white space. Syntax: func Fields(str string) []string Returns: A slice of substrings of str or an empty slice if str contains only white space. Example 1: // Golang program to illustrate the// strings.Fields() Functionpackage main import ( "fmt" "strings") func main() { // String s is split on the basis of white spaces // and store in a string array s := "GeeksforGeeks is a computer science portal !" v := strings.Fields(s) fmt.Println(v) // Another example by passing the string as argument // directly to the Fields() function v = strings.Fields("I am a software developer, I love coding") fmt.Println(v)} Output: [GeeksforGeeks is a computer science portal !] [I am a software developer, I love coding] Example 2: // Golang program to illustrate the// strings.Fields() Functionpackage main import ( "fmt" "strings") func main() { // Fields function also splits the string // on the basis of white spaces and tabs s := strings.Fields(" I \t love \n to \n code \n all \t day.") fmt.Println(s) // Splits into 5 words which have // newline character in between s = strings.Fields("I\nam\nlearning\nGo\nlanguage") fmt.Println(s)} Output: [I love to code all day.] [I am learning Go language] Golang-String Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Parse JSON in Golang? How to iterate over an Array using for loop in Golang? Structures in Golang Loops in Go Language Time Durations in Golang Strings in Golang Constants- Go Language time.Parse() Function in Golang With Examples Go Variables Class and Object in Golang
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Apr, 2020" }, { "code": null, "e": 293, "s": 28, "text": "strings.Fields() Function in Golang is used to splits the given string around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of substrings of str or an empty slice if str contains only white space." }, { "code": null, "e": 301, "s": 293, "text": "Syntax:" }, { "code": null, "e": 334, "s": 301, "text": "func Fields(str string) []string" }, { "code": null, "e": 424, "s": 334, "text": "Returns: A slice of substrings of str or an empty slice if str contains only white space." }, { "code": null, "e": 435, "s": 424, "text": "Example 1:" }, { "code": "// Golang program to illustrate the// strings.Fields() Functionpackage main import ( \"fmt\" \"strings\") func main() { // String s is split on the basis of white spaces // and store in a string array s := \"GeeksforGeeks is a computer science portal !\" v := strings.Fields(s) fmt.Println(v) // Another example by passing the string as argument // directly to the Fields() function v = strings.Fields(\"I am a software developer, I love coding\") fmt.Println(v)}", "e": 960, "s": 435, "text": null }, { "code": null, "e": 968, "s": 960, "text": "Output:" }, { "code": null, "e": 1059, "s": 968, "text": "[GeeksforGeeks is a computer science portal !]\n[I am a software developer, I love coding]\n" }, { "code": null, "e": 1070, "s": 1059, "text": "Example 2:" }, { "code": "// Golang program to illustrate the// strings.Fields() Functionpackage main import ( \"fmt\" \"strings\") func main() { // Fields function also splits the string // on the basis of white spaces and tabs s := strings.Fields(\" I \\t love \\n to \\n code \\n all \\t day.\") fmt.Println(s) // Splits into 5 words which have // newline character in between s = strings.Fields(\"I\\nam\\nlearning\\nGo\\nlanguage\") fmt.Println(s)}", "e": 1517, "s": 1070, "text": null }, { "code": null, "e": 1525, "s": 1517, "text": "Output:" }, { "code": null, "e": 1580, "s": 1525, "text": "[I love to code all day.]\n[I am learning Go language]\n" }, { "code": null, "e": 1594, "s": 1580, "text": "Golang-String" }, { "code": null, "e": 1601, "s": 1594, "text": "Picked" }, { "code": null, "e": 1613, "s": 1601, "text": "Go Language" }, { "code": null, "e": 1711, "s": 1613, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1740, "s": 1711, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 1795, "s": 1740, "text": "How to iterate over an Array using for loop in Golang?" }, { "code": null, "e": 1816, "s": 1795, "text": "Structures in Golang" }, { "code": null, "e": 1837, "s": 1816, "text": "Loops in Go Language" }, { "code": null, "e": 1862, "s": 1837, "text": "Time Durations in Golang" }, { "code": null, "e": 1880, "s": 1862, "text": "Strings in Golang" }, { "code": null, "e": 1903, "s": 1880, "text": "Constants- Go Language" }, { "code": null, "e": 1949, "s": 1903, "text": "time.Parse() Function in Golang With Examples" }, { "code": null, "e": 1962, "s": 1949, "text": "Go Variables" } ]
Introduction to Handsontable.js
22 Feb, 2021 What is handsontable.js ? Handsontable.js is a JavaScript data-grid component that can be used to build excel like web apps. Its basically a JavaScript library. One good thing about handsontable.js is that you can use it with vanilla JavaScript or React or Vue or Angular. Installation: You have two options to work with handsontable.js. You can either install by npm or you can use CDN. To install handsontable you need to run the following command on your node terminal: npm install handsontable If you have yarn instead of node then you have to run the following command: yarn add handsontable After installing it you have to include the below code in your html file: <script src=”node_modules/handsontable/dist/handsontable.full.min.js”></script><link href=”node_modules/handsontable/dist/handsontable.full.min.css” rel=”stylesheet” media=”screen”> As an alternative you can use CDN. In that case embed the following code in the html file. There is no need of installation: <script src=”https://cdn.jsdelivr.net/npm/[email protected]/dist/handsontable.full.min.js”></script><link href=”https://cdn.jsdelivr.net/npm/[email protected]/dist/handsontable.full.min.css”rel=”stylesheet” media=”screen”> How to use handsontable.js ? Building a basic spreadsheet is quite easy. Follow these steps to build a basic data-grid – First make an empty div element in the html file. This will be the container of the spreadsheet.HTMLHTML<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Introduction to Handsontable.js</title> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/handsontable.full.min.js"> </script> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/handsontable.full.min.css" rel="stylesheet" media="screen"> </head> <body> <h1> <center>Create your first data-grid</center> </h1> <!-- container to wrap the data-grid --> <div class="handsontable-container"></div> <script src="index.js"></script></body> </html> HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Introduction to Handsontable.js</title> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/handsontable.full.min.js"> </script> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/handsontable.full.min.css" rel="stylesheet" media="screen"> </head> <body> <h1> <center>Create your first data-grid</center> </h1> <!-- container to wrap the data-grid --> <div class="handsontable-container"></div> <script src="index.js"></script></body> </html> Now in the index.js file (or you can use script tags in html file), create a 2D array that will work as initial data on the data-grid. Each row of the 2D array represents each row of the handsontable. For example, if the following array is used as data source for handsontable object then the generated spread sheet will contain 13 rows and 5 columns. Note that you can also use objects as data source instead of 2D array.const data = [ ['roll','name','stream','semester','email id'], [1,'Raj','IT',8,'[email protected]'], [2,'Timir','CSE',4,'[email protected]'], [4,'Arjesh','IT',2,'[email protected]'], [5,'Haris ali','IT',6,'[email protected]'], [6,'Deepak','CSE',4,'[email protected]'], [7,'Dibyendu','ECE',4,'[email protected]'], [8,'Aman','IT',4,'[email protected]'], [9,'Binayak','CSE',6,'[email protected]'], [10,'Harshad','ECE',6,'[email protected]'], [11,'Abhra','IT',4,'[email protected]'], [12,'Sayan','IT',4,'[email protected]'], ] const data = [ ['roll','name','stream','semester','email id'], [1,'Raj','IT',8,'[email protected]'], [2,'Timir','CSE',4,'[email protected]'], [4,'Arjesh','IT',2,'[email protected]'], [5,'Haris ali','IT',6,'[email protected]'], [6,'Deepak','CSE',4,'[email protected]'], [7,'Dibyendu','ECE',4,'[email protected]'], [8,'Aman','IT',4,'[email protected]'], [9,'Binayak','CSE',6,'[email protected]'], [10,'Harshad','ECE',6,'[email protected]'], [11,'Abhra','IT',4,'[email protected]'], [12,'Sayan','IT',4,'[email protected]'], ] Grab the div elementlet container = document.querySelector(‘.handsontable-container’); let container = document.querySelector(‘.handsontable-container’); Create a handsontable object. Here Handontable constructor creates a spread sheet. It takes a DOM element as first argument which will contain the handsontable data grid. The second argument is an object that contains the properties of the data grid. For example, in the below code a handsontable object has defined with two arguments – container element and an object containing the data source for data grid.JavascriptJavascriptconst data = [ ['roll','name','stream','semester','email id'], [1,'Raj','IT',8,'[email protected]'], [2,'Timir','CSE',4,'[email protected]'], [4,'Arjesh','IT',2,'[email protected]'], [5,'Haris ali','IT',6,'[email protected]'], [6,'Deepak','CSE',4,'[email protected]'], [7,'Dibyendu','ECE',4,'[email protected]'], [8,'Aman','IT',4,'[email protected]'], [9,'Binayak','CSE',6,'[email protected]'], [10,'Harshad','ECE',6,'[email protected]'], [11,'Abhra','IT',4,'[email protected]'], [12,'Sayan','IT',4,'[email protected]'],] let container = document.querySelector('.handsontable-container'); let hot = new Handsontable(container,{ data: data // Initiating handsontable object }) Javascript const data = [ ['roll','name','stream','semester','email id'], [1,'Raj','IT',8,'[email protected]'], [2,'Timir','CSE',4,'[email protected]'], [4,'Arjesh','IT',2,'[email protected]'], [5,'Haris ali','IT',6,'[email protected]'], [6,'Deepak','CSE',4,'[email protected]'], [7,'Dibyendu','ECE',4,'[email protected]'], [8,'Aman','IT',4,'[email protected]'], [9,'Binayak','CSE',6,'[email protected]'], [10,'Harshad','ECE',6,'[email protected]'], [11,'Abhra','IT',4,'[email protected]'], [12,'Sayan','IT',4,'[email protected]'],] let container = document.querySelector('.handsontable-container'); let hot = new Handsontable(container,{ data: data // Initiating handsontable object }) Output: As shown in the above image, we have build an excel like spread sheet. Similar to excel, you can change the data of each column. This a basic data grid. However, you can customize it by adding lot of features. For example, If we want to add headers with several options , we can do it easily by adding additional key-value pairs to the object – Javascript let hot = new Handsontable(container, { data: data, // Added additional features // For adding headers on each row rowHeaders: true, // For adding headers on each column colHeaders: true, // For adding dropdown menu to each headers dropdownMenu: true,}) Output: If you want to give custom names to headers instead of A, B, C, D... you can do it by giving colHeaders attribute an array instead of true – let hot = new Handsontable(container,{ data: data, rowHeaders: true, // For giving custom names to headers colHeaders: ['roll', 'name', 'stream', 'semester', 'email'], dropdownMenu: true, // To add filter feature in table filters: true, } ) And then omit the first element of the data array – const data = [ [1,'Raj','IT',8,'[email protected]'], // The first array element deleted [2,'Timir','CSE',4,'[email protected]'], [4,'Arjesh','IT',2,'[email protected]'], [5,'Haris ali','IT',6,'[email protected]'], [6,'Deepak','CSE',4,'[email protected]'], [7,'Dibyendu','ECE',4,'[email protected]'], [8,'Aman','IT',4,'[email protected]'], [9,'Binayak','CSE',6,'[email protected]'], [10,'Harshad','ECE',6,'[email protected]'], [11,'Abhra','IT',4,'[email protected]'], [12,'Sayan','IT',4,'[email protected]'], ] Output: This article shows the basic of Handsontable. However handsontable.js has many other features than this. You can define functions to specific columns or cells, export it to excel, merge multiple rows or columns etc. Possibilities are endless! See the docs here to explore it. JavaScript-Questions JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises 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": 53, "s": 25, "text": "\n22 Feb, 2021" }, { "code": null, "e": 79, "s": 53, "text": "What is handsontable.js ?" }, { "code": null, "e": 326, "s": 79, "text": "Handsontable.js is a JavaScript data-grid component that can be used to build excel like web apps. Its basically a JavaScript library. One good thing about handsontable.js is that you can use it with vanilla JavaScript or React or Vue or Angular." }, { "code": null, "e": 340, "s": 326, "text": "Installation:" }, { "code": null, "e": 526, "s": 340, "text": "You have two options to work with handsontable.js. You can either install by npm or you can use CDN. To install handsontable you need to run the following command on your node terminal:" }, { "code": null, "e": 551, "s": 526, "text": "npm install handsontable" }, { "code": null, "e": 628, "s": 551, "text": "If you have yarn instead of node then you have to run the following command:" }, { "code": null, "e": 650, "s": 628, "text": "yarn add handsontable" }, { "code": null, "e": 724, "s": 650, "text": "After installing it you have to include the below code in your html file:" }, { "code": null, "e": 906, "s": 724, "text": "<script src=”node_modules/handsontable/dist/handsontable.full.min.js”></script><link href=”node_modules/handsontable/dist/handsontable.full.min.css” rel=”stylesheet” media=”screen”>" }, { "code": null, "e": 1031, "s": 906, "text": "As an alternative you can use CDN. In that case embed the following code in the html file. There is no need of installation:" }, { "code": null, "e": 1256, "s": 1031, "text": "<script src=”https://cdn.jsdelivr.net/npm/[email protected]/dist/handsontable.full.min.js”></script><link href=”https://cdn.jsdelivr.net/npm/[email protected]/dist/handsontable.full.min.css”rel=”stylesheet” media=”screen”>" }, { "code": null, "e": 1286, "s": 1256, "text": "How to use handsontable.js ?" }, { "code": null, "e": 1379, "s": 1286, "text": "Building a basic spreadsheet is quite easy. Follow these steps to build a basic data-grid –" }, { "code": null, "e": 2168, "s": 1379, "text": "First make an empty div element in the html file. This will be the container of the spreadsheet.HTMLHTML<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Introduction to Handsontable.js</title> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/handsontable.full.min.js\"> </script> <link href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/handsontable.full.min.css\" rel=\"stylesheet\" media=\"screen\"> </head> <body> <h1> <center>Create your first data-grid</center> </h1> <!-- container to wrap the data-grid --> <div class=\"handsontable-container\"></div> <script src=\"index.js\"></script></body> </html>" }, { "code": null, "e": 2173, "s": 2168, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Introduction to Handsontable.js</title> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/handsontable.full.min.js\"> </script> <link href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/handsontable.full.min.css\" rel=\"stylesheet\" media=\"screen\"> </head> <body> <h1> <center>Create your first data-grid</center> </h1> <!-- container to wrap the data-grid --> <div class=\"handsontable-container\"></div> <script src=\"index.js\"></script></body> </html>", "e": 2858, "s": 2173, "text": null }, { "code": null, "e": 3807, "s": 2858, "text": "Now in the index.js file (or you can use script tags in html file), create a 2D array that will work as initial data on the data-grid. Each row of the 2D array represents each row of the handsontable. For example, if the following array is used as data source for handsontable object then the generated spread sheet will contain 13 rows and 5 columns. Note that you can also use objects as data source instead of 2D array.const data = [\n ['roll','name','stream','semester','email id'],\n [1,'Raj','IT',8,'[email protected]'],\n [2,'Timir','CSE',4,'[email protected]'],\n [4,'Arjesh','IT',2,'[email protected]'],\n [5,'Haris ali','IT',6,'[email protected]'],\n [6,'Deepak','CSE',4,'[email protected]'],\n [7,'Dibyendu','ECE',4,'[email protected]'],\n [8,'Aman','IT',4,'[email protected]'],\n [9,'Binayak','CSE',6,'[email protected]'],\n [10,'Harshad','ECE',6,'[email protected]'],\n [11,'Abhra','IT',4,'[email protected]'],\n [12,'Sayan','IT',4,'[email protected]'],\n]" }, { "code": null, "e": 4334, "s": 3807, "text": "const data = [\n ['roll','name','stream','semester','email id'],\n [1,'Raj','IT',8,'[email protected]'],\n [2,'Timir','CSE',4,'[email protected]'],\n [4,'Arjesh','IT',2,'[email protected]'],\n [5,'Haris ali','IT',6,'[email protected]'],\n [6,'Deepak','CSE',4,'[email protected]'],\n [7,'Dibyendu','ECE',4,'[email protected]'],\n [8,'Aman','IT',4,'[email protected]'],\n [9,'Binayak','CSE',6,'[email protected]'],\n [10,'Harshad','ECE',6,'[email protected]'],\n [11,'Abhra','IT',4,'[email protected]'],\n [12,'Sayan','IT',4,'[email protected]'],\n]" }, { "code": null, "e": 4421, "s": 4334, "text": "Grab the div elementlet container = document.querySelector(‘.handsontable-container’);" }, { "code": null, "e": 4488, "s": 4421, "text": "let container = document.querySelector(‘.handsontable-container’);" }, { "code": null, "e": 5597, "s": 4488, "text": "Create a handsontable object. Here Handontable constructor creates a spread sheet. It takes a DOM element as first argument which will contain the handsontable data grid. The second argument is an object that contains the properties of the data grid. For example, in the below code a handsontable object has defined with two arguments – container element and an object containing the data source for data grid.JavascriptJavascriptconst data = [ ['roll','name','stream','semester','email id'], [1,'Raj','IT',8,'[email protected]'], [2,'Timir','CSE',4,'[email protected]'], [4,'Arjesh','IT',2,'[email protected]'], [5,'Haris ali','IT',6,'[email protected]'], [6,'Deepak','CSE',4,'[email protected]'], [7,'Dibyendu','ECE',4,'[email protected]'], [8,'Aman','IT',4,'[email protected]'], [9,'Binayak','CSE',6,'[email protected]'], [10,'Harshad','ECE',6,'[email protected]'], [11,'Abhra','IT',4,'[email protected]'], [12,'Sayan','IT',4,'[email protected]'],] let container = document.querySelector('.handsontable-container'); let hot = new Handsontable(container,{ data: data // Initiating handsontable object })" }, { "code": null, "e": 5608, "s": 5597, "text": "Javascript" }, { "code": "const data = [ ['roll','name','stream','semester','email id'], [1,'Raj','IT',8,'[email protected]'], [2,'Timir','CSE',4,'[email protected]'], [4,'Arjesh','IT',2,'[email protected]'], [5,'Haris ali','IT',6,'[email protected]'], [6,'Deepak','CSE',4,'[email protected]'], [7,'Dibyendu','ECE',4,'[email protected]'], [8,'Aman','IT',4,'[email protected]'], [9,'Binayak','CSE',6,'[email protected]'], [10,'Harshad','ECE',6,'[email protected]'], [11,'Abhra','IT',4,'[email protected]'], [12,'Sayan','IT',4,'[email protected]'],] let container = document.querySelector('.handsontable-container'); let hot = new Handsontable(container,{ data: data // Initiating handsontable object })", "e": 6287, "s": 5608, "text": null }, { "code": null, "e": 6295, "s": 6287, "text": "Output:" }, { "code": null, "e": 6506, "s": 6295, "text": "As shown in the above image, we have build an excel like spread sheet. Similar to excel, you can change the data of each column. This a basic data grid. However, you can customize it by adding lot of features." }, { "code": null, "e": 6641, "s": 6506, "text": "For example, If we want to add headers with several options , we can do it easily by adding additional key-value pairs to the object –" }, { "code": null, "e": 6652, "s": 6641, "text": "Javascript" }, { "code": "let hot = new Handsontable(container, { data: data, // Added additional features // For adding headers on each row rowHeaders: true, // For adding headers on each column colHeaders: true, // For adding dropdown menu to each headers dropdownMenu: true,})", "e": 6937, "s": 6652, "text": null }, { "code": null, "e": 6945, "s": 6937, "text": "Output:" }, { "code": null, "e": 7086, "s": 6945, "text": "If you want to give custom names to headers instead of A, B, C, D... you can do it by giving colHeaders attribute an array instead of true –" }, { "code": null, "e": 7359, "s": 7086, "text": "let hot = new Handsontable(container,{\n data: data,\n\n rowHeaders: true, \n\n // For giving custom names to headers\n colHeaders: ['roll', 'name', 'stream', 'semester', 'email'],\n dropdownMenu: true,\n\n // To add filter feature in table\n filters: true,\n}\n)" }, { "code": null, "e": 7411, "s": 7359, "text": "And then omit the first element of the data array –" }, { "code": null, "e": 7926, "s": 7411, "text": "const data = [\n [1,'Raj','IT',8,'[email protected]'],\n\n // The first array element deleted\n [2,'Timir','CSE',4,'[email protected]'],\n [4,'Arjesh','IT',2,'[email protected]'],\n [5,'Haris ali','IT',6,'[email protected]'],\n [6,'Deepak','CSE',4,'[email protected]'],\n [7,'Dibyendu','ECE',4,'[email protected]'],\n [8,'Aman','IT',4,'[email protected]'],\n [9,'Binayak','CSE',6,'[email protected]'],\n [10,'Harshad','ECE',6,'[email protected]'],\n [11,'Abhra','IT',4,'[email protected]'],\n [12,'Sayan','IT',4,'[email protected]'],\n]" }, { "code": null, "e": 7934, "s": 7926, "text": "Output:" }, { "code": null, "e": 8210, "s": 7934, "text": "This article shows the basic of Handsontable. However handsontable.js has many other features than this. You can define functions to specific columns or cells, export it to excel, merge multiple rows or columns etc. Possibilities are endless! See the docs here to explore it." }, { "code": null, "e": 8231, "s": 8210, "text": "JavaScript-Questions" }, { "code": null, "e": 8242, "s": 8231, "text": "JavaScript" }, { "code": null, "e": 8259, "s": 8242, "text": "Web Technologies" }, { "code": null, "e": 8357, "s": 8259, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8418, "s": 8357, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 8458, "s": 8418, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 8499, "s": 8458, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 8541, "s": 8499, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 8563, "s": 8541, "text": "JavaScript | Promises" }, { "code": null, "e": 8596, "s": 8563, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 8658, "s": 8596, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 8719, "s": 8658, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 8769, "s": 8719, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python – Assigning Key values to list elements from Value list Dictionary
01 Aug, 2020 Given List of elements, map them with keys of matching value from value list. Input : test_list = [4, 6, 3, 5, 3], test_dict = {“Gfg” : [5, 3, 6], “is” : [8, 4]}Output : [‘is’, ‘Gfg’, ‘Gfg’, ‘Gfg’, ‘Gfg’]Explanation : 4 is present in “is” key, hence mapped in new list. Input : test_list = [6, 3, 5, 3], test_dict = {“Gfg” : [5, 3, 6], “is” : [18, 14]}Output : [‘Gfg’, ‘Gfg’, ‘Gfg’, ‘Gfg’]Explanation : All elements present in “Gfg” key. Method #1 : Using list comprehension This is one of the ways in which this task can be performed. In this, we extract each element of dictionary value list to check list value occurrence, if matched, we assign that key’s value to that index. Python3 # Python3 code to demonstrate working of # Assigning Key values to list elements from Value list Dictionary# Using list comprehension # initializing listtest_list = [4, 6, 3, 10, 5, 3] # printing original listprint("The original list : " + str(test_list)) # initializing dictionary test_dict = {"Gfg" : [5, 3, 6], "is" : [8, 4], "Best" : [10, 11]} # nested loop inside list comprehension to check each key res = [key for ele in test_list for key, val in test_dict.items() if ele in val] # printing result print("The filtered list : " + str(res)) The original list : [4, 6, 3, 10, 5, 3] The filtered list : ['is', 'Gfg', 'Gfg', 'Best', 'Gfg', 'Gfg'] Method #2 : Using dictionary comprehension + list comprehension This is yet another way in which this task can be performed. In this we create inverse dictionary, and map each list value with its key, post that each key is mapped with argument key list elements for matching key value. Python3 # Python3 code to demonstrate working of # Assigning Key values to list elements from Value list Dictionary# Using dictionary comprehension + list comprehension # initializing listtest_list = [4, 6, 3, 10, 5, 3] # printing original listprint("The original list : " + str(test_list)) # initializing dictionary test_dict = {"Gfg" : [5, 3, 6], "is" : [8, 4], "Best" : [10, 11]} # creating inverse dictionary of elements temp = {j : i for i, k in test_dict.items() for j in k} # creating end result by mapping elementsres = [temp.get(key) for key in test_list] # printing result print("The filtered list : " + str(res)) The original list : [4, 6, 3, 10, 5, 3] The filtered list : ['is', 'Gfg', 'Gfg', 'Best', 'Gfg', 'Gfg'] Python dictionary-programs Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Aug, 2020" }, { "code": null, "e": 130, "s": 52, "text": "Given List of elements, map them with keys of matching value from value list." }, { "code": null, "e": 322, "s": 130, "text": "Input : test_list = [4, 6, 3, 5, 3], test_dict = {“Gfg” : [5, 3, 6], “is” : [8, 4]}Output : [‘is’, ‘Gfg’, ‘Gfg’, ‘Gfg’, ‘Gfg’]Explanation : 4 is present in “is” key, hence mapped in new list." }, { "code": null, "e": 490, "s": 322, "text": "Input : test_list = [6, 3, 5, 3], test_dict = {“Gfg” : [5, 3, 6], “is” : [18, 14]}Output : [‘Gfg’, ‘Gfg’, ‘Gfg’, ‘Gfg’]Explanation : All elements present in “Gfg” key." }, { "code": null, "e": 527, "s": 490, "text": "Method #1 : Using list comprehension" }, { "code": null, "e": 732, "s": 527, "text": "This is one of the ways in which this task can be performed. In this, we extract each element of dictionary value list to check list value occurrence, if matched, we assign that key’s value to that index." }, { "code": null, "e": 740, "s": 732, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Assigning Key values to list elements from Value list Dictionary# Using list comprehension # initializing listtest_list = [4, 6, 3, 10, 5, 3] # printing original listprint(\"The original list : \" + str(test_list)) # initializing dictionary test_dict = {\"Gfg\" : [5, 3, 6], \"is\" : [8, 4], \"Best\" : [10, 11]} # nested loop inside list comprehension to check each key res = [key for ele in test_list for key, val in test_dict.items() if ele in val] # printing result print(\"The filtered list : \" + str(res))", "e": 1297, "s": 740, "text": null }, { "code": null, "e": 1401, "s": 1297, "text": "The original list : [4, 6, 3, 10, 5, 3]\nThe filtered list : ['is', 'Gfg', 'Gfg', 'Best', 'Gfg', 'Gfg']\n" }, { "code": null, "e": 1465, "s": 1401, "text": "Method #2 : Using dictionary comprehension + list comprehension" }, { "code": null, "e": 1688, "s": 1465, "text": "This is yet another way in which this task can be performed. In this we create inverse dictionary, and map each list value with its key, post that each key is mapped with argument key list elements for matching key value." }, { "code": null, "e": 1696, "s": 1688, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Assigning Key values to list elements from Value list Dictionary# Using dictionary comprehension + list comprehension # initializing listtest_list = [4, 6, 3, 10, 5, 3] # printing original listprint(\"The original list : \" + str(test_list)) # initializing dictionary test_dict = {\"Gfg\" : [5, 3, 6], \"is\" : [8, 4], \"Best\" : [10, 11]} # creating inverse dictionary of elements temp = {j : i for i, k in test_dict.items() for j in k} # creating end result by mapping elementsres = [temp.get(key) for key in test_list] # printing result print(\"The filtered list : \" + str(res))", "e": 2318, "s": 1696, "text": null }, { "code": null, "e": 2422, "s": 2318, "text": "The original list : [4, 6, 3, 10, 5, 3]\nThe filtered list : ['is', 'Gfg', 'Gfg', 'Best', 'Gfg', 'Gfg']\n" }, { "code": null, "e": 2449, "s": 2422, "text": "Python dictionary-programs" }, { "code": null, "e": 2470, "s": 2449, "text": "Python list-programs" }, { "code": null, "e": 2477, "s": 2470, "text": "Python" }, { "code": null, "e": 2493, "s": 2477, "text": "Python Programs" } ]
Vulnerability in input() function – Python 2.x
Difficulty Level : Medium This article aims at explaining and exploring the vulnerability in the input() function in Python 2.x. In Python 3, the raw_input() function was erased, and its functionality was transferred to a new built-in function known as input(). There are two common methods to receive input in Python 2.x: Using the input() function: This function takes the value and type of the input you enter as it is without modifying any type.Using the raw_input() function: This function explicitly converts the input you give to type string, Using the input() function: This function takes the value and type of the input you enter as it is without modifying any type. Using the raw_input() function: This function explicitly converts the input you give to type string, Let us use the following program to determine the difference between the two: Python # Python 2.x program to show differences between# input() and rawinput()function # 3 inputs using raw_input() function,# after which data type of the value# entered is displayeds1 = raw_input("Enter input to test raw_input() function: ")print type(s1) s2 = raw_input("Enter input to test raw_input() function: ")print type(s2) s3 = raw_input("Enter input to test raw_input() function: ")print type(s3) # 3 inputs using input() function,# after which data type of the value# entered is displayeds4 = input("Enter input to test input() function: ")print type(s4) s5 = input("Enter input to test input() function: ")print type(s5) s6 = input("Enter input to test input() function: ")print type(s6) Input: Hello 456 [1,2,3] 45 "goodbye" [1,2,3] Output: Enter input to test raw_input() function: <type 'str'> Enter input to test raw_input() function: <type 'str'> Enter input to test raw_input() function: <type 'str'> Enter input to test input() function: <type 'int'> Enter input to test input() function: <type 'str'> Enter input to test input() function: <type 'list'> Note: While giving string input in the input() function, we have to enclose to value in double-quotes. This is not required in raw_input() The vulnerability in input() method lies in the fact that the variable accessing the value of input can be accessed by anyone just by using the name of the variable or method. Let us explore this one by one: The variable having the value of input variable is able to access the value of the input variable directly. Python Python3 # Python 2.x program to show Vulnerabilities# in input() function using a variable import randomsecret_number = random.randint(1,500)print "Pick a number between 1 to 500"while True: res = input("Guess the number: ") if res==secret_number: print "You win" break else: print "You lose" continue # Python 3 to demonstrate difference in input() function import randomsecret_number = random.randint(1,500)print ("Pick a number between 1 to 500")while True: res = input("Guess the number: ") if res==secret_number: print ("You win") break else: print ("You lose") continue Input: 15 Output: Pick a number between 1 to 500 Guess the number: You lose Guess the number: Input: secret_number Output: Pick a number between 1 to 500 Guess the number: You win As it can be seen, in the second case the variable “secret_number” can be directly given as input and the answer is always “You won”. It evaluates the variable as if a number was directly entered, which means it returns a True Boolean always. Using raw_input, would not be possible as it disallows reading the variable directly. Python 3 shows different results. If “secret_number” is given as input, answer is ‘You lose’. The vulnerability lies here as we can even provide the name of a function as input and access values that are otherwise not meant to be accessed. Python # Python 2.x program to demonstrate input() function# vulnerability by passing function name as parametersecret_value = 500 # function that returns the secret valuedef secretfunction(): return secret_value # using raw_input() to enter the numberinput1 = raw_input("Raw_input(): Guess secret number: ") # input1 will be explicitly converted to a stringif input1 == secret_value: print "You guessed correct"else: print "wrong answer" # using input() to enter the numberinput2 = input("Input(): Guess the secret number: ") #input2 is evaluated as it is enteredif input2 == secret_value: print "You guessed correct"else: print "wrong answer" Input: 400 secretfunction() Output: Raw_input(): Guess secret number: wrong answer Input(): Guess the secret number: You guessed correct In this set of input/output, we can see that when we use raw_input, we necessarily have to input the correct number. However while using the input() function, we can even provide the name of a function or variable, and the interpreter will evaluate that. Here for example, the input for input() function has been given as the name of a function ‘secretfunction()’. The interpreter evaluates this function call and returns the secret number that we wish to find and hence our if the condition evaluates to be true, even though we did not enter the secret number Input: secretfunction() secret_value Output: Raw_input(): Guess secret number: wrong answer Input(): Guess the secret number: You guessed correct As explained in the first point, in this example also we were able to simply enter the variable name ‘secret_number’ in the input for ‘input()’ function and we were able to gain access to the secret value. However, while trying to call secretfunction() in the input for the raw_input() function, it gives us false as the interpreter converts our argument to a string, and doesn’t evaluate it as a function call. It is always better to use raw_input() in python 2.x and then explicitly convert the input to whatever type we require. For example, if we wish to take the input of an integer, we can do the following n = int(raw_input()) This prevents the malicious calling or evaluation of functions. This article is contributed by Deepak Srivatsav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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. Santhosh220897 nitinsrivastava06 bhawnachelani123 secure-coding vulnerability Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Read a file line by line in Python How to Install PIP on Windows ? Python String | replace() *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method
[ { "code": null, "e": 26, "s": 0, "text": "Difficulty Level :\nMedium" }, { "code": null, "e": 262, "s": 26, "text": "This article aims at explaining and exploring the vulnerability in the input() function in Python 2.x. In Python 3, the raw_input() function was erased, and its functionality was transferred to a new built-in function known as input()." }, { "code": null, "e": 323, "s": 262, "text": "There are two common methods to receive input in Python 2.x:" }, { "code": null, "e": 550, "s": 323, "text": "Using the input() function: This function takes the value and type of the input you enter as it is without modifying any type.Using the raw_input() function: This function explicitly converts the input you give to type string," }, { "code": null, "e": 677, "s": 550, "text": "Using the input() function: This function takes the value and type of the input you enter as it is without modifying any type." }, { "code": null, "e": 778, "s": 677, "text": "Using the raw_input() function: This function explicitly converts the input you give to type string," }, { "code": null, "e": 857, "s": 778, "text": "Let us use the following program to determine the difference between the two: " }, { "code": null, "e": 864, "s": 857, "text": "Python" }, { "code": "# Python 2.x program to show differences between# input() and rawinput()function # 3 inputs using raw_input() function,# after which data type of the value# entered is displayeds1 = raw_input(\"Enter input to test raw_input() function: \")print type(s1) s2 = raw_input(\"Enter input to test raw_input() function: \")print type(s2) s3 = raw_input(\"Enter input to test raw_input() function: \")print type(s3) # 3 inputs using input() function,# after which data type of the value# entered is displayeds4 = input(\"Enter input to test input() function: \")print type(s4) s5 = input(\"Enter input to test input() function: \")print type(s5) s6 = input(\"Enter input to test input() function: \")print type(s6)", "e": 1559, "s": 864, "text": null }, { "code": null, "e": 1566, "s": 1559, "text": "Input:" }, { "code": null, "e": 1605, "s": 1566, "text": "Hello\n456\n[1,2,3]\n45\n\"goodbye\"\n[1,2,3]" }, { "code": null, "e": 1613, "s": 1605, "text": "Output:" }, { "code": null, "e": 1933, "s": 1613, "text": "Enter input to test raw_input() function: <type 'str'>\nEnter input to test raw_input() function: <type 'str'>\nEnter input to test raw_input() function: <type 'str'>\n\nEnter input to test input() function: <type 'int'>\nEnter input to test input() function: <type 'str'>\nEnter input to test input() function: <type 'list'>" }, { "code": null, "e": 2072, "s": 1933, "text": "Note: While giving string input in the input() function, we have to enclose to value in double-quotes. This is not required in raw_input()" }, { "code": null, "e": 2280, "s": 2072, "text": "The vulnerability in input() method lies in the fact that the variable accessing the value of input can be accessed by anyone just by using the name of the variable or method. Let us explore this one by one:" }, { "code": null, "e": 2389, "s": 2280, "text": "The variable having the value of input variable is able to access the value of the input variable directly. " }, { "code": null, "e": 2396, "s": 2389, "text": "Python" }, { "code": null, "e": 2404, "s": 2396, "text": "Python3" }, { "code": "# Python 2.x program to show Vulnerabilities# in input() function using a variable import randomsecret_number = random.randint(1,500)print \"Pick a number between 1 to 500\"while True: res = input(\"Guess the number: \") if res==secret_number: print \"You win\" break else: print \"You lose\" continue", "e": 2735, "s": 2404, "text": null }, { "code": "# Python 3 to demonstrate difference in input() function import randomsecret_number = random.randint(1,500)print (\"Pick a number between 1 to 500\")while True: res = input(\"Guess the number: \") if res==secret_number: print (\"You win\") break else: print (\"You lose\") continue", "e": 3047, "s": 2735, "text": null }, { "code": null, "e": 3054, "s": 3047, "text": "Input:" }, { "code": null, "e": 3057, "s": 3054, "text": "15" }, { "code": null, "e": 3065, "s": 3057, "text": "Output:" }, { "code": null, "e": 3142, "s": 3065, "text": "Pick a number between 1 to 500\nGuess the number: You lose\nGuess the number: " }, { "code": null, "e": 3149, "s": 3142, "text": "Input:" }, { "code": null, "e": 3163, "s": 3149, "text": "secret_number" }, { "code": null, "e": 3171, "s": 3163, "text": "Output:" }, { "code": null, "e": 3228, "s": 3171, "text": "Pick a number between 1 to 500\nGuess the number: You win" }, { "code": null, "e": 3557, "s": 3228, "text": "As it can be seen, in the second case the variable “secret_number” can be directly given as input and the answer is always “You won”. It evaluates the variable as if a number was directly entered, which means it returns a True Boolean always. Using raw_input, would not be possible as it disallows reading the variable directly." }, { "code": null, "e": 3653, "s": 3557, "text": "Python 3 shows different results. If “secret_number” is given as input, answer is ‘You lose’." }, { "code": null, "e": 3800, "s": 3653, "text": "The vulnerability lies here as we can even provide the name of a function as input and access values that are otherwise not meant to be accessed. " }, { "code": null, "e": 3807, "s": 3800, "text": "Python" }, { "code": "# Python 2.x program to demonstrate input() function# vulnerability by passing function name as parametersecret_value = 500 # function that returns the secret valuedef secretfunction(): return secret_value # using raw_input() to enter the numberinput1 = raw_input(\"Raw_input(): Guess secret number: \") # input1 will be explicitly converted to a stringif input1 == secret_value: print \"You guessed correct\"else: print \"wrong answer\" # using input() to enter the numberinput2 = input(\"Input(): Guess the secret number: \") #input2 is evaluated as it is enteredif input2 == secret_value: print \"You guessed correct\"else: print \"wrong answer\"", "e": 4464, "s": 3807, "text": null }, { "code": null, "e": 4471, "s": 4464, "text": "Input:" }, { "code": null, "e": 4492, "s": 4471, "text": "400\nsecretfunction()" }, { "code": null, "e": 4500, "s": 4492, "text": "Output:" }, { "code": null, "e": 4601, "s": 4500, "text": "Raw_input(): Guess secret number: wrong answer\nInput(): Guess the secret number: You guessed correct" }, { "code": null, "e": 5169, "s": 4601, "text": "In this set of input/output, we can see that when we use raw_input, we necessarily have to input the correct number. However while using the input() function, we can even provide the name of a function or variable, and the interpreter will evaluate that. Here for example, the input for input() function has been given as the name of a function ‘secretfunction()’. The interpreter evaluates this function call and returns the secret number that we wish to find and hence our if the condition evaluates to be true, even though we did not enter the secret number Input:" }, { "code": null, "e": 5199, "s": 5169, "text": "secretfunction()\nsecret_value" }, { "code": null, "e": 5207, "s": 5199, "text": "Output:" }, { "code": null, "e": 5308, "s": 5207, "text": "Raw_input(): Guess secret number: wrong answer\nInput(): Guess the secret number: You guessed correct" }, { "code": null, "e": 5720, "s": 5308, "text": "As explained in the first point, in this example also we were able to simply enter the variable name ‘secret_number’ in the input for ‘input()’ function and we were able to gain access to the secret value. However, while trying to call secretfunction() in the input for the raw_input() function, it gives us false as the interpreter converts our argument to a string, and doesn’t evaluate it as a function call." }, { "code": null, "e": 5921, "s": 5720, "text": "It is always better to use raw_input() in python 2.x and then explicitly convert the input to whatever type we require. For example, if we wish to take the input of an integer, we can do the following" }, { "code": null, "e": 5942, "s": 5921, "text": "n = int(raw_input())" }, { "code": null, "e": 6007, "s": 5942, "text": "This prevents the malicious calling or evaluation of functions. " }, { "code": null, "e": 6432, "s": 6007, "text": "This article is contributed by Deepak Srivatsav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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": 6447, "s": 6432, "text": "Santhosh220897" }, { "code": null, "e": 6465, "s": 6447, "text": "nitinsrivastava06" }, { "code": null, "e": 6482, "s": 6465, "text": "bhawnachelani123" }, { "code": null, "e": 6496, "s": 6482, "text": "secure-coding" }, { "code": null, "e": 6510, "s": 6496, "text": "vulnerability" }, { "code": null, "e": 6517, "s": 6510, "text": "Python" }, { "code": null, "e": 6615, "s": 6517, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6633, "s": 6615, "text": "Python Dictionary" }, { "code": null, "e": 6675, "s": 6633, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 6710, "s": 6675, "text": "Read a file line by line in Python" }, { "code": null, "e": 6742, "s": 6710, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 6768, "s": 6742, "text": "Python String | replace()" }, { "code": null, "e": 6797, "s": 6768, "text": "*args and **kwargs in Python" }, { "code": null, "e": 6824, "s": 6797, "text": "Python Classes and Objects" }, { "code": null, "e": 6845, "s": 6824, "text": "Python OOPs Concepts" }, { "code": null, "e": 6868, "s": 6845, "text": "Introduction To PYTHON" } ]
PostgreSQL – Rename Database
22 Feb, 2021 In PostgreSQL, the ALTER DATABASE RENAME TO statement is used to rename a database. The below steps need to be followed while renaming a database: Disconnect from the database that you want to rename by connecting to a different database.Terminate all connections, connected to the database to be renamed.Now you can use the ALTER DATABASE statement to rename the database. Disconnect from the database that you want to rename by connecting to a different database. Terminate all connections, connected to the database to be renamed. Now you can use the ALTER DATABASE statement to rename the database. Now let’s look into the below example to see how to rename a database in PostgreSQL. Example: Step 1: Create a database named “test_db” using the below commands: CREATE DATABASE test_db; Step 2: Now to rename the “test_db” database, disconnect from that database using the below command and connect to the Postgres database: test_db=# \connect postgres; Step 3: Use the below query to check all active connections to the “test_db” database: SELECT * FROM pg_stat_activity WHERE datname = 'test_db'; Step 4: Use the below query to terminate all the connections to the test_db database: SELECT pg_terminate_backend (pid) FROM pg_stat_activity WHERE datname = 'test_db'; Step 5: Now use the ALTER DATABASE RENAME TO statement to rename the database as “new_test_db”(say) as follows: ALTER DATABASE test_db RENAME TO new_test_db; RajuKumar19 postgreSQL-managing-database PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Feb, 2021" }, { "code": null, "e": 176, "s": 28, "text": "In PostgreSQL, the ALTER DATABASE RENAME TO statement is used to rename a database. The below steps need to be followed while renaming a database: " }, { "code": null, "e": 404, "s": 176, "text": "Disconnect from the database that you want to rename by connecting to a different database.Terminate all connections, connected to the database to be renamed.Now you can use the ALTER DATABASE statement to rename the database. " }, { "code": null, "e": 496, "s": 404, "text": "Disconnect from the database that you want to rename by connecting to a different database." }, { "code": null, "e": 564, "s": 496, "text": "Terminate all connections, connected to the database to be renamed." }, { "code": null, "e": 634, "s": 564, "text": "Now you can use the ALTER DATABASE statement to rename the database. " }, { "code": null, "e": 720, "s": 634, "text": "Now let’s look into the below example to see how to rename a database in PostgreSQL. " }, { "code": null, "e": 730, "s": 720, "text": "Example: " }, { "code": null, "e": 798, "s": 730, "text": "Step 1: Create a database named “test_db” using the below commands:" }, { "code": null, "e": 823, "s": 798, "text": "CREATE DATABASE test_db;" }, { "code": null, "e": 962, "s": 823, "text": "Step 2: Now to rename the “test_db” database, disconnect from that database using the below command and connect to the Postgres database: " }, { "code": null, "e": 991, "s": 962, "text": "test_db=# \\connect postgres;" }, { "code": null, "e": 1079, "s": 991, "text": "Step 3: Use the below query to check all active connections to the “test_db” database: " }, { "code": null, "e": 1149, "s": 1079, "text": "SELECT\n *\nFROM\n pg_stat_activity\nWHERE\n datname = 'test_db';" }, { "code": null, "e": 1236, "s": 1149, "text": "Step 4: Use the below query to terminate all the connections to the test_db database: " }, { "code": null, "e": 1331, "s": 1236, "text": "SELECT\n pg_terminate_backend (pid)\nFROM\n pg_stat_activity\nWHERE\n datname = 'test_db';" }, { "code": null, "e": 1444, "s": 1331, "text": "Step 5: Now use the ALTER DATABASE RENAME TO statement to rename the database as “new_test_db”(say) as follows: " }, { "code": null, "e": 1491, "s": 1444, "text": "ALTER DATABASE test_db RENAME TO new_test_db; " }, { "code": null, "e": 1503, "s": 1491, "text": "RajuKumar19" }, { "code": null, "e": 1532, "s": 1503, "text": "postgreSQL-managing-database" }, { "code": null, "e": 1543, "s": 1532, "text": "PostgreSQL" } ]
TreeMap in Java
07 Jul, 2022 The TreeMap in Java is used to implement Map interface and NavigableMap along with the AbstractMap Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. This proves to be an efficient way of sorting and storing the key-value pairs. The storing order maintained by the treemap must be consistent with equals just like any other sorted map, irrespective of the explicit comparators. The treemap implementation is not synchronized in the sense that if a map is accessed by multiple threads, concurrently and at least one of the threads modifies the map structurally, it must be synchronized externally. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Some important features of the treemap are as follows: This class is a member of the Java Collections Framework.The class implements Map interfaces including NavigableMap, SortedMap, and extends AbstractMap class.TreeMap in Java does not allow null keys (like Map) and thus a NullPointerException is thrown. However, multiple null values can be associated with different keys.Entry pairs returned by the methods in this class and its views represent snapshots of mappings at the time they were produced. They do not support the Entry.setValue method. This class is a member of the Java Collections Framework. The class implements Map interfaces including NavigableMap, SortedMap, and extends AbstractMap class. TreeMap in Java does not allow null keys (like Map) and thus a NullPointerException is thrown. However, multiple null values can be associated with different keys. Entry pairs returned by the methods in this class and its views represent snapshots of mappings at the time they were produced. They do not support the Entry.setValue method. Now let us move forward and discuss Synchronized TreeMap. The implementation of a TreeMap is not synchronized. This means that if multiple threads access a tree set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by using the Collections.synchronizedSortedMap method. This is best done at the creation time, to prevent accidental unsynchronized access to the set. This can be done as: SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...)); Geeks, now you must be wondering how does the TreeMap works internally? The methods in a TreeMap while getting keyset and values, return an Iterator that is fail-fast in nature. Thus, any concurrent modification will throw ConcurrentModificationException. A TreeMap is based upon a red-black tree data structure. Each node in the tree has: 3 Variables (K key=Key, V value=Value, boolean color=Color) 3 References (Entry left = Left, Entry right = Right, Entry parent = Parent) In order to create a TreeMap, we need to create an object of the TreeMap class. The TreeMap class consists of various constructors that allow the possible creation of the TreeMap. The following are the constructors available in this class: TreeMap()TreeMap(Comparator comp)TreeMap(Map M)TreeMap(SortedMap sm) TreeMap() TreeMap(Comparator comp) TreeMap(Map M) TreeMap(SortedMap sm) Let us discuss them individually alongside implementing every constructor as follows: Constructor 1: TreeMap() This constructor is used to build an empty treemap that will be sorted by using the natural order of its keys. Example Java // Java Program to Demonstrate TreeMap// using the Default Constructor // Importing required classesimport java.util.*;import java.util.concurrent.*; // Main class// TreeMapImplementationpublic class GFG { // Method 1 // To show TreeMap constructor static void Example1stConstructor() { // Creating an empty TreeMap TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>(); // Mapping string values to int keys // using put() method tree_map.put(10, "Geeks"); tree_map.put(15, "4"); tree_map.put(20, "Geeks"); tree_map.put(25, "Welcomes"); tree_map.put(30, "You"); // Printing the elements of TreeMap System.out.println("TreeMap: " + tree_map); } // Method 2 // Main driver method public static void main(String[] args) { System.out.println("TreeMap using " + "TreeMap() constructor:\n"); // Calling constructor Example1stConstructor(); }} TreeMap using TreeMap() constructor: TreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You} Constructor 2: TreeMap(Comparator comp) This constructor is used to build an empty TreeMap object in which the elements will need an external specification of the sorting order. Example Java // Java Program to Demonstrate TreeMap// using Comparator Constructor // Importing required classesimport java.util.*;import java.util.concurrent.*; // Class 1// Helper class representing Studentclass Student { // Attributes of a student int rollno; String name, address; // Constructor public Student(int rollno, String name, String address) { // This keyword refers to current object itself this.rollno = rollno; this.name = name; this.address = address; } // Method of this class // To print student details public String toString() { return this.rollno + " " + this.name + " " + this.address; }} // Class 2// Helper class - Comparator implementationclass Sortbyroll implements Comparator<Student> { // Used for sorting in ascending order of // roll number public int compare(Student a, Student b) { return a.rollno - b.rollno; }} // Class 3// Main classpublic class GFG { // Calling constructor inside main() static void Example2ndConstructor() { // Creating an empty TreeMap TreeMap<Student, Integer> tree_map = new TreeMap<Student, Integer>( new Sortbyroll()); // Mapping string values to int keys tree_map.put(new Student(111, "bbbb", "london"), 2); tree_map.put(new Student(131, "aaaa", "nyc"), 3); tree_map.put(new Student(121, "cccc", "jaipur"), 1); // Printing the elements of TreeMap System.out.println("TreeMap: " + tree_map); } // Main driver method public static void main(String[] args) { System.out.println("TreeMap using " + "TreeMap(Comparator)" + " constructor:\n"); Example2ndConstructor(); }} TreeMap using TreeMap(Comparator) constructor: TreeMap: {111 bbbb london=2, 121 cccc jaipur=1, 131 aaaa nyc=3} Constructor 3: TreeMap(Map M) This constructor is used to initialize a TreeMap with the entries from the given map M which will be sorted by using the natural order of the keys. Example Java // Java Program to Demonstrate TreeMap// using the Default Constructor // Importing required classesimport java.util.*;import java.util.concurrent.*; // Main classpublic class TreeMapImplementation { // Method 1 // To illustrate constructor<Map> static void Example3rdConstructor() { // Creating an empty HashMap Map<Integer, String> hash_map = new HashMap<Integer, String>(); // Mapping string values to int keys // using put() method hash_map.put(10, "Geeks"); hash_map.put(15, "4"); hash_map.put(20, "Geeks"); hash_map.put(25, "Welcomes"); hash_map.put(30, "You"); // Creating the TreeMap using the Map TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>(hash_map); // Printing the elements of TreeMap System.out.println("TreeMap: " + tree_map); } // Method 2 // Main driver method public static void main(String[] args) { System.out.println("TreeMap using " + "TreeMap(Map)" + " constructor:\n"); Example3rdConstructor(); }} TreeMap using TreeMap(Map) constructor: TreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You} Constructor 4: TreeMap(SortedMap sm) This constructor is used to initialize a TreeMap with the entries from the given sorted map which will be stored in the same order as the given sorted map. Example Java // Java Program to Demonstrate TreeMap// using the SortedMap Constructor // Importing required classesimport java.util.*;import java.util.concurrent.*; // Main class// TreeMapImplementationpublic class GFG { // Method // To show TreeMap(SortedMap) constructor static void Example4thConstructor() { // Creating a SortedMap SortedMap<Integer, String> sorted_map = new ConcurrentSkipListMap<Integer, String>(); // Mapping string values to int keys // using put() method sorted_map.put(10, "Geeks"); sorted_map.put(15, "4"); sorted_map.put(20, "Geeks"); sorted_map.put(25, "Welcomes"); sorted_map.put(30, "You"); // Creating the TreeMap using the SortedMap TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>(sorted_map); // Printing the elements of TreeMap System.out.println("TreeMap: " + tree_map); } // Method 2 // Main driver method public static void main(String[] args) { System.out.println("TreeMap using " + "TreeMap(SortedMap)" + " constructor:\n"); Example4thConstructor(); }} TreeMap using TreeMap(SortedMap) constructor: TreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You} Implementation: The following programs below will demonstrate better how to create, insert, and traverse through the TreeMap. Illustration: Java // Java Program to Illustrate Operations in TreeMap// Such as Creation, insertion// searching, and traversal // Importing required classesimport java.util.*;import java.util.concurrent.*; // Main class// Implementation of TreeMappublic class GFG { // Declaring a TreeMap static TreeMap<Integer, String> tree_map; // Method 1 // To create TreeMap static void create() { // Creating an empty TreeMap tree_map = new TreeMap<Integer, String>(); // Display message only System.out.println("TreeMap successfully" + " created"); } // Method 2 // To Insert values in the TreeMap static void insert() { // Mapping string values to int keys // using put() method tree_map.put(10, "Geeks"); tree_map.put(15, "4"); tree_map.put(20, "Geeks"); tree_map.put(25, "Welcomes"); tree_map.put(30, "You"); // Display message only System.out.println("\nElements successfully" + " inserted in the TreeMap"); } // Method 3 // To search a key in TreeMap static void search(int key) { // Checking for the key System.out.println("\nIs key \"" + key + "\" present? " + tree_map.containsKey(key)); } // Method 4 // To search a value in TreeMap static void search(String value) { // Checking for the value System.out.println("\nIs value \"" + value + "\" present? " + tree_map.containsValue(value)); } // Method 5 // To display the elements in TreeMap static void display() { // Displaying the TreeMap System.out.println("\nDisplaying the TreeMap:"); System.out.println("TreeMap: " + tree_map); } // Method 6 // To traverse TreeMap static void traverse() { // Display message only System.out.println("\nTraversing the TreeMap:"); for (Map.Entry<Integer, String> e : tree_map.entrySet()) System.out.println(e.getKey() + " " + e.getValue()); } // Method 6 // Main driver method public static void main(String[] args) { // Calling above defined methods inside main() // Creating a TreeMap create(); // Inserting the values in the TreeMap insert(); // Search key "50" in the TreeMap search(50); // Search value "Geeks" in the TreeMap search("Geeks"); // Display the elements in TreeMap display(); // Traversing the TreeMap traverse(); }} TreeMap successfully created Elements successfully inserted in the TreeMap Is key "50" present? false Is value "Geeks" present? true Displaying the TreeMap: TreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You} Traversing the TreeMap: 10 Geeks 15 4 20 Geeks 25 Welcomes 30 You After the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the TreeMap. Now, let’s see how to perform a few frequently used operations on the TreeMap. Operation 1: Adding Elements In order to add an element to the TreeMap, we can use the put() method. However, the insertion order is not retained in the TreeMap. Internally, for every element, the keys are compared and sorted in ascending order. Example Java // Java Program to Illustrate Addition of Elements// in TreeMap using put() Method // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Default Initialization of a TreeMap TreeMap tm1 = new TreeMap(); // Inserting the elements in TreeMap // using put() method tm1.put(3, "Geeks"); tm1.put(2, "For"); tm1.put(1, "Geeks"); // Initialization of a TreeMap using Generics TreeMap<Integer, String> tm2 = new TreeMap<Integer, String>(); // Inserting the elements in TreeMap // again using put() method tm2.put(new Integer(3), "Geeks"); tm2.put(new Integer(2), "For"); tm2.put(new Integer(1), "Geeks"); // Printing the elements of both TreeMaps // Map 1 System.out.println(tm1); // Map 2 System.out.println(tm2); }} {1=Geeks, 2=For, 3=Geeks} {1=Geeks, 2=For, 3=Geeks} Operation 2: Changing Elements After adding the elements if we wish to change the element, it can be done by again adding the element with the put() method. Since the elements in the treemap are indexed using the keys, the value of the key can be changed by simply inserting the updated value for the key for which we wish to change. Example Java // Java program to Illustrate Updation of Elements// in TreeMap using put() Method // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Initialization of a TreeMap // using Generics TreeMap<Integer, String> tm = new TreeMap<Integer, String>(); // Inserting the elements in Map // using put() method tm.put(3, "Geeks"); tm.put(2, "Geeks"); tm.put(1, "Geeks"); // Print all current elements in map System.out.println(tm); // Inserting the element at specified // corresponding to specified key tm.put(2, "For"); // Printing the updated elements of Map System.out.println(tm); }} {1=Geeks, 2=Geeks, 3=Geeks} {1=Geeks, 2=For, 3=Geeks} Operation 3: Removing Element In order to remove an element from the TreeMap, we can use the remove() method. This method takes the key value and removes the mapping for the key from this treemap if it is present in the map. Example Java // Java program to Illustrate Removal of Elements// in TreeMap using remove() Method // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Initialization of a TreeMap // using Generics TreeMap<Integer, String> tm = new TreeMap<Integer, String>(); // Inserting the elements // using put() method tm.put(3, "Geeks"); tm.put(2, "Geeks"); tm.put(1, "Geeks"); tm.put(4, "For"); // Printing all elements of Map System.out.println(tm); // Removing the element corresponding to key tm.remove(4); // Printing updated TreeMap System.out.println(tm); }} {1=Geeks, 2=Geeks, 3=Geeks, 4=For} {1=Geeks, 2=Geeks, 3=Geeks} Operation 4: Iterating through the TreeMap There are multiple ways to iterate through the Map. The most famous way is to use a for-each loop and get the keys. The value of the key is found by using the getValue() method. Example Java // Java Program to Illustrate Iterating over TreeMap// using // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Initialization of a TreeMap // using Generics TreeMap<Integer, String> tm = new TreeMap<Integer, String>(); // Inserting the elements // using put() method tm.put(3, "Geeks"); tm.put(2, "For"); tm.put(1, "Geeks"); // For-each loop for traversal over Map // via entrySet() Method for (Map.Entry mapElement : tm.entrySet()) { int key = (int)mapElement.getKey(); // Finding the value String value = (String)mapElement.getValue(); // Printing the key and value System.out.println(key + " : " + value); } }} 1 : Geeks 2 : For 3 : Geeks RishabhPrabhu KaashyapMSK shine561995 solankimayank simmytarika5 varshagumber28 germanshephered48 rambharatnandu Java-Collections Picked Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jul, 2022" }, { "code": null, "e": 763, "s": 54, "text": "The TreeMap in Java is used to implement Map interface and NavigableMap along with the AbstractMap Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. This proves to be an efficient way of sorting and storing the key-value pairs. The storing order maintained by the treemap must be consistent with equals just like any other sorted map, irrespective of the explicit comparators. The treemap implementation is not synchronized in the sense that if a map is accessed by multiple threads, concurrently and at least one of the threads modifies the map structurally, it must be synchronized externally. " }, { "code": null, "e": 772, "s": 763, "text": "Chapters" }, { "code": null, "e": 799, "s": 772, "text": "descriptions off, selected" }, { "code": null, "e": 849, "s": 799, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 872, "s": 849, "text": "captions off, selected" }, { "code": null, "e": 880, "s": 872, "text": "English" }, { "code": null, "e": 904, "s": 880, "text": "This is a modal window." }, { "code": null, "e": 973, "s": 904, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 995, "s": 973, "text": "End of dialog window." }, { "code": null, "e": 1051, "s": 995, "text": "Some important features of the treemap are as follows: " }, { "code": null, "e": 1547, "s": 1051, "text": "This class is a member of the Java Collections Framework.The class implements Map interfaces including NavigableMap, SortedMap, and extends AbstractMap class.TreeMap in Java does not allow null keys (like Map) and thus a NullPointerException is thrown. However, multiple null values can be associated with different keys.Entry pairs returned by the methods in this class and its views represent snapshots of mappings at the time they were produced. They do not support the Entry.setValue method." }, { "code": null, "e": 1605, "s": 1547, "text": "This class is a member of the Java Collections Framework." }, { "code": null, "e": 1707, "s": 1605, "text": "The class implements Map interfaces including NavigableMap, SortedMap, and extends AbstractMap class." }, { "code": null, "e": 1871, "s": 1707, "text": "TreeMap in Java does not allow null keys (like Map) and thus a NullPointerException is thrown. However, multiple null values can be associated with different keys." }, { "code": null, "e": 2046, "s": 1871, "text": "Entry pairs returned by the methods in this class and its views represent snapshots of mappings at the time they were produced. They do not support the Entry.setValue method." }, { "code": null, "e": 2514, "s": 2046, "text": "Now let us move forward and discuss Synchronized TreeMap. The implementation of a TreeMap is not synchronized. This means that if multiple threads access a tree set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by using the Collections.synchronizedSortedMap method. This is best done at the creation time, to prevent accidental unsynchronized access to the set. This can be done as:" }, { "code": null, "e": 2582, "s": 2514, "text": "SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...)); " }, { "code": null, "e": 2655, "s": 2582, "text": "Geeks, now you must be wondering how does the TreeMap works internally? " }, { "code": null, "e": 2897, "s": 2655, "text": "The methods in a TreeMap while getting keyset and values, return an Iterator that is fail-fast in nature. Thus, any concurrent modification will throw ConcurrentModificationException. A TreeMap is based upon a red-black tree data structure. " }, { "code": null, "e": 2925, "s": 2897, "text": "Each node in the tree has: " }, { "code": null, "e": 2985, "s": 2925, "text": "3 Variables (K key=Key, V value=Value, boolean color=Color)" }, { "code": null, "e": 3062, "s": 2985, "text": "3 References (Entry left = Left, Entry right = Right, Entry parent = Parent)" }, { "code": null, "e": 3302, "s": 3062, "text": "In order to create a TreeMap, we need to create an object of the TreeMap class. The TreeMap class consists of various constructors that allow the possible creation of the TreeMap. The following are the constructors available in this class:" }, { "code": null, "e": 3371, "s": 3302, "text": "TreeMap()TreeMap(Comparator comp)TreeMap(Map M)TreeMap(SortedMap sm)" }, { "code": null, "e": 3381, "s": 3371, "text": "TreeMap()" }, { "code": null, "e": 3406, "s": 3381, "text": "TreeMap(Comparator comp)" }, { "code": null, "e": 3421, "s": 3406, "text": "TreeMap(Map M)" }, { "code": null, "e": 3443, "s": 3421, "text": "TreeMap(SortedMap sm)" }, { "code": null, "e": 3529, "s": 3443, "text": "Let us discuss them individually alongside implementing every constructor as follows:" }, { "code": null, "e": 3554, "s": 3529, "text": "Constructor 1: TreeMap()" }, { "code": null, "e": 3666, "s": 3554, "text": "This constructor is used to build an empty treemap that will be sorted by using the natural order of its keys. " }, { "code": null, "e": 3674, "s": 3666, "text": "Example" }, { "code": null, "e": 3679, "s": 3674, "text": "Java" }, { "code": "// Java Program to Demonstrate TreeMap// using the Default Constructor // Importing required classesimport java.util.*;import java.util.concurrent.*; // Main class// TreeMapImplementationpublic class GFG { // Method 1 // To show TreeMap constructor static void Example1stConstructor() { // Creating an empty TreeMap TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>(); // Mapping string values to int keys // using put() method tree_map.put(10, \"Geeks\"); tree_map.put(15, \"4\"); tree_map.put(20, \"Geeks\"); tree_map.put(25, \"Welcomes\"); tree_map.put(30, \"You\"); // Printing the elements of TreeMap System.out.println(\"TreeMap: \" + tree_map); } // Method 2 // Main driver method public static void main(String[] args) { System.out.println(\"TreeMap using \" + \"TreeMap() constructor:\\n\"); // Calling constructor Example1stConstructor(); }}", "e": 4706, "s": 3679, "text": null }, { "code": null, "e": 4800, "s": 4706, "text": "TreeMap using TreeMap() constructor:\nTreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}" }, { "code": null, "e": 4842, "s": 4802, "text": "Constructor 2: TreeMap(Comparator comp)" }, { "code": null, "e": 4980, "s": 4842, "text": "This constructor is used to build an empty TreeMap object in which the elements will need an external specification of the sorting order." }, { "code": null, "e": 4988, "s": 4980, "text": "Example" }, { "code": null, "e": 4993, "s": 4988, "text": "Java" }, { "code": "// Java Program to Demonstrate TreeMap// using Comparator Constructor // Importing required classesimport java.util.*;import java.util.concurrent.*; // Class 1// Helper class representing Studentclass Student { // Attributes of a student int rollno; String name, address; // Constructor public Student(int rollno, String name, String address) { // This keyword refers to current object itself this.rollno = rollno; this.name = name; this.address = address; } // Method of this class // To print student details public String toString() { return this.rollno + \" \" + this.name + \" \" + this.address; }} // Class 2// Helper class - Comparator implementationclass Sortbyroll implements Comparator<Student> { // Used for sorting in ascending order of // roll number public int compare(Student a, Student b) { return a.rollno - b.rollno; }} // Class 3// Main classpublic class GFG { // Calling constructor inside main() static void Example2ndConstructor() { // Creating an empty TreeMap TreeMap<Student, Integer> tree_map = new TreeMap<Student, Integer>( new Sortbyroll()); // Mapping string values to int keys tree_map.put(new Student(111, \"bbbb\", \"london\"), 2); tree_map.put(new Student(131, \"aaaa\", \"nyc\"), 3); tree_map.put(new Student(121, \"cccc\", \"jaipur\"), 1); // Printing the elements of TreeMap System.out.println(\"TreeMap: \" + tree_map); } // Main driver method public static void main(String[] args) { System.out.println(\"TreeMap using \" + \"TreeMap(Comparator)\" + \" constructor:\\n\"); Example2ndConstructor(); }}", "e": 6808, "s": 4993, "text": null }, { "code": null, "e": 6919, "s": 6808, "text": "TreeMap using TreeMap(Comparator) constructor:\nTreeMap: {111 bbbb london=2, 121 cccc jaipur=1, 131 aaaa nyc=3}" }, { "code": null, "e": 6951, "s": 6921, "text": "Constructor 3: TreeMap(Map M)" }, { "code": null, "e": 7099, "s": 6951, "text": "This constructor is used to initialize a TreeMap with the entries from the given map M which will be sorted by using the natural order of the keys." }, { "code": null, "e": 7107, "s": 7099, "text": "Example" }, { "code": null, "e": 7112, "s": 7107, "text": "Java" }, { "code": "// Java Program to Demonstrate TreeMap// using the Default Constructor // Importing required classesimport java.util.*;import java.util.concurrent.*; // Main classpublic class TreeMapImplementation { // Method 1 // To illustrate constructor<Map> static void Example3rdConstructor() { // Creating an empty HashMap Map<Integer, String> hash_map = new HashMap<Integer, String>(); // Mapping string values to int keys // using put() method hash_map.put(10, \"Geeks\"); hash_map.put(15, \"4\"); hash_map.put(20, \"Geeks\"); hash_map.put(25, \"Welcomes\"); hash_map.put(30, \"You\"); // Creating the TreeMap using the Map TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>(hash_map); // Printing the elements of TreeMap System.out.println(\"TreeMap: \" + tree_map); } // Method 2 // Main driver method public static void main(String[] args) { System.out.println(\"TreeMap using \" + \"TreeMap(Map)\" + \" constructor:\\n\"); Example3rdConstructor(); }}", "e": 8279, "s": 7112, "text": null }, { "code": null, "e": 8376, "s": 8279, "text": "TreeMap using TreeMap(Map) constructor:\nTreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}" }, { "code": null, "e": 8415, "s": 8378, "text": "Constructor 4: TreeMap(SortedMap sm)" }, { "code": null, "e": 8571, "s": 8415, "text": "This constructor is used to initialize a TreeMap with the entries from the given sorted map which will be stored in the same order as the given sorted map." }, { "code": null, "e": 8579, "s": 8571, "text": "Example" }, { "code": null, "e": 8584, "s": 8579, "text": "Java" }, { "code": "// Java Program to Demonstrate TreeMap// using the SortedMap Constructor // Importing required classesimport java.util.*;import java.util.concurrent.*; // Main class// TreeMapImplementationpublic class GFG { // Method // To show TreeMap(SortedMap) constructor static void Example4thConstructor() { // Creating a SortedMap SortedMap<Integer, String> sorted_map = new ConcurrentSkipListMap<Integer, String>(); // Mapping string values to int keys // using put() method sorted_map.put(10, \"Geeks\"); sorted_map.put(15, \"4\"); sorted_map.put(20, \"Geeks\"); sorted_map.put(25, \"Welcomes\"); sorted_map.put(30, \"You\"); // Creating the TreeMap using the SortedMap TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>(sorted_map); // Printing the elements of TreeMap System.out.println(\"TreeMap: \" + tree_map); } // Method 2 // Main driver method public static void main(String[] args) { System.out.println(\"TreeMap using \" + \"TreeMap(SortedMap)\" + \" constructor:\\n\"); Example4thConstructor(); }}", "e": 9806, "s": 8584, "text": null }, { "code": null, "e": 9909, "s": 9806, "text": "TreeMap using TreeMap(SortedMap) constructor:\nTreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}" }, { "code": null, "e": 10038, "s": 9911, "text": "Implementation: The following programs below will demonstrate better how to create, insert, and traverse through the TreeMap. " }, { "code": null, "e": 10053, "s": 10038, "text": "Illustration: " }, { "code": null, "e": 10058, "s": 10053, "text": "Java" }, { "code": "// Java Program to Illustrate Operations in TreeMap// Such as Creation, insertion// searching, and traversal // Importing required classesimport java.util.*;import java.util.concurrent.*; // Main class// Implementation of TreeMappublic class GFG { // Declaring a TreeMap static TreeMap<Integer, String> tree_map; // Method 1 // To create TreeMap static void create() { // Creating an empty TreeMap tree_map = new TreeMap<Integer, String>(); // Display message only System.out.println(\"TreeMap successfully\" + \" created\"); } // Method 2 // To Insert values in the TreeMap static void insert() { // Mapping string values to int keys // using put() method tree_map.put(10, \"Geeks\"); tree_map.put(15, \"4\"); tree_map.put(20, \"Geeks\"); tree_map.put(25, \"Welcomes\"); tree_map.put(30, \"You\"); // Display message only System.out.println(\"\\nElements successfully\" + \" inserted in the TreeMap\"); } // Method 3 // To search a key in TreeMap static void search(int key) { // Checking for the key System.out.println(\"\\nIs key \\\"\" + key + \"\\\" present? \" + tree_map.containsKey(key)); } // Method 4 // To search a value in TreeMap static void search(String value) { // Checking for the value System.out.println(\"\\nIs value \\\"\" + value + \"\\\" present? \" + tree_map.containsValue(value)); } // Method 5 // To display the elements in TreeMap static void display() { // Displaying the TreeMap System.out.println(\"\\nDisplaying the TreeMap:\"); System.out.println(\"TreeMap: \" + tree_map); } // Method 6 // To traverse TreeMap static void traverse() { // Display message only System.out.println(\"\\nTraversing the TreeMap:\"); for (Map.Entry<Integer, String> e : tree_map.entrySet()) System.out.println(e.getKey() + \" \" + e.getValue()); } // Method 6 // Main driver method public static void main(String[] args) { // Calling above defined methods inside main() // Creating a TreeMap create(); // Inserting the values in the TreeMap insert(); // Search key \"50\" in the TreeMap search(50); // Search value \"Geeks\" in the TreeMap search(\"Geeks\"); // Display the elements in TreeMap display(); // Traversing the TreeMap traverse(); }}", "e": 12786, "s": 10058, "text": null }, { "code": null, "e": 13066, "s": 12786, "text": "TreeMap successfully created\nElements successfully inserted in the TreeMap\nIs key \"50\" present? false\nIs value \"Geeks\" present? true\nDisplaying the TreeMap:\nTreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}\nTraversing the TreeMap:\n10 Geeks\n15 4\n20 Geeks\n25 Welcomes\n30 You" }, { "code": null, "e": 13276, "s": 13068, "text": "After the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the TreeMap. Now, let’s see how to perform a few frequently used operations on the TreeMap." }, { "code": null, "e": 13305, "s": 13276, "text": "Operation 1: Adding Elements" }, { "code": null, "e": 13523, "s": 13305, "text": "In order to add an element to the TreeMap, we can use the put() method. However, the insertion order is not retained in the TreeMap. Internally, for every element, the keys are compared and sorted in ascending order. " }, { "code": null, "e": 13531, "s": 13523, "text": "Example" }, { "code": null, "e": 13536, "s": 13531, "text": "Java" }, { "code": "// Java Program to Illustrate Addition of Elements// in TreeMap using put() Method // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Default Initialization of a TreeMap TreeMap tm1 = new TreeMap(); // Inserting the elements in TreeMap // using put() method tm1.put(3, \"Geeks\"); tm1.put(2, \"For\"); tm1.put(1, \"Geeks\"); // Initialization of a TreeMap using Generics TreeMap<Integer, String> tm2 = new TreeMap<Integer, String>(); // Inserting the elements in TreeMap // again using put() method tm2.put(new Integer(3), \"Geeks\"); tm2.put(new Integer(2), \"For\"); tm2.put(new Integer(1), \"Geeks\"); // Printing the elements of both TreeMaps // Map 1 System.out.println(tm1); // Map 2 System.out.println(tm2); }}", "e": 14501, "s": 13536, "text": null }, { "code": null, "e": 14553, "s": 14501, "text": "{1=Geeks, 2=For, 3=Geeks}\n{1=Geeks, 2=For, 3=Geeks}" }, { "code": null, "e": 14586, "s": 14555, "text": "Operation 2: Changing Elements" }, { "code": null, "e": 14889, "s": 14586, "text": "After adding the elements if we wish to change the element, it can be done by again adding the element with the put() method. Since the elements in the treemap are indexed using the keys, the value of the key can be changed by simply inserting the updated value for the key for which we wish to change." }, { "code": null, "e": 14897, "s": 14889, "text": "Example" }, { "code": null, "e": 14902, "s": 14897, "text": "Java" }, { "code": "// Java program to Illustrate Updation of Elements// in TreeMap using put() Method // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Initialization of a TreeMap // using Generics TreeMap<Integer, String> tm = new TreeMap<Integer, String>(); // Inserting the elements in Map // using put() method tm.put(3, \"Geeks\"); tm.put(2, \"Geeks\"); tm.put(1, \"Geeks\"); // Print all current elements in map System.out.println(tm); // Inserting the element at specified // corresponding to specified key tm.put(2, \"For\"); // Printing the updated elements of Map System.out.println(tm); }}", "e": 15706, "s": 14902, "text": null }, { "code": null, "e": 15760, "s": 15706, "text": "{1=Geeks, 2=Geeks, 3=Geeks}\n{1=Geeks, 2=For, 3=Geeks}" }, { "code": null, "e": 15792, "s": 15762, "text": "Operation 3: Removing Element" }, { "code": null, "e": 15987, "s": 15792, "text": "In order to remove an element from the TreeMap, we can use the remove() method. This method takes the key value and removes the mapping for the key from this treemap if it is present in the map." }, { "code": null, "e": 15995, "s": 15987, "text": "Example" }, { "code": null, "e": 16000, "s": 15995, "text": "Java" }, { "code": "// Java program to Illustrate Removal of Elements// in TreeMap using remove() Method // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Initialization of a TreeMap // using Generics TreeMap<Integer, String> tm = new TreeMap<Integer, String>(); // Inserting the elements // using put() method tm.put(3, \"Geeks\"); tm.put(2, \"Geeks\"); tm.put(1, \"Geeks\"); tm.put(4, \"For\"); // Printing all elements of Map System.out.println(tm); // Removing the element corresponding to key tm.remove(4); // Printing updated TreeMap System.out.println(tm); }}", "e": 16770, "s": 16000, "text": null }, { "code": null, "e": 16833, "s": 16770, "text": "{1=Geeks, 2=Geeks, 3=Geeks, 4=For}\n{1=Geeks, 2=Geeks, 3=Geeks}" }, { "code": null, "e": 16878, "s": 16835, "text": "Operation 4: Iterating through the TreeMap" }, { "code": null, "e": 17056, "s": 16878, "text": "There are multiple ways to iterate through the Map. The most famous way is to use a for-each loop and get the keys. The value of the key is found by using the getValue() method." }, { "code": null, "e": 17064, "s": 17056, "text": "Example" }, { "code": null, "e": 17069, "s": 17064, "text": "Java" }, { "code": "// Java Program to Illustrate Iterating over TreeMap// using // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Initialization of a TreeMap // using Generics TreeMap<Integer, String> tm = new TreeMap<Integer, String>(); // Inserting the elements // using put() method tm.put(3, \"Geeks\"); tm.put(2, \"For\"); tm.put(1, \"Geeks\"); // For-each loop for traversal over Map // via entrySet() Method for (Map.Entry mapElement : tm.entrySet()) { int key = (int)mapElement.getKey(); // Finding the value String value = (String)mapElement.getValue(); // Printing the key and value System.out.println(key + \" : \" + value); } }}", "e": 17949, "s": 17069, "text": null }, { "code": null, "e": 17977, "s": 17949, "text": "1 : Geeks\n2 : For\n3 : Geeks" }, { "code": null, "e": 17993, "s": 17979, "text": "RishabhPrabhu" }, { "code": null, "e": 18005, "s": 17993, "text": "KaashyapMSK" }, { "code": null, "e": 18017, "s": 18005, "text": "shine561995" }, { "code": null, "e": 18031, "s": 18017, "text": "solankimayank" }, { "code": null, "e": 18044, "s": 18031, "text": "simmytarika5" }, { "code": null, "e": 18059, "s": 18044, "text": "varshagumber28" }, { "code": null, "e": 18077, "s": 18059, "text": "germanshephered48" }, { "code": null, "e": 18092, "s": 18077, "text": "rambharatnandu" }, { "code": null, "e": 18109, "s": 18092, "text": "Java-Collections" }, { "code": null, "e": 18116, "s": 18109, "text": "Picked" }, { "code": null, "e": 18121, "s": 18116, "text": "Java" }, { "code": null, "e": 18126, "s": 18121, "text": "Java" }, { "code": null, "e": 18143, "s": 18126, "text": "Java-Collections" } ]
Uploading Image Using Django with Firebase
23 Jun, 2021 Firebase is a product of Google which helps developers to build, manage, and grow their apps easily. It helps developers to build their apps faster and in a more secure way. No programming is required on the firebase side which makes it easy to use its features more efficiently. It provides cloud storage. It uses NoSQL for the storage of data. Here, We are going to learn How we can upload images using Django in firebase. While working with the database we may require to upload a pdf file also. Step 1: Firstly, We are going to create a project on Firebase to connect our static web page. Visit the Firebase page for configuring your project. Visit the website and click the On Add Project button as shown below: Step 2: Give a Name to your project and click on the Continue button. Step 3: Now click on the Continue button. Step 4: Now choose Default Account For Firebase and click on the Create Project button. Step 5: Now your project is created, and you are now good to go. Step 6: Now click on the 3rd icon that’s the Web button(</>). Step 7: Give a nickname to your web project and click on the Register App button. Step 8: Now you will see the configuration of your App like this. Copy this code somewhere as we will use it later. Step 9: Click On The Realtime Database button As Shown In Figure. Step 10: Now Click On Create Database. Step 11: Now Click On Test Mode and then Click On Enable. Step 12: Activate Firebase Storage. Click on the Storage button on the left and click on Get Started. After that this box will pop up. Click on Next. Then click on Done. Use the below command to create a Django project: $ django-admin startproject imageupload Let’s verify your Django project works. Change into the outer mysite directory, if you haven’t already, and run the following commands: $ python manage.py runserver You’ll see the following output on the command line: Performing system checks... System check identified no issues (0 silenced). You have unapplied migrations; your app may not work properly until they are applied. Run 'python manage.py migrate' to apply them. April 09, 2021 - 15:50:53 Django version 3.2, using settings 'imageupload.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Now, we hope that you have already created a project in Django. If not then refer to How to Create a Basic Project using MVT in Django? Since we are using firebase as a Database, We need to install pyrebase. For this type the following command in terminal: $pip install pyrebase4 Create a views.py file in your project directly. The Structure should be like this. Step 13: Go to the urls.py file and create a path to move to the webpage to upload the image. Python from django.contrib import adminfrom django.urls import pathfrom . import viewsurlpatterns = [ path('check/',views.check,name="check"), ] Step 14: Then move to views.py file and write the following function to render to html page. Python from django.shortcuts import renderimport pyrebase def check(request): return render(request,"check.html") Step 15: Then we will move to check.html page and write the following code to upload the image in firebase. Comments are written inside to understand it better. HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Work</title> <style> body{ background-image: url(https://images.unsplash.com/photo-1493723843671-1d655e66ac1c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80); } div{ position:absolute; right:10px; top:5px; } input{ margin-top:20px; height: 30px; width: 150px; padding: 12px 20px; border-radius: 5px; color: black; } input[type="submit"]{ background-color: rgba(7, 179, 185, 0.753); color: rgb(255, 255, 255); border: none; border-radius: 5px; } button{ background-color: rgba(7, 179, 185, 0.753); color: white; width: 150px; height: 30px; border: none; border-radius: 5px; opacity: 0.3; } </style></head><body><div><button type="button" onclick="location.href='{% url 'log' %}' ">Logout</button> </div><h2>Add Image</h2><form action="/postcreate/" method="post"> {% csrf_token %} <br> Title: <input type="text" name="work" required><br><br> Type Something: <textarea rows="5" cols="40" name="progress" required></textarea> <br><br> Document Upload: <input type="file" name="files[]" id="files"> <input type="hidden" name="url" id="url"> <button type="button" onclick="uploadimage()">Upload</button><br><br> <input type="submit" value="Submit"><br><br></form></body><script src="https://www.gstatic.com/firebasejs/3.7.4/firebase.js"></script><script> var firebaseConfig = { apiKey: "", authDomain: "", databaseURL: "", storageBucket: "", }; firebase.initializeApp(firebaseConfig); function uploadimage(){ var storage = firebase.storage(); var file=document.getElementById("files").files[0]; var storageref=storage.ref(); var thisref=storageref.child(file.name).put(file); thisref.on('state_changed',function(snapshot) { console.log('Done'); }, function(error) { console.log('Error',error); }, function() { // Uploaded completed successfully, now we can get the download URL thisref.snapshot.ref.getDownloadURL().then(function(downloadURL) { console.log('File available at', downloadURL); document.getElementById("url").value=downloadURL; alert('uploaded successfully'); });});}</script></html> Now move to your project directory and run our project using the given command : python manage.py runserver Output: simmytarika5 Django-Projects Firebase How To Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Set Git Username and Password in GitBash? How to Permanently Disable Swap in Linux? How to Install Jupyter Notebook on MacOS? How to Import JSON Data into SQL Server? How to Install and Use NVM on Windows? Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas How to get column names in Pandas dataframe
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2021" }, { "code": null, "e": 400, "s": 54, "text": "Firebase is a product of Google which helps developers to build, manage, and grow their apps easily. It helps developers to build their apps faster and in a more secure way. No programming is required on the firebase side which makes it easy to use its features more efficiently. It provides cloud storage. It uses NoSQL for the storage of data." }, { "code": null, "e": 553, "s": 400, "text": "Here, We are going to learn How we can upload images using Django in firebase. While working with the database we may require to upload a pdf file also." }, { "code": null, "e": 771, "s": 553, "text": "Step 1: Firstly, We are going to create a project on Firebase to connect our static web page. Visit the Firebase page for configuring your project. Visit the website and click the On Add Project button as shown below:" }, { "code": null, "e": 841, "s": 771, "text": "Step 2: Give a Name to your project and click on the Continue button." }, { "code": null, "e": 883, "s": 841, "text": "Step 3: Now click on the Continue button." }, { "code": null, "e": 971, "s": 883, "text": "Step 4: Now choose Default Account For Firebase and click on the Create Project button." }, { "code": null, "e": 1036, "s": 971, "text": "Step 5: Now your project is created, and you are now good to go." }, { "code": null, "e": 1098, "s": 1036, "text": "Step 6: Now click on the 3rd icon that’s the Web button(</>)." }, { "code": null, "e": 1180, "s": 1098, "text": "Step 7: Give a nickname to your web project and click on the Register App button." }, { "code": null, "e": 1296, "s": 1180, "text": "Step 8: Now you will see the configuration of your App like this. Copy this code somewhere as we will use it later." }, { "code": null, "e": 1364, "s": 1296, "text": "Step 9: Click On The Realtime Database button As Shown In Figure. " }, { "code": null, "e": 1403, "s": 1364, "text": "Step 10: Now Click On Create Database." }, { "code": null, "e": 1461, "s": 1403, "text": "Step 11: Now Click On Test Mode and then Click On Enable." }, { "code": null, "e": 1563, "s": 1461, "text": "Step 12: Activate Firebase Storage. Click on the Storage button on the left and click on Get Started." }, { "code": null, "e": 1611, "s": 1563, "text": "After that this box will pop up. Click on Next." }, { "code": null, "e": 1631, "s": 1611, "text": "Then click on Done." }, { "code": null, "e": 1681, "s": 1631, "text": "Use the below command to create a Django project:" }, { "code": null, "e": 1721, "s": 1681, "text": "$ django-admin startproject imageupload" }, { "code": null, "e": 1857, "s": 1721, "text": "Let’s verify your Django project works. Change into the outer mysite directory, if you haven’t already, and run the following commands:" }, { "code": null, "e": 1886, "s": 1857, "text": "$ python manage.py runserver" }, { "code": null, "e": 1939, "s": 1886, "text": "You’ll see the following output on the command line:" }, { "code": null, "e": 2317, "s": 1939, "text": "Performing system checks...\nSystem check identified no issues (0 silenced).\nYou have unapplied migrations; your app may not work properly until they are applied.\nRun 'python manage.py migrate' to apply them.\nApril 09, 2021 - 15:50:53\nDjango version 3.2, using settings 'imageupload.settings'\nStarting development server at http://127.0.0.1:8000/\nQuit the server with CONTROL-C." }, { "code": null, "e": 2574, "s": 2317, "text": "Now, we hope that you have already created a project in Django. If not then refer to How to Create a Basic Project using MVT in Django? Since we are using firebase as a Database, We need to install pyrebase. For this type the following command in terminal:" }, { "code": null, "e": 2597, "s": 2574, "text": "$pip install pyrebase4" }, { "code": null, "e": 2681, "s": 2597, "text": "Create a views.py file in your project directly. The Structure should be like this." }, { "code": null, "e": 2775, "s": 2681, "text": "Step 13: Go to the urls.py file and create a path to move to the webpage to upload the image." }, { "code": null, "e": 2782, "s": 2775, "text": "Python" }, { "code": "from django.contrib import adminfrom django.urls import pathfrom . import viewsurlpatterns = [ path('check/',views.check,name=\"check\"), ]", "e": 2930, "s": 2782, "text": null }, { "code": null, "e": 3024, "s": 2930, "text": "Step 14: Then move to views.py file and write the following function to render to html page. " }, { "code": null, "e": 3031, "s": 3024, "text": "Python" }, { "code": "from django.shortcuts import renderimport pyrebase def check(request): return render(request,\"check.html\")", "e": 3141, "s": 3031, "text": null }, { "code": null, "e": 3303, "s": 3141, "text": " Step 15: Then we will move to check.html page and write the following code to upload the image in firebase. Comments are written inside to understand it better." }, { "code": null, "e": 3308, "s": 3303, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <title>Work</title> <style> body{ background-image: url(https://images.unsplash.com/photo-1493723843671-1d655e66ac1c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80); } div{ position:absolute; right:10px; top:5px; } input{ margin-top:20px; height: 30px; width: 150px; padding: 12px 20px; border-radius: 5px; color: black; } input[type=\"submit\"]{ background-color: rgba(7, 179, 185, 0.753); color: rgb(255, 255, 255); border: none; border-radius: 5px; } button{ background-color: rgba(7, 179, 185, 0.753); color: white; width: 150px; height: 30px; border: none; border-radius: 5px; opacity: 0.3; } </style></head><body><div><button type=\"button\" onclick=\"location.href='{% url 'log' %}' \">Logout</button> </div><h2>Add Image</h2><form action=\"/postcreate/\" method=\"post\"> {% csrf_token %} <br> Title: <input type=\"text\" name=\"work\" required><br><br> Type Something: <textarea rows=\"5\" cols=\"40\" name=\"progress\" required></textarea> <br><br> Document Upload: <input type=\"file\" name=\"files[]\" id=\"files\"> <input type=\"hidden\" name=\"url\" id=\"url\"> <button type=\"button\" onclick=\"uploadimage()\">Upload</button><br><br> <input type=\"submit\" value=\"Submit\"><br><br></form></body><script src=\"https://www.gstatic.com/firebasejs/3.7.4/firebase.js\"></script><script> var firebaseConfig = { apiKey: \"\", authDomain: \"\", databaseURL: \"\", storageBucket: \"\", }; firebase.initializeApp(firebaseConfig); function uploadimage(){ var storage = firebase.storage(); var file=document.getElementById(\"files\").files[0]; var storageref=storage.ref(); var thisref=storageref.child(file.name).put(file); thisref.on('state_changed',function(snapshot) { console.log('Done'); }, function(error) { console.log('Error',error); }, function() { // Uploaded completed successfully, now we can get the download URL thisref.snapshot.ref.getDownloadURL().then(function(downloadURL) { console.log('File available at', downloadURL); document.getElementById(\"url\").value=downloadURL; alert('uploaded successfully'); });});}</script></html>", "e": 5774, "s": 3308, "text": null }, { "code": null, "e": 5856, "s": 5774, "text": "Now move to your project directory and run our project using the given command : " }, { "code": null, "e": 5883, "s": 5856, "text": "python manage.py runserver" }, { "code": null, "e": 5891, "s": 5883, "text": "Output:" }, { "code": null, "e": 5904, "s": 5891, "text": "simmytarika5" }, { "code": null, "e": 5920, "s": 5904, "text": "Django-Projects" }, { "code": null, "e": 5929, "s": 5920, "text": "Firebase" }, { "code": null, "e": 5936, "s": 5929, "text": "How To" }, { "code": null, "e": 5943, "s": 5936, "text": "Python" }, { "code": null, "e": 6041, "s": 5943, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6090, "s": 6041, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 6132, "s": 6090, "text": "How to Permanently Disable Swap in Linux?" }, { "code": null, "e": 6174, "s": 6132, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 6215, "s": 6174, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 6254, "s": 6215, "text": "How to Install and Use NVM on Windows?" }, { "code": null, "e": 6282, "s": 6254, "text": "Read JSON file using Python" }, { "code": null, "e": 6304, "s": 6282, "text": "Python map() function" }, { "code": null, "e": 6354, "s": 6304, "text": "Adding new column to existing DataFrame in Pandas" } ]
Variable Length Arrays in C/C++ - GeeksforGeeks
07 Jan, 2022 Variable length arrays are also known as runtime sized or variable sized arrays. The size of such arrays is defined at run-time. Variably modified types include variable length arrays and pointers to variable length arrays. Variably changed types must be declared at either block scope or function prototype scope. Variable length arrays is a feature where we can allocate an auto array (on stack) of variable size. It can be used in a typedef statement. C supports variable sized arrays from C99 standard. For example, the below program compiles and runs fine in C. void fun(int n) { int arr[n]; // ...... } int main() { fun(6); } NOTE: In C99 or C11 standards, there is feature called flexible array members, which works same as the above. But C++ standard (till C++11) doesn’t support variable sized arrays. The C++11 standard mentions array size as a constant-expression. So the above program may not be a valid C++ program. The program may work in GCC compiler, because GCC compiler provides an extension to support them.As a side note, the latest C++14 mentions array size as a simple expression (not constant-expression). Implementation C // C program for variable length members in structures in// GCC before C99#include <stdio.h>#include <stdlib.h>#include <string.h> // Structure of type studentstruct student { int stud_id; int name_len; int struct_size; char stud_name[0]; // variable length array must be // last.}; // Memory allocation and initialisation of structurestruct student* createStudent(struct student* s, int id, char a[]){ s = malloc(sizeof(*s) + sizeof(char) * strlen(a)); s->stud_id = id; s->name_len = strlen(a); strcpy(s->stud_name, a); s->struct_size = (sizeof(*s) + sizeof(char) * strlen(s->stud_name)); return s;} // Print student detailsvoid printStudent(struct student* s){ printf("Student_id : %d\n" "Stud_Name : %s\n" "Name_Length: %d\n" "Allocated_Struct_size: %d\n\n", s->stud_id, s->stud_name, s->name_len, s->struct_size); // Value of Allocated_Struct_size here is in bytes.} // Driver Codeint main(){ struct student *s1, *s2; s1 = createStudent(s1, 523, "Sanjayulsha"); s2 = createStudent(s2, 535, "Cherry"); printStudent(s1); printStudent(s2); // size in bytes printf("Size of Struct student: %lu\n", sizeof(struct student)); // size in bytes printf("Size of Struct pointer: %lu", sizeof(s1)); return 0;} Student_id : 523 Stud_Name : Sanjayulsha Name_Length: 11 Allocated_Struct_size: 23 Student_id : 535 Stud_Name : Cherry Name_Length: 6 Allocated_Struct_size: 18 Size of Struct student: 12 Size of Struct pointer: 8 This article is contributed by Abhay Rathi and Sanjay Kanna. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. anshikajain26 C Array and String cpp-array C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ fork() in C Command line arguments in C/C++ Core Dump (Segmentation fault) in C/C++ Vector in C++ STL Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) Inheritance in C++ Constructors in C++
[ { "code": null, "e": 24019, "s": 23991, "text": "\n07 Jan, 2022" }, { "code": null, "e": 24149, "s": 24019, "text": "Variable length arrays are also known as runtime sized or variable sized arrays. The size of such arrays is defined at run-time. " }, { "code": null, "e": 24335, "s": 24149, "text": "Variably modified types include variable length arrays and pointers to variable length arrays. Variably changed types must be declared at either block scope or function prototype scope." }, { "code": null, "e": 24587, "s": 24335, "text": "Variable length arrays is a feature where we can allocate an auto array (on stack) of variable size. It can be used in a typedef statement. C supports variable sized arrays from C99 standard. For example, the below program compiles and runs fine in C." }, { "code": null, "e": 24658, "s": 24587, "text": "void fun(int n)\n{\n int arr[n];\n // ......\n} \nint main()\n{\n fun(6);\n}" }, { "code": null, "e": 24769, "s": 24658, "text": "NOTE: In C99 or C11 standards, there is feature called flexible array members, which works same as the above. " }, { "code": null, "e": 25171, "s": 24769, "text": "But C++ standard (till C++11) doesn’t support variable sized arrays. The C++11 standard mentions array size as a constant-expression. So the above program may not be a valid C++ program. The program may work in GCC compiler, because GCC compiler provides an extension to support them.As a side note, the latest C++14 mentions array size as a simple expression (not constant-expression). Implementation" }, { "code": null, "e": 25173, "s": 25171, "text": "C" }, { "code": "// C program for variable length members in structures in// GCC before C99#include <stdio.h>#include <stdlib.h>#include <string.h> // Structure of type studentstruct student { int stud_id; int name_len; int struct_size; char stud_name[0]; // variable length array must be // last.}; // Memory allocation and initialisation of structurestruct student* createStudent(struct student* s, int id, char a[]){ s = malloc(sizeof(*s) + sizeof(char) * strlen(a)); s->stud_id = id; s->name_len = strlen(a); strcpy(s->stud_name, a); s->struct_size = (sizeof(*s) + sizeof(char) * strlen(s->stud_name)); return s;} // Print student detailsvoid printStudent(struct student* s){ printf(\"Student_id : %d\\n\" \"Stud_Name : %s\\n\" \"Name_Length: %d\\n\" \"Allocated_Struct_size: %d\\n\\n\", s->stud_id, s->stud_name, s->name_len, s->struct_size); // Value of Allocated_Struct_size here is in bytes.} // Driver Codeint main(){ struct student *s1, *s2; s1 = createStudent(s1, 523, \"Sanjayulsha\"); s2 = createStudent(s2, 535, \"Cherry\"); printStudent(s1); printStudent(s2); // size in bytes printf(\"Size of Struct student: %lu\\n\", sizeof(struct student)); // size in bytes printf(\"Size of Struct pointer: %lu\", sizeof(s1)); return 0;}", "e": 26561, "s": 25173, "text": null }, { "code": null, "e": 26776, "s": 26561, "text": "Student_id : 523\nStud_Name : Sanjayulsha\nName_Length: 11\nAllocated_Struct_size: 23\n\nStudent_id : 535\nStud_Name : Cherry\nName_Length: 6\nAllocated_Struct_size: 18\n\nSize of Struct student: 12\nSize of Struct pointer: 8" }, { "code": null, "e": 26962, "s": 26776, "text": "This article is contributed by Abhay Rathi and Sanjay Kanna. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 26976, "s": 26962, "text": "anshikajain26" }, { "code": null, "e": 26995, "s": 26976, "text": "C Array and String" }, { "code": null, "e": 27005, "s": 26995, "text": "cpp-array" }, { "code": null, "e": 27016, "s": 27005, "text": "C Language" }, { "code": null, "e": 27020, "s": 27016, "text": "C++" }, { "code": null, "e": 27024, "s": 27020, "text": "CPP" }, { "code": null, "e": 27122, "s": 27024, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27131, "s": 27122, "text": "Comments" }, { "code": null, "e": 27144, "s": 27131, "text": "Old Comments" }, { "code": null, "e": 27172, "s": 27144, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 27218, "s": 27172, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 27230, "s": 27218, "text": "fork() in C" }, { "code": null, "e": 27262, "s": 27230, "text": "Command line arguments in C/C++" }, { "code": null, "e": 27302, "s": 27262, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 27320, "s": 27302, "text": "Vector in C++ STL" }, { "code": null, "e": 27366, "s": 27320, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 27409, "s": 27366, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 27428, "s": 27409, "text": "Inheritance in C++" } ]
Docker - ADD Instruction - GeeksforGeeks
29 Oct, 2020 If you want to extract a TAR file inside a Docker Container or copy files from a URL or local directory, you can specify ADD Instructions inside your Dockerfile. This is different from COPY instruction because COPY instruction only allows you to copy files and directories from the local machine. In this article, we will see practical examples where you can use ADD instruction to extract a tar file inside your Docker Image. For this example, we are simply going to create a TAR file of a folder. You can use this command to create a tar file. tar -zcvf my-tar-folder.tar.gz ~/Desktop/my-tar-folder After you have your Tar file ready, you can now create a Dockerfile with ADD instruction. FROM ubuntu:latest RUN apt-get -y update ADD my-tar-folder.tar.gz . In the above Dockerfile, we have pulled the Ubuntu base Image from Docker Hub and updated the Image using an apt-get update. After that, we have included the ADD instruction to extract the TAR file located inside the same directory as that of the Dockerfile. After creating the Dockerfile, you can now create the Docker Image using the Docker build command. sudo docker build -t sample-image . To confirm whether the image has been successfully built or not, use the Image list command. sudo docker images After you have created the Docker Image, you can now run the Docker Container associated with the Docker Image using the Docker Run command. sudo docker run -it sample-image bash After you have the bash of the Container running, you can use the list command to list the directories and verify the instruction. Docker Container linux Advanced Computer Subject Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Decision Tree Reinforcement learning Decision Tree Introduction with example Copying Files to and from Docker Containers Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux cut command in Linux with examples cp command in Linux with examples
[ { "code": null, "e": 25865, "s": 25837, "text": "\n29 Oct, 2020" }, { "code": null, "e": 26162, "s": 25865, "text": "If you want to extract a TAR file inside a Docker Container or copy files from a URL or local directory, you can specify ADD Instructions inside your Dockerfile. This is different from COPY instruction because COPY instruction only allows you to copy files and directories from the local machine." }, { "code": null, "e": 26292, "s": 26162, "text": "In this article, we will see practical examples where you can use ADD instruction to extract a tar file inside your Docker Image." }, { "code": null, "e": 26411, "s": 26292, "text": "For this example, we are simply going to create a TAR file of a folder. You can use this command to create a tar file." }, { "code": null, "e": 26467, "s": 26411, "text": "tar -zcvf my-tar-folder.tar.gz ~/Desktop/my-tar-folder\n" }, { "code": null, "e": 26558, "s": 26467, "text": "After you have your Tar file ready, you can now create a Dockerfile with ADD instruction. " }, { "code": null, "e": 26627, "s": 26558, "text": "FROM ubuntu:latest\nRUN apt-get -y update\nADD my-tar-folder.tar.gz .\n" }, { "code": null, "e": 26886, "s": 26627, "text": "In the above Dockerfile, we have pulled the Ubuntu base Image from Docker Hub and updated the Image using an apt-get update. After that, we have included the ADD instruction to extract the TAR file located inside the same directory as that of the Dockerfile." }, { "code": null, "e": 26985, "s": 26886, "text": "After creating the Dockerfile, you can now create the Docker Image using the Docker build command." }, { "code": null, "e": 27022, "s": 26985, "text": "sudo docker build -t sample-image .\n" }, { "code": null, "e": 27115, "s": 27022, "text": "To confirm whether the image has been successfully built or not, use the Image list command." }, { "code": null, "e": 27135, "s": 27115, "text": "sudo docker images\n" }, { "code": null, "e": 27276, "s": 27135, "text": "After you have created the Docker Image, you can now run the Docker Container associated with the Docker Image using the Docker Run command." }, { "code": null, "e": 27315, "s": 27276, "text": "sudo docker run -it sample-image bash\n" }, { "code": null, "e": 27446, "s": 27315, "text": "After you have the bash of the Container running, you can use the list command to list the directories and verify the instruction." }, { "code": null, "e": 27463, "s": 27446, "text": "Docker Container" }, { "code": null, "e": 27469, "s": 27463, "text": "linux" }, { "code": null, "e": 27495, "s": 27469, "text": "Advanced Computer Subject" }, { "code": null, "e": 27506, "s": 27495, "text": "Linux-Unix" }, { "code": null, "e": 27604, "s": 27506, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27627, "s": 27604, "text": "ML | Linear Regression" }, { "code": null, "e": 27641, "s": 27627, "text": "Decision Tree" }, { "code": null, "e": 27664, "s": 27641, "text": "Reinforcement learning" }, { "code": null, "e": 27704, "s": 27664, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 27748, "s": 27704, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 27788, "s": 27748, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 27828, "s": 27788, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 27855, "s": 27828, "text": "grep command in Unix/Linux" }, { "code": null, "e": 27890, "s": 27855, "text": "cut command in Linux with examples" } ]
uint keyword in C# - GeeksforGeeks
22 Jun, 2020 Keywords are the words in a language that are used for some internal process or represent some predefined actions. uint is a keyword that is used to declare a variable which can store an integral type of value (unsigned integer) from the range of 0 to 4,294,967,295. It keyword is an alias of System.UInt32. uint keyword occupies 4 bytes (32 bits) space in the memory. Syntax: uint variable_name = value; Example: Input: num: 67 Output: num2: 67 Size of a uint variable: 4 Input: num = 24680 Output: Type of num1: System.UInt32 num1: 24680 Size of a uint variable: 4 Example 1: // C# program for uint keywordusing System;using System.Text; class GFG { static void Main(string[] args) { // variable declaration uint num2 = 67; // to print value Console.WriteLine("num2: " + num2); // to print size Console.WriteLine("Size of a uint variable: " + sizeof(uint)); }} Output: num2: 67 Size of a uint variable: 4 Example 2: // C# program for uint keywordusing System;using System.Text; namespace Geeks { class GFG { static void Main(string[] args) { // variable declaration uint num1 = 24680; // to print type of variable Console.WriteLine("Type of num1: " + num1.GetType()); // to print value Console.WriteLine("num1: " + num1); // to print size Console.WriteLine("Size of a uint variable: " + sizeof(uint)); // to print minimum & maximum value of uint Console.WriteLine("Min value of uint: " + uint.MinValue); Console.WriteLine("Max value of uint: " + uint.MaxValue); // hit ENTER to exit Console.ReadLine(); }}} Output: Type of num1: System.UInt32 num1: 24680 Size of a uint variable: 4 Min value of uint: 0 Max value of uint: 4294967295 Example 3: // C# program for uint keywordusing System;using System.Text; class GFG { static void Main(string[] args) { // variable declaration uint num2 = 4294967297; // to print type of variable Console.WriteLine("Type of num2: " + num2.GetType()); // to print value Console.WriteLine("num2: " + num2); // to print size Console.WriteLine("Size of a uint variable: " + sizeof(uint)); }} Error: When we input wrong integer and also input number beyond the range Constant value `4294967297′ cannot be converted to a `uint’ CSharp-keyword C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Replace() Method C# | String.IndexOf( ) Method | Set - 1 Introduction to .NET Framework C# | Arrays HashSet in C# with Examples
[ { "code": null, "e": 25135, "s": 25107, "text": "\n22 Jun, 2020" }, { "code": null, "e": 25443, "s": 25135, "text": "Keywords are the words in a language that are used for some internal process or represent some predefined actions. uint is a keyword that is used to declare a variable which can store an integral type of value (unsigned integer) from the range of 0 to 4,294,967,295. It keyword is an alias of System.UInt32." }, { "code": null, "e": 25504, "s": 25443, "text": "uint keyword occupies 4 bytes (32 bits) space in the memory." }, { "code": null, "e": 25512, "s": 25504, "text": "Syntax:" }, { "code": null, "e": 25540, "s": 25512, "text": "uint variable_name = value;" }, { "code": null, "e": 25549, "s": 25540, "text": "Example:" }, { "code": null, "e": 25730, "s": 25549, "text": "Input: num: 67\n\nOutput: num2: 67\n Size of a uint variable: 4\n\nInput: num = 24680\n\nOutput: Type of num1: System.UInt32\n num1: 24680\n Size of a uint variable: 4\n" }, { "code": null, "e": 25741, "s": 25730, "text": "Example 1:" }, { "code": "// C# program for uint keywordusing System;using System.Text; class GFG { static void Main(string[] args) { // variable declaration uint num2 = 67; // to print value Console.WriteLine(\"num2: \" + num2); // to print size Console.WriteLine(\"Size of a uint variable: \" + sizeof(uint)); }}", "e": 26084, "s": 25741, "text": null }, { "code": null, "e": 26092, "s": 26084, "text": "Output:" }, { "code": null, "e": 26129, "s": 26092, "text": "num2: 67\nSize of a uint variable: 4\n" }, { "code": null, "e": 26140, "s": 26129, "text": "Example 2:" }, { "code": "// C# program for uint keywordusing System;using System.Text; namespace Geeks { class GFG { static void Main(string[] args) { // variable declaration uint num1 = 24680; // to print type of variable Console.WriteLine(\"Type of num1: \" + num1.GetType()); // to print value Console.WriteLine(\"num1: \" + num1); // to print size Console.WriteLine(\"Size of a uint variable: \" + sizeof(uint)); // to print minimum & maximum value of uint Console.WriteLine(\"Min value of uint: \" + uint.MinValue); Console.WriteLine(\"Max value of uint: \" + uint.MaxValue); // hit ENTER to exit Console.ReadLine(); }}}", "e": 26845, "s": 26140, "text": null }, { "code": null, "e": 26853, "s": 26845, "text": "Output:" }, { "code": null, "e": 26972, "s": 26853, "text": "Type of num1: System.UInt32\nnum1: 24680\nSize of a uint variable: 4\nMin value of uint: 0\nMax value of uint: 4294967295\n" }, { "code": null, "e": 26983, "s": 26972, "text": "Example 3:" }, { "code": "// C# program for uint keywordusing System;using System.Text; class GFG { static void Main(string[] args) { // variable declaration uint num2 = 4294967297; // to print type of variable Console.WriteLine(\"Type of num2: \" + num2.GetType()); // to print value Console.WriteLine(\"num2: \" + num2); // to print size Console.WriteLine(\"Size of a uint variable: \" + sizeof(uint)); }}", "e": 27433, "s": 26983, "text": null }, { "code": null, "e": 27507, "s": 27433, "text": "Error: When we input wrong integer and also input number beyond the range" }, { "code": null, "e": 27567, "s": 27507, "text": "Constant value `4294967297′ cannot be converted to a `uint’" }, { "code": null, "e": 27582, "s": 27567, "text": "CSharp-keyword" }, { "code": null, "e": 27585, "s": 27582, "text": "C#" }, { "code": null, "e": 27683, "s": 27585, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27711, "s": 27683, "text": "C# Dictionary with examples" }, { "code": null, "e": 27726, "s": 27711, "text": "C# | Delegates" }, { "code": null, "e": 27748, "s": 27726, "text": "C# | Abstract Classes" }, { "code": null, "e": 27794, "s": 27748, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 27817, "s": 27794, "text": "Extension Method in C#" }, { "code": null, "e": 27839, "s": 27817, "text": "C# | Replace() Method" }, { "code": null, "e": 27879, "s": 27839, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 27910, "s": 27879, "text": "Introduction to .NET Framework" }, { "code": null, "e": 27922, "s": 27910, "text": "C# | Arrays" } ]
GeeksforGeeks | A computer science portal for geeks
Events at GeeksforGeeks Courses at GeeksforGeeks Write an Article Java Tutorial Python Tutorial Data Structures Tutorial Coding Practice Events at GeeksforGeeks Courses at GeeksforGeeks Write an Article Java Tutorial Python Tutorial Data Structures Tutorial Coding Practice Get Hired With GeeksforGeeks and Win Exciting Rewards! October 30, 2021 October 30, 2021 Master the Coding Interview – Contest Series Based On Real Interviews October 5, 2021 October 5, 2021 Recently Asked Interview Questions in Product Based Companies May 11, 2021 May 11, 2021 Bridge the Gap Between Engineering and Your Dream Job – Complete Interview Preparation May 1, 2021 May 1, 2021 100 Days of Code – A Complete Guide For Beginners and Experienced May 1, 2021 May 1, 2021 Guest Blogs Must Do Coding Questions Company-wise Practice for cracking any coding interview Placements Complete Interview Preparation With Doubt Assistance GATE Computer Science Notes Machine Learning Django Tutorial Computer Science Projects Amazon SDE Test Series Company Interview Corner The C++ Standard Template Library (STL) Software Design Patterns SQL Tutorial Advanced Data Structures
[ { "code": null, "e": 21950, "s": 21920, "text": "\n\n\nEvents at GeeksforGeeks\n\n\n" }, { "code": null, "e": 21981, "s": 21950, "text": "\n\n\nCourses at GeeksforGeeks\n\n\n" }, { "code": null, "e": 22004, "s": 21981, "text": "\n\n\nWrite an Article\n\n\n" }, { "code": null, "e": 22024, "s": 22004, "text": "\n\n\nJava Tutorial\n\n\n" }, { "code": null, "e": 22046, "s": 22024, "text": "\n\n\nPython Tutorial\n\n\n" }, { "code": null, "e": 22077, "s": 22046, "text": "\n\n\nData Structures Tutorial\n\n\n" }, { "code": null, "e": 22099, "s": 22077, "text": "\n\n\nCoding Practice\n\n\n" }, { "code": null, "e": 22129, "s": 22099, "text": "\n\n\nEvents at GeeksforGeeks\n\n\n" }, { "code": null, "e": 22160, "s": 22129, "text": "\n\n\nCourses at GeeksforGeeks\n\n\n" }, { "code": null, "e": 22183, "s": 22160, "text": "\n\n\nWrite an Article\n\n\n" }, { "code": null, "e": 22203, "s": 22183, "text": "\n\n\nJava Tutorial\n\n\n" }, { "code": null, "e": 22225, "s": 22203, "text": "\n\n\nPython Tutorial\n\n\n" }, { "code": null, "e": 22256, "s": 22225, "text": "\n\n\nData Structures Tutorial\n\n\n" }, { "code": null, "e": 22278, "s": 22256, "text": "\n\n\nCoding Practice\n\n\n" }, { "code": null, "e": 22373, "s": 22278, "text": "\nGet Hired With GeeksforGeeks and Win Exciting Rewards!\n \nOctober 30, 2021\n" }, { "code": null, "e": 22390, "s": 22373, "text": "October 30, 2021" }, { "code": null, "e": 22499, "s": 22390, "text": "\nMaster the Coding Interview – Contest Series Based On Real Interviews\n \nOctober 5, 2021\n" }, { "code": null, "e": 22515, "s": 22499, "text": "October 5, 2021" }, { "code": null, "e": 22613, "s": 22515, "text": "\nRecently Asked Interview Questions in Product Based Companies\n \nMay 11, 2021\n" }, { "code": null, "e": 22626, "s": 22613, "text": "May 11, 2021" }, { "code": null, "e": 22748, "s": 22626, "text": "\nBridge the Gap Between Engineering and Your Dream Job – Complete Interview Preparation\n \nMay 1, 2021\n" }, { "code": null, "e": 22760, "s": 22748, "text": "May 1, 2021" }, { "code": null, "e": 22861, "s": 22760, "text": "\n100 Days of Code – A Complete Guide For Beginners and Experienced\n \nMay 1, 2021\n" }, { "code": null, "e": 22873, "s": 22861, "text": "May 1, 2021" }, { "code": null, "e": 22890, "s": 22873, "text": "\n\n\nGuest Blogs\n\n" }, { "code": null, "e": 22977, "s": 22890, "text": "\n\n\nMust Do Coding Questions\n Company-wise\n\n" }, { "code": null, "e": 23069, "s": 22977, "text": "\n\n\nPractice for cracking any coding\n interview\n\n" }, { "code": null, "e": 23085, "s": 23069, "text": "\n\n\nPlacements\n\n" }, { "code": null, "e": 23187, "s": 23085, "text": "\n\n\nComplete Interview Preparation With\n Doubt Assistance\n\n" }, { "code": null, "e": 23220, "s": 23187, "text": "\n\n\nGATE Computer Science Notes\n\n" }, { "code": null, "e": 23242, "s": 23220, "text": "\n\n\nMachine Learning\n\n" }, { "code": null, "e": 23263, "s": 23242, "text": "\n\n\nDjango Tutorial\n\n" }, { "code": null, "e": 23294, "s": 23263, "text": "\n\n\nComputer Science Projects\n\n" }, { "code": null, "e": 23322, "s": 23294, "text": "\n\n\nAmazon SDE Test Series\n\n" }, { "code": null, "e": 23352, "s": 23322, "text": "\n\n\nCompany Interview Corner\n\n" }, { "code": null, "e": 23441, "s": 23352, "text": "\n\n\nThe C++ Standard Template Library\n (STL)\n\n" }, { "code": null, "e": 23471, "s": 23441, "text": "\n\n\nSoftware Design Patterns\n\n" }, { "code": null, "e": 23489, "s": 23471, "text": "\n\n\nSQL Tutorial\n\n" } ]
Exploratory text analysis in Python | by Zolzaya Luvsandorj | Towards Data Science
Why do we do exploratory data analysis before we build a model? I would say ‘to understand the data better so that we preprocess the data in a suitable way and choose an appropriate modelling technique’. This necessity to understand data is still relevant when working with text data. This post is the first of the three sequential posts on steps to build a sentiment classifier. In this post, we will look at one way to conduct exploratory data analysis on text, or exploratory text analysis for brevity. Before we dive in, let’s take a step back and look at the bigger picture first. CRISP-DM methodology outlines the process flow for a successful data science project. In the diagram below, 2–4th stages of data science project are shown. In data understanding stage, exploratory data analysis is one of the key tasks. When working on a data science project, it is not unusual to be going back and forth between stages rather than linearly progressing. This is because ideas and questions come up in subsequent stages and you want to go back a stage or two to try out the idea or find the answer to the question. The pink arrows are not in the official CRISP-DM, however, I think these are often necessary. In fact, we will be doing a bit of data preparation in this post for the purpose of exploratory text analysis. For those who are interested to learn more about CRISP-DM, this is a nice short introduction and this resource provides a more detailed explanation. This post assumes that the reader (👀 yes, you!) has access to and is familiar with Python including installing packages, defining functions and other basic tasks. If you are new to Python, this is a good place to get started. I have tested the scripts in Python 3.7.1 in Jupyter Notebook. Let’s make sure you have the following libraries installed before we start:◼️ Data manipulation/analysis: numpy, pandas◼️ Data partitioning: sklearn◼️ Text preprocessing/analysis: nltk◼️ Visualisation: matplotlib, seaborn Once you have nltk installed, please make sure you have downloaded ‘punkt’, ‘stopwords’ and ‘wordnet’ from nltk with the script below: import nltknltk.download('punkt') # for sent_tokenizenltk.download('stopwords') nltk.download('wordnet') # for WordNetLemmatizer If you have already downloaded, running this will notify you of so. Now, we are ready to import all the packages: # Setting random seedseed = 123# Data manipulation/analysisimport numpy as npimport pandas as pd# Data partitioningfrom sklearn.model_selection import train_test_split# Text preprocessing/analysisimport refrom nltk import word_tokenize, sent_tokenize, FreqDistfrom nltk.util import ngramsfrom nltk.corpus import stopwordsfrom nltk.stem import WordNetLemmatizerfrom nltk.tokenize import RegexpTokenizer# Visualisationimport matplotlib.pyplot as pltimport seaborn as snssns.set(style="whitegrid", context='talk', palette=['#D44D5C', '#43AA8B']) Takeaways or notes will be accompanied with 🍀 when exploring. We will use IMDB movie reviews dataset. You can download the dataset here and save it in your working directory. Once saved, let’s import it to Python: sample = pd.read_csv('IMDB Dataset.csv')print(f"{sample.shape[0]} rows and {sample.shape[1]} columns")sample.head() From looking at the head of the data, we can instantly see that there are html tags in the second record. 🍀 Inspect html tags further and see how prevalent they are. Let’s look at the split between sentiments: sample['sentiment'].value_counts() Sentiment is evenly split in the sample data. Before we start exploratory text analysis, let’s first partition the data into two sets: train and test. We will set aside 5000 cases for testing: # Split data into train & testX_train, X_test, y_train, y_test = train_test_split(sample['review'], sample['sentiment'], test_size=5000, random_state=seed, stratify=sample['sentiment'])# Append sentiment back using indicestrain = pd.concat([X_train, y_train], axis=1)test = pd.concat([X_test, y_test], axis=1)# Check dimensionsprint(f"Train: {train.shape[0]} rows and {train.shape[1]} columns")print(f"{train['sentiment'].value_counts()}\n")print(f"Test: {test.shape[0]} rows and {test.shape[1]} columns")print(test['sentiment'].value_counts()) By specifying the stratify argument, we ensured that sentiment is evenly split in both sets. We will be using train for the exploratory text analysis in this post. Once we explore the training dataset, it may be useful to check the key characteristics of test set separately. Ideally, both sets should be representative of the underlying population. Let’s inspect the head of the training dataset: train.head() Alright, we are all set to explore! ✨ One way to guide exploratory data analysis is to write down questions that you are interested in and answer them with the data. Finding answers to questions often leads to other questions that you may want to explore. Here are some example questions we could answer: 📋 2.1. Warm-up:* How many strings are there?* What are the most common strings?* How do the shortest strings look like?* How do the longest strings look like? 📋 2.2. Tokens: 💡 Token is a sequence of characters. Tokens are often loosely referred to as words.💡 Tokenisation is a process of splitting a document into tokens and sometimes also throwing away certain characters such as punctuation. Example: Tokenisation turns ‘This movie was awesome’ into 4 tokens: [‘This’, ‘movie’, ‘was’, ‘awesome’] * How many tokens are there?* How many unique tokens are there?* What is the average number of characters per token? 📋 2.3. Stop words: 💡 Stop words are common words which provide little to no value to the meaning of the text. Example: the, a, and. * What are the most common stop words?* What other words occur so often such that could be added to stop words? 📋 2.4. Common word n-grams: 💡 Word n-grams are all combinations of adjacent n words in text data. Example: Bigrams in ‘This movie was awesome’ are [‘This movie’, ‘movie was’, ‘was awesome’] * What are the most common tokens?* What are the most common bigrams?* What are the most common trigrams?* What are the most common fourgrams? 📋 2.5. Documents: 💡 Document is a text record. Example: each movie review is a document.💡 Corpus is a collection of documents. Simply put, text data is a corpus. Example: we can refer training data as training corpus. * What is the average number of sentences per document?* What is the average number of tokens per document?* What is the average number of characters per document?* What is the average number of stop words per document?* How do the answers differ by sentiment? Now, it’s time to find answers to these questions! 😃 Let’s merge all the reviews into one string and then split it into sub-strings (here onward referred to as strings) on white space. This ensures the corpus is minimally altered (e.g. keeping punctuation as it is) for this warm-up exploration: # Prepare training corpus into one giant stringtrain_string = " ".join(X_train.values)print(f"***** Extract of train_string ***** \n{train_string[:101]}", "\n")# Split train_corpus by white spacesplits = train_string.split() print(f"***** Extract of splits ***** \n{splits[:18]}\n") ✏️ 2.1.1. How many strings are there? print(f"Number of strings: {len(splits)}")print(f"Number of unique strings: {len(set(splits))}") There are over 10 million strings in the training corpus with around 410 thousand unique strings. This gives us initial ballpark figures. We will get a view on how these numbers look for tokens after we tokenise properly. ✏️ 2.1.2. What are the most common strings? Let’s prepare frequency distribution for each string to answer the question: freq_splits = FreqDist(splits)print(f"***** 10 most common strings ***** \n{freq_splits.most_common(10)}", "\n") It is not surprising to see that most common strings are stop words. We will explore stop words further later in section 2.3. Stop words. 🍀 Remove stop words before looking at common tokens and n-grams. ✏️ 2.1.3. How do the shortest strings look like? Let’s define short string as strings with a length of less than 4 characters and check their frequency: short = set(s for s in splits if len(s)<4)short = [(s, freq_splits[s]) for s in short]short.sort(key=lambda x:x[1], reverse=True)short Many short strings appear to be stop words but there are also numbers and other short words. 🍀 There are numbers in different forms: 3, 2nd, 70s, 90% — we need to decide whether to drop or keep them. 🍀 There is case variation: ‘the’, ‘The’, ‘THE’ - these need to be normalised. Because we haven’t tokenised yet, some strings currently contain punctuation that is attached to a word. As a result, otherwise same words are considered as different as shown in this example: 🍀 Discarding punctuation will be helpful to further normalise words. ✏️ 2.1.4. How do the longest strings look like? Let’s define long strings as 16+ characters long and repeat the process. long = set(s for s in splits if len(s)>15)long = [(s, freq_splits[s]) for s in long]long.sort(key=lambda x:x[1], reverse=True)long The frequency of long string looks much lower than short strings which is not too surprising. Long strings look quite interesting and there are a few key takeaways: 🍀 There is American and British spelling of the same word: ‘characterization’ vs ‘characterisation’. After a quick check using the script below, American spelling looks more dominant for this word. Quantifying how prevalent the two spelling in the entire training corpus is a bit tricky. print(f"characterisation: {sum([c for s, c in long if re.match(r'characterisation*', s.lower())])} strings")print(f"characterization: {sum([c for s, c in long if re.match(r'characterization*', s.lower())])} strings") 🍀 There are hyphenated words: ‘thought-provoking’, ‘post-apocalyptic’, ‘under-appreciated’ and ‘film--specially’ (this one with double hyphens). If we tokenise on white space or punctuation, these strings will be split into separate words. For most cases, this will conserve the gist of the sentence. If we keep hyphenated words as they are, they won’t be as common and consequently removed as rare words. 🍀 There are words combined with other punctuation (some due to lack of space): ‘actors/actresses’, ‘Mission:Impossible’, “actors(HA!HA!HA!)...they’re”, ‘different:actually,Bullock’. It would be good to separate these cases into separate words when tokenising. So probably tokenising based on white space or punctuation is a good idea. 🍀 There are websites and email addresses: ‘/>www.ResidentHazard.com’, ‘http://www.PetitionOnline.com/gh1215/petition.html’, ‘[email protected]’’. However, there doesn’t seem to be many. 🍀 There are outlaw words that repeats the same character more than twice: “Booooring.......Don’t”, ‘NOOOOOOIIIISE!),’. If you know the correct term for these elongated words, I would love to find out. Until then, we will refer them as ‘outlaw words’. These outlaw cases seem to appear very rarely. There are other interesting findings we could add to these but these are good starters for now. It’s important to understand whether these cases that we just explored are prevalent enough to justify additional preprocessing steps (i.e. longer run time). It’s useful to experiment to see if adding an additional preprocessing step improves model performance. We will do a bit of this in the third post. ✏️ 2.1.5. Following up questions emerged so far We have answered all 4 warm up questions! While looking for answers, we have gathered even more questions. Before we jump to the next set of predefined questions, let’s quickly follow up some of the questions that have came up on the go. ◼️ How frequent is html tags? This question emerged when we were looking at head of the sample data in section 1. Data. The example html tag: ‘<br /><br />’ would have been split into three strings: ‘<br’, ‘/><br’ and ‘/>’ when we split the data based on white space. On side note, the <br> tag seems to be used to break lines. Let’s roughly gauge how prevalent the html tags are. All follow up questions are similar since we are going to assess the frequency of a particular type of string. To avoid repeating ourselves, let’s make a function. def summarise(pattern, strings, freq): """Summarise strings matching a pattern.""" # Find matches compiled_pattern = re.compile(pattern) matches = [s for s in strings if compiled_pattern.search(s)] # Print volume and proportion of matches print("{} strings, that is {:.2%} of total".format(len(matches), len(matches)/ len(strings))) # Create list of tuples containing matches and their frequency output = [(s, freq[s]) for s in set(matches)] output.sort(key=lambda x:x[1], reverse=True) return output# Find strings possibly containing html tagsummarise(r"/?>?w*<|/>", splits, freq_splits) If we scroll through the output, there aren’t many html tags other than the <br> tag and a few cases of <i> tag. 🍀 If we remove punctuation when tokenising, ‘/><br’ and ‘<br’ will become ‘br’ and we could probably add ‘br’ to stop words. ◼ ️How frequent are numbers? We found some instances of numbers from section 2.1.3. Short strings. Let’s see how frequent they are with the following script: summarise(r"\d", splits, freq_splits) Strings containing numbers are infrequent. In the context of movie reviews, it’s hard to intuitively make sense of how numbers would be useful. 10/10 could be an indication of positive sentiment but what can we infer from numbers such as 4, 80’s and 20th? We will drop numbers when tokenising. Depending on the timeline of a project, you may not have enough time to try all the interesting ideas. In that case, it’s handy to keep a list of nice-to-try items which you could experiment with when you have time. We will add the following tasks to that list: 1) Keep and convert numbers to text2) Create a feature indicating whether a review contains numbers or not ◼ ️How frequent are hyphenated words? We saw hyphenated words when inspecting long strings in section 2.1.4.Let’s see how frequent they are: summarise(r"\w+-+\w+", splits, freq_splits) Roughly less than 1% of strings contained hyphenated words. From glancing through the hyphenated words, it makes more sense to separate them out to keep the data simple. For example: We should tokenise ‘camera-work’ to 2 tokens: [‘camera’, ‘work’] instead of 1 token: [‘camera-work’]. We could add ‘keep hyphenated words as they are’ to the list of nice-to-try items. ◼ ️How frequent are words combined by other punctuation? Much like the previous question, we saw these cases during long string exploration. Let’s see how frequent they are: summarise(r"\w+[_!&/)(<\|}{\[\]]\w+", splits, freq_splits) Not too frequent, these ones definitely need to be separated. ◼ ️How frequent are outlaw words? We saw elongated words like ‘NOOOOOOIIIISE!),’ earlier. Let’s see how prevalent they are: def find_outlaw(word): """Find words that contain a same character 3+ times in a row.""" is_outlaw = False for i, letter in enumerate(word): if i > 1: if word[i] == word[i-1] == word[i-2] and word[i].isalpha(): is_outlaw = True break return is_outlawoutlaws = [s for s in splits if find_outlaw(s)]print("{} strings, that is {:.2%} of total".format(len(outlaws), len(outlaws)/ len(splits)))outlaw_freq = [(s, freq_splits[s]) for s in set(outlaws)]outlaw_freq.sort(key=lambda x:x[1], reverse=True)outlaw_freq These are not worth correcting for because there too few cases. That was the last follow up question! We have learned a little bit about the data. Hope you are feeling warmed up. 💦 You may have noticed how easily we could keep expanding our questions and keep exploring? In the interest of time, we will stop this section here and try to keep the next sections as succinct as possible. Otherwise, this post will be over a few hours long. 💤 Let’s answer these two questions at one go: ✏️ 2.2.1. How many tokens are there?✏️ 2.2.2. How many unique tokens are there? We have to tokenise the data first. Recalling from earlier exploration, it seemed best to drop punctuation and numbers when tokenising. With this in mind, let’s tokenise the text into alphabetic tokens: tokeniser = RegexpTokenizer("[A-Za-z]+")tokens = tokeniser.tokenize(train_string)print(tokens[:20], "\n") Now we have tokenised, we can answer the first two questions: print(f"Number of tokens: {len(tokens)}")print(f"Number of unique tokens: {len(set(tokens))}") There are over 10 million tokens in the training data with around 122 thousand unique tokens. Currently, ‘Watch’, ‘watch’ and ‘watching’ are counted as different tokens. Hmm, wouldn’t it be great if we could normalise them to ‘watch’ and count them as one unique token? If we normalise, the number of unique tokens would be lower. Let’s quickly do two things: convert all tokens into lowercase and lemmatise them: lemmatiser = WordNetLemmatizer()tokens_norm = [lemmatiser.lemmatize(t.lower(), "v") for t in tokens]print(f"Number of unique tokens: {len(set(tokens_norm))}") Great, the number of unique tokens dropped by about 30%. 📌 Exercise: If you are keen and have time, instead of combining both steps like above, try separating out and see how the number of unique tokens change at each step. For instance, you could first convert tokens to lowercase, and check the number, and then lemmatise and check the number again. If you change the order of these two operations, is the final number of unique tokens different than 82562? Why would that be? 👂 Psst, I will show another way to lemmatise in the next post when preprocessing the text for the model. ✏️ 2.2.3. What is the average number of characters per token? Let’s find out the average token length and inspect its the distribution: # Create list of token lengths for each tokentoken_length = [len(t) for t in tokens]# Average number of characters per tokenprint(f"Average number of characters per token: {round(np.mean(token_length),4)}")# Plot distributionplt.figure(figsize=(12, 12))sns.countplot(y=token_length)plt.title("Counts of token length", size=20); There are a few tokens that is very long but also very rare. Let’s look at the exact counts for those longer than 10 characters: pd.DataFrame(data=token_length, columns=['length']).query("length>10").value_counts() 17+ characters long words are infrequent. Let’s inspect some of them: [t for t in tokens if len(t)>=20] Interesting, some are valid long words whereas some are long because they lack white space or outlaw words (i.e. elongated). 🍀 When preprocessing, we should make sure that very rare tokens like these ones are dropped such that they won’t create separate columns when vectorising tokens into a matrix. ✏️ 2.3.1. What are the most frequent stop words? Let’s first inspect all stop words: stop_words = stopwords.words("english")print(f"There are {len(stop_words)} stopwords.\n")print(stop_words) At the time of writing this post, there are 179 stop words. The list of stop words could extend in future. It appears that we could extend the stop words to include a few more. In fact, I have proposed on Github to add generic stop words from below to the list of English stop words in nltk. Let’s also make sure to add a custom stop word ‘br’ to the list: stop_words.extend(["cannot", "could", "done", "let", "may" "mayn", "might", "must", "need", "ought", "oughtn", "shall", "would", "br"])print(f"There are {len(stop_words)} stopwords.\n") Now, let’s check what are the most common stop words: freq_stopwords = [(sw, tokens_norm.count(sw)) for sw in stop_words]freq_stopwords.sort(key=lambda x: x[1], reverse=True)freq_stopwords[:10] The frequency is really high (duh, I mean they are stop words, of course they will be frequent 😈), especially for ‘be’ and ‘the’. Wouldn’t it be interesting to find out what proportion of tokens are stop words? Let’s quickly check: n_stopwords = len([t for t in tokens_norm if t in stop_words])print(f"{n_stopwords} tokens are stop words.")print(f"That is {round(100*n_stopwords/len(tokens_norm),2)}%.") About half of the tokens are stop words. 💭 ✏️2.3.2. What other words occur so often such that could be added to stop words? We will answer this question when we look at common tokens soon. It’s time to find out common n-grams. Let’s answer all four questions together: ✏️ 2.4.1–4. What are the most common tokens, bigrams, trigrams and fourgrams? Firstly, let’s remove stop words: tokens_clean = [t for t in tokens_norm if t not in stop_words]print(f"Number of tokens: {len(tokens_clean)}") This is the remaining 49% of tokens. Now, we can inspect the common tokens (i.e. unigrams), bigrams, trigrams and fourgrams: def preprocess_text(text): """Preprocess text into normalised tokens.""" # Tokenise words into alphabetic tokens tokeniser = RegexpTokenizer(r'[A-Za-z]{2,}') tokens = tokeniser.tokenize(text) # Lowercase and lemmatise lemmatiser = WordNetLemmatizer() lemmas = [lemmatiser.lemmatize(token.lower(), pos='v') for token in tokens] # Remove stopwords keywords= [lemma for lemma in lemmas if lemma not in stop_words] return keywordsdef get_frequent_ngram(corpus, ngram, n=20): """Find most common n n-grams tokens.""" # Preprocess each document documents = [preprocess_text(document) for document in corpus] # Find ngrams per document n_grams = [list(ngrams(document, ngram)) for document in documents] # Find frequency of ngrams n_grams_flattened = [item for sublist in n_grams for item in sublist] freq_dist = FreqDist(n_grams_flattened) top_freq = freq_dist.most_common(n) return pd.DataFrame(top_freq, columns=["ngram", "count"])# Get frequent ngrams for all 4for i in range(1,5): mapping = {1:"uni", 2:"bi", 3:"tri", 4:"four"} plt.figure(figsize=(12,10)) sns.barplot(x="count", y="ngram", data=get_frequent_ngram(train['review'], i)) plt.title(f"Most common {mapping[i]}grams"); The word ‘film’ and ‘movie’ looks quite frequent compared to the other frequent words. The answer to question 2.3.2. is to potentially add ‘movie’, and ‘film’ to stop words. It’s interesting to see frequent bigrams, trigrams and fourgrams. As we increase n, the frequency drops as expected. Bigrams may be potentially useful but trigrams and fourgrams are not frequent enough relative to the token frequency. Let’s answer these questions together: ✏️ 2.5.1. What is the average number of sentences per document?✏️ 2.5.2. What is the average number of tokens per document?✏️ 2.5.3. What is the average number of characters per document?✏️ 2.5.4. What is the average number of stop words per document?✏️ 2.5.5. How do answers to these questions differ by sentiment? Firstly, we have to prepare the data: # tokeniser = RegexpTokenizer("[A-Za-z]+")train["n_sentences"] = train["review"].apply(sent_tokenize).apply(len)train["tokens"] = train["review"].apply(tokeniser.tokenize)train["n_tokens"] = train["tokens"].apply(len)train["n_characters"] = train["review"].apply(len)train["n_stopwords"] = train["tokens"].apply(lambda tokens: len([t for t in tokens if t in stop_words]))train["p_stopwords"] = train["n_stopwords"]/train["n_tokens"]# Inspect headcolumns = ['sentiment', 'n_sentences', 'n_tokens', 'n_characters', 'n_stopwords', 'p_stopwords']train[columns].head() Let’s check the descriptive statistics of the variables of interest: train.describe() We have the answers to the first four questions in this table. Now, let’s see if it differs by sentiment. If they differ significantly, we could use the variable as a feature to the model: num_vars = train.select_dtypes(np.number).columnstrain.groupby("sentiment")[num_vars].agg(["mean", "median"]) From looking at central tendency, it doesn’t appear to differ by sentiment substantially. Just to be sure, let’s look at the distribution: def plot_distribution(df, var, hue): """Plot overlayed histogram and density plot per sentiment.""" fig, ax = plt.subplots(nrows=1, ncols=2, figsize=[16,4]) # Histogram sns.histplot(data=df, x=var, hue=hue, bins=30, kde=False, ax=ax[0]) ax[0].set_title(f"Histogram for {var}") # Density plot sns.kdeplot(data=df, x=var, hue=hue, shade=True, ax=ax[1]) ax[1].set_title(f"Density plot for {var}"); # Plot for all numerical variablesfor var in num_vars: plot_distribution(train, var, 'sentiment') The distribution of variables seem pretty similar between sentiments. It’s unlikely that they will be useful as features, but we could always experiment. Maybe we could add this to a list of nice-to-try items? Before we wrap up, let’s look at one last thing - whether common words differ by sentiment. Let’s prepare the data for each sentiment: pos_documents = [preprocess_text(document) for document in train.loc[train['sentiment']=='positive', 'review']]pos_tokens = [item for sublist in pos_documents for item in sublist]pos_freq = FreqDist(pos_tokens)pos_common = [word for word, frequency in pos_freq.most_common(20)]print(f"***** 20 frequent tokens in positive reviews: *****\n{pos_common}\n")neg_documents = [preprocess_text(document) for document in train.loc[train['sentiment']=='negative', 'review']]neg_tokens = [item for sublist in neg_documents for item in sublist]neg_freq = FreqDist(neg_tokens)neg_common = [word for word, frequency in neg_freq.most_common(20)]print(f"***** 20 frequent tokens in negative reviews: *****\n{neg_common}\n")common = set(neg_common).union(pos_common)print(f"***** Their union: *****\n{common}\n") The 3 most common tokens in both sentiments are ‘film’, ‘movie’ and ‘one’. Let’s look at their frequencies: # Create a dataframe containing the common tokens and their frequencycommon_freq = pd.DataFrame(index=common, columns=["neg", "pos"])for token in common: common_freq.loc[token, "pos"] = pos_freq[token] common_freq.loc[token, "neg"] = neg_freq[token]common_freq.sort_values(by="pos", inplace=True)# Add ranks and rank differencecommon_freq['pos_rank'] = common_freq['pos'].rank()common_freq['neg_rank'] = common_freq['neg'].rank()common_freq['rank_diff'] = common_freq['neg_rank'] - common_freq['pos_rank']common_freq.sort_values(by='rank_diff', inplace=True)common_freq.head() Now, time to visualise: fig, ax =plt.subplots(1, 2, figsize=(16, 10))sns.barplot(x="pos", y=common_freq.index, data = common_freq, ax=ax[0])sns.barplot(x="neg", y=common_freq.index, data = common_freq, ax=ax[1])fig.suptitle('Top tokens and their frequency by sentiment'); Hmm, it’s interesting to see ‘film’ is more frequent than ‘movie’ in positive reviews. In negative reviews, it’s flipped. Maybe they shouldn’t be added to stop words after all despite their frequency. Let’s look at the chart again, but excluding these two common words: rest = common_freq.index.drop(['film', 'movie'])fig, ax =plt.subplots(1, 2, figsize=(16, 10))sns.barplot(x="pos", y=rest, data = common_freq.loc[rest], ax=ax[0])sns.barplot(x="neg", y=rest, data = common_freq.loc[rest], ax=ax[1])fig.suptitle('Top tokens and their frequency by sentiment'); It’s intuitive to see that the word ‘great’, ‘well’ and ‘love’ are more frequent in positive reviews whereas ‘even’ and ‘bad’ are more frequent in negative reviews. There are still many things to explore, but it’s time to wrap up! 🕛 Well done to you for making this far! 😎 Let’s summarise the key points:◼️ Remove punctuation and numbers when tokenising◼️ Normalise text (lowercase, lemmatise, etc)◼️ Enrich stop words with ‘br’ and other missing auxillary verbs◼️ Remove rare words A list of nice-to-try items: ◼️ Convert British spelling to American spelling (or vice versa)◼️ Keep numbers and convert them to words◼️ Keep hyphenated words as they are when tokenising◼️ Include bigrams◼️ Add numerical features such as number of sentences, tokens, characters and stop words Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me. Thank you for reading my post. Exploratory data analysis is an open-ended and subjective task. You may have noticed that we had to make many small choices when exploring and preprocessing. I hope this post gave you a taste of how to structure the analysis and showed example questions you could think about during the process. Having done some exploratory analysis, we are one step closer to building a model. In the next post, we will prepare the data for the model. Here are links to the other two posts of the series:◼️ Preprocessing text in Python◼️ Sentiment classification in Python Here are links to the my other NLP-related posts:◼️ Simple wordcloud in Python(Below lists a series of posts on Introduction to NLP)◼️ Part 1: Preprocessing text in Python◼️ Part 2: Difference between lemmatisation and stemming◼️ Part 3: TF-IDF explained◼️ Part 4: Supervised text classification model in Python◼️ Part 5A: Unsupervised topic model in Python (sklearn)◼️ Part 5B: Unsupervised topic model in Python (gensim) Bye for now 🏃💨
[ { "code": null, "e": 678, "s": 172, "text": "Why do we do exploratory data analysis before we build a model? I would say ‘to understand the data better so that we preprocess the data in a suitable way and choose an appropriate modelling technique’. This necessity to understand data is still relevant when working with text data. This post is the first of the three sequential posts on steps to build a sentiment classifier. In this post, we will look at one way to conduct exploratory data analysis on text, or exploratory text analysis for brevity." }, { "code": null, "e": 994, "s": 678, "text": "Before we dive in, let’s take a step back and look at the bigger picture first. CRISP-DM methodology outlines the process flow for a successful data science project. In the diagram below, 2–4th stages of data science project are shown. In data understanding stage, exploratory data analysis is one of the key tasks." }, { "code": null, "e": 1642, "s": 994, "text": "When working on a data science project, it is not unusual to be going back and forth between stages rather than linearly progressing. This is because ideas and questions come up in subsequent stages and you want to go back a stage or two to try out the idea or find the answer to the question. The pink arrows are not in the official CRISP-DM, however, I think these are often necessary. In fact, we will be doing a bit of data preparation in this post for the purpose of exploratory text analysis. For those who are interested to learn more about CRISP-DM, this is a nice short introduction and this resource provides a more detailed explanation." }, { "code": null, "e": 1868, "s": 1642, "text": "This post assumes that the reader (👀 yes, you!) has access to and is familiar with Python including installing packages, defining functions and other basic tasks. If you are new to Python, this is a good place to get started." }, { "code": null, "e": 1931, "s": 1868, "text": "I have tested the scripts in Python 3.7.1 in Jupyter Notebook." }, { "code": null, "e": 2153, "s": 1931, "text": "Let’s make sure you have the following libraries installed before we start:◼️ Data manipulation/analysis: numpy, pandas◼️ Data partitioning: sklearn◼️ Text preprocessing/analysis: nltk◼️ Visualisation: matplotlib, seaborn" }, { "code": null, "e": 2288, "s": 2153, "text": "Once you have nltk installed, please make sure you have downloaded ‘punkt’, ‘stopwords’ and ‘wordnet’ from nltk with the script below:" }, { "code": null, "e": 2417, "s": 2288, "text": "import nltknltk.download('punkt') # for sent_tokenizenltk.download('stopwords') nltk.download('wordnet') # for WordNetLemmatizer" }, { "code": null, "e": 2485, "s": 2417, "text": "If you have already downloaded, running this will notify you of so." }, { "code": null, "e": 2531, "s": 2485, "text": "Now, we are ready to import all the packages:" }, { "code": null, "e": 3082, "s": 2531, "text": "# Setting random seedseed = 123# Data manipulation/analysisimport numpy as npimport pandas as pd# Data partitioningfrom sklearn.model_selection import train_test_split# Text preprocessing/analysisimport refrom nltk import word_tokenize, sent_tokenize, FreqDistfrom nltk.util import ngramsfrom nltk.corpus import stopwordsfrom nltk.stem import WordNetLemmatizerfrom nltk.tokenize import RegexpTokenizer# Visualisationimport matplotlib.pyplot as pltimport seaborn as snssns.set(style=\"whitegrid\", context='talk', palette=['#D44D5C', '#43AA8B'])" }, { "code": null, "e": 3144, "s": 3082, "text": "Takeaways or notes will be accompanied with 🍀 when exploring." }, { "code": null, "e": 3296, "s": 3144, "text": "We will use IMDB movie reviews dataset. You can download the dataset here and save it in your working directory. Once saved, let’s import it to Python:" }, { "code": null, "e": 3412, "s": 3296, "text": "sample = pd.read_csv('IMDB Dataset.csv')print(f\"{sample.shape[0]} rows and {sample.shape[1]} columns\")sample.head()" }, { "code": null, "e": 3518, "s": 3412, "text": "From looking at the head of the data, we can instantly see that there are html tags in the second record." }, { "code": null, "e": 3578, "s": 3518, "text": "🍀 Inspect html tags further and see how prevalent they are." }, { "code": null, "e": 3622, "s": 3578, "text": "Let’s look at the split between sentiments:" }, { "code": null, "e": 3657, "s": 3622, "text": "sample['sentiment'].value_counts()" }, { "code": null, "e": 3850, "s": 3657, "text": "Sentiment is evenly split in the sample data. Before we start exploratory text analysis, let’s first partition the data into two sets: train and test. We will set aside 5000 cases for testing:" }, { "code": null, "e": 4447, "s": 3850, "text": "# Split data into train & testX_train, X_test, y_train, y_test = train_test_split(sample['review'], sample['sentiment'], test_size=5000, random_state=seed, stratify=sample['sentiment'])# Append sentiment back using indicestrain = pd.concat([X_train, y_train], axis=1)test = pd.concat([X_test, y_test], axis=1)# Check dimensionsprint(f\"Train: {train.shape[0]} rows and {train.shape[1]} columns\")print(f\"{train['sentiment'].value_counts()}\\n\")print(f\"Test: {test.shape[0]} rows and {test.shape[1]} columns\")print(test['sentiment'].value_counts())" }, { "code": null, "e": 4540, "s": 4447, "text": "By specifying the stratify argument, we ensured that sentiment is evenly split in both sets." }, { "code": null, "e": 4845, "s": 4540, "text": "We will be using train for the exploratory text analysis in this post. Once we explore the training dataset, it may be useful to check the key characteristics of test set separately. Ideally, both sets should be representative of the underlying population. Let’s inspect the head of the training dataset:" }, { "code": null, "e": 4858, "s": 4845, "text": "train.head()" }, { "code": null, "e": 4896, "s": 4858, "text": "Alright, we are all set to explore! ✨" }, { "code": null, "e": 5163, "s": 4896, "text": "One way to guide exploratory data analysis is to write down questions that you are interested in and answer them with the data. Finding answers to questions often leads to other questions that you may want to explore. Here are some example questions we could answer:" }, { "code": null, "e": 5322, "s": 5163, "text": "📋 2.1. Warm-up:* How many strings are there?* What are the most common strings?* How do the shortest strings look like?* How do the longest strings look like?" }, { "code": null, "e": 5337, "s": 5322, "text": "📋 2.2. Tokens:" }, { "code": null, "e": 5661, "s": 5337, "text": "💡 Token is a sequence of characters. Tokens are often loosely referred to as words.💡 Tokenisation is a process of splitting a document into tokens and sometimes also throwing away certain characters such as punctuation. Example: Tokenisation turns ‘This movie was awesome’ into 4 tokens: [‘This’, ‘movie’, ‘was’, ‘awesome’]" }, { "code": null, "e": 5778, "s": 5661, "text": "* How many tokens are there?* How many unique tokens are there?* What is the average number of characters per token?" }, { "code": null, "e": 5797, "s": 5778, "text": "📋 2.3. Stop words:" }, { "code": null, "e": 5910, "s": 5797, "text": "💡 Stop words are common words which provide little to no value to the meaning of the text. Example: the, a, and." }, { "code": null, "e": 6022, "s": 5910, "text": "* What are the most common stop words?* What other words occur so often such that could be added to stop words?" }, { "code": null, "e": 6050, "s": 6022, "text": "📋 2.4. Common word n-grams:" }, { "code": null, "e": 6212, "s": 6050, "text": "💡 Word n-grams are all combinations of adjacent n words in text data. Example: Bigrams in ‘This movie was awesome’ are [‘This movie’, ‘movie was’, ‘was awesome’]" }, { "code": null, "e": 6355, "s": 6212, "text": "* What are the most common tokens?* What are the most common bigrams?* What are the most common trigrams?* What are the most common fourgrams?" }, { "code": null, "e": 6373, "s": 6355, "text": "📋 2.5. Documents:" }, { "code": null, "e": 6573, "s": 6373, "text": "💡 Document is a text record. Example: each movie review is a document.💡 Corpus is a collection of documents. Simply put, text data is a corpus. Example: we can refer training data as training corpus." }, { "code": null, "e": 6834, "s": 6573, "text": "* What is the average number of sentences per document?* What is the average number of tokens per document?* What is the average number of characters per document?* What is the average number of stop words per document?* How do the answers differ by sentiment?" }, { "code": null, "e": 6887, "s": 6834, "text": "Now, it’s time to find answers to these questions! 😃" }, { "code": null, "e": 7130, "s": 6887, "text": "Let’s merge all the reviews into one string and then split it into sub-strings (here onward referred to as strings) on white space. This ensures the corpus is minimally altered (e.g. keeping punctuation as it is) for this warm-up exploration:" }, { "code": null, "e": 7414, "s": 7130, "text": "# Prepare training corpus into one giant stringtrain_string = \" \".join(X_train.values)print(f\"***** Extract of train_string ***** \\n{train_string[:101]}\", \"\\n\")# Split train_corpus by white spacesplits = train_string.split() print(f\"***** Extract of splits ***** \\n{splits[:18]}\\n\")" }, { "code": null, "e": 7452, "s": 7414, "text": "✏️ 2.1.1. How many strings are there?" }, { "code": null, "e": 7549, "s": 7452, "text": "print(f\"Number of strings: {len(splits)}\")print(f\"Number of unique strings: {len(set(splits))}\")" }, { "code": null, "e": 7771, "s": 7549, "text": "There are over 10 million strings in the training corpus with around 410 thousand unique strings. This gives us initial ballpark figures. We will get a view on how these numbers look for tokens after we tokenise properly." }, { "code": null, "e": 7815, "s": 7771, "text": "✏️ 2.1.2. What are the most common strings?" }, { "code": null, "e": 7892, "s": 7815, "text": "Let’s prepare frequency distribution for each string to answer the question:" }, { "code": null, "e": 8005, "s": 7892, "text": "freq_splits = FreqDist(splits)print(f\"***** 10 most common strings ***** \\n{freq_splits.most_common(10)}\", \"\\n\")" }, { "code": null, "e": 8143, "s": 8005, "text": "It is not surprising to see that most common strings are stop words. We will explore stop words further later in section 2.3. Stop words." }, { "code": null, "e": 8208, "s": 8143, "text": "🍀 Remove stop words before looking at common tokens and n-grams." }, { "code": null, "e": 8257, "s": 8208, "text": "✏️ 2.1.3. How do the shortest strings look like?" }, { "code": null, "e": 8361, "s": 8257, "text": "Let’s define short string as strings with a length of less than 4 characters and check their frequency:" }, { "code": null, "e": 8496, "s": 8361, "text": "short = set(s for s in splits if len(s)<4)short = [(s, freq_splits[s]) for s in short]short.sort(key=lambda x:x[1], reverse=True)short" }, { "code": null, "e": 8589, "s": 8496, "text": "Many short strings appear to be stop words but there are also numbers and other short words." }, { "code": null, "e": 8696, "s": 8589, "text": "🍀 There are numbers in different forms: 3, 2nd, 70s, 90% — we need to decide whether to drop or keep them." }, { "code": null, "e": 8774, "s": 8696, "text": "🍀 There is case variation: ‘the’, ‘The’, ‘THE’ - these need to be normalised." }, { "code": null, "e": 8967, "s": 8774, "text": "Because we haven’t tokenised yet, some strings currently contain punctuation that is attached to a word. As a result, otherwise same words are considered as different as shown in this example:" }, { "code": null, "e": 9036, "s": 8967, "text": "🍀 Discarding punctuation will be helpful to further normalise words." }, { "code": null, "e": 9084, "s": 9036, "text": "✏️ 2.1.4. How do the longest strings look like?" }, { "code": null, "e": 9157, "s": 9084, "text": "Let’s define long strings as 16+ characters long and repeat the process." }, { "code": null, "e": 9288, "s": 9157, "text": "long = set(s for s in splits if len(s)>15)long = [(s, freq_splits[s]) for s in long]long.sort(key=lambda x:x[1], reverse=True)long" }, { "code": null, "e": 9453, "s": 9288, "text": "The frequency of long string looks much lower than short strings which is not too surprising. Long strings look quite interesting and there are a few key takeaways:" }, { "code": null, "e": 9741, "s": 9453, "text": "🍀 There is American and British spelling of the same word: ‘characterization’ vs ‘characterisation’. After a quick check using the script below, American spelling looks more dominant for this word. Quantifying how prevalent the two spelling in the entire training corpus is a bit tricky." }, { "code": null, "e": 9958, "s": 9741, "text": "print(f\"characterisation: {sum([c for s, c in long if re.match(r'characterisation*', s.lower())])} strings\")print(f\"characterization: {sum([c for s, c in long if re.match(r'characterization*', s.lower())])} strings\")" }, { "code": null, "e": 10364, "s": 9958, "text": "🍀 There are hyphenated words: ‘thought-provoking’, ‘post-apocalyptic’, ‘under-appreciated’ and ‘film--specially’ (this one with double hyphens). If we tokenise on white space or punctuation, these strings will be split into separate words. For most cases, this will conserve the gist of the sentence. If we keep hyphenated words as they are, they won’t be as common and consequently removed as rare words." }, { "code": null, "e": 10699, "s": 10364, "text": "🍀 There are words combined with other punctuation (some due to lack of space): ‘actors/actresses’, ‘Mission:Impossible’, “actors(HA!HA!HA!)...they’re”, ‘different:actually,Bullock’. It would be good to separate these cases into separate words when tokenising. So probably tokenising based on white space or punctuation is a good idea." }, { "code": null, "e": 10887, "s": 10699, "text": "🍀 There are websites and email addresses: ‘/>www.ResidentHazard.com’, ‘http://www.PetitionOnline.com/gh1215/petition.html’, ‘[email protected]’’. However, there doesn’t seem to be many." }, { "code": null, "e": 11185, "s": 10887, "text": "🍀 There are outlaw words that repeats the same character more than twice: “Booooring.......Don’t”, ‘NOOOOOOIIIISE!),’. If you know the correct term for these elongated words, I would love to find out. Until then, we will refer them as ‘outlaw words’. These outlaw cases seem to appear very rarely." }, { "code": null, "e": 11281, "s": 11185, "text": "There are other interesting findings we could add to these but these are good starters for now." }, { "code": null, "e": 11587, "s": 11281, "text": "It’s important to understand whether these cases that we just explored are prevalent enough to justify additional preprocessing steps (i.e. longer run time). It’s useful to experiment to see if adding an additional preprocessing step improves model performance. We will do a bit of this in the third post." }, { "code": null, "e": 11635, "s": 11587, "text": "✏️ 2.1.5. Following up questions emerged so far" }, { "code": null, "e": 11873, "s": 11635, "text": "We have answered all 4 warm up questions! While looking for answers, we have gathered even more questions. Before we jump to the next set of predefined questions, let’s quickly follow up some of the questions that have came up on the go." }, { "code": null, "e": 12254, "s": 11873, "text": "◼️ How frequent is html tags? This question emerged when we were looking at head of the sample data in section 1. Data. The example html tag: ‘<br /><br />’ would have been split into three strings: ‘<br’, ‘/><br’ and ‘/>’ when we split the data based on white space. On side note, the <br> tag seems to be used to break lines. Let’s roughly gauge how prevalent the html tags are." }, { "code": null, "e": 12418, "s": 12254, "text": "All follow up questions are similar since we are going to assess the frequency of a particular type of string. To avoid repeating ourselves, let’s make a function." }, { "code": null, "e": 13049, "s": 12418, "text": "def summarise(pattern, strings, freq): \"\"\"Summarise strings matching a pattern.\"\"\" # Find matches compiled_pattern = re.compile(pattern) matches = [s for s in strings if compiled_pattern.search(s)] # Print volume and proportion of matches print(\"{} strings, that is {:.2%} of total\".format(len(matches), len(matches)/ len(strings))) # Create list of tuples containing matches and their frequency output = [(s, freq[s]) for s in set(matches)] output.sort(key=lambda x:x[1], reverse=True) return output# Find strings possibly containing html tagsummarise(r\"/?>?w*<|/>\", splits, freq_splits)" }, { "code": null, "e": 13162, "s": 13049, "text": "If we scroll through the output, there aren’t many html tags other than the <br> tag and a few cases of <i> tag." }, { "code": null, "e": 13287, "s": 13162, "text": "🍀 If we remove punctuation when tokenising, ‘/><br’ and ‘<br’ will become ‘br’ and we could probably add ‘br’ to stop words." }, { "code": null, "e": 13445, "s": 13287, "text": "◼ ️How frequent are numbers? We found some instances of numbers from section 2.1.3. Short strings. Let’s see how frequent they are with the following script:" }, { "code": null, "e": 13483, "s": 13445, "text": "summarise(r\"\\d\", splits, freq_splits)" }, { "code": null, "e": 13777, "s": 13483, "text": "Strings containing numbers are infrequent. In the context of movie reviews, it’s hard to intuitively make sense of how numbers would be useful. 10/10 could be an indication of positive sentiment but what can we infer from numbers such as 4, 80’s and 20th? We will drop numbers when tokenising." }, { "code": null, "e": 14146, "s": 13777, "text": "Depending on the timeline of a project, you may not have enough time to try all the interesting ideas. In that case, it’s handy to keep a list of nice-to-try items which you could experiment with when you have time. We will add the following tasks to that list: 1) Keep and convert numbers to text2) Create a feature indicating whether a review contains numbers or not" }, { "code": null, "e": 14287, "s": 14146, "text": "◼ ️How frequent are hyphenated words? We saw hyphenated words when inspecting long strings in section 2.1.4.Let’s see how frequent they are:" }, { "code": null, "e": 14331, "s": 14287, "text": "summarise(r\"\\w+-+\\w+\", splits, freq_splits)" }, { "code": null, "e": 14699, "s": 14331, "text": "Roughly less than 1% of strings contained hyphenated words. From glancing through the hyphenated words, it makes more sense to separate them out to keep the data simple. For example: We should tokenise ‘camera-work’ to 2 tokens: [‘camera’, ‘work’] instead of 1 token: [‘camera-work’]. We could add ‘keep hyphenated words as they are’ to the list of nice-to-try items." }, { "code": null, "e": 14873, "s": 14699, "text": "◼ ️How frequent are words combined by other punctuation? Much like the previous question, we saw these cases during long string exploration. Let’s see how frequent they are:" }, { "code": null, "e": 14932, "s": 14873, "text": "summarise(r\"\\w+[_!&/)(<\\|}{\\[\\]]\\w+\", splits, freq_splits)" }, { "code": null, "e": 14994, "s": 14932, "text": "Not too frequent, these ones definitely need to be separated." }, { "code": null, "e": 15118, "s": 14994, "text": "◼ ️How frequent are outlaw words? We saw elongated words like ‘NOOOOOOIIIISE!),’ earlier. Let’s see how prevalent they are:" }, { "code": null, "e": 15685, "s": 15118, "text": "def find_outlaw(word): \"\"\"Find words that contain a same character 3+ times in a row.\"\"\" is_outlaw = False for i, letter in enumerate(word): if i > 1: if word[i] == word[i-1] == word[i-2] and word[i].isalpha(): is_outlaw = True break return is_outlawoutlaws = [s for s in splits if find_outlaw(s)]print(\"{} strings, that is {:.2%} of total\".format(len(outlaws), len(outlaws)/ len(splits)))outlaw_freq = [(s, freq_splits[s]) for s in set(outlaws)]outlaw_freq.sort(key=lambda x:x[1], reverse=True)outlaw_freq" }, { "code": null, "e": 15749, "s": 15685, "text": "These are not worth correcting for because there too few cases." }, { "code": null, "e": 16125, "s": 15749, "text": "That was the last follow up question! We have learned a little bit about the data. Hope you are feeling warmed up. 💦 You may have noticed how easily we could keep expanding our questions and keep exploring? In the interest of time, we will stop this section here and try to keep the next sections as succinct as possible. Otherwise, this post will be over a few hours long. 💤" }, { "code": null, "e": 16169, "s": 16125, "text": "Let’s answer these two questions at one go:" }, { "code": null, "e": 16249, "s": 16169, "text": "✏️ 2.2.1. How many tokens are there?✏️ 2.2.2. How many unique tokens are there?" }, { "code": null, "e": 16452, "s": 16249, "text": "We have to tokenise the data first. Recalling from earlier exploration, it seemed best to drop punctuation and numbers when tokenising. With this in mind, let’s tokenise the text into alphabetic tokens:" }, { "code": null, "e": 16558, "s": 16452, "text": "tokeniser = RegexpTokenizer(\"[A-Za-z]+\")tokens = tokeniser.tokenize(train_string)print(tokens[:20], \"\\n\")" }, { "code": null, "e": 16620, "s": 16558, "text": "Now we have tokenised, we can answer the first two questions:" }, { "code": null, "e": 16715, "s": 16620, "text": "print(f\"Number of tokens: {len(tokens)}\")print(f\"Number of unique tokens: {len(set(tokens))}\")" }, { "code": null, "e": 17129, "s": 16715, "text": "There are over 10 million tokens in the training data with around 122 thousand unique tokens. Currently, ‘Watch’, ‘watch’ and ‘watching’ are counted as different tokens. Hmm, wouldn’t it be great if we could normalise them to ‘watch’ and count them as one unique token? If we normalise, the number of unique tokens would be lower. Let’s quickly do two things: convert all tokens into lowercase and lemmatise them:" }, { "code": null, "e": 17288, "s": 17129, "text": "lemmatiser = WordNetLemmatizer()tokens_norm = [lemmatiser.lemmatize(t.lower(), \"v\") for t in tokens]print(f\"Number of unique tokens: {len(set(tokens_norm))}\")" }, { "code": null, "e": 17345, "s": 17288, "text": "Great, the number of unique tokens dropped by about 30%." }, { "code": null, "e": 17767, "s": 17345, "text": "📌 Exercise: If you are keen and have time, instead of combining both steps like above, try separating out and see how the number of unique tokens change at each step. For instance, you could first convert tokens to lowercase, and check the number, and then lemmatise and check the number again. If you change the order of these two operations, is the final number of unique tokens different than 82562? Why would that be?" }, { "code": null, "e": 17872, "s": 17767, "text": "👂 Psst, I will show another way to lemmatise in the next post when preprocessing the text for the model." }, { "code": null, "e": 17934, "s": 17872, "text": "✏️ 2.2.3. What is the average number of characters per token?" }, { "code": null, "e": 18008, "s": 17934, "text": "Let’s find out the average token length and inspect its the distribution:" }, { "code": null, "e": 18336, "s": 18008, "text": "# Create list of token lengths for each tokentoken_length = [len(t) for t in tokens]# Average number of characters per tokenprint(f\"Average number of characters per token: {round(np.mean(token_length),4)}\")# Plot distributionplt.figure(figsize=(12, 12))sns.countplot(y=token_length)plt.title(\"Counts of token length\", size=20);" }, { "code": null, "e": 18465, "s": 18336, "text": "There are a few tokens that is very long but also very rare. Let’s look at the exact counts for those longer than 10 characters:" }, { "code": null, "e": 18551, "s": 18465, "text": "pd.DataFrame(data=token_length, columns=['length']).query(\"length>10\").value_counts()" }, { "code": null, "e": 18621, "s": 18551, "text": "17+ characters long words are infrequent. Let’s inspect some of them:" }, { "code": null, "e": 18655, "s": 18621, "text": "[t for t in tokens if len(t)>=20]" }, { "code": null, "e": 18780, "s": 18655, "text": "Interesting, some are valid long words whereas some are long because they lack white space or outlaw words (i.e. elongated)." }, { "code": null, "e": 18956, "s": 18780, "text": "🍀 When preprocessing, we should make sure that very rare tokens like these ones are dropped such that they won’t create separate columns when vectorising tokens into a matrix." }, { "code": null, "e": 19005, "s": 18956, "text": "✏️ 2.3.1. What are the most frequent stop words?" }, { "code": null, "e": 19041, "s": 19005, "text": "Let’s first inspect all stop words:" }, { "code": null, "e": 19148, "s": 19041, "text": "stop_words = stopwords.words(\"english\")print(f\"There are {len(stop_words)} stopwords.\\n\")print(stop_words)" }, { "code": null, "e": 19505, "s": 19148, "text": "At the time of writing this post, there are 179 stop words. The list of stop words could extend in future. It appears that we could extend the stop words to include a few more. In fact, I have proposed on Github to add generic stop words from below to the list of English stop words in nltk. Let’s also make sure to add a custom stop word ‘br’ to the list:" }, { "code": null, "e": 19692, "s": 19505, "text": "stop_words.extend([\"cannot\", \"could\", \"done\", \"let\", \"may\" \"mayn\", \"might\", \"must\", \"need\", \"ought\", \"oughtn\", \"shall\", \"would\", \"br\"])print(f\"There are {len(stop_words)} stopwords.\\n\")" }, { "code": null, "e": 19746, "s": 19692, "text": "Now, let’s check what are the most common stop words:" }, { "code": null, "e": 19886, "s": 19746, "text": "freq_stopwords = [(sw, tokens_norm.count(sw)) for sw in stop_words]freq_stopwords.sort(key=lambda x: x[1], reverse=True)freq_stopwords[:10]" }, { "code": null, "e": 20118, "s": 19886, "text": "The frequency is really high (duh, I mean they are stop words, of course they will be frequent 😈), especially for ‘be’ and ‘the’. Wouldn’t it be interesting to find out what proportion of tokens are stop words? Let’s quickly check:" }, { "code": null, "e": 20290, "s": 20118, "text": "n_stopwords = len([t for t in tokens_norm if t in stop_words])print(f\"{n_stopwords} tokens are stop words.\")print(f\"That is {round(100*n_stopwords/len(tokens_norm),2)}%.\")" }, { "code": null, "e": 20333, "s": 20290, "text": "About half of the tokens are stop words. 💭" }, { "code": null, "e": 20414, "s": 20333, "text": "✏️2.3.2. What other words occur so often such that could be added to stop words?" }, { "code": null, "e": 20479, "s": 20414, "text": "We will answer this question when we look at common tokens soon." }, { "code": null, "e": 20559, "s": 20479, "text": "It’s time to find out common n-grams. Let’s answer all four questions together:" }, { "code": null, "e": 20637, "s": 20559, "text": "✏️ 2.4.1–4. What are the most common tokens, bigrams, trigrams and fourgrams?" }, { "code": null, "e": 20671, "s": 20637, "text": "Firstly, let’s remove stop words:" }, { "code": null, "e": 20781, "s": 20671, "text": "tokens_clean = [t for t in tokens_norm if t not in stop_words]print(f\"Number of tokens: {len(tokens_clean)}\")" }, { "code": null, "e": 20906, "s": 20781, "text": "This is the remaining 49% of tokens. Now, we can inspect the common tokens (i.e. unigrams), bigrams, trigrams and fourgrams:" }, { "code": null, "e": 22173, "s": 20906, "text": "def preprocess_text(text): \"\"\"Preprocess text into normalised tokens.\"\"\" # Tokenise words into alphabetic tokens tokeniser = RegexpTokenizer(r'[A-Za-z]{2,}') tokens = tokeniser.tokenize(text) # Lowercase and lemmatise lemmatiser = WordNetLemmatizer() lemmas = [lemmatiser.lemmatize(token.lower(), pos='v') for token in tokens] # Remove stopwords keywords= [lemma for lemma in lemmas if lemma not in stop_words] return keywordsdef get_frequent_ngram(corpus, ngram, n=20): \"\"\"Find most common n n-grams tokens.\"\"\" # Preprocess each document documents = [preprocess_text(document) for document in corpus] # Find ngrams per document n_grams = [list(ngrams(document, ngram)) for document in documents] # Find frequency of ngrams n_grams_flattened = [item for sublist in n_grams for item in sublist] freq_dist = FreqDist(n_grams_flattened) top_freq = freq_dist.most_common(n) return pd.DataFrame(top_freq, columns=[\"ngram\", \"count\"])# Get frequent ngrams for all 4for i in range(1,5): mapping = {1:\"uni\", 2:\"bi\", 3:\"tri\", 4:\"four\"} plt.figure(figsize=(12,10)) sns.barplot(x=\"count\", y=\"ngram\", data=get_frequent_ngram(train['review'], i)) plt.title(f\"Most common {mapping[i]}grams\");" }, { "code": null, "e": 22582, "s": 22173, "text": "The word ‘film’ and ‘movie’ looks quite frequent compared to the other frequent words. The answer to question 2.3.2. is to potentially add ‘movie’, and ‘film’ to stop words. It’s interesting to see frequent bigrams, trigrams and fourgrams. As we increase n, the frequency drops as expected. Bigrams may be potentially useful but trigrams and fourgrams are not frequent enough relative to the token frequency." }, { "code": null, "e": 22621, "s": 22582, "text": "Let’s answer these questions together:" }, { "code": null, "e": 22937, "s": 22621, "text": "✏️ 2.5.1. What is the average number of sentences per document?✏️ 2.5.2. What is the average number of tokens per document?✏️ 2.5.3. What is the average number of characters per document?✏️ 2.5.4. What is the average number of stop words per document?✏️ 2.5.5. How do answers to these questions differ by sentiment?" }, { "code": null, "e": 22975, "s": 22937, "text": "Firstly, we have to prepare the data:" }, { "code": null, "e": 23539, "s": 22975, "text": "# tokeniser = RegexpTokenizer(\"[A-Za-z]+\")train[\"n_sentences\"] = train[\"review\"].apply(sent_tokenize).apply(len)train[\"tokens\"] = train[\"review\"].apply(tokeniser.tokenize)train[\"n_tokens\"] = train[\"tokens\"].apply(len)train[\"n_characters\"] = train[\"review\"].apply(len)train[\"n_stopwords\"] = train[\"tokens\"].apply(lambda tokens: len([t for t in tokens if t in stop_words]))train[\"p_stopwords\"] = train[\"n_stopwords\"]/train[\"n_tokens\"]# Inspect headcolumns = ['sentiment', 'n_sentences', 'n_tokens', 'n_characters', 'n_stopwords', 'p_stopwords']train[columns].head()" }, { "code": null, "e": 23608, "s": 23539, "text": "Let’s check the descriptive statistics of the variables of interest:" }, { "code": null, "e": 23625, "s": 23608, "text": "train.describe()" }, { "code": null, "e": 23814, "s": 23625, "text": "We have the answers to the first four questions in this table. Now, let’s see if it differs by sentiment. If they differ significantly, we could use the variable as a feature to the model:" }, { "code": null, "e": 23924, "s": 23814, "text": "num_vars = train.select_dtypes(np.number).columnstrain.groupby(\"sentiment\")[num_vars].agg([\"mean\", \"median\"])" }, { "code": null, "e": 24063, "s": 23924, "text": "From looking at central tendency, it doesn’t appear to differ by sentiment substantially. Just to be sure, let’s look at the distribution:" }, { "code": null, "e": 24594, "s": 24063, "text": "def plot_distribution(df, var, hue): \"\"\"Plot overlayed histogram and density plot per sentiment.\"\"\" fig, ax = plt.subplots(nrows=1, ncols=2, figsize=[16,4]) # Histogram sns.histplot(data=df, x=var, hue=hue, bins=30, kde=False, ax=ax[0]) ax[0].set_title(f\"Histogram for {var}\") # Density plot sns.kdeplot(data=df, x=var, hue=hue, shade=True, ax=ax[1]) ax[1].set_title(f\"Density plot for {var}\"); # Plot for all numerical variablesfor var in num_vars: plot_distribution(train, var, 'sentiment')" }, { "code": null, "e": 24804, "s": 24594, "text": "The distribution of variables seem pretty similar between sentiments. It’s unlikely that they will be useful as features, but we could always experiment. Maybe we could add this to a list of nice-to-try items?" }, { "code": null, "e": 24939, "s": 24804, "text": "Before we wrap up, let’s look at one last thing - whether common words differ by sentiment. Let’s prepare the data for each sentiment:" }, { "code": null, "e": 25736, "s": 24939, "text": "pos_documents = [preprocess_text(document) for document in train.loc[train['sentiment']=='positive', 'review']]pos_tokens = [item for sublist in pos_documents for item in sublist]pos_freq = FreqDist(pos_tokens)pos_common = [word for word, frequency in pos_freq.most_common(20)]print(f\"***** 20 frequent tokens in positive reviews: *****\\n{pos_common}\\n\")neg_documents = [preprocess_text(document) for document in train.loc[train['sentiment']=='negative', 'review']]neg_tokens = [item for sublist in neg_documents for item in sublist]neg_freq = FreqDist(neg_tokens)neg_common = [word for word, frequency in neg_freq.most_common(20)]print(f\"***** 20 frequent tokens in negative reviews: *****\\n{neg_common}\\n\")common = set(neg_common).union(pos_common)print(f\"***** Their union: *****\\n{common}\\n\")" }, { "code": null, "e": 25844, "s": 25736, "text": "The 3 most common tokens in both sentiments are ‘film’, ‘movie’ and ‘one’. Let’s look at their frequencies:" }, { "code": null, "e": 26427, "s": 25844, "text": "# Create a dataframe containing the common tokens and their frequencycommon_freq = pd.DataFrame(index=common, columns=[\"neg\", \"pos\"])for token in common: common_freq.loc[token, \"pos\"] = pos_freq[token] common_freq.loc[token, \"neg\"] = neg_freq[token]common_freq.sort_values(by=\"pos\", inplace=True)# Add ranks and rank differencecommon_freq['pos_rank'] = common_freq['pos'].rank()common_freq['neg_rank'] = common_freq['neg'].rank()common_freq['rank_diff'] = common_freq['neg_rank'] - common_freq['pos_rank']common_freq.sort_values(by='rank_diff', inplace=True)common_freq.head()" }, { "code": null, "e": 26451, "s": 26427, "text": "Now, time to visualise:" }, { "code": null, "e": 26699, "s": 26451, "text": "fig, ax =plt.subplots(1, 2, figsize=(16, 10))sns.barplot(x=\"pos\", y=common_freq.index, data = common_freq, ax=ax[0])sns.barplot(x=\"neg\", y=common_freq.index, data = common_freq, ax=ax[1])fig.suptitle('Top tokens and their frequency by sentiment');" }, { "code": null, "e": 26969, "s": 26699, "text": "Hmm, it’s interesting to see ‘film’ is more frequent than ‘movie’ in positive reviews. In negative reviews, it’s flipped. Maybe they shouldn’t be added to stop words after all despite their frequency. Let’s look at the chart again, but excluding these two common words:" }, { "code": null, "e": 27259, "s": 26969, "text": "rest = common_freq.index.drop(['film', 'movie'])fig, ax =plt.subplots(1, 2, figsize=(16, 10))sns.barplot(x=\"pos\", y=rest, data = common_freq.loc[rest], ax=ax[0])sns.barplot(x=\"neg\", y=rest, data = common_freq.loc[rest], ax=ax[1])fig.suptitle('Top tokens and their frequency by sentiment');" }, { "code": null, "e": 27424, "s": 27259, "text": "It’s intuitive to see that the word ‘great’, ‘well’ and ‘love’ are more frequent in positive reviews whereas ‘even’ and ‘bad’ are more frequent in negative reviews." }, { "code": null, "e": 27492, "s": 27424, "text": "There are still many things to explore, but it’s time to wrap up! 🕛" }, { "code": null, "e": 27742, "s": 27492, "text": "Well done to you for making this far! 😎 Let’s summarise the key points:◼️ Remove punctuation and numbers when tokenising◼️ Normalise text (lowercase, lemmatise, etc)◼️ Enrich stop words with ‘br’ and other missing auxillary verbs◼️ Remove rare words" }, { "code": null, "e": 28035, "s": 27742, "text": "A list of nice-to-try items: ◼️ Convert British spelling to American spelling (or vice versa)◼️ Keep numbers and convert them to words◼️ Keep hyphenated words as they are when tokenising◼️ Include bigrams◼️ Add numerical features such as number of sentences, tokens, characters and stop words" }, { "code": null, "e": 28259, "s": 28035, "text": "Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me." }, { "code": null, "e": 28848, "s": 28259, "text": "Thank you for reading my post. Exploratory data analysis is an open-ended and subjective task. You may have noticed that we had to make many small choices when exploring and preprocessing. I hope this post gave you a taste of how to structure the analysis and showed example questions you could think about during the process. Having done some exploratory analysis, we are one step closer to building a model. In the next post, we will prepare the data for the model. Here are links to the other two posts of the series:◼️ Preprocessing text in Python◼️ Sentiment classification in Python" }, { "code": null, "e": 29271, "s": 28848, "text": "Here are links to the my other NLP-related posts:◼️ Simple wordcloud in Python(Below lists a series of posts on Introduction to NLP)◼️ Part 1: Preprocessing text in Python◼️ Part 2: Difference between lemmatisation and stemming◼️ Part 3: TF-IDF explained◼️ Part 4: Supervised text classification model in Python◼️ Part 5A: Unsupervised topic model in Python (sklearn)◼️ Part 5B: Unsupervised topic model in Python (gensim)" } ]
HTML <a> Tag - GeeksforGeeks
17 Mar, 2022 The <a> tag (anchor tag) in HTML is used to create a hyperlink on the webpage. This hyperlink is used to link the webpage to other web pages. It’s either used to provide an absolute reference or a relative reference as its “href” value. Syntax: <a href = "link"> Link Name </a> Attribute: The anchor tag contains many attributes which are listed below. HTML <a> charset Attribute: This attribute is used to specifies the character-set. It is not supported by HTML 5. HTML <a> download Attribute: It is used to specify the target link to download when the user clicks. HTML <a> hreflang Attribute: It is used to specify the language of the linked document. HTML <a> media Attribute: It is used to specify the linked media. HTML <a> coords Attribute: It is used to specify the coordinate of links. It is not supported by HTML 5. HTML <a> name Attribute: It is used to specify the anchor name. It is not supported by HTML 5 you can use the global id attribute instead. HTML <a> rel Attribute: It is used to specify the relation between the current document and the linked document. HTML <a> shape Attribute: It is used to specify the shape of the link. It is not supported by HTML 5. HTML <a> type Attribute: It is used to specify the type of links. HTML <a> target Attribute: It specifies the target link. HTML <a> rev Attribute: It is used to specify the relation between the linked document and the current document. It is not supported by HTML 5. Example 1: In this example, the GeeksforGeeks HTML Tutorial page will open when you click on the GeeksforGeeks HTML Tutorial link. HTML <!DOCTYPE html><html><body> <h2>Welcome to GeeksforGeeks HTML Tutorial</h2> <a href="https://www.geeksforgeeks.org/html-tutorials/"> GeeksforGeeks HTML Tutorial </a> </body> </html> Output: HTML <a> tag Example 2: In this example we simply redirect from the GeeksforGeeks to the Geeksforgeeks page. HTML <!DOCTYPE html><html> <body> <h1> Welcome to <a href="https://www.geeksforgeeks.org/"> GeeksforGeeks </a> </h1> <h2>This is anchor Tag</h2></body> </html> Output: Redirecting the linked text to the site using <a> tag Example 3: In this example, we will use an image to redirect to the Geeksforgeeks page. HTML <!DOCTYPE html><html><body> <p>Click on the image to open web page.</p> <!-- anchor tag starts here --> <a href="https://www.geeksforgeeks.org/"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/gfg1-11.png" width="300" height="250" /> </a> <!-- anchor tag ends here --></body> </html> Output: Redirecting the linked image to website using HTML <a> tag Supported Browsers: Google Chrome Internet Explorer Firefox Opera Safari Microsoft Edge Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. adhya20kumari shubhamyadav4 bhaskargeeksforgeeks vshylaja HTML-Tags Picked HTML HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property Types of CSS (Cascading Style Sheet) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form REST API (Introduction)
[ { "code": null, "e": 30009, "s": 29981, "text": "\n17 Mar, 2022" }, { "code": null, "e": 30246, "s": 30009, "text": "The <a> tag (anchor tag) in HTML is used to create a hyperlink on the webpage. This hyperlink is used to link the webpage to other web pages. It’s either used to provide an absolute reference or a relative reference as its “href” value." }, { "code": null, "e": 30255, "s": 30246, "text": "Syntax: " }, { "code": null, "e": 30288, "s": 30255, "text": "<a href = \"link\"> Link Name </a>" }, { "code": null, "e": 30363, "s": 30288, "text": "Attribute: The anchor tag contains many attributes which are listed below." }, { "code": null, "e": 30477, "s": 30363, "text": "HTML <a> charset Attribute: This attribute is used to specifies the character-set. It is not supported by HTML 5." }, { "code": null, "e": 30578, "s": 30477, "text": "HTML <a> download Attribute: It is used to specify the target link to download when the user clicks." }, { "code": null, "e": 30666, "s": 30578, "text": "HTML <a> hreflang Attribute: It is used to specify the language of the linked document." }, { "code": null, "e": 30732, "s": 30666, "text": "HTML <a> media Attribute: It is used to specify the linked media." }, { "code": null, "e": 30837, "s": 30732, "text": "HTML <a> coords Attribute: It is used to specify the coordinate of links. It is not supported by HTML 5." }, { "code": null, "e": 30976, "s": 30837, "text": "HTML <a> name Attribute: It is used to specify the anchor name. It is not supported by HTML 5 you can use the global id attribute instead." }, { "code": null, "e": 31089, "s": 30976, "text": "HTML <a> rel Attribute: It is used to specify the relation between the current document and the linked document." }, { "code": null, "e": 31191, "s": 31089, "text": "HTML <a> shape Attribute: It is used to specify the shape of the link. It is not supported by HTML 5." }, { "code": null, "e": 31257, "s": 31191, "text": "HTML <a> type Attribute: It is used to specify the type of links." }, { "code": null, "e": 31314, "s": 31257, "text": "HTML <a> target Attribute: It specifies the target link." }, { "code": null, "e": 31458, "s": 31314, "text": "HTML <a> rev Attribute: It is used to specify the relation between the linked document and the current document. It is not supported by HTML 5." }, { "code": null, "e": 31589, "s": 31458, "text": "Example 1: In this example, the GeeksforGeeks HTML Tutorial page will open when you click on the GeeksforGeeks HTML Tutorial link." }, { "code": null, "e": 31594, "s": 31589, "text": "HTML" }, { "code": "<!DOCTYPE html><html><body> <h2>Welcome to GeeksforGeeks HTML Tutorial</h2> <a href=\"https://www.geeksforgeeks.org/html-tutorials/\"> GeeksforGeeks HTML Tutorial </a> </body> </html>", "e": 31789, "s": 31594, "text": null }, { "code": null, "e": 31797, "s": 31789, "text": "Output:" }, { "code": null, "e": 31810, "s": 31797, "text": "HTML <a> tag" }, { "code": null, "e": 31906, "s": 31810, "text": "Example 2: In this example we simply redirect from the GeeksforGeeks to the Geeksforgeeks page." }, { "code": null, "e": 31911, "s": 31906, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1> Welcome to <a href=\"https://www.geeksforgeeks.org/\"> GeeksforGeeks </a> </h1> <h2>This is anchor Tag</h2></body> </html>", "e": 32085, "s": 31911, "text": null }, { "code": null, "e": 32094, "s": 32085, "text": "Output: " }, { "code": null, "e": 32148, "s": 32094, "text": "Redirecting the linked text to the site using <a> tag" }, { "code": null, "e": 32236, "s": 32148, "text": "Example 3: In this example, we will use an image to redirect to the Geeksforgeeks page." }, { "code": null, "e": 32241, "s": 32236, "text": "HTML" }, { "code": "<!DOCTYPE html><html><body> <p>Click on the image to open web page.</p> <!-- anchor tag starts here --> <a href=\"https://www.geeksforgeeks.org/\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/gfg1-11.png\" width=\"300\" height=\"250\" /> </a> <!-- anchor tag ends here --></body> </html>", "e": 32562, "s": 32241, "text": null }, { "code": null, "e": 32570, "s": 32562, "text": "Output:" }, { "code": null, "e": 32629, "s": 32570, "text": "Redirecting the linked image to website using HTML <a> tag" }, { "code": null, "e": 32650, "s": 32629, "text": "Supported Browsers: " }, { "code": null, "e": 32664, "s": 32650, "text": "Google Chrome" }, { "code": null, "e": 32682, "s": 32664, "text": "Internet Explorer" }, { "code": null, "e": 32690, "s": 32682, "text": "Firefox" }, { "code": null, "e": 32696, "s": 32690, "text": "Opera" }, { "code": null, "e": 32703, "s": 32696, "text": "Safari" }, { "code": null, "e": 32718, "s": 32703, "text": "Microsoft Edge" }, { "code": null, "e": 32855, "s": 32718, "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": 32869, "s": 32855, "text": "adhya20kumari" }, { "code": null, "e": 32883, "s": 32869, "text": "shubhamyadav4" }, { "code": null, "e": 32904, "s": 32883, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 32913, "s": 32904, "text": "vshylaja" }, { "code": null, "e": 32923, "s": 32913, "text": "HTML-Tags" }, { "code": null, "e": 32930, "s": 32923, "text": "Picked" }, { "code": null, "e": 32935, "s": 32930, "text": "HTML" }, { "code": null, "e": 32940, "s": 32935, "text": "HTML" }, { "code": null, "e": 33038, "s": 32940, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33047, "s": 33038, "text": "Comments" }, { "code": null, "e": 33060, "s": 33047, "text": "Old Comments" }, { "code": null, "e": 33122, "s": 33060, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 33172, "s": 33122, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 33232, "s": 33172, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 33280, "s": 33232, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 33341, "s": 33280, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 33394, "s": 33341, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 33431, "s": 33394, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 33481, "s": 33431, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 33531, "s": 33481, "text": "CSS to put icon inside an input element in a form" } ]
Angular7 - Pipes
In this chapter, we will discuss about Pipes in Angular 7. Pipes were earlier called filters in Angular1 and called pipes from Angular2 onwards. The | character is used to transform data. Following is the syntax for the same − {{ Welcome to Angular 7 | lowercase}} It takes integers, strings, arrays, and date as input separated with | to be converted in the format as required and display the same in the browser. Let us consider a few examples using pipes. Here, we want to display the text given to uppercase. This can be done using pipes as follows − In the app.component.ts file, we have defined the title variable as follows − app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 7 Project!'; } The following line of code goes into the app.component.html file − <b>{{title | uppercase}}</b><br/> <b>{{title | lowercase}}</b> The browser appears as shown in the following screenshot − Here are some built-in pipes available with angular − Lowercasepipe Uppercasepipe Datepipe Currencypipe Jsonpipe Percentpipe Decimalpipe Slicepipe We have already seen the lowercase and uppercase pipes. Let us now see how the other pipes work. The following line of code will help us define the required variables in app.component.ts file − import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 7 Project!'; todaydate = new Date(); jsonval = {name:'Rox', age:'25', address:{a1:'Mumbai', a2:'Karnataka'}}; months = ["Jan", "Feb", "Mar", "April", "May", "Jun", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]; } We will use the pipes in the app.component.html file as shown below − <!--The content below is only a placeholder and can be replaced.--> <div style = "width:100%;"> <div style = "width:40%;float:left;border:solid 1px black;"> <h1>Uppercase Pipe</h1> <b>{{title | uppercase}}</b> <br/> <h1>Lowercase Pipe</h1> <b>{{title | lowercase}}</b> <h1>Currency Pipe</h1> <b>{{6589.23 | currency:"USD"}}</b> <br/> <b>{{6589.23 | currency:"USD":true}}</b> // Boolean true is used to get the sign of the currency. <h1>Date pipe</h1> <b>{{todaydate | date:'d/M/y'}}</b> <br/> <b>{{todaydate | date:'shortTime'}}</b> <h1>Decimal Pipe</h1> <b>{{ 454.78787814 | number: '3.4-4' }}</b> // 3 is for main integer, 4 -4 are for integers to be displayed. </div> <div style = "width:40%;float:left;border:solid 1px black;"< <h1<Json Pipe</h1> <b>{{ jsonval | json }}</b> <h1>Percent Pipe</h1> <b>{{00.54565 | percent}}</b> <h1>Slice Pipe</h1> <b>{{months | slice:2:6}}</b> // here 2 and 6 refers to the start and the end index </div> </div> The following screenshots show the output for each pipe − To create a custom pipe, we have created a new ts file. Here, we want to create the sqrt custom pipe. We have given the same name to the file and it looks as follows − app.sqrt.ts import {Pipe, PipeTransform} from '@angular/core'; @Pipe ({ name : 'sqrt' }) export class SqrtPipe implements PipeTransform { transform(val : number) : number { return Math.sqrt(val); } } To create a custom pipe, we have to import Pipe and Pipe Transform from Angular/core. In the @Pipe directive, we have to give the name to our pipe, which will be used in our .html file. Since, we are creating the sqrt pipe, we will name it sqrt. As we proceed further, we have to create the class and the class name is SqrtPipe. This class will implement the PipeTransform. The transform method defined in the class will take argument as the number and will return the number after taking the square root. Since we have created a new file, we need to add the same in app.module.ts. This is done as follows − import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { NewCmpComponent } from './new-cmp/new-cmp.component'; import { ChangeTextDirective } from './change-text.directive'; import { SqrtPipe } from './app.sqrt'; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } We have created the app.sqrt.ts class. We have to import the same in app.module.ts and specify the path of the file. It also has to be included in the declarations as shown above. Let us now see the call made to the sqrt pipe in the app.component.html file. <h1>Custom Pipe</h1> <b>Square root of 25 is: {{25 | sqrt}}</b> <br/> <b>Square root of 729 is: {{729 | sqrt}}</b> Following is the output − 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": 2206, "s": 2061, "text": "In this chapter, we will discuss about Pipes in Angular 7. Pipes were earlier called filters in Angular1 and called pipes from Angular2 onwards." }, { "code": null, "e": 2288, "s": 2206, "text": "The | character is used to transform data. Following is the syntax for the same −" }, { "code": null, "e": 2327, "s": 2288, "text": "{{ Welcome to Angular 7 | lowercase}}\n" }, { "code": null, "e": 2477, "s": 2327, "text": "It takes integers, strings, arrays, and date as input separated with | to be converted in the format as required and display the same in the browser." }, { "code": null, "e": 2617, "s": 2477, "text": "Let us consider a few examples using pipes. Here, we want to display the text given to uppercase. This can be done using pipes as follows −" }, { "code": null, "e": 2695, "s": 2617, "text": "In the app.component.ts file, we have defined the title variable as follows −" }, { "code": null, "e": 2712, "s": 2695, "text": "app.component.ts" }, { "code": null, "e": 2943, "s": 2712, "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 = 'Angular 7 Project!'; \n}" }, { "code": null, "e": 3010, "s": 2943, "text": "The following line of code goes into the app.component.html file −" }, { "code": null, "e": 3075, "s": 3010, "text": "<b>{{title | uppercase}}</b><br/> \n<b>{{title | lowercase}}</b>\n" }, { "code": null, "e": 3134, "s": 3075, "text": "The browser appears as shown in the following screenshot −" }, { "code": null, "e": 3188, "s": 3134, "text": "Here are some built-in pipes available with angular −" }, { "code": null, "e": 3202, "s": 3188, "text": "Lowercasepipe" }, { "code": null, "e": 3216, "s": 3202, "text": "Uppercasepipe" }, { "code": null, "e": 3225, "s": 3216, "text": "Datepipe" }, { "code": null, "e": 3238, "s": 3225, "text": "Currencypipe" }, { "code": null, "e": 3247, "s": 3238, "text": "Jsonpipe" }, { "code": null, "e": 3259, "s": 3247, "text": "Percentpipe" }, { "code": null, "e": 3271, "s": 3259, "text": "Decimalpipe" }, { "code": null, "e": 3281, "s": 3271, "text": "Slicepipe" }, { "code": null, "e": 3475, "s": 3281, "text": "We have already seen the lowercase and uppercase pipes. Let us now see how the other pipes work. The following line of code will help us define the required variables in app.component.ts file −" }, { "code": null, "e": 3919, "s": 3475, "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 = 'Angular 7 Project!'; \n todaydate = new Date(); \n jsonval = {name:'Rox', age:'25', address:{a1:'Mumbai', a2:'Karnataka'}}; \n months = [\"Jan\", \"Feb\", \"Mar\", \"April\", \"May\", \"Jun\", \"July\", \"Aug\", \n \"Sept\", \"Oct\", \"Nov\", \"Dec\"]; \n}" }, { "code": null, "e": 3989, "s": 3919, "text": "We will use the pipes in the app.component.html file as shown below −" }, { "code": null, "e": 5145, "s": 3989, "text": "<!--The content below is only a placeholder and can be replaced.--> \n<div style = \"width:100%;\"> \n <div style = \"width:40%;float:left;border:solid 1px black;\"> \n <h1>Uppercase Pipe</h1> \n <b>{{title | uppercase}}</b>\n <br/> \n \n <h1>Lowercase Pipe</h1> \n <b>{{title | lowercase}}</b> \n <h1>Currency Pipe</h1> \n <b>{{6589.23 | currency:\"USD\"}}</b>\n <br/> \n \n <b>{{6589.23 | currency:\"USD\":true}}</b> \n // Boolean true is used to get the sign of the currency. \n <h1>Date pipe</h1> \n <b>{{todaydate | date:'d/M/y'}}</b>\n <br/> \n \n <b>{{todaydate | date:'shortTime'}}</b> \n <h1>Decimal Pipe</h1> \n <b>{{ 454.78787814 | number: '3.4-4' }}</b> \n // 3 is for main integer, 4 -4 are for integers to be displayed. \n </div> \n \n <div style = \"width:40%;float:left;border:solid 1px black;\"< \n <h1<Json Pipe</h1> \n <b>{{ jsonval | json }}</b>\n <h1>Percent Pipe</h1> \n <b>{{00.54565 | percent}}</b> \n <h1>Slice Pipe</h1> \n <b>{{months | slice:2:6}}</b> \n // here 2 and 6 refers to the start and the end index \n </div> \n</div>" }, { "code": null, "e": 5203, "s": 5145, "text": "The following screenshots show the output for each pipe −" }, { "code": null, "e": 5371, "s": 5203, "text": "To create a custom pipe, we have created a new ts file. Here, we want to create the sqrt custom pipe. We have given the same name to the file and it looks as follows −" }, { "code": null, "e": 5383, "s": 5371, "text": "app.sqrt.ts" }, { "code": null, "e": 5589, "s": 5383, "text": "import {Pipe, PipeTransform} from '@angular/core'; \n@Pipe ({ \n name : 'sqrt'\n}) \nexport class SqrtPipe implements PipeTransform {\n transform(val : number) : number {\n return Math.sqrt(val);\n }\n}" }, { "code": null, "e": 5835, "s": 5589, "text": "To create a custom pipe, we have to import Pipe and Pipe Transform from Angular/core. In the @Pipe directive, we have to give the name to our pipe, which will be used in our .html file. Since, we are creating the sqrt pipe, we will name it sqrt." }, { "code": null, "e": 5963, "s": 5835, "text": "As we proceed further, we have to create the class and the class name is SqrtPipe. This class will implement the PipeTransform." }, { "code": null, "e": 6095, "s": 5963, "text": "The transform method defined in the class will take argument as the number and will return the number after taking the square root." }, { "code": null, "e": 6197, "s": 6095, "text": "Since we have created a new file, we need to add the same in app.module.ts. This is done as follows −" }, { "code": null, "e": 6849, "s": 6197, "text": "import { BrowserModule } from '@angular/platform-browser'; \nimport { NgModule } from '@angular/core';\nimport { AppRoutingModule } from './app-routing.module'; \nimport { AppComponent } from './app.component'; \nimport { NewCmpComponent } from './new-cmp/new-cmp.component'; \nimport { ChangeTextDirective } from './change-text.directive'; \nimport { SqrtPipe } from './app.sqrt';\n\n@NgModule({\n declarations: [ \n SqrtPipe, \n AppComponent, \n NewCmpComponent, \n ChangeTextDirective \n ], \n imports: [ \n BrowserModule, \n AppRoutingModule\n ], \n providers: [], \n bootstrap: [AppComponent] \n}) \nexport class AppModule { }" }, { "code": null, "e": 7029, "s": 6849, "text": "We have created the app.sqrt.ts class. We have to import the same in app.module.ts and specify the path of the file. It also has to be included in the declarations as shown above." }, { "code": null, "e": 7107, "s": 7029, "text": "Let us now see the call made to the sqrt pipe in the app.component.html file." }, { "code": null, "e": 7226, "s": 7107, "text": "<h1>Custom Pipe</h1> \n<b>Square root of 25 is: {{25 | sqrt}}</b> \n<br/> \n<b>Square root of 729 is: {{729 | sqrt}}</b>\n" }, { "code": null, "e": 7252, "s": 7226, "text": "Following is the output −" }, { "code": null, "e": 7287, "s": 7252, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7301, "s": 7287, "text": " Anadi Sharma" }, { "code": null, "e": 7336, "s": 7301, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7350, "s": 7336, "text": " Anadi Sharma" }, { "code": null, "e": 7385, "s": 7350, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 7405, "s": 7385, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 7440, "s": 7405, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7457, "s": 7440, "text": " Frahaan Hussain" }, { "code": null, "e": 7490, "s": 7457, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 7502, "s": 7490, "text": " Senol Atac" }, { "code": null, "e": 7537, "s": 7502, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7549, "s": 7537, "text": " Senol Atac" }, { "code": null, "e": 7556, "s": 7549, "text": " Print" }, { "code": null, "e": 7567, "s": 7556, "text": " Add Notes" } ]
Compound Assignment Operators in C++
The compound assignment operators are specified in the form e1 op= e2, where e1 is a modifiable l-value not of const type and e2 is one of the following − An arithmetic type A pointer, if op is + or – The e1 op= e2 form behaves as e1 = e1 op e2, but e1 is evaluated only once. The following are the compound assignment operators in C++ − Let's have a look at an example using some of these operators − #include<iostream> using namespace std; int main() { int a = 3, b = 2; a += b; cout << a << endl; a -= b; cout << a << endl; a *= b; cout << a << endl; a /= b; cout << a << endl; return 0; } This will give the output − 5 3 6 3 Note that Compound assignment to an enumerated type generates an error message. If the left operand is of a pointer type, the right operand must be of a pointer type or it must be a constant expression that evaluates to 0. If the left operand is of an integral type, the right operand must not be of a pointer type.
[ { "code": null, "e": 1217, "s": 1062, "text": "The compound assignment operators are specified in the form e1 op= e2, where e1 is a modifiable l-value not of const type and e2 is one of the following −" }, { "code": null, "e": 1236, "s": 1217, "text": "An arithmetic type" }, { "code": null, "e": 1263, "s": 1236, "text": "A pointer, if op is + or –" }, { "code": null, "e": 1339, "s": 1263, "text": "The e1 op= e2 form behaves as e1 = e1 op e2, but e1 is evaluated only once." }, { "code": null, "e": 1400, "s": 1339, "text": "The following are the compound assignment operators in C++ −" }, { "code": null, "e": 1464, "s": 1400, "text": "Let's have a look at an example using some of these operators −" }, { "code": null, "e": 1691, "s": 1464, "text": "#include<iostream>\nusing namespace std;\n\nint main() {\n int a = 3, b = 2;\n\n a += b;\n cout << a << endl;\n\n a -= b;\n cout << a << endl;\n\n a *= b;\n cout << a << endl;\n\n a /= b;\n cout << a << endl;\n\n return 0;\n}" }, { "code": null, "e": 1719, "s": 1691, "text": "This will give the output −" }, { "code": null, "e": 1727, "s": 1719, "text": "5\n3\n6\n3" }, { "code": null, "e": 2043, "s": 1727, "text": "Note that Compound assignment to an enumerated type generates an error message. If the left operand is of a pointer type, the right operand must be of a pointer type or it must be a constant expression that evaluates to 0. If the left operand is of an integral type, the right operand must not be of a pointer type." } ]
HBase Interview Questions
Dear readers, these HBase Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of HBase. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer: There are 5 atomic commands which carry out different operations by Hbase. Get, Put, Delete, Scan and Increment. A connection to Hbase is established through Hbase Shell which is a Java API. The Master server assigns regions to region servers and handles load balancing in the cluster. The zookeeper maintains configuration information, provides distributed synchronization, and also maintains the communication between clients and region servers. In Hbase a table is disabled to allow it to be modified or change its settings. .When a table is disabled it cannot be accessed through the scan command. Hbase > is_disabled “table name” hbase > disable_all 'p.*' The command will disable all the table starting with the letter p Filters are used to get specific data form a Hbase table rather than all the records. They are of the following types. Column Value Filter Column Value comparators KeyValue Metadata filters. RowKey filters. Hbase does not have in-built authentication/permission mechanism Hbase does not have in-built authentication/permission mechanism The indexes can be created only on a key column, but in RDBMS it can be done in any column. The indexes can be created only on a key column, but in RDBMS it can be done in any column. With one HMaster node there is a single point of failure. With one HMaster node there is a single point of failure. The catalog tables in Hbase maintain the metadata information. They are named as −ROOT− and .META. The −ROOT− table stores information about location of .META> table and the .META> table holds information about all regions and their locations. Hbase runs on top of Hadoop which is a distributed system. Haddop can only scale uo as and when required by adding more machines on the fly. So Hbase is a scale out process. In Hbase the client does not write directly into the HFile. The client first writes to WAL(Write Access Log), which then is accessed by Memstore. The Memstore Flushes the data into permanent memory from time to time. As more and more data is written to Hbase, many HFiles get created. Compaction is the process of merging these HFiles to one file and after the merged file is created successfully, discard the old file. There are two types of compaction. Major and Minor compaction. In minor compaction, the adjacent small HFiles are merged to create a single HFile without removing the deleted HFiles. Files to be merged are chosen randomly. In Major compaction, all the HFiles of a column are emerged and a single HFiles is created. The delted HFiles are discarded and it is generally triggered manually. The Delete column command deletes all versions of a column but the delete family deletes all columns of a particular family. A cell in Hbase is the smallest unit of a Hbase table which holds a piece of data in the form of a tuple{row,column,version} This class is used to store information about a column family such as the number of versions, compression settings, etc. It is used as input when creating a table or adding a column. The lower bound of versions indicates the minimum number of versions to be stored in Hbase for a column. For example If the value is set to 3 then three latest version wil be maintained and the older ones will be removed. TTL is a data retention technique using which the version of a cell can be preserved till a specific time period.Once that timestamp is reached the specific version will be removed. Hbase does not support table jons. But using a mapreduce job we can specify join queries to retrieve data from multiple Hbase tables. Each row in Hbase is identified by a unique byte of array called row key. The data in Hbase can be accessed in two ways. Using the rowkey and table scan for a range of row key values. Using the rowkey and table scan for a range of row key values. Using mapreduce in a batch manner. Using mapreduce in a batch manner. They are − (i) Short and Wide (ii) Tall and Thin The short and wide table design is considered when there is There is a small number of columns There is a small number of columns There is a large number of rows There is a large number of rows The tall and thin table design is considered when there is There is a large number of columns There is a large number of columns There is a small number of rows There is a small number of rows hbase > alter 'tablename', {NAME => 'ColFamily', VERSIONS => 4} hbase > alter 'tablename', {NAME => 'colFamily', METHOD => 'delete'} This command deletes the column family form the table. Hbase > disable ‘tablename’ Hbase > alter ‘tablename’ {NAME => ‘oldcolfamily’,NAME=>’newcolfamily’} Habse > enable ‘tablename’ scan 'tablename', {LIMIT=>10, STARTROW=>"start_row", STOPROW=>"stop_row"} major_compact 'tablename' Run a major compaction on the table. There are two main steps to do a data bulk load in Hbase. Generate Hbase data file(StoreFile) using a custom mapreduce job) from the data source. The StoreFile is created in Hbase internal format which can be efficiently loaded. Generate Hbase data file(StoreFile) using a custom mapreduce job) from the data source. The StoreFile is created in Hbase internal format which can be efficiently loaded. The prepared file is imported using another tool like comletebulkload to import data into a running cluster. Each file gets loaded to one specific region. The prepared file is imported using another tool like comletebulkload to import data into a running cluster. Each file gets loaded to one specific region. Hbase uses a feature called region replication. In this feature for each region of a table, there will be multiple replicas that are opened in different RegionServers. The Load Balancer ensures that the region replicas are not co-hosted in the same region servers. The Hmaster is the Master server responsible for monitoring all RegionServer instances in the cluster and it is the interface for all metadata changes. In a distributed cluster, it runs on the Namenode. HRegionServer is the RegionServer implementation. It is responsible for serving and managing regions. In a distributed cluster, a RegionServer runs on a DataNode. HBase provides two different BlockCache implementations: the default on-heap LruBlockCache and the BucketCache, which is (usually) off-heap. The Write Ahead Log (WAL) records all changes to data in HBase, to file-based storage. if a RegionServer crashes or becomes unavailable before the MemStore is flushed, the WAL ensures that the changes to the data can be replayed. With a single WAL per RegionServer, the RegionServer must write to the WAL serially, because HDFS files must be sequential. This causes the WAL to be a performance bottleneck. When a region is edited, the edits in the WAL file which belong to that region need to be replayed. Therefore, edits in the WAL file must be grouped by region so that particular sets can be replayed to regenerate the data in a particular region. The process of grouping the WAL edits by region is called log splitting. WAL can be disabled to improve performance bottleneck. This is done by calling the Hbase client field Mutation.writeToWAL(false). The manual region splitting is done we have an unexpected hotspot in your table because of many clients querying the same table. A Habse Store hosts a MemStore and 0 or more StoreFiles (HFiles). A Store corresponds to a column family for a table for a given region. The HFile in Habse which stores the Actual data(not metadata) is designed after the SSTable file of BigTable. Tables in HBase are initially created with one region by default. Then for bulk imports, all clients will write to the same region until it is large enough to split and become distributed across the cluster. So empty regions are created to make this process faster. Hotspotting is asituation when a large amount of client traffic is directed at one node, or only a few nodes, of a cluster. This traffic may represent reads, writes, or other operations. This traffic overwhelms the single machine responsible for hosting that region, causing performance degradation and potentially leading to region unavailability. Hotspotting can be avoided or minimized by distributing the rowkeys across multiple regions. The different techniques to do this is salting and Hashing. In Hbase values are always freighted with their coordinates; as a cell value passes through the system, it’ll be accompanied by its row, column name, and timestamp. If the rows and column names are large, especially compared to the size of the cell value, then indices that are kept on HBase storefiles (StoreFile (HFile)) to facilitate random access may end up occupying large chunks of the HBase allotted RAM than the data itself because the cell value coordinates are large. Rowkeys are scoped to ColumnFamilies. The same rowkey could exist in each ColumnFamily that exists in a table without collision. The Hbase:meta tables stores details of region in the system in the following format. info:regioninfo (serialized HRegionInfo instance for this region) info:server (server:port of the RegionServer containing this region) info:serverstartcode (start-time of the RegionServer process containing this region) A Namespace is a logical grouping of tables . It is similar to a database object in a Relational database system. The complete list of columns in a column family can be obtained only querying all the rows for that column family. The records fetched form Hbase are always sorted in the order of rowkey-> column Family-> column qualifier-> tiestamp. Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong. Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-) Print Add Notes Bookmark this page
[ { "code": null, "e": 2471, "s": 2037, "text": "Dear readers, these HBase Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of HBase. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer:" }, { "code": null, "e": 2546, "s": 2471, "text": "There are 5 atomic commands which carry out different operations by Hbase." }, { "code": null, "e": 2584, "s": 2546, "text": "Get, Put, Delete, Scan and Increment." }, { "code": null, "e": 2662, "s": 2584, "text": "A connection to Hbase is established through Hbase Shell which is a Java API." }, { "code": null, "e": 2757, "s": 2662, "text": "The Master server assigns regions to region servers and handles load balancing in the cluster." }, { "code": null, "e": 2919, "s": 2757, "text": "The zookeeper maintains configuration information, provides distributed synchronization, and also maintains the communication between clients and region servers." }, { "code": null, "e": 3073, "s": 2919, "text": "In Hbase a table is disabled to allow it to be modified or change its settings. .When a table is disabled it cannot be accessed through the scan command." }, { "code": null, "e": 3106, "s": 3073, "text": "Hbase > is_disabled “table name”" }, { "code": null, "e": 3132, "s": 3106, "text": "hbase > disable_all 'p.*'" }, { "code": null, "e": 3198, "s": 3132, "text": "The command will disable all the table starting with the letter p" }, { "code": null, "e": 3284, "s": 3198, "text": "Filters are used to get specific data form a Hbase table rather than all the records." }, { "code": null, "e": 3317, "s": 3284, "text": "They are of the following types." }, { "code": null, "e": 3337, "s": 3317, "text": "Column Value Filter" }, { "code": null, "e": 3362, "s": 3337, "text": "Column Value comparators" }, { "code": null, "e": 3389, "s": 3362, "text": "KeyValue Metadata filters." }, { "code": null, "e": 3405, "s": 3389, "text": "RowKey filters." }, { "code": null, "e": 3470, "s": 3405, "text": "Hbase does not have in-built authentication/permission mechanism" }, { "code": null, "e": 3535, "s": 3470, "text": "Hbase does not have in-built authentication/permission mechanism" }, { "code": null, "e": 3627, "s": 3535, "text": "The indexes can be created only on a key column, but in RDBMS it can be done in any column." }, { "code": null, "e": 3719, "s": 3627, "text": "The indexes can be created only on a key column, but in RDBMS it can be done in any column." }, { "code": null, "e": 3778, "s": 3719, "text": "With one HMaster node there is a single point of failure." }, { "code": null, "e": 3837, "s": 3778, "text": "With one HMaster node there is a single point of failure." }, { "code": null, "e": 4081, "s": 3837, "text": "The catalog tables in Hbase maintain the metadata information. They are named as −ROOT− and .META. The −ROOT− table stores information about location of .META> table and the .META> table holds information about all regions and their locations." }, { "code": null, "e": 4255, "s": 4081, "text": "Hbase runs on top of Hadoop which is a distributed system. Haddop can only scale uo as and when required by adding more machines on the fly. So Hbase is a scale out process." }, { "code": null, "e": 4473, "s": 4255, "text": "In Hbase the client does not write directly into the HFile. The client first writes to WAL(Write Access Log), which then is accessed by Memstore. The Memstore Flushes the data into permanent memory from time to time." }, { "code": null, "e": 4676, "s": 4473, "text": "As more and more data is written to Hbase, many HFiles get created. Compaction is the process of merging these HFiles to one file and after the merged file is created successfully, discard the old file." }, { "code": null, "e": 4900, "s": 4676, "text": "There are two types of compaction. Major and Minor compaction. In minor compaction, the adjacent small HFiles are merged to create a single HFile without removing the deleted HFiles. Files to be merged are chosen randomly." }, { "code": null, "e": 5064, "s": 4900, "text": "In Major compaction, all the HFiles of a column are emerged and a single HFiles is created. The delted HFiles are discarded and it is generally triggered manually." }, { "code": null, "e": 5189, "s": 5064, "text": "The Delete column command deletes all versions of a column but the delete family deletes all columns of a particular family." }, { "code": null, "e": 5314, "s": 5189, "text": "A cell in Hbase is the smallest unit of a Hbase table which holds a piece of data in the form of a tuple{row,column,version}" }, { "code": null, "e": 5498, "s": 5314, "text": "This class is used to store information about a column family such as the number of versions, compression settings, etc. It is used as input when creating a table or adding a column." }, { "code": null, "e": 5720, "s": 5498, "text": "The lower bound of versions indicates the minimum number of versions to be stored in Hbase for a column. For example If the value is set to 3 then three latest version wil be maintained and the older ones will be removed." }, { "code": null, "e": 5902, "s": 5720, "text": "TTL is a data retention technique using which the version of a cell can be preserved till a specific time period.Once that timestamp is reached the specific version will be removed." }, { "code": null, "e": 6036, "s": 5902, "text": "Hbase does not support table jons. But using a mapreduce job we can specify join queries to retrieve data from multiple Hbase tables." }, { "code": null, "e": 6110, "s": 6036, "text": "Each row in Hbase is identified by a unique byte of array called row key." }, { "code": null, "e": 6157, "s": 6110, "text": "The data in Hbase can be accessed in two ways." }, { "code": null, "e": 6220, "s": 6157, "text": "Using the rowkey and table scan for a range of row key values." }, { "code": null, "e": 6283, "s": 6220, "text": "Using the rowkey and table scan for a range of row key values." }, { "code": null, "e": 6318, "s": 6283, "text": "Using mapreduce in a batch manner." }, { "code": null, "e": 6353, "s": 6318, "text": "Using mapreduce in a batch manner." }, { "code": null, "e": 6402, "s": 6353, "text": "They are − (i) Short and Wide (ii) Tall and Thin" }, { "code": null, "e": 6462, "s": 6402, "text": "The short and wide table design is considered when there is" }, { "code": null, "e": 6497, "s": 6462, "text": "There is a small number of columns" }, { "code": null, "e": 6532, "s": 6497, "text": "There is a small number of columns" }, { "code": null, "e": 6564, "s": 6532, "text": "There is a large number of rows" }, { "code": null, "e": 6596, "s": 6564, "text": "There is a large number of rows" }, { "code": null, "e": 6656, "s": 6596, "text": " The tall and thin table design is considered when there is" }, { "code": null, "e": 6691, "s": 6656, "text": "There is a large number of columns" }, { "code": null, "e": 6726, "s": 6691, "text": "There is a large number of columns" }, { "code": null, "e": 6758, "s": 6726, "text": "There is a small number of rows" }, { "code": null, "e": 6790, "s": 6758, "text": "There is a small number of rows" }, { "code": null, "e": 6854, "s": 6790, "text": "hbase > alter 'tablename', {NAME => 'ColFamily', VERSIONS => 4}" }, { "code": null, "e": 6923, "s": 6854, "text": "hbase > alter 'tablename', {NAME => 'colFamily', METHOD => 'delete'}" }, { "code": null, "e": 6978, "s": 6923, "text": "This command deletes the column family form the table." }, { "code": null, "e": 7107, "s": 6978, "text": " \nHbase > disable ‘tablename’\nHbase > alter ‘tablename’ {NAME => ‘oldcolfamily’,NAME=>’newcolfamily’}\nHabse > enable ‘tablename’" }, { "code": null, "e": 7183, "s": 7107, "text": " \nscan 'tablename', {LIMIT=>10,\nSTARTROW=>\"start_row\",\nSTOPROW=>\"stop_row\"}" }, { "code": null, "e": 7209, "s": 7183, "text": "major_compact 'tablename'" }, { "code": null, "e": 7246, "s": 7209, "text": "Run a major compaction on the table." }, { "code": null, "e": 7304, "s": 7246, "text": "There are two main steps to do a data bulk load in Hbase." }, { "code": null, "e": 7475, "s": 7304, "text": "Generate Hbase data file(StoreFile) using a custom mapreduce job) from the data source. The StoreFile is created in Hbase internal format which can be efficiently loaded." }, { "code": null, "e": 7646, "s": 7475, "text": "Generate Hbase data file(StoreFile) using a custom mapreduce job) from the data source. The StoreFile is created in Hbase internal format which can be efficiently loaded." }, { "code": null, "e": 7801, "s": 7646, "text": "The prepared file is imported using another tool like comletebulkload to import data into a running cluster. Each file gets loaded to one specific region." }, { "code": null, "e": 7956, "s": 7801, "text": "The prepared file is imported using another tool like comletebulkload to import data into a running cluster. Each file gets loaded to one specific region." }, { "code": null, "e": 8222, "s": 7956, "text": "Hbase uses a feature called region replication. In this feature for each region of a table, there will be multiple replicas that are opened in different RegionServers. The Load Balancer ensures that the region replicas are not co-hosted in the same region servers." }, { "code": null, "e": 8425, "s": 8222, "text": "The Hmaster is the Master server responsible for monitoring all RegionServer instances in the cluster and it is the interface for all metadata changes. In a distributed cluster, it runs on the Namenode." }, { "code": null, "e": 8588, "s": 8425, "text": "HRegionServer is the RegionServer implementation. It is responsible for serving and managing regions. In a distributed cluster, a RegionServer runs on a DataNode." }, { "code": null, "e": 8729, "s": 8588, "text": "HBase provides two different BlockCache implementations: the default on-heap LruBlockCache and the BucketCache, which is (usually) off-heap." }, { "code": null, "e": 8959, "s": 8729, "text": "The Write Ahead Log (WAL) records all changes to data in HBase, to file-based storage. if a RegionServer crashes or becomes unavailable before the MemStore is flushed, the WAL ensures that the changes to the data can be replayed." }, { "code": null, "e": 9135, "s": 8959, "text": "With a single WAL per RegionServer, the RegionServer must write to the WAL serially, because HDFS files must be sequential. This causes the WAL to be a performance bottleneck." }, { "code": null, "e": 9454, "s": 9135, "text": "When a region is edited, the edits in the WAL file which belong to that region need to be replayed. Therefore, edits in the WAL file must be grouped by region so that particular sets can be replayed to regenerate the data in a particular region. The process of grouping the WAL edits by region is called log splitting." }, { "code": null, "e": 9509, "s": 9454, "text": "WAL can be disabled to improve performance bottleneck." }, { "code": null, "e": 9584, "s": 9509, "text": "This is done by calling the Hbase client field Mutation.writeToWAL(false)." }, { "code": null, "e": 9713, "s": 9584, "text": "The manual region splitting is done we have an unexpected hotspot in your table because of many clients querying the same table." }, { "code": null, "e": 9850, "s": 9713, "text": "A Habse Store hosts a MemStore and 0 or more StoreFiles (HFiles). A Store corresponds to a column family for a table for a given region." }, { "code": null, "e": 9960, "s": 9850, "text": "The HFile in Habse which stores the Actual data(not metadata) is designed after the SSTable file of BigTable." }, { "code": null, "e": 10226, "s": 9960, "text": "Tables in HBase are initially created with one region by default. Then for bulk imports, all clients will write to the same region until it is large enough to split and become distributed across the cluster. So empty regions are created to make this process faster." }, { "code": null, "e": 10575, "s": 10226, "text": "Hotspotting is asituation when a large amount of client traffic is directed at one node, or only a few nodes, of a cluster. This traffic may represent reads, writes, or other operations. This traffic overwhelms the single machine responsible for hosting that region, causing performance degradation and potentially leading to region unavailability." }, { "code": null, "e": 10728, "s": 10575, "text": "Hotspotting can be avoided or minimized by distributing the rowkeys across multiple regions. The different techniques to do this is salting and Hashing." }, { "code": null, "e": 11207, "s": 10728, "text": "In Hbase values are always freighted with their coordinates; as a cell value passes through the system, it’ll be accompanied by its row, column name, and timestamp. If the rows and column names are large, especially compared to the size of the cell value, then indices that are kept on HBase storefiles (StoreFile (HFile)) to facilitate random access may end up occupying large chunks of the HBase allotted RAM than the data itself because the cell value coordinates are large." }, { "code": null, "e": 11336, "s": 11207, "text": "Rowkeys are scoped to ColumnFamilies. The same rowkey could exist in each ColumnFamily that exists in a table without collision." }, { "code": null, "e": 11422, "s": 11336, "text": "The Hbase:meta tables stores details of region in the system in the following format." }, { "code": null, "e": 11488, "s": 11422, "text": "info:regioninfo (serialized HRegionInfo instance for this region)" }, { "code": null, "e": 11557, "s": 11488, "text": "info:server (server:port of the RegionServer containing this region)" }, { "code": null, "e": 11642, "s": 11557, "text": "info:serverstartcode (start-time of the RegionServer process containing this region)" }, { "code": null, "e": 11756, "s": 11642, "text": "A Namespace is a logical grouping of tables . It is similar to a database object in a Relational database system." }, { "code": null, "e": 11871, "s": 11756, "text": "The complete list of columns in a column family can be obtained only querying all the rows for that column family." }, { "code": null, "e": 11990, "s": 11871, "text": "The records fetched form Hbase are always sorted in the order of rowkey-> column Family-> column qualifier-> tiestamp." }, { "code": null, "e": 12277, "s": 11990, "text": "Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong." }, { "code": null, "e": 12607, "s": 12277, "text": "Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)" }, { "code": null, "e": 12614, "s": 12607, "text": " Print" }, { "code": null, "e": 12625, "s": 12614, "text": " Add Notes" } ]
Find missing elements in List in Python
If we have a list containing numbers, we can check if the numbers are contiguous or not and also find which numbers are missing from a range of numbers considering the highest number as the final value. We can design a for loop to check for absence of values in a range using the not in operator. Then capture all these values by adding them to a new list which becomes the result set. Live Demo listA = [1,5,6, 7,11,14] # Original list print("Given list : ",listA) # using range and max res = [ele for ele in range(max(listA) + 1) if ele not in listA] # Result print("Missing elements from the list : \n" ,res) Running the above code gives us the following result − Given list : [1, 5, 6, 7, 11, 14] Missing elements from the list : [0, 2, 3, 4, 8, 9, 10, 12, 13] We apply the set function to hold all the unique values for a given range and then subtracting the given list from it. So this gives the result set containing the missing values from the contiguous numbers. Live Demo listA = [1,5,6, 7,11,14] # printing original list print("Given list : ",listA) # using set res = list(set(range(max(listA) + 1)) - set(listA)) # Result print("Missing elements from the list : \n" ,res) Running the above code gives us the following result − Given list : [1, 5, 6, 7, 11, 14] Missing elements from the list : [0, 2, 3, 4, 8, 9, 10, 12, 13]
[ { "code": null, "e": 1265, "s": 1062, "text": "If we have a list containing numbers, we can check if the numbers are contiguous or not and also find which numbers are missing from a range of numbers considering the highest number as the final value." }, { "code": null, "e": 1448, "s": 1265, "text": "We can design a for loop to check for absence of values in a range using the not in operator. Then capture all these values by adding them to a new list which becomes the result set." }, { "code": null, "e": 1459, "s": 1448, "text": " Live Demo" }, { "code": null, "e": 1678, "s": 1459, "text": "listA = [1,5,6, 7,11,14]\n\n# Original list\nprint(\"Given list : \",listA)\n\n# using range and max\nres = [ele for ele in range(max(listA) + 1) if ele not in listA]\n\n# Result\nprint(\"Missing elements from the list : \\n\" ,res)" }, { "code": null, "e": 1733, "s": 1678, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1831, "s": 1733, "text": "Given list : [1, 5, 6, 7, 11, 14]\nMissing elements from the list :\n[0, 2, 3, 4, 8, 9, 10, 12, 13]" }, { "code": null, "e": 2038, "s": 1831, "text": "We apply the set function to hold all the unique values for a given range and then subtracting the given list from it. So this gives the result set containing the missing values from the contiguous numbers." }, { "code": null, "e": 2049, "s": 2038, "text": " Live Demo" }, { "code": null, "e": 2254, "s": 2049, "text": "listA = [1,5,6, 7,11,14]\n\n# printing original list\nprint(\"Given list : \",listA)\n\n# using set\nres = list(set(range(max(listA) + 1)) - set(listA))\n\n# Result\nprint(\"Missing elements from the list : \\n\" ,res)" }, { "code": null, "e": 2309, "s": 2254, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2407, "s": 2309, "text": "Given list : [1, 5, 6, 7, 11, 14]\nMissing elements from the list :\n[0, 2, 3, 4, 8, 9, 10, 12, 13]" } ]
Maven - Project Templates
Maven provides users, a very large list of different types of project templates (614 in numbers) using the concept of Archetype. Maven helps users to quickly start a new java project using the following command. mvn archetype:generate Archetype is a Maven plugin whose task is to create a project structure as per its template. We are going to use quickstart archetype plugin to create a simple java application here. Let's open the command console, go to the C:\ > MVN directory and execute the following mvn command. C:\MVN>mvn archetype:generate Maven will start processing and will ask to choose the required archetype. C:\MVN>mvn archetype:generate [INFO] Scanning for projects... [INFO] [INFO] ------------------< org.apache.maven:standalone-pom >------------------- [INFO] Building Maven Stub Project (No POM) 1 [INFO] --------------------------------[ pom ]--------------------------------- [INFO] [INFO] >>> maven-archetype-plugin:3.2.0:generate (default-cli) > generate-sources @ standalone-pom >>> [INFO] [INFO] <<< maven-archetype-plugin:3.2.0:generate (default-cli) < generate-sources @ standalone-pom <<< [INFO] [INFO] [INFO] --- maven-archetype-plugin:3.2.0:generate (default-cli) @ standalone-pom --- [INFO] Generating project in Interactive mode [INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0) Choose archetype: 1: remote -> am.ik.archetype:elm-spring-boot-blank-archetype (Blank multi project for Spring Boot + Elm) 2: remote -> am.ik.archetype:graalvm-blank-archetype (Blank project for GraalVM) ... 3021: remote -> za.co.absa.hyperdrive:component-archetype_2.12 (-) Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 1843: Press Enter to choose to default option (1843: maven-archetype-quickstart) Maven will ask for particular version of archetype. Choose org.apache.maven.archetypes:maven-archetype-quickstart version: 1: 1.0-alpha-1 2: 1.0-alpha-2 3: 1.0-alpha-3 4: 1.0-alpha-4 5: 1.0 6: 1.1 7: 1.3 8: 1.4 Choose a number: 8: Press Enter to choose to default option (8: maven-archetype-quickstart:1.4) Maven will ask for the project detail. Enter project detail as asked. Press Enter if the default value is provided. You can override them by entering your own value. Define value for property 'groupId': : com.companyname.insurance Define value for property 'artifactId': : health Define value for property 'version': 1.0-SNAPSHOT: Define value for property 'package': com.companyname.insurance: Maven will ask for the project detail confirmation. Press enter or press Y. Confirm properties configuration: groupId: com.companyname.insurance artifactId: health version: 1.0-SNAPSHOT package: com.companyname.insurance Y: Now Maven will start creating the project structure and will display the following − [INFO] ---------------------------------------------------------------------------- [INFO] Using following parameters for creating project from Archetype: maven-archetype-quickstart:1.4 [INFO] ---------------------------------------------------------------------------- [INFO] Parameter: groupId, Value: com.companyname.insurance [INFO] Parameter: artifactId, Value: health [INFO] Parameter: version, Value: 1.0-SNAPSHOT [INFO] Parameter: package, Value: com.companyname.insurance [INFO] Parameter: packageInPathFormat, Value: com/companyname/insurance [INFO] Parameter: package, Value: com.companyname.insurance [INFO] Parameter: groupId, Value: com.companyname.insurance [INFO] Parameter: artifactId, Value: health [INFO] Parameter: version, Value: 1.0-SNAPSHOT [INFO] Project created from Archetype in dir: C:\MVN\health [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 04:44 min [INFO] Finished at: 2021-12-13T18:52:59+05:30 [INFO] ------------------------------------------------------------------------ Now go to C:\ > MVN directory. You'll see a java application project created, named health, which was given as artifactId at the time of project creation. Maven will create a standard directory layout for the project as shown below − Maven generates a POM.xml file for the project as listed below − <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.insurance</groupId> <artifactId>health</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <name>health</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> </project> Maven generates sample java source file, App.java for the project as listed below − Location: C:\ > MVN > health > src > main > java > com > companyname > insurance > App.java. package com.companyname.insurance; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); } } Maven generates sample java source test file, AppTest.java for the project as listed below − Location: C:\ > MVN > health > src > test > java > com > companyname > insurance > AppTest.java. package com.companyname.insurance; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } } Now you can see the power of Maven. You can create any kind of project using single command in maven and can kick-start your development. maven-archetype-archetype An archetype, which contains a sample archetype. maven-archetype-j2ee-simple An archetype, which contains a simplified sample J2EE application. maven-archetype-mojo An archetype, which contains a sample a sample Maven plugin. maven-archetype-plugin An archetype, which contains a sample Maven plugin. maven-archetype-plugin-site An archetype, which contains a sample Maven plugin site. maven-archetype-portlet An archetype, which contains a sample JSR-268 Portlet. maven-archetype-quickstart An archetype, which contains a sample Maven project. maven-archetype-simple An archetype, which contains a simple Maven project. maven-archetype-site An archetype, which contains a sample Maven site to demonstrates some of the supported document types like APT, XDoc, and FML and demonstrates how to i18n your site. maven-archetype-site-simple An archetype, which contains a sample Maven site. maven-archetype-webapp An archetype, which contains a sample Maven Webapp project. 34 Lectures 4 hours Karthikeya T 14 Lectures 1.5 hours Quaatso Learning Print Add Notes Bookmark this page
[ { "code": null, "e": 2272, "s": 2060, "text": "Maven provides users, a very large list of different types of project templates (614 in numbers) using the concept of Archetype. Maven helps users to quickly start a new java project using the following command." }, { "code": null, "e": 2296, "s": 2272, "text": "mvn archetype:generate\n" }, { "code": null, "e": 2479, "s": 2296, "text": "Archetype is a Maven plugin whose task is to create a project structure as per its template. We are going to use quickstart archetype plugin to create a simple java application here." }, { "code": null, "e": 2580, "s": 2479, "text": "Let's open the command console, go to the C:\\ > MVN directory and execute the following mvn command." }, { "code": null, "e": 2612, "s": 2580, "text": "C:\\MVN>mvn archetype:generate \n" }, { "code": null, "e": 2687, "s": 2612, "text": "Maven will start processing and will ask to choose the required archetype." }, { "code": null, "e": 3821, "s": 2687, "text": "\nC:\\MVN>mvn archetype:generate\n[INFO] Scanning for projects...\n[INFO]\n[INFO] ------------------< org.apache.maven:standalone-pom >-------------------\n[INFO] Building Maven Stub Project (No POM) 1\n[INFO] --------------------------------[ pom ]---------------------------------\n[INFO]\n[INFO] >>> maven-archetype-plugin:3.2.0:generate (default-cli) > generate-sources @ standalone-pom >>>\n[INFO]\n[INFO] <<< maven-archetype-plugin:3.2.0:generate (default-cli) < generate-sources @ standalone-pom <<<\n[INFO]\n[INFO]\n[INFO] --- maven-archetype-plugin:3.2.0:generate (default-cli) @ standalone-pom ---\n[INFO] Generating project in Interactive mode\n[INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0)\nChoose archetype:\n1: remote -> am.ik.archetype:elm-spring-boot-blank-archetype (Blank multi project for Spring Boot + Elm)\n2: remote -> am.ik.archetype:graalvm-blank-archetype (Blank project for GraalVM)\n...\n3021: remote -> za.co.absa.hyperdrive:component-archetype_2.12 (-)\nChoose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 1843:\n" }, { "code": null, "e": 3896, "s": 3821, "text": "Press Enter to choose to default option (1843: maven-archetype-quickstart)" }, { "code": null, "e": 3948, "s": 3896, "text": "Maven will ask for particular version of archetype." }, { "code": null, "e": 4128, "s": 3948, "text": "Choose org.apache.maven.archetypes:maven-archetype-quickstart version:\n1: 1.0-alpha-1\n2: 1.0-alpha-2\n3: 1.0-alpha-3\n4: 1.0-alpha-4\n5: 1.0\n6: 1.1\n7: 1.3\n8: 1.4\nChoose a number: 8:\n" }, { "code": null, "e": 4204, "s": 4128, "text": "Press Enter to choose to default option (8: maven-archetype-quickstart:1.4)" }, { "code": null, "e": 4370, "s": 4204, "text": "Maven will ask for the project detail. Enter project detail as asked. Press Enter if the default value is provided. You can override them by entering your own value." }, { "code": null, "e": 4599, "s": 4370, "text": "Define value for property 'groupId': : com.companyname.insurance\nDefine value for property 'artifactId': : health\nDefine value for property 'version': 1.0-SNAPSHOT:\nDefine value for property 'package': com.companyname.insurance:" }, { "code": null, "e": 4675, "s": 4599, "text": "Maven will ask for the project detail confirmation. Press enter or press Y." }, { "code": null, "e": 4823, "s": 4675, "text": "Confirm properties configuration:\ngroupId: com.companyname.insurance\nartifactId: health\nversion: 1.0-SNAPSHOT\npackage: com.companyname.insurance\nY:" }, { "code": null, "e": 4908, "s": 4823, "text": "Now Maven will start creating the project structure and will display the following −" }, { "code": null, "e": 6070, "s": 4908, "text": "[INFO] ----------------------------------------------------------------------------\n[INFO] Using following parameters for creating project from Archetype: maven-archetype-quickstart:1.4\n[INFO] ----------------------------------------------------------------------------\n[INFO] Parameter: groupId, Value: com.companyname.insurance\n[INFO] Parameter: artifactId, Value: health\n[INFO] Parameter: version, Value: 1.0-SNAPSHOT\n[INFO] Parameter: package, Value: com.companyname.insurance\n[INFO] Parameter: packageInPathFormat, Value: com/companyname/insurance\n[INFO] Parameter: package, Value: com.companyname.insurance\n[INFO] Parameter: groupId, Value: com.companyname.insurance\n[INFO] Parameter: artifactId, Value: health\n[INFO] Parameter: version, Value: 1.0-SNAPSHOT\n[INFO] Project created from Archetype in dir: C:\\MVN\\health\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 04:44 min\n[INFO] Finished at: 2021-12-13T18:52:59+05:30\n[INFO] ------------------------------------------------------------------------\n" }, { "code": null, "e": 6304, "s": 6070, "text": "Now go to C:\\ > MVN directory. You'll see a java application project created, named health, which was given as artifactId at the time of project creation. Maven will create a standard directory layout for the project as shown below −" }, { "code": null, "e": 6369, "s": 6304, "text": "Maven generates a POM.xml file for the project as listed below −" }, { "code": null, "e": 7165, "s": 6369, "text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.insurance</groupId>\n <artifactId>health</artifactId>\n <version>1.0-SNAPSHOT</version>\n <packaging>jar</packaging>\n <name>health</name>\n <url>http://maven.apache.org</url>\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n </properties>\n <dependencies>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>3.8.1</version>\n <scope>test</scope>\n </dependency>\n </dependencies>\n</project>" }, { "code": null, "e": 7249, "s": 7165, "text": "Maven generates sample java source file, App.java for the project as listed below −" }, { "code": null, "e": 7342, "s": 7249, "text": "Location: C:\\ > MVN > health > src > main > java > com > companyname > insurance > App.java." }, { "code": null, "e": 7518, "s": 7342, "text": "package com.companyname.insurance;\n\n/**\n* Hello world!\n*\n*/\npublic class App {\n public static void main( String[] args ) {\n System.out.println( \"Hello World!\" );\n }\n}" }, { "code": null, "e": 7611, "s": 7518, "text": "Maven generates sample java source test file, AppTest.java for the project as listed below −" }, { "code": null, "e": 7708, "s": 7611, "text": "Location: C:\\ > MVN > health > src > test > java > com > companyname > insurance > AppTest.java." }, { "code": null, "e": 8318, "s": 7708, "text": "package com.companyname.insurance;\n\nimport junit.framework.Test;\nimport junit.framework.TestCase;\nimport junit.framework.TestSuite;\n\n/**\n * Unit test for simple App.\n*/\npublic class AppTest extends TestCase {\n /**\n * Create the test case\n *\n * @param testName name of the test case\n */\n public AppTest( String testName ) {\n super( testName );\n }\n /**\n * @return the suite of tests being tested\n */\n public static Test suite() {\n return new TestSuite( AppTest.class );\n }\n /**\n * Rigourous Test :-)\n */\n public void testApp() {\n assertTrue( true );\n }\n}" }, { "code": null, "e": 8456, "s": 8318, "text": "Now you can see the power of Maven. You can create any kind of project using single command in maven and can kick-start your development." }, { "code": null, "e": 8482, "s": 8456, "text": "maven-archetype-archetype" }, { "code": null, "e": 8531, "s": 8482, "text": "An archetype, which contains a sample archetype." }, { "code": null, "e": 8559, "s": 8531, "text": "maven-archetype-j2ee-simple" }, { "code": null, "e": 8626, "s": 8559, "text": "An archetype, which contains a simplified sample J2EE application." }, { "code": null, "e": 8647, "s": 8626, "text": "maven-archetype-mojo" }, { "code": null, "e": 8708, "s": 8647, "text": "An archetype, which contains a sample a sample Maven plugin." }, { "code": null, "e": 8731, "s": 8708, "text": "maven-archetype-plugin" }, { "code": null, "e": 8783, "s": 8731, "text": "An archetype, which contains a sample Maven plugin." }, { "code": null, "e": 8811, "s": 8783, "text": "maven-archetype-plugin-site" }, { "code": null, "e": 8868, "s": 8811, "text": "An archetype, which contains a sample Maven plugin site." }, { "code": null, "e": 8892, "s": 8868, "text": "maven-archetype-portlet" }, { "code": null, "e": 8947, "s": 8892, "text": "An archetype, which contains a sample JSR-268 Portlet." }, { "code": null, "e": 8974, "s": 8947, "text": "maven-archetype-quickstart" }, { "code": null, "e": 9027, "s": 8974, "text": "An archetype, which contains a sample Maven project." }, { "code": null, "e": 9050, "s": 9027, "text": "maven-archetype-simple" }, { "code": null, "e": 9103, "s": 9050, "text": "An archetype, which contains a simple Maven project." }, { "code": null, "e": 9124, "s": 9103, "text": "maven-archetype-site" }, { "code": null, "e": 9290, "s": 9124, "text": "An archetype, which contains a sample Maven site to demonstrates some of the supported document types like APT, XDoc, and FML and demonstrates how to i18n your site." }, { "code": null, "e": 9318, "s": 9290, "text": "maven-archetype-site-simple" }, { "code": null, "e": 9368, "s": 9318, "text": "An archetype, which contains a sample Maven site." }, { "code": null, "e": 9391, "s": 9368, "text": "maven-archetype-webapp" }, { "code": null, "e": 9451, "s": 9391, "text": "An archetype, which contains a sample Maven Webapp project." }, { "code": null, "e": 9484, "s": 9451, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 9498, "s": 9484, "text": " Karthikeya T" }, { "code": null, "e": 9533, "s": 9498, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9551, "s": 9533, "text": " Quaatso Learning" }, { "code": null, "e": 9558, "s": 9551, "text": " Print" }, { "code": null, "e": 9569, "s": 9558, "text": " Add Notes" } ]
MongoDB $regex operator i or I for case insensitive search
For this, you need to use case insensitive (i). Let us create a collection with documents − > db.demo759.insertOne({SubjectName:"MySQL"}); { "acknowledged" : true, "insertedId" : ObjectId("5eb02ba95637cd592b2a4ae7") } > db.demo759.insertOne({SubjectName:"MongoDB"}); { "acknowledged" : true, "insertedId" : ObjectId("5eb02baa5637cd592b2a4ae8") } > db.demo759.insertOne({SubjectName:"mongodb"}); { "acknowledged" : true, "insertedId" : ObjectId("5eb02baf5637cd592b2a4ae9") } > db.demo759.insertOne({SubjectName:"MONGODB"}); { "acknowledged" : true, "insertedId" : ObjectId("5eb02bb85637cd592b2a4aea") } Display all documents from a collection with the help of find() method − > db.demo759.find(); This will produce the following output − { "_id" : ObjectId("5eb02ba95637cd592b2a4ae7"), "SubjectName" : "MySQL" } { "_id" : ObjectId("5eb02baa5637cd592b2a4ae8"), "SubjectName" : "MongoDB" } { "_id" : ObjectId("5eb02baf5637cd592b2a4ae9"), "SubjectName" : "mongodb" } { "_id" : ObjectId("5eb02bb85637cd592b2a4aea"), "SubjectName" : "MONGODB" } Following is the query implementing MongoDB regex operator − > db.demo759.find({"SubjectName":{$regex:/mongodb/i}}); This will produce the following output − { "_id" : ObjectId("5eb02baa5637cd592b2a4ae8"), "SubjectName" : "MongoDB" } { "_id" : ObjectId("5eb02baf5637cd592b2a4ae9"), "SubjectName" : "mongodb" } { "_id" : ObjectId("5eb02bb85637cd592b2a4aea"), "SubjectName" : "MONGODB" }
[ { "code": null, "e": 1154, "s": 1062, "text": "For this, you need to use case insensitive (i). Let us create a collection with documents −" }, { "code": null, "e": 1688, "s": 1154, "text": "> db.demo759.insertOne({SubjectName:\"MySQL\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5eb02ba95637cd592b2a4ae7\")\n}\n> db.demo759.insertOne({SubjectName:\"MongoDB\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5eb02baa5637cd592b2a4ae8\")\n}\n> db.demo759.insertOne({SubjectName:\"mongodb\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5eb02baf5637cd592b2a4ae9\")\n}\n> db.demo759.insertOne({SubjectName:\"MONGODB\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5eb02bb85637cd592b2a4aea\")\n}" }, { "code": null, "e": 1761, "s": 1688, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1782, "s": 1761, "text": "> db.demo759.find();" }, { "code": null, "e": 1823, "s": 1782, "text": "This will produce the following output −" }, { "code": null, "e": 2125, "s": 1823, "text": "{ \"_id\" : ObjectId(\"5eb02ba95637cd592b2a4ae7\"), \"SubjectName\" : \"MySQL\" }\n{ \"_id\" : ObjectId(\"5eb02baa5637cd592b2a4ae8\"), \"SubjectName\" : \"MongoDB\" }\n{ \"_id\" : ObjectId(\"5eb02baf5637cd592b2a4ae9\"), \"SubjectName\" : \"mongodb\" }\n{ \"_id\" : ObjectId(\"5eb02bb85637cd592b2a4aea\"), \"SubjectName\" : \"MONGODB\" }" }, { "code": null, "e": 2186, "s": 2125, "text": "Following is the query implementing MongoDB regex operator −" }, { "code": null, "e": 2242, "s": 2186, "text": "> db.demo759.find({\"SubjectName\":{$regex:/mongodb/i}});" }, { "code": null, "e": 2283, "s": 2242, "text": "This will produce the following output −" }, { "code": null, "e": 2511, "s": 2283, "text": "{ \"_id\" : ObjectId(\"5eb02baa5637cd592b2a4ae8\"), \"SubjectName\" : \"MongoDB\" }\n{ \"_id\" : ObjectId(\"5eb02baf5637cd592b2a4ae9\"), \"SubjectName\" : \"mongodb\" }\n{ \"_id\" : ObjectId(\"5eb02bb85637cd592b2a4aea\"), \"SubjectName\" : \"MONGODB\" }" } ]
Build with PyCaret: Deploy on Google Cloud Platform | by MA Raza, Ph.D. | Towards Data Science
In this story, I have developed a working tutorial on deploying a model trained with pycaret on Google Cloud Platform. This tutorial can be used to deploy any machine learning model(s) with slight modifications. We will learn how to deploy models trained with pycaret to Google Cloud Platform. As you might know, pycaret already has support to deploy the trained models on AWS but not with GCP or Azure at the moment. I followed the similar code-practices as used in the library for deploying models on AWS and added essential utilities for GCP deploying. PyCaret is an open source, low-code machine learning library in Python that allows you to go from preparing your data to deploying your model within seconds in your choice of notebook environment [source]. A PyCaret is an autoML framework for citizen data scientists term used in its official documentation. PyCaret is relatively a new library released a few months ago for public use and still under active development. After going through some source code, I realized the current public release lacks support for the deployment of trained/finalized models to Google Cloud Platform. Although, It has support only for deploying on Amazon web services. Keeping in a view wide use of GCP as cloud service, I have given a try to add a tutorial on deploying the trained model on google cloud using PyCaret’s way. For this tutorial, we will use the Regression Tutorial (REG101) — Level Beginner for model training. !pip install pycaret We need to mount the google drive to read/write the data in colab environment. Below is the simplest way to mount it. You will be asked to enter the token generated by your access procedure. Here is the link to the article about mounting gdrive We will save models locally on Google drive for this tutorial. from google.colab import drivedrive.mount('/content/drive')Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True). Let us create a directory to save models locally. # Create directory on google drive to save models locally. You can use temp paths.import osmodel_dir = '/content/drive/My Drive/gcp_deploy_model/'os.makedirs(model_dir, exist_ok=True) You can download the data from the original source found here and load it using pandas (Learn How) or you can use PyCaret’s data repository to load the data using the get_data() function (This will require internet connection). from pycaret.datasets import get_datadataset = get_data('diamond') #check the shape of datadataset.shape(6000, 8)data = dataset.sample(frac=0.9, random_state=786).reset_index(drop=True)data_unseen = dataset.drop(data.index).reset_index(drop=True)print('Data for Modeling: ' + str(data.shape))print('Unseen Data For Predictions: ' + str(data_unseen.shape))Data for Modeling: (5400, 8)Unseen Data For Predictions: (600, 8) Let us prepare a modeling pipeline using PyCaret’s setup module. from pycaret.regression import *exp_reg101 = setup(data = data, target = 'Price', session_id=123)Setup Succesfully Completed! For this tutorial, we model the data using Light GBM from many options implemented in PyCaret. You can choose any model of your choice but that is not the focus of this tutorial. lightgbm = create_model('lightgbm') Let us train the model also called tuning the model in PyCaret’s terminologies. tuned_lightgbm = tune_model('lightgbm') Below are the plots to see the residual errors for the model plot_model(tuned_lightgbm) Let us plot the prediction errors vs true values of target. plot_model(tuned_lightgbm, plot = 'error') feature importance is a very informative plot to see the contribution of each feature in the model. plot_model(tuned_lightgbm, plot='feature') Another way to analyze the performance of models is to use the evaluate_model() function which displays a user interface for all of the available plots for a given model. It internally uses the plot_model() function. evaluate_model(tuned_lightgbm)interactive(children=(ToggleButtons(description='Plot Type:', icons=('',), options=(('Hyperparameters', 'param... predict_model(tuned_lightgbm); final_lightgbm = finalize_model(tuned_lightgbm)#Final Light Gradient Boosting Machine parameters for deploymentprint(final_lightgbm)LGBMRegressor(boosting_type='gbdt', class_weight=None, colsample_bytree=1.0, importance_type='split', learning_rate=0.4, max_depth=10, min_child_samples=20, min_child_weight=0.001, min_split_gain=0.9, n_estimators=90, n_jobs=-1, num_leaves=10, objective=None, random_state=123, reg_alpha=0.9, reg_lambda=0.2, silent=True, subsample=1.0, subsample_for_bin=200000, subsample_freq=0)predict_model(final_lightgbm) unseen_predictions = predict_model(final_lightgbm, data=data_unseen)unseen_predictions.head() The Label column is added onto the data_unseen set. The label is the predicted value using the final_lightgbm model. If you want predictions to be rounded, you can use round parameter inside predict_model(). Let us first save the model locally model_dirmodel_name = 'Final_lightgbm_model''/content/drive/My Drive/gcp_deploy_model/'# Saving model to google drivesave_model(final_lightgbm, model_dir + model_name)Transformation Pipeline and Model Succesfully Saved To load a saved model at a future date in the same or an alternative environment, we would use PyCaret’s load_model() function and then easily apply the saved model on new unseen data for prediction. saved_final_lightgbm = load_model(model_dir + model_name)Transformation Pipeline and Model Sucessfully Loaded Once the model is loaded in the environment, you can simply use it to predict any new data using the same predict_model() function. Below we have applied the loaded model to predict the same data_unseen that we used in the section above. new_prediction = predict_model(saved_final_lightgbm, data=data_unseen)new_prediction.head() Notice that the results of unseen_predictions and new_prediction are identical. Once, we have the trained model the next task is to deploy it to serve the clients. There are various deployment options available however in this section I focus on deploying it on Google Cloud AI platform. I try to use a similar approach as followed in pycaret library for deploying on AWS. The pre-requisites to deploy the machine learning models on google cloud are Familiarity with Google Cloud Projects Basic understanding of storage buckets and it gsutil command-line tool Basic Understanding of gcloud command-line tool to interact with Google Cloud A Final Trained Model with PyCaret Read the Guide from google.colab import authauth.authenticate_user() Define google cloud project, target bucket, and set the cloud_project Environment variable. Create a google cloud project if not created earlier. Follow the above guide for more information on it. # GCP project name, Change the name based on your own GCP project.CLOUD_PROJECT = 'gcpessentials-rz' # GCP project namebucket_name = 'pycaret-reg101-rz' # bucket name for storage of your modelBUCKET = 'gs://' + CLOUD_PROJECT + '-{}'.format(bucket_name)# Set the gcloud consol to $CLOUD_PROJECT Environment Variable for your Desired Project)!gcloud config set project $CLOUD_PROJECTUpdated property [core/project]. We define some utility functions to create a google cloud storage bucket, uploading a blob to storage bucket, and downloading the blob from the storage bucket. The codes are taken from Google official documentation and modified slightly based on our requirements here. from google.cloud import storagedef create_bucket(project_name, bucket_name): """Creates a new bucket.""" # bucket_name = "your-new-bucket-name" storage_client = storage.Client(project_name) buckets = storage_client.list_buckets() if bucket_name not in buckets: bucket = storage_client.create_bucket(bucket_name) print("Bucket {} created".format(bucket.name)) else: raise FileExistsError('{} already exists'.format(bucket_name))def upload_blob(project_name, bucket_name, source_file_name, destination_blob_name): """Uploads a file to the bucket.""" # bucket_name = "your-bucket-name" # source_file_name = "local/path/to/file" # destination_blob_name = "storage-object-name" storage_client = storage.Client(project_name) bucket = storage_client.bucket(bucket_name) blob = bucket.blob(destination_blob_name) blob.upload_from_filename(source_file_name) print( "File {} uploaded to {}.".format( source_file_name, destination_blob_name ) )def download_blob(project_name, bucket_name, source_blob_name, destination_file_name): """Downloads a blob from the bucket.""" # bucket_name = "your-bucket-name" # source_blob_name = "storage-object-name" # destination_file_name = "local/path/to/file" storage_client = storage.Client(project_name) bucket = storage_client.bucket(bucket_name) blob = bucket.blob(source_blob_name) if destination_file_name is not None: blob.download_to_filename(destination_file_name) print( "Blob {} downloaded to {}.".format( source_blob_name, destination_file_name ) ) return blob Using the above utilities, use the below code to upload the model to the GCP storage bucket. # Create Bucketcreate_bucket(CLOUD_PROJECT, bucket_name)Bucket pycaret-reg101-rz created Upload the model to google cloud storage bucket # Save Model Local/google drive and upload to GCPmodel_name_gcp = 'lightgbm-reg101-gcp'save_model(final_lightgbm, model_name= model_dir + model_name_gcp, verbose=False)model_src = model_dir + model_name_gcp +'.pkl'model_dst = str(model_name)+'.pkl'upload_blob(CLOUD_PROJECT, bucket_name, model_src, model_dst)File /content/drive/My Drive/gcp_deploy_model/lightgbm-reg101-gcp.pkl uploaded to Final_lightgbm_model.pkl. Once your model is upload to GCP, you can download anytime to perform the predictions. I follow a simple flow, where the model is downloaded locally or in google drive first, and then using the load_model function, predictions can be generated. outfile_name = model_dir + 'lightgbm-reg101-gcp-downloaded'model_gcp_src = str(model_name)+'.pkl'model_downloaded = download_blob(CLOUD_PROJECT, bucket_name, model_gcp_src, outfile_name + '.pkl')Blob Final_lightgbm_model.pkl downloaded to /content/drive/My Drive/gcp_deploy_model/lightgbm-reg101-gcp-downloaded.pkl.os.listdir(model_dir)['Final_lightgbm_model.pkl', 'lightgbm-reg101-gcp.pkl', 'lightgbm-reg101-gcp-downloaded.pkl'] Use the recently downloaded model from GCP to perform the prediction. # Loading the model for predictionsgcp_final_lightgbm = load_model(outfile_name)Transformation Pipeline and Model Sucessfully Loaded# Predictions from deployed modelnew_prediction_gcp = predict_model(gcp_final_lightgbm, data=data_unseen)new_prediction_gcp.head() Follow the below Google colaboratory notebook to reproduce and practice this guide. In this tutorial, we learned how to deploy the model to GCP when trained with pycaret library. The main objective was to use built-in utils of pycaret to deploy and load the model from GCP. Below are some highlights Mount google drive for saving models A train Regression model with pycaret Saving and loading the trained/finalized model google drive Deploying trained/finalized model to GCP Bucket Using the GCP deployed model to perform predictions PyCaret’s way
[ { "code": null, "e": 384, "s": 172, "text": "In this story, I have developed a working tutorial on deploying a model trained with pycaret on Google Cloud Platform. This tutorial can be used to deploy any machine learning model(s) with slight modifications." }, { "code": null, "e": 728, "s": 384, "text": "We will learn how to deploy models trained with pycaret to Google Cloud Platform. As you might know, pycaret already has support to deploy the trained models on AWS but not with GCP or Azure at the moment. I followed the similar code-practices as used in the library for deploying models on AWS and added essential utilities for GCP deploying." }, { "code": null, "e": 934, "s": 728, "text": "PyCaret is an open source, low-code machine learning library in Python that allows you to go from preparing your data to deploying your model within seconds in your choice of notebook environment [source]." }, { "code": null, "e": 1380, "s": 934, "text": "A PyCaret is an autoML framework for citizen data scientists term used in its official documentation. PyCaret is relatively a new library released a few months ago for public use and still under active development. After going through some source code, I realized the current public release lacks support for the deployment of trained/finalized models to Google Cloud Platform. Although, It has support only for deploying on Amazon web services." }, { "code": null, "e": 1537, "s": 1380, "text": "Keeping in a view wide use of GCP as cloud service, I have given a try to add a tutorial on deploying the trained model on google cloud using PyCaret’s way." }, { "code": null, "e": 1638, "s": 1537, "text": "For this tutorial, we will use the Regression Tutorial (REG101) — Level Beginner for model training." }, { "code": null, "e": 1659, "s": 1638, "text": "!pip install pycaret" }, { "code": null, "e": 1904, "s": 1659, "text": "We need to mount the google drive to read/write the data in colab environment. Below is the simplest way to mount it. You will be asked to enter the token generated by your access procedure. Here is the link to the article about mounting gdrive" }, { "code": null, "e": 1967, "s": 1904, "text": "We will save models locally on Google drive for this tutorial." }, { "code": null, "e": 2155, "s": 1967, "text": "from google.colab import drivedrive.mount('/content/drive')Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True)." }, { "code": null, "e": 2205, "s": 2155, "text": "Let us create a directory to save models locally." }, { "code": null, "e": 2389, "s": 2205, "text": "# Create directory on google drive to save models locally. You can use temp paths.import osmodel_dir = '/content/drive/My Drive/gcp_deploy_model/'os.makedirs(model_dir, exist_ok=True)" }, { "code": null, "e": 2617, "s": 2389, "text": "You can download the data from the original source found here and load it using pandas (Learn How) or you can use PyCaret’s data repository to load the data using the get_data() function (This will require internet connection)." }, { "code": null, "e": 2684, "s": 2617, "text": "from pycaret.datasets import get_datadataset = get_data('diamond')" }, { "code": null, "e": 3038, "s": 2684, "text": "#check the shape of datadataset.shape(6000, 8)data = dataset.sample(frac=0.9, random_state=786).reset_index(drop=True)data_unseen = dataset.drop(data.index).reset_index(drop=True)print('Data for Modeling: ' + str(data.shape))print('Unseen Data For Predictions: ' + str(data_unseen.shape))Data for Modeling: (5400, 8)Unseen Data For Predictions: (600, 8)" }, { "code": null, "e": 3103, "s": 3038, "text": "Let us prepare a modeling pipeline using PyCaret’s setup module." }, { "code": null, "e": 3229, "s": 3103, "text": "from pycaret.regression import *exp_reg101 = setup(data = data, target = 'Price', session_id=123)Setup Succesfully Completed!" }, { "code": null, "e": 3408, "s": 3229, "text": "For this tutorial, we model the data using Light GBM from many options implemented in PyCaret. You can choose any model of your choice but that is not the focus of this tutorial." }, { "code": null, "e": 3444, "s": 3408, "text": "lightgbm = create_model('lightgbm')" }, { "code": null, "e": 3524, "s": 3444, "text": "Let us train the model also called tuning the model in PyCaret’s terminologies." }, { "code": null, "e": 3564, "s": 3524, "text": "tuned_lightgbm = tune_model('lightgbm')" }, { "code": null, "e": 3625, "s": 3564, "text": "Below are the plots to see the residual errors for the model" }, { "code": null, "e": 3652, "s": 3625, "text": "plot_model(tuned_lightgbm)" }, { "code": null, "e": 3712, "s": 3652, "text": "Let us plot the prediction errors vs true values of target." }, { "code": null, "e": 3755, "s": 3712, "text": "plot_model(tuned_lightgbm, plot = 'error')" }, { "code": null, "e": 3855, "s": 3755, "text": "feature importance is a very informative plot to see the contribution of each feature in the model." }, { "code": null, "e": 3898, "s": 3855, "text": "plot_model(tuned_lightgbm, plot='feature')" }, { "code": null, "e": 4115, "s": 3898, "text": "Another way to analyze the performance of models is to use the evaluate_model() function which displays a user interface for all of the available plots for a given model. It internally uses the plot_model() function." }, { "code": null, "e": 4259, "s": 4115, "text": "evaluate_model(tuned_lightgbm)interactive(children=(ToggleButtons(description='Plot Type:', icons=('',), options=(('Hyperparameters', 'param..." }, { "code": null, "e": 4290, "s": 4259, "text": "predict_model(tuned_lightgbm);" }, { "code": null, "e": 4897, "s": 4290, "text": "final_lightgbm = finalize_model(tuned_lightgbm)#Final Light Gradient Boosting Machine parameters for deploymentprint(final_lightgbm)LGBMRegressor(boosting_type='gbdt', class_weight=None, colsample_bytree=1.0, importance_type='split', learning_rate=0.4, max_depth=10, min_child_samples=20, min_child_weight=0.001, min_split_gain=0.9, n_estimators=90, n_jobs=-1, num_leaves=10, objective=None, random_state=123, reg_alpha=0.9, reg_lambda=0.2, silent=True, subsample=1.0, subsample_for_bin=200000, subsample_freq=0)predict_model(final_lightgbm)" }, { "code": null, "e": 4991, "s": 4897, "text": "unseen_predictions = predict_model(final_lightgbm, data=data_unseen)unseen_predictions.head()" }, { "code": null, "e": 5199, "s": 4991, "text": "The Label column is added onto the data_unseen set. The label is the predicted value using the final_lightgbm model. If you want predictions to be rounded, you can use round parameter inside predict_model()." }, { "code": null, "e": 5235, "s": 5199, "text": "Let us first save the model locally" }, { "code": null, "e": 5454, "s": 5235, "text": "model_dirmodel_name = 'Final_lightgbm_model''/content/drive/My Drive/gcp_deploy_model/'# Saving model to google drivesave_model(final_lightgbm, model_dir + model_name)Transformation Pipeline and Model Succesfully Saved" }, { "code": null, "e": 5654, "s": 5454, "text": "To load a saved model at a future date in the same or an alternative environment, we would use PyCaret’s load_model() function and then easily apply the saved model on new unseen data for prediction." }, { "code": null, "e": 5764, "s": 5654, "text": "saved_final_lightgbm = load_model(model_dir + model_name)Transformation Pipeline and Model Sucessfully Loaded" }, { "code": null, "e": 6002, "s": 5764, "text": "Once the model is loaded in the environment, you can simply use it to predict any new data using the same predict_model() function. Below we have applied the loaded model to predict the same data_unseen that we used in the section above." }, { "code": null, "e": 6094, "s": 6002, "text": "new_prediction = predict_model(saved_final_lightgbm, data=data_unseen)new_prediction.head()" }, { "code": null, "e": 6174, "s": 6094, "text": "Notice that the results of unseen_predictions and new_prediction are identical." }, { "code": null, "e": 6467, "s": 6174, "text": "Once, we have the trained model the next task is to deploy it to serve the clients. There are various deployment options available however in this section I focus on deploying it on Google Cloud AI platform. I try to use a similar approach as followed in pycaret library for deploying on AWS." }, { "code": null, "e": 6544, "s": 6467, "text": "The pre-requisites to deploy the machine learning models on google cloud are" }, { "code": null, "e": 6583, "s": 6544, "text": "Familiarity with Google Cloud Projects" }, { "code": null, "e": 6654, "s": 6583, "text": "Basic understanding of storage buckets and it gsutil command-line tool" }, { "code": null, "e": 6732, "s": 6654, "text": "Basic Understanding of gcloud command-line tool to interact with Google Cloud" }, { "code": null, "e": 6767, "s": 6732, "text": "A Final Trained Model with PyCaret" }, { "code": null, "e": 6782, "s": 6767, "text": "Read the Guide" }, { "code": null, "e": 6836, "s": 6782, "text": "from google.colab import authauth.authenticate_user()" }, { "code": null, "e": 7033, "s": 6836, "text": "Define google cloud project, target bucket, and set the cloud_project Environment variable. Create a google cloud project if not created earlier. Follow the above guide for more information on it." }, { "code": null, "e": 7447, "s": 7033, "text": "# GCP project name, Change the name based on your own GCP project.CLOUD_PROJECT = 'gcpessentials-rz' # GCP project namebucket_name = 'pycaret-reg101-rz' # bucket name for storage of your modelBUCKET = 'gs://' + CLOUD_PROJECT + '-{}'.format(bucket_name)# Set the gcloud consol to $CLOUD_PROJECT Environment Variable for your Desired Project)!gcloud config set project $CLOUD_PROJECTUpdated property [core/project]." }, { "code": null, "e": 7607, "s": 7447, "text": "We define some utility functions to create a google cloud storage bucket, uploading a blob to storage bucket, and downloading the blob from the storage bucket." }, { "code": null, "e": 7716, "s": 7607, "text": "The codes are taken from Google official documentation and modified slightly based on our requirements here." }, { "code": null, "e": 9387, "s": 7716, "text": "from google.cloud import storagedef create_bucket(project_name, bucket_name): \"\"\"Creates a new bucket.\"\"\" # bucket_name = \"your-new-bucket-name\" storage_client = storage.Client(project_name) buckets = storage_client.list_buckets() if bucket_name not in buckets: bucket = storage_client.create_bucket(bucket_name) print(\"Bucket {} created\".format(bucket.name)) else: raise FileExistsError('{} already exists'.format(bucket_name))def upload_blob(project_name, bucket_name, source_file_name, destination_blob_name): \"\"\"Uploads a file to the bucket.\"\"\" # bucket_name = \"your-bucket-name\" # source_file_name = \"local/path/to/file\" # destination_blob_name = \"storage-object-name\" storage_client = storage.Client(project_name) bucket = storage_client.bucket(bucket_name) blob = bucket.blob(destination_blob_name) blob.upload_from_filename(source_file_name) print( \"File {} uploaded to {}.\".format( source_file_name, destination_blob_name ) )def download_blob(project_name, bucket_name, source_blob_name, destination_file_name): \"\"\"Downloads a blob from the bucket.\"\"\" # bucket_name = \"your-bucket-name\" # source_blob_name = \"storage-object-name\" # destination_file_name = \"local/path/to/file\" storage_client = storage.Client(project_name) bucket = storage_client.bucket(bucket_name) blob = bucket.blob(source_blob_name) if destination_file_name is not None: blob.download_to_filename(destination_file_name) print( \"Blob {} downloaded to {}.\".format( source_blob_name, destination_file_name ) ) return blob" }, { "code": null, "e": 9480, "s": 9387, "text": "Using the above utilities, use the below code to upload the model to the GCP storage bucket." }, { "code": null, "e": 9569, "s": 9480, "text": "# Create Bucketcreate_bucket(CLOUD_PROJECT, bucket_name)Bucket pycaret-reg101-rz created" }, { "code": null, "e": 9617, "s": 9569, "text": "Upload the model to google cloud storage bucket" }, { "code": null, "e": 10034, "s": 9617, "text": "# Save Model Local/google drive and upload to GCPmodel_name_gcp = 'lightgbm-reg101-gcp'save_model(final_lightgbm, model_name= model_dir + model_name_gcp, verbose=False)model_src = model_dir + model_name_gcp +'.pkl'model_dst = str(model_name)+'.pkl'upload_blob(CLOUD_PROJECT, bucket_name, model_src, model_dst)File /content/drive/My Drive/gcp_deploy_model/lightgbm-reg101-gcp.pkl uploaded to Final_lightgbm_model.pkl." }, { "code": null, "e": 10279, "s": 10034, "text": "Once your model is upload to GCP, you can download anytime to perform the predictions. I follow a simple flow, where the model is downloaded locally or in google drive first, and then using the load_model function, predictions can be generated." }, { "code": null, "e": 10709, "s": 10279, "text": "outfile_name = model_dir + 'lightgbm-reg101-gcp-downloaded'model_gcp_src = str(model_name)+'.pkl'model_downloaded = download_blob(CLOUD_PROJECT, bucket_name, model_gcp_src, outfile_name + '.pkl')Blob Final_lightgbm_model.pkl downloaded to /content/drive/My Drive/gcp_deploy_model/lightgbm-reg101-gcp-downloaded.pkl.os.listdir(model_dir)['Final_lightgbm_model.pkl', 'lightgbm-reg101-gcp.pkl', 'lightgbm-reg101-gcp-downloaded.pkl']" }, { "code": null, "e": 10779, "s": 10709, "text": "Use the recently downloaded model from GCP to perform the prediction." }, { "code": null, "e": 11042, "s": 10779, "text": "# Loading the model for predictionsgcp_final_lightgbm = load_model(outfile_name)Transformation Pipeline and Model Sucessfully Loaded# Predictions from deployed modelnew_prediction_gcp = predict_model(gcp_final_lightgbm, data=data_unseen)new_prediction_gcp.head()" }, { "code": null, "e": 11126, "s": 11042, "text": "Follow the below Google colaboratory notebook to reproduce and practice this guide." }, { "code": null, "e": 11221, "s": 11126, "text": "In this tutorial, we learned how to deploy the model to GCP when trained with pycaret library." }, { "code": null, "e": 11342, "s": 11221, "text": "The main objective was to use built-in utils of pycaret to deploy and load the model from GCP. Below are some highlights" }, { "code": null, "e": 11379, "s": 11342, "text": "Mount google drive for saving models" }, { "code": null, "e": 11417, "s": 11379, "text": "A train Regression model with pycaret" }, { "code": null, "e": 11477, "s": 11417, "text": "Saving and loading the trained/finalized model google drive" }, { "code": null, "e": 11525, "s": 11477, "text": "Deploying trained/finalized model to GCP Bucket" } ]
Count the Frequency of elements in a Numeric Vector - tabulate() Function - GeeksforGeeks
05 Jun, 2020 tabulate() function in R Language is used to count the frequency of occurrence of a element in the vector. This function checks for each element in the vector and returns the number of times it occurs in the vector. It will create a vector of the length of the maximum element present in the vector. Syntax: tabulate(x, nbins) Parameters:x: Numeric Vectornbins: to control length of output vector Example 1: # R program to count frequency # of elements in a vector # Creating a vectorx1 <- c(3, 5, 3, 7, 9, 4, 6)x2 <- c(-1, -4, 2.4, 6, -7) # Calling tabulate() functiontabulate(x1)tabulate(x2) Output: [1] 0 0 2 1 1 1 1 0 1 [1] 0 1 0 0 0 1 Here, in the above code, the tabulate() function has ignored the negative values in the second vector, because it works only on numbers which are positive integers. Example 2: # R program to count frequency # of elements in a vector # Creating a vectorx1 <- c(3, 5, 3, 7, 9, 4, 6)x2 <- c(-1, -4, 2.6, 6, -7, 35) # Calling tabulate() functiontabulate(x1, nbins = 4)tabulate(x2, nbins = 8) Output: [1] 0 0 2 1 [1] 0 1 0 0 0 1 0 0 Here, in the above code, the length of the output vector is limited by the nbins passed as argument. R Vector-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to Change Axis Scales in R Plots? Printing Output of an R Program K-Means Clustering in R Programming
[ { "code": null, "e": 26125, "s": 26097, "text": "\n05 Jun, 2020" }, { "code": null, "e": 26425, "s": 26125, "text": "tabulate() function in R Language is used to count the frequency of occurrence of a element in the vector. This function checks for each element in the vector and returns the number of times it occurs in the vector. It will create a vector of the length of the maximum element present in the vector." }, { "code": null, "e": 26452, "s": 26425, "text": "Syntax: tabulate(x, nbins)" }, { "code": null, "e": 26522, "s": 26452, "text": "Parameters:x: Numeric Vectornbins: to control length of output vector" }, { "code": null, "e": 26533, "s": 26522, "text": "Example 1:" }, { "code": "# R program to count frequency # of elements in a vector # Creating a vectorx1 <- c(3, 5, 3, 7, 9, 4, 6)x2 <- c(-1, -4, 2.4, 6, -7) # Calling tabulate() functiontabulate(x1)tabulate(x2)", "e": 26721, "s": 26533, "text": null }, { "code": null, "e": 26729, "s": 26721, "text": "Output:" }, { "code": null, "e": 26768, "s": 26729, "text": "[1] 0 0 2 1 1 1 1 0 1\n[1] 0 1 0 0 0 1\n" }, { "code": null, "e": 26933, "s": 26768, "text": "Here, in the above code, the tabulate() function has ignored the negative values in the second vector, because it works only on numbers which are positive integers." }, { "code": null, "e": 26944, "s": 26933, "text": "Example 2:" }, { "code": "# R program to count frequency # of elements in a vector # Creating a vectorx1 <- c(3, 5, 3, 7, 9, 4, 6)x2 <- c(-1, -4, 2.6, 6, -7, 35) # Calling tabulate() functiontabulate(x1, nbins = 4)tabulate(x2, nbins = 8)", "e": 27158, "s": 26944, "text": null }, { "code": null, "e": 27166, "s": 27158, "text": "Output:" }, { "code": null, "e": 27199, "s": 27166, "text": "[1] 0 0 2 1\n[1] 0 1 0 0 0 1 0 0\n" }, { "code": null, "e": 27300, "s": 27199, "text": "Here, in the above code, the length of the output vector is limited by the nbins passed as argument." }, { "code": null, "e": 27318, "s": 27300, "text": "R Vector-Function" }, { "code": null, "e": 27329, "s": 27318, "text": "R Language" }, { "code": null, "e": 27427, "s": 27329, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27485, "s": 27427, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 27537, "s": 27485, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 27569, "s": 27537, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 27613, "s": 27569, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 27665, "s": 27613, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27700, "s": 27665, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27758, "s": 27700, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27796, "s": 27758, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27828, "s": 27796, "text": "Printing Output of an R Program" } ]
Naive Bayes Classifiers
02 Feb, 2022 This article discusses the theory behind the Naive Bayes classifiers and their implementation. Naive Bayes classifiers are a collection of classification algorithms based on Bayes’ Theorem. It is not a single algorithm but a family of algorithms where all of them share a common principle, i.e. every pair of features being classified is independent of each other. To start with, let us consider a dataset. Consider a fictional dataset that describes the weather conditions for playing a game of golf. Given the weather conditions, each tuple classifies the conditions as fit(“Yes”) or unfit(“No”) for playing golf. Here is a tabular representation of our dataset. The dataset is divided into two parts, namely, feature matrix and the response vector. Feature matrix contains all the vectors(rows) of dataset in which each vector consists of the value of dependent features. In above dataset, features are ‘Outlook’, ‘Temperature’, ‘Humidity’ and ‘Windy’. Response vector contains the value of class variable(prediction or output) for each row of feature matrix. In above dataset, the class variable name is ‘Play golf’. Assumption: The fundamental Naive Bayes assumption is that each feature makes an: independent equal contribution to the outcome. With relation to our dataset, this concept can be understood as: We assume that no pair of features are dependent. For example, the temperature being ‘Hot’ has nothing to do with the humidity or the outlook being ‘Rainy’ has no effect on the winds. Hence, the features are assumed to be independent. Secondly, each feature is given the same weight(or importance). For example, knowing only temperature and humidity alone can’t predict the outcome accurately. None of the attributes is irrelevant and assumed to be contributing equally to the outcome. Note: The assumptions made by Naive Bayes are not generally correct in real-world situations. In-fact, the independence assumption is never correct but often works well in practice. Now, before moving to the formula for Naive Bayes, it is important to know about Bayes’ theorem. Bayes’ Theorem Bayes’ Theorem finds the probability of an event occurring given the probability of another event that has already occurred. Bayes’ theorem is stated mathematically as the following equation: where A and B are events and P(B) ≠ 0. Basically, we are trying to find probability of event A, given the event B is true. Event B is also termed as evidence. P(A) is the priori of A (the prior probability, i.e. Probability of event before evidence is seen). The evidence is an attribute value of an unknown instance(here, it is event B). P(A|B) is a posteriori probability of B, i.e. probability of event after evidence is seen. Now, with regards to our dataset, we can apply Bayes’ theorem in following way: where, y is class variable and X is a dependent feature vector (of size n) where: Just to clear, an example of a feature vector and corresponding class variable can be: (refer 1st row of dataset) X = (Rainy, Hot, High, False) y = No So basically, P(y|X) here means, the probability of “Not playing golf” given that the weather conditions are “Rainy outlook”, “Temperature is hot”, “high humidity” and “no wind”. Naive assumption Now, its time to put a naive assumption to the Bayes’ theorem, which is, independence among the features. So now, we split evidence into the independent parts. Now, if any two events A and B are independent, then, P(A,B) = P(A)P(B) Hence, we reach to the result: which can be expressed as: Now, as the denominator remains constant for a given input, we can remove that term: Now, we need to create a classifier model. For this, we find the probability of given set of inputs for all possible values of the class variable y and pick up the output with maximum probability. This can be expressed mathematically as: So, finally, we are left with the task of calculating P(y) and P(xi | y). Please note that P(y) is also called class probability and P(xi | y) is called conditional probability. The different naive Bayes classifiers differ mainly by the assumptions they make regarding the distribution of P(xi | y). Let us try to apply the above formula manually on our weather dataset. For this, we need to do some precomputations on our dataset. We need to find P(xi | yj) for each xi in X and yj in y. All these calculations have been demonstrated in the tables below: So, in the figure above, we have calculated P(xi | yj) for each xi in X and yj in y manually in the tables 1-4. For example, probability of playing golf given that the temperature is cool, i.e P(temp. = cool | play golf = Yes) = 3/9. Also, we need to find class probabilities (P(y)) which has been calculated in the table 5. For example, P(play golf = Yes) = 9/14. So now, we are done with our pre-computations and the classifier is ready! Let us test it on a new set of features (let us call it today): today = (Sunny, Hot, Normal, False) So, probability of playing golf is given by: and probability to not play golf is given by: Since, P(today) is common in both probabilities, we can ignore P(today) and find proportional probabilities as: and Now, since These numbers can be converted into a probability by making the sum equal to 1 (normalization): and Since So, prediction that golf would be played is ‘Yes’. The method that we discussed above is applicable for discrete data. In case of continuous data, we need to make some assumptions regarding the distribution of values of each feature. The different naive Bayes classifiers differ mainly by the assumptions they make regarding the distribution of P(xi | y). Now, we discuss one of such classifiers here. Gaussian Naive Bayes classifier In Gaussian Naive Bayes, continuous values associated with each feature are assumed to be distributed according to a Gaussian distribution. A Gaussian distribution is also called Normal distribution. When plotted, it gives a bell shaped curve which is symmetric about the mean of the feature values as shown below: The likelihood of the features is assumed to be Gaussian, hence, conditional probability is given by: Now, we look at an implementation of Gaussian Naive Bayes classifier using scikit-learn. # load the iris datasetfrom sklearn.datasets import load_irisiris = load_iris() # store the feature matrix (X) and response vector (y)X = iris.datay = iris.target # splitting X and y into training and testing setsfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=1) # training the model on training setfrom sklearn.naive_bayes import GaussianNBgnb = GaussianNB()gnb.fit(X_train, y_train) # making predictions on the testing sety_pred = gnb.predict(X_test) # comparing actual response values (y_test) with predicted response values (y_pred)from sklearn import metricsprint("Gaussian Naive Bayes model accuracy(in %):", metrics.accuracy_score(y_test, y_pred)*100) Output: Gaussian Naive Bayes model accuracy(in %): 95.0 Other popular Naive Bayes classifiers are: Multinomial Naive Bayes: Feature vectors represent the frequencies with which certain events have been generated by a multinomial distribution. This is the event model typically used for document classification. Bernoulli Naive Bayes: In the multivariate Bernoulli event model, features are independent booleans (binary variables) describing inputs. Like the multinomial model, this model is popular for document classification tasks, where binary term occurrence(i.e. a word occurs in a document or not) features are used rather than term frequencies(i.e. frequency of a word in the document). As we reach to the end of this article, here are some important points to ponder upon: In spite of their apparently over-simplified assumptions, naive Bayes classifiers have worked quite well in many real-world situations, famously document classification and spam filtering. They require a small amount of training data to estimate the necessary parameters. Naive Bayes learners and classifiers can be extremely fast compared to more sophisticated methods. The decoupling of the class conditional feature distributions means that each distribution can be independently estimated as a one dimensional distribution. This in turn helps to alleviate problems stemming from the curse of dimensionality. References: https://en.wikipedia.org/wiki/Naive_Bayes_classifier http://gerardnico.com/wiki/data_mining/naive_bayes http://scikit-learn.org/stable/modules/naive_bayes.html This blog is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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. Sambhav_Khurana shivamraj74 raunaksrivastava22 germanshephered48 rkbhola5 Advanced Computer Subject Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. System Design Tutorial Docker - COPY Instruction Decision Tree Introduction with example Getting started with Machine Learning How to Run a Python Script using Docker? Agents in Artificial Intelligence Decision Tree Introduction with example Search Algorithms in AI Getting started with Machine Learning Introduction to Recurrent Neural Network
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Feb, 2022" }, { "code": null, "e": 149, "s": 54, "text": "This article discusses the theory behind the Naive Bayes classifiers and their implementation." }, { "code": null, "e": 419, "s": 149, "text": "Naive Bayes classifiers are a collection of classification algorithms based on Bayes’ Theorem. It is not a single algorithm but a family of algorithms where all of them share a common principle, i.e. every pair of features being classified is independent of each other." }, { "code": null, "e": 461, "s": 419, "text": "To start with, let us consider a dataset." }, { "code": null, "e": 670, "s": 461, "text": "Consider a fictional dataset that describes the weather conditions for playing a game of golf. Given the weather conditions, each tuple classifies the conditions as fit(“Yes”) or unfit(“No”) for playing golf." }, { "code": null, "e": 719, "s": 670, "text": "Here is a tabular representation of our dataset." }, { "code": null, "e": 806, "s": 719, "text": "The dataset is divided into two parts, namely, feature matrix and the response vector." }, { "code": null, "e": 1010, "s": 806, "text": "Feature matrix contains all the vectors(rows) of dataset in which each vector consists of the value of dependent features. In above dataset, features are ‘Outlook’, ‘Temperature’, ‘Humidity’ and ‘Windy’." }, { "code": null, "e": 1175, "s": 1010, "text": "Response vector contains the value of class variable(prediction or output) for each row of feature matrix. In above dataset, the class variable name is ‘Play golf’." }, { "code": null, "e": 1187, "s": 1175, "text": "Assumption:" }, { "code": null, "e": 1257, "s": 1187, "text": "The fundamental Naive Bayes assumption is that each feature makes an:" }, { "code": null, "e": 1269, "s": 1257, "text": "independent" }, { "code": null, "e": 1275, "s": 1269, "text": "equal" }, { "code": null, "e": 1304, "s": 1275, "text": "contribution to the outcome." }, { "code": null, "e": 1369, "s": 1304, "text": "With relation to our dataset, this concept can be understood as:" }, { "code": null, "e": 1604, "s": 1369, "text": "We assume that no pair of features are dependent. For example, the temperature being ‘Hot’ has nothing to do with the humidity or the outlook being ‘Rainy’ has no effect on the winds. Hence, the features are assumed to be independent." }, { "code": null, "e": 1855, "s": 1604, "text": "Secondly, each feature is given the same weight(or importance). For example, knowing only temperature and humidity alone can’t predict the outcome accurately. None of the attributes is irrelevant and assumed to be contributing equally to the outcome." }, { "code": null, "e": 2037, "s": 1855, "text": "Note: The assumptions made by Naive Bayes are not generally correct in real-world situations. In-fact, the independence assumption is never correct but often works well in practice." }, { "code": null, "e": 2134, "s": 2037, "text": "Now, before moving to the formula for Naive Bayes, it is important to know about Bayes’ theorem." }, { "code": null, "e": 2149, "s": 2134, "text": "Bayes’ Theorem" }, { "code": null, "e": 2341, "s": 2149, "text": "Bayes’ Theorem finds the probability of an event occurring given the probability of another event that has already occurred. Bayes’ theorem is stated mathematically as the following equation:" }, { "code": null, "e": 2381, "s": 2341, "text": "where A and B are events and P(B) ≠ 0." }, { "code": null, "e": 2501, "s": 2381, "text": "Basically, we are trying to find probability of event A, given the event B is true. Event B is also termed as evidence." }, { "code": null, "e": 2681, "s": 2501, "text": "P(A) is the priori of A (the prior probability, i.e. Probability of event before evidence is seen). The evidence is an attribute value of an unknown instance(here, it is event B)." }, { "code": null, "e": 2772, "s": 2681, "text": "P(A|B) is a posteriori probability of B, i.e. probability of event after evidence is seen." }, { "code": null, "e": 2852, "s": 2772, "text": "Now, with regards to our dataset, we can apply Bayes’ theorem in following way:" }, { "code": null, "e": 2934, "s": 2852, "text": "where, y is class variable and X is a dependent feature vector (of size n) where:" }, { "code": null, "e": 3048, "s": 2934, "text": "Just to clear, an example of a feature vector and corresponding class variable can be: (refer 1st row of dataset)" }, { "code": null, "e": 3086, "s": 3048, "text": "X = (Rainy, Hot, High, False)\ny = No\n" }, { "code": null, "e": 3265, "s": 3086, "text": "So basically, P(y|X) here means, the probability of “Not playing golf” given that the weather conditions are “Rainy outlook”, “Temperature is hot”, “high humidity” and “no wind”." }, { "code": null, "e": 3282, "s": 3265, "text": "Naive assumption" }, { "code": null, "e": 3442, "s": 3282, "text": "Now, its time to put a naive assumption to the Bayes’ theorem, which is, independence among the features. So now, we split evidence into the independent parts." }, { "code": null, "e": 3496, "s": 3442, "text": "Now, if any two events A and B are independent, then," }, { "code": null, "e": 3515, "s": 3496, "text": "P(A,B) = P(A)P(B)\n" }, { "code": null, "e": 3546, "s": 3515, "text": "Hence, we reach to the result:" }, { "code": null, "e": 3573, "s": 3546, "text": "which can be expressed as:" }, { "code": null, "e": 3658, "s": 3573, "text": "Now, as the denominator remains constant for a given input, we can remove that term:" }, { "code": null, "e": 3896, "s": 3658, "text": "Now, we need to create a classifier model. For this, we find the probability of given set of inputs for all possible values of the class variable y and pick up the output with maximum probability. This can be expressed mathematically as:" }, { "code": null, "e": 3970, "s": 3896, "text": "So, finally, we are left with the task of calculating P(y) and P(xi | y)." }, { "code": null, "e": 4074, "s": 3970, "text": "Please note that P(y) is also called class probability and P(xi | y) is called conditional probability." }, { "code": null, "e": 4196, "s": 4074, "text": "The different naive Bayes classifiers differ mainly by the assumptions they make regarding the distribution of P(xi | y)." }, { "code": null, "e": 4328, "s": 4196, "text": "Let us try to apply the above formula manually on our weather dataset. For this, we need to do some precomputations on our dataset." }, { "code": null, "e": 4452, "s": 4328, "text": "We need to find P(xi | yj) for each xi in X and yj in y. All these calculations have been demonstrated in the tables below:" }, { "code": null, "e": 4686, "s": 4452, "text": "So, in the figure above, we have calculated P(xi | yj) for each xi in X and yj in y manually in the tables 1-4. For example, probability of playing golf given that the temperature is cool, i.e P(temp. = cool | play golf = Yes) = 3/9." }, { "code": null, "e": 4817, "s": 4686, "text": "Also, we need to find class probabilities (P(y)) which has been calculated in the table 5. For example, P(play golf = Yes) = 9/14." }, { "code": null, "e": 4892, "s": 4817, "text": "So now, we are done with our pre-computations and the classifier is ready!" }, { "code": null, "e": 4956, "s": 4892, "text": "Let us test it on a new set of features (let us call it today):" }, { "code": null, "e": 4993, "s": 4956, "text": "today = (Sunny, Hot, Normal, False)\n" }, { "code": null, "e": 5038, "s": 4993, "text": "So, probability of playing golf is given by:" }, { "code": null, "e": 5084, "s": 5038, "text": "and probability to not play golf is given by:" }, { "code": null, "e": 5196, "s": 5084, "text": "Since, P(today) is common in both probabilities, we can ignore P(today) and find proportional probabilities as:" }, { "code": null, "e": 5200, "s": 5196, "text": "and" }, { "code": null, "e": 5211, "s": 5200, "text": "Now, since" }, { "code": null, "e": 5307, "s": 5211, "text": "These numbers can be converted into a probability by making the sum equal to 1 (normalization):" }, { "code": null, "e": 5311, "s": 5307, "text": "and" }, { "code": null, "e": 5317, "s": 5311, "text": "Since" }, { "code": null, "e": 5368, "s": 5317, "text": "So, prediction that golf would be played is ‘Yes’." }, { "code": null, "e": 5673, "s": 5368, "text": "The method that we discussed above is applicable for discrete data. In case of continuous data, we need to make some assumptions regarding the distribution of values of each feature. The different naive Bayes classifiers differ mainly by the assumptions they make regarding the distribution of P(xi | y)." }, { "code": null, "e": 5719, "s": 5673, "text": "Now, we discuss one of such classifiers here." }, { "code": null, "e": 5751, "s": 5719, "text": "Gaussian Naive Bayes classifier" }, { "code": null, "e": 6066, "s": 5751, "text": "In Gaussian Naive Bayes, continuous values associated with each feature are assumed to be distributed according to a Gaussian distribution. A Gaussian distribution is also called Normal distribution. When plotted, it gives a bell shaped curve which is symmetric about the mean of the feature values as shown below:" }, { "code": null, "e": 6168, "s": 6066, "text": "The likelihood of the features is assumed to be Gaussian, hence, conditional probability is given by:" }, { "code": null, "e": 6257, "s": 6168, "text": "Now, we look at an implementation of Gaussian Naive Bayes classifier using scikit-learn." }, { "code": "# load the iris datasetfrom sklearn.datasets import load_irisiris = load_iris() # store the feature matrix (X) and response vector (y)X = iris.datay = iris.target # splitting X and y into training and testing setsfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=1) # training the model on training setfrom sklearn.naive_bayes import GaussianNBgnb = GaussianNB()gnb.fit(X_train, y_train) # making predictions on the testing sety_pred = gnb.predict(X_test) # comparing actual response values (y_test) with predicted response values (y_pred)from sklearn import metricsprint(\"Gaussian Naive Bayes model accuracy(in %):\", metrics.accuracy_score(y_test, y_pred)*100)", "e": 7007, "s": 6257, "text": null }, { "code": null, "e": 7015, "s": 7007, "text": "Output:" }, { "code": null, "e": 7063, "s": 7015, "text": "Gaussian Naive Bayes model accuracy(in %): 95.0" }, { "code": null, "e": 7106, "s": 7063, "text": "Other popular Naive Bayes classifiers are:" }, { "code": null, "e": 7318, "s": 7106, "text": "Multinomial Naive Bayes: Feature vectors represent the frequencies with which certain events have been generated by a multinomial distribution. This is the event model typically used for document classification." }, { "code": null, "e": 7701, "s": 7318, "text": "Bernoulli Naive Bayes: In the multivariate Bernoulli event model, features are independent booleans (binary variables) describing inputs. Like the multinomial model, this model is popular for document classification tasks, where binary term occurrence(i.e. a word occurs in a document or not) features are used rather than term frequencies(i.e. frequency of a word in the document)." }, { "code": null, "e": 7788, "s": 7701, "text": "As we reach to the end of this article, here are some important points to ponder upon:" }, { "code": null, "e": 8060, "s": 7788, "text": "In spite of their apparently over-simplified assumptions, naive Bayes classifiers have worked quite well in many real-world situations, famously document classification and spam filtering. They require a small amount of training data to estimate the necessary parameters." }, { "code": null, "e": 8400, "s": 8060, "text": "Naive Bayes learners and classifiers can be extremely fast compared to more sophisticated methods. The decoupling of the class conditional feature distributions means that each distribution can be independently estimated as a one dimensional distribution. This in turn helps to alleviate problems stemming from the curse of dimensionality." }, { "code": null, "e": 8412, "s": 8400, "text": "References:" }, { "code": null, "e": 8465, "s": 8412, "text": "https://en.wikipedia.org/wiki/Naive_Bayes_classifier" }, { "code": null, "e": 8516, "s": 8465, "text": "http://gerardnico.com/wiki/data_mining/naive_bayes" }, { "code": null, "e": 8572, "s": 8516, "text": "http://scikit-learn.org/stable/modules/naive_bayes.html" }, { "code": null, "e": 8864, "s": 8572, "text": "This blog is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 8989, "s": 8864, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 9005, "s": 8989, "text": "Sambhav_Khurana" }, { "code": null, "e": 9017, "s": 9005, "text": "shivamraj74" }, { "code": null, "e": 9036, "s": 9017, "text": "raunaksrivastava22" }, { "code": null, "e": 9054, "s": 9036, "text": "germanshephered48" }, { "code": null, "e": 9063, "s": 9054, "text": "rkbhola5" }, { "code": null, "e": 9089, "s": 9063, "text": "Advanced Computer Subject" }, { "code": null, "e": 9106, "s": 9089, "text": "Machine Learning" }, { "code": null, "e": 9113, "s": 9106, "text": "Python" }, { "code": null, "e": 9130, "s": 9113, "text": "Machine Learning" }, { "code": null, "e": 9228, "s": 9130, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9251, "s": 9228, "text": "System Design Tutorial" }, { "code": null, "e": 9277, "s": 9251, "text": "Docker - COPY Instruction" }, { "code": null, "e": 9317, "s": 9277, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 9355, "s": 9317, "text": "Getting started with Machine Learning" }, { "code": null, "e": 9396, "s": 9355, "text": "How to Run a Python Script using Docker?" }, { "code": null, "e": 9430, "s": 9396, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 9470, "s": 9430, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 9494, "s": 9470, "text": "Search Algorithms in AI" }, { "code": null, "e": 9532, "s": 9494, "text": "Getting started with Machine Learning" } ]
Find the min/max element of an Array using JavaScript
18 May, 2019 The minimum and maximum element in an array can be found using 2 approaches: Method 1: Using Math.min() and Math.max()The min() and max() methods of the Math object are static functions that return the minimum and maximum element passed to it. These functions could be passed an array with the spread(...) operator. The spread operator allows an iterable to expand in places where multiple arguments are expected. In this case, it automatically expands array and gives the numbers to the functions. Syntax: minValue = Math.min(...array); maxValue = Math.max(...array); Example 1: <!DOCTYPE html><html> <head> <title> Find the min/max element of an Array using JavaScript </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>Find the min/max element of an Array using JavaScript</b> <p>Click on the button below t o find out the minimum and maximum of the array [50, 60, 20, 10, 40]</p> <p>Minimum element is: <span class="min"> </span> <br>Maximum Element is: <span class="max"> </span></p> <button onclick="findMinMax()"> Click to check </button> <script> function findMinMax() { array = [50, 60, 20, 10, 40]; minValue = Math.min(...array); maxValue = Math.max(...array); document.querySelector( '.min').textContent = minValue; document.querySelector( '.max').textContent = maxValue; } </script></body> </html> Output: Before clicking the button: After clicking the button: Method 2: Iterating through the array and keeping track of the minimum and maximum element The minimum and maximum element can be kept track by iterating through all the elements in the array and updating the minimum and maximum element upto that point by comparing them to the current minimum and maximum values. Initially, the minimum and maximum values are initialized to Infinity and -Infinity. Syntax: minValue = Infinity; maxValue = -Infinity; for (item of array) { // find minimum value if (item < minValue) minValue = item; // find maximum value if (item > maxValue) maxValue = item; } Example: <!DOCTYPE html><html> <head> <title> Find the min/max element of an Array using JavaScript </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> Find the min/max element of an Array using JavaScript </b> <p> Click on the button below to find out the minimum and maximum of the array [50, 60, 20, 10, 40] </p> <p>Minimum element is: <span class="min"> </span> <br>Maximum Element is: <span class="max"> </span></p> <button onclick="findMinMax()"> Click to check </button> <script> function findMinMax() { array = [50, 60, 20, 10, 40]; minValue = Infinity; maxValue = -Infinity; for (item of array) { // find minimum value if (item < minValue) minValue = item; // find maximum value if (item > maxValue) maxValue = item; } document.querySelector( '.min').textContent = minValue; document.querySelector( '.max').textContent = maxValue; } </script></body> </html> Output: Before clicking the button: After clicking the button: javascript-array Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n18 May, 2019" }, { "code": null, "e": 130, "s": 53, "text": "The minimum and maximum element in an array can be found using 2 approaches:" }, { "code": null, "e": 552, "s": 130, "text": "Method 1: Using Math.min() and Math.max()The min() and max() methods of the Math object are static functions that return the minimum and maximum element passed to it. These functions could be passed an array with the spread(...) operator. The spread operator allows an iterable to expand in places where multiple arguments are expected. In this case, it automatically expands array and gives the numbers to the functions." }, { "code": null, "e": 560, "s": 552, "text": "Syntax:" }, { "code": null, "e": 622, "s": 560, "text": "minValue = Math.min(...array);\nmaxValue = Math.max(...array);" }, { "code": null, "e": 633, "s": 622, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <title> Find the min/max element of an Array using JavaScript </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>Find the min/max element of an Array using JavaScript</b> <p>Click on the button below t o find out the minimum and maximum of the array [50, 60, 20, 10, 40]</p> <p>Minimum element is: <span class=\"min\"> </span> <br>Maximum Element is: <span class=\"max\"> </span></p> <button onclick=\"findMinMax()\"> Click to check </button> <script> function findMinMax() { array = [50, 60, 20, 10, 40]; minValue = Math.min(...array); maxValue = Math.max(...array); document.querySelector( '.min').textContent = minValue; document.querySelector( '.max').textContent = maxValue; } </script></body> </html>", "e": 1576, "s": 633, "text": null }, { "code": null, "e": 1584, "s": 1576, "text": "Output:" }, { "code": null, "e": 1612, "s": 1584, "text": "Before clicking the button:" }, { "code": null, "e": 1639, "s": 1612, "text": "After clicking the button:" }, { "code": null, "e": 1730, "s": 1639, "text": "Method 2: Iterating through the array and keeping track of the minimum and maximum element" }, { "code": null, "e": 2038, "s": 1730, "text": "The minimum and maximum element can be kept track by iterating through all the elements in the array and updating the minimum and maximum element upto that point by comparing them to the current minimum and maximum values. Initially, the minimum and maximum values are initialized to Infinity and -Infinity." }, { "code": null, "e": 2046, "s": 2038, "text": "Syntax:" }, { "code": null, "e": 2275, "s": 2046, "text": "minValue = Infinity;\nmaxValue = -Infinity;\n\nfor (item of array) {\n // find minimum value\n if (item < minValue)\n minValue = item;\n \n // find maximum value\n if (item > maxValue)\n maxValue = item;\n}" }, { "code": null, "e": 2284, "s": 2275, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> Find the min/max element of an Array using JavaScript </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> Find the min/max element of an Array using JavaScript </b> <p> Click on the button below to find out the minimum and maximum of the array [50, 60, 20, 10, 40] </p> <p>Minimum element is: <span class=\"min\"> </span> <br>Maximum Element is: <span class=\"max\"> </span></p> <button onclick=\"findMinMax()\"> Click to check </button> <script> function findMinMax() { array = [50, 60, 20, 10, 40]; minValue = Infinity; maxValue = -Infinity; for (item of array) { // find minimum value if (item < minValue) minValue = item; // find maximum value if (item > maxValue) maxValue = item; } document.querySelector( '.min').textContent = minValue; document.querySelector( '.max').textContent = maxValue; } </script></body> </html>", "e": 3490, "s": 2284, "text": null }, { "code": null, "e": 3498, "s": 3490, "text": "Output:" }, { "code": null, "e": 3526, "s": 3498, "text": "Before clicking the button:" }, { "code": null, "e": 3553, "s": 3526, "text": "After clicking the button:" }, { "code": null, "e": 3570, "s": 3553, "text": "javascript-array" }, { "code": null, "e": 3577, "s": 3570, "text": "Picked" }, { "code": null, "e": 3588, "s": 3577, "text": "JavaScript" }, { "code": null, "e": 3605, "s": 3588, "text": "Web Technologies" } ]
Python | Remove all digits from a list of strings
11 Feb, 2019 Given a list of strings, write a Python program to remove all digits from the list of string. Examples: Input : ['alice1', 'bob2', 'cara3'] Output : ['alice', 'bob', 'cara'] Input : ['4geeks', '3for', '4geeks'] Output : ['geeks', 'for', 'geeks'] Method #1 : Python Regex Python regex pattern can also be used to find if each string contains a digit or not and converting them to “”. # Python program to Remove all # digits from a list of stringimport re def remove(list): pattern = '[0-9]' list = [re.sub(pattern, '', i) for i in list] return list # Driver code list = ['4geeks', '3for', '4geeks']print(remove(list)) ['geeks', 'for', 'geeks'] Method #2 : Using str.maketrans() methodThe maketrans() method returns a translation table that maps each character in the intabstring into the character at the same position in the outtab string. In this particular problem we translate each each digit to “” using for loop. # Python program to Remove all # digits from a list of stringfrom string import digits def remove(list): remove_digits = str.maketrans('', '', digits) list = [i.translate(remove_digits) for i in list] return list # Driver code list = ['4geeks', '3for', '4geeks']print(remove(list)) ['geeks', 'for', 'geeks'] Method #3 : Using str.isalpha() methodIn ,this approach we use two for loops and check if the character of string is an alphabet or not. If yes, join it within the list, otherwise leave it. # Python program to Remove all # digits from a list of stringfrom string import digits def remove(list): list = [''.join(x for x in i if x.isalpha()) for i in list] return list # Driver code list = ['4geeks', '3for', '4geeks']print(remove(list)) ['geeks', 'for', 'geeks'] Python list-programs python-list Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() 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 | Convert string dictionary to dictionary
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Feb, 2019" }, { "code": null, "e": 147, "s": 53, "text": "Given a list of strings, write a Python program to remove all digits from the list of string." }, { "code": null, "e": 157, "s": 147, "text": "Examples:" }, { "code": null, "e": 301, "s": 157, "text": "Input : ['alice1', 'bob2', 'cara3']\nOutput : ['alice', 'bob', 'cara']\n\nInput : ['4geeks', '3for', '4geeks']\nOutput : ['geeks', 'for', 'geeks']\n" }, { "code": null, "e": 328, "s": 303, "text": "Method #1 : Python Regex" }, { "code": null, "e": 440, "s": 328, "text": "Python regex pattern can also be used to find if each string contains a digit or not and converting them to “”." }, { "code": "# Python program to Remove all # digits from a list of stringimport re def remove(list): pattern = '[0-9]' list = [re.sub(pattern, '', i) for i in list] return list # Driver code list = ['4geeks', '3for', '4geeks']print(remove(list))", "e": 687, "s": 440, "text": null }, { "code": null, "e": 714, "s": 687, "text": "['geeks', 'for', 'geeks']\n" }, { "code": null, "e": 990, "s": 714, "text": " Method #2 : Using str.maketrans() methodThe maketrans() method returns a translation table that maps each character in the intabstring into the character at the same position in the outtab string. In this particular problem we translate each each digit to “” using for loop." }, { "code": "# Python program to Remove all # digits from a list of stringfrom string import digits def remove(list): remove_digits = str.maketrans('', '', digits) list = [i.translate(remove_digits) for i in list] return list # Driver code list = ['4geeks', '3for', '4geeks']print(remove(list))", "e": 1285, "s": 990, "text": null }, { "code": null, "e": 1312, "s": 1285, "text": "['geeks', 'for', 'geeks']\n" }, { "code": null, "e": 1503, "s": 1312, "text": " Method #3 : Using str.isalpha() methodIn ,this approach we use two for loops and check if the character of string is an alphabet or not. If yes, join it within the list, otherwise leave it." }, { "code": "# Python program to Remove all # digits from a list of stringfrom string import digits def remove(list): list = [''.join(x for x in i if x.isalpha()) for i in list] return list # Driver code list = ['4geeks', '3for', '4geeks']print(remove(list))", "e": 1773, "s": 1503, "text": null }, { "code": null, "e": 1800, "s": 1773, "text": "['geeks', 'for', 'geeks']\n" }, { "code": null, "e": 1821, "s": 1800, "text": "Python list-programs" }, { "code": null, "e": 1833, "s": 1821, "text": "python-list" }, { "code": null, "e": 1840, "s": 1833, "text": "Python" }, { "code": null, "e": 1856, "s": 1840, "text": "Python Programs" }, { "code": null, "e": 1868, "s": 1856, "text": "python-list" }, { "code": null, "e": 1966, "s": 1868, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1984, "s": 1966, "text": "Python Dictionary" }, { "code": null, "e": 2026, "s": 1984, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2048, "s": 2026, "text": "Enumerate() in Python" }, { "code": null, "e": 2083, "s": 2048, "text": "Read a file line by line in Python" }, { "code": null, "e": 2109, "s": 2083, "text": "Python String | replace()" }, { "code": null, "e": 2152, "s": 2109, "text": "Python program to convert a list to string" }, { "code": null, "e": 2174, "s": 2152, "text": "Defaultdict in Python" }, { "code": null, "e": 2213, "s": 2174, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2251, "s": 2213, "text": "Python | Convert a list to dictionary" } ]
Maximum weighted edge in path between two nodes in an N-ary tree using binary lifting
19 Apr, 2022 Given an N-ary tree with weighted edge and Q queries where each query contains two nodes of the tree. The task is to find the maximum weighted edge in the simple path between these two nodes.Examples: Naive Approach: A simple solution is to traverse the whole tree for each query and find the path between the two nodes.Efficient Approach: The idea is to use binary lifting to pre-compute the maximum weighted edge from every node to every other node at distance of some . We will store the maximum weighted edge till level. and where j is the node and i is the distance of dp[i][j] stores the parent of j at distance if present, else it will store 0 mx[i][j] stores the maximum edge from node j to the parent of this node at distance. We’ll do a depth-first search to find all the parents at distance and their weight and then precompute parents and maximum edges at every distance.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find the// maximum weighted edge in the simple// path between two nodes in N-ary Tree #include <bits/stdc++.h> using namespace std; const int N = 100005; // Depths of Nodesvector<int> level(N);const int LG = 20; // Parent at every 2^i levelvector<vector<int> > dp(LG, vector<int>(N)); // Maximum node at every 2^i levelvector<vector<int> > mx(LG, vector<int>(N)); // Graph that stores destinations// and its weightvector<vector<pair<int, int> > > v(N);int n; // Function to traverse the nodes// using the Depth-First Search Traversalvoid dfs_lca(int a, int par, int lev){ dp[0][a] = par; level[a] = lev; for (auto i : v[a]) { // Condition to check if its // equal to its parent then skip if (i.first == par) continue; mx[0][i.first] = i.second; // DFS Recursive Call dfs_lca(i.first, a, lev + 1); }} // Function to find the ancestorvoid find_ancestor(){ // Loop to set every 2^i distance for (int i = 1; i < LG; i++) { // Loop to calculate for // each node in the N-ary tree for (int j = 1; j <= n; j++) { dp[i][j] = dp[i - 1][dp[i - 1][j]]; // Storing maximum edge mx[i][j] = max(mx[i - 1][j], mx[i - 1][dp[i - 1][j]]); } }} int getMax(int a, int b){ // Swaping if node a is at more depth // than node b because we will // always take at more depth if (level[b] < level[a]) swap(a, b); int ans = 0; // Difference between the depth of // the two given nodes int diff = level[b] - level[a]; while (diff > 0) { int log = log2(diff); ans = max(ans, mx[log][b]); // Changing Node B to its // parent at 2 ^ i distance b = dp[log][b]; // Subtracting distance by 2^i diff -= (1 << log); } // Take both a, b to its // lca and find maximum while (a != b) { int i = log2(level[a]); // Loop to find the 2^ith // parent that is different // for both a and b i.e below the lca while (i > 0 && dp[i][a] == dp[i][b]) i--; // Updating ans ans = max(ans, mx[i][a]); ans = max(ans, mx[i][b]); // Changing value to its parent a = dp[i][a]; b = dp[i][b]; } return ans;} // Function to compute the Least// common Ancestorvoid compute_lca(){ dfs_lca(1, 0, 0); find_ancestor();} // Driver Codeint main(){ // Undirected tree n = 5; v[1].push_back(make_pair(2, 2)); v[2].push_back(make_pair(1, 2)); v[1].push_back(make_pair(3, 5)); v[3].push_back(make_pair(1, 5)); v[3].push_back(make_pair(4, 3)); v[4].push_back(make_pair(3, 4)); v[3].push_back(make_pair(5, 1)); v[5].push_back(make_pair(3, 1)); // Computing LCA compute_lca(); int queries[][2] = { { 3, 5 }, { 2, 3 }, { 2, 4 } }; int q = 3; for (int i = 0; i < q; i++) { int max_edge = getMax(queries[i][0], queries[i][1]); cout << max_edge << endl; } return 0;} // Java implementation to find the// maximum weighted edge in the simple// path between two nodes in N-ary Treeimport java.util.*;import java.awt.Point;public class Main{ static int N = 100005; // Depths of Nodes static int[] level = new int[N]; static int LG = 20; // Parent at every 2^i level static int[][] dp = new int[LG][N]; // Maximum node at every 2^i level static int[][] mx = new int[LG][N]; // Graph that stores destinations // and its weight static Vector<Vector<Point>> v = new Vector<Vector<Point>>(); static int n = 0; // Function to traverse the // nodes using the Depth-First // Search Traversal static void dfs_lca(int a, int par, int lev) { dp[0][a] = par; level[a] = lev; for(int i = 0; i < v.get(a).size(); i++) { // Condition to check // if its equal to its // parent then skip if (v.get(a).get(i).x == par) continue; mx[0][v.get(a).get(i).x] = v.get(a).get(i).y; // DFS Recursive Call dfs_lca(v.get(a).get(i).x, a, lev + 1); } } // Function to find the ancestor static void find_ancestor() { // Loop to set every 2^i distance for(int i = 1; i < 16; i++) { // Loop to calculate for // each node in the N-ary tree for(int j = 1; j < n + 1; j++) { dp[i][j] = dp[i - 1][dp[i - 1][j]]; // Storing maximum edge mx[i][j] = Math.max(mx[i - 1][j], mx[i - 1][dp[i - 1][j]]); } } } static int getMax(int a, int b) { // Swaping if node a is at more depth // than node b because we will // always take at more depth if (level[b] < level[a]) { int temp = a; a = b; b = temp; } int ans = 0; // Difference between the // depth of the two given // nodes int diff = level[b] - level[a]; while (diff > 0) { int log = (int)(Math.log(diff) / Math.log(2)); ans = Math.max(ans, mx[log][b]); // Changing Node B to its // parent at 2 ^ i distance b = dp[log][b]; // Subtracting distance by 2^i diff -= (1 << log); } // Take both a, b to its // lca and find maximum while (a != b) { int i = (int)(Math.log(level[a]) / Math.log(2)); // Loop to find the maximum 2^ith // parent the is different // for both a and b while (i > 0 && dp[i][a] == dp[i][b]) { i-=1; } // Updating ans ans = Math.max(ans, mx[i][a]); ans = Math.max(ans, mx[i][b]); // Changing value to // its parent a = dp[i][a]; b = dp[i][b]; } return ans; } // Function to compute the Least // common Ancestor static void compute_lca() { dfs_lca(1, 0, 0); find_ancestor(); } public static void main(String[] args) { for(int i = 0; i < LG; i++) { for(int j = 0; j < N; j++) { dp[i][j] = 0; mx[i][j] = 0; } } for(int i = 0; i < N; i++) { v.add(new Vector<Point>()); } // Undirected tree v.get(1).add(new Point(2, 2)); v.get(2).add(new Point(1, 2)); v.get(1).add(new Point(3, 5)); v.get(3).add(new Point(1, 5)); v.get(3).add(new Point(4, 3)); v.get(4).add(new Point(3, 4)); v.get(3).add(new Point(5, 1)); v.get(5).add(new Point(3, 1)); // Computing LCA compute_lca(); int[][] queries = { { 3, 5 }, { 2, 3 }, { 2, 4 } }; int q = 3; for (int i = 0; i < q; i++) { int max_edge = getMax(queries[i][0], queries[i][1]); System.out.println(max_edge); } }} // This code is contributed by decode2207. # Python3 implementation to# find the maximum weighted# edge in the simple path# between two nodes in N-ary Treeimport mathN = 100005; # Depths of Nodeslevel = [0 for i in range(N)]LG = 20; # Parent at every 2^i leveldp = [[0 for j in range(N)] for i in range(LG)] # Maximum node at every 2^i levelmx = [[0 for j in range(N)] for i in range(LG)] # Graph that stores destinations# and its weightv = [[] for i in range(N)]n = 0 # Function to traverse the# nodes using the Depth-First# Search Traversaldef dfs_lca(a, par, lev): dp[0][a] = par; level[a] = lev; for i in v[a]: # Condition to check # if its equal to its # parent then skip if (i[0] == par): continue; mx[0][i[0]] = i[1]; # DFS Recursive Call dfs_lca(i[0], a, lev + 1); # Function to find the ancestordef find_ancestor(): # Loop to set every 2^i distance for i in range(1, 16): # Loop to calculate for # each node in the N-ary tree for j in range(1, n + 1): dp[i][j] = dp[i - 1][dp[i - 1][j]]; # Storing maximum edge mx[i][j] = max(mx[i - 1][j], mx[i - 1][dp[i - 1][j]]); def getMax(a, b): # Swaping if node a is at more depth # than node b because we will # always take at more depth if (level[b] < level[a]): a, b = b, a ans = 0; # Difference between the # depth of the two given # nodes diff = level[b] - level[a]; while (diff > 0): log = int(math.log2(diff)); ans = max(ans, mx[log][b]); # Changing Node B to its # parent at 2 ^ i distance b = dp[log][b]; # Subtracting distance by 2^i diff -= (1 << log); # Take both a, b to its # lca and find maximum while (a != b): i = int(math.log2(level[a])); # Loop to find the maximum 2^ith # parent the is different # for both a and b while (i > 0 and dp[i][a] == dp[i][b]): i-=1 # Updating ans ans = max(ans, mx[i][a]); ans = max(ans, mx[i][b]); # Changing value to # its parent a = dp[i][a]; b = dp[i][b]; return ans; # Function to compute the Least# common Ancestordef compute_lca(): dfs_lca(1, 0, 0); find_ancestor(); # Driver codeif __name__=="__main__": # Undirected tree n = 5; v[1].append([2, 2]); v[2].append([1, 2]); v[1].append([3, 5]); v[3].append([1, 5]); v[3].append([4, 3]); v[4].append([3, 4]); v[3].append([5, 1]); v[5].append([3, 1]); # Computing LCA compute_lca(); queries= [[3, 5], [2, 3], [2,4]] q = 3; for i in range(q): max_edge = getMax(queries[i][0], queries[i][1]); print(max_edge) # This code is contributed by Rutvik_56 // C# implementation to find the// maximum weighted edge in the simple// path between two nodes in N-ary Treeusing System;using System.Collections.Generic;class GFG { static int N = 100005; // Depths of Nodes static int[] level = new int[N]; static int LG = 20; // Parent at every 2^i level static int[,] dp = new int[LG, N]; // Maximum node at every 2^i level static int[,] mx = new int[LG, N]; // Graph that stores destinations // and its weight static List<List<Tuple<int,int>>> v = new List<List<Tuple<int,int>>>(); static int n = 0; // Function to traverse the // nodes using the Depth-First // Search Traversal static void dfs_lca(int a, int par, int lev) { dp[0,a] = par; level[a] = lev; for(int i = 0; i < v[a].Count; i++) { // Condition to check // if its equal to its // parent then skip if (v[a][i].Item1 == par) continue; mx[0,v[a][i].Item1] = v[a][i].Item2; // DFS Recursive Call dfs_lca(v[a][i].Item1, a, lev + 1); } } // Function to find the ancestor static void find_ancestor() { // Loop to set every 2^i distance for(int i = 1; i < 16; i++) { // Loop to calculate for // each node in the N-ary tree for(int j = 1; j < n + 1; j++) { dp[i,j] = dp[i - 1,dp[i - 1,j]]; // Storing maximum edge mx[i,j] = Math.Max(mx[i - 1,j], mx[i - 1,dp[i - 1,j]]); } } } static int getMax(int a, int b) { // Swaping if node a is at more depth // than node b because we will // always take at more depth if (level[b] < level[a]) { int temp = a; a = b; b = temp; } int ans = 0; // Difference between the // depth of the two given // nodes int diff = level[b] - level[a]; while (diff > 0) { int log = (int)(Math.Log(diff) / Math.Log(2)); ans = Math.Max(ans, mx[log,b]); // Changing Node B to its // parent at 2 ^ i distance b = dp[log,b]; // Subtracting distance by 2^i diff -= (1 << log); } // Take both a, b to its // lca and find maximum while (a != b) { int i = (int)(Math.Log(level[a]) / Math.Log(2)); // Loop to find the maximum 2^ith // parent the is different // for both a and b while (i > 0 && dp[i,a] == dp[i,b]) { i-=1; } // Updating ans ans = Math.Max(ans, mx[i,a]); ans = Math.Max(ans, mx[i,b]); // Changing value to // its parent a = dp[i,a]; b = dp[i,b]; } return ans; } // Function to compute the Least // common Ancestor static void compute_lca() { dfs_lca(1, 0, 0); find_ancestor(); } static void Main() { for(int i = 0; i < LG; i++) { for(int j = 0; j < N; j++) { dp[i,j] = 0; mx[i,j] = 0; } } for(int i = 0; i < N; i++) { v.Add(new List<Tuple<int,int>>()); } // Undirected tree v[1].Add(new Tuple<int,int>(2, 2)); v[2].Add(new Tuple<int,int>(1, 2)); v[1].Add(new Tuple<int,int>(3, 5)); v[3].Add(new Tuple<int,int>(1, 5)); v[3].Add(new Tuple<int,int>(4, 3)); v[4].Add(new Tuple<int,int>(3, 4)); v[3].Add(new Tuple<int,int>(5, 1)); v[5].Add(new Tuple<int,int>(3, 1)); // Computing LCA compute_lca(); int[,] queries = { { 3, 5 }, { 2, 3 }, { 2, 4 } }; int q = 3; for (int i = 0; i < q; i++) { int max_edge = getMax(queries[i,0], queries[i,1]); Console.WriteLine(max_edge); } }} // This code is contributed by divyesh072019. <script> // Javascript implementation to find the // maximum weighted edge in the simple // path between two nodes in N-ary Tree let N = 100005; // Depths of Nodes let level = new Array(N); level.fill(0); let LG = 20; // Parent at every 2^i level let dp = new Array(LG); for(let i = 0; i < LG; i++) { dp[i] = new Array(N); for(let j = 0; j < N; j++) { dp[i][j] = 0; } } // Maximum node at every 2^i level let mx = new Array(LG); for(let i = 0; i < LG; i++) { mx[i] = new Array(N); for(let j = 0; j < N; j++) { mx[i][j] = 0; } } // Graph that stores destinations // and its weight let v = []; for(let i = 0; i < N; i++) { v.push([]); } let n = 0; // Function to traverse the // nodes using the Depth-First // Search Traversal function dfs_lca(a, par, lev) { dp[0][a] = par; level[a] = lev; for(let i = 0; i < 2; i++) { // Condition to check // if its equal to its // parent then skip if (v[a][0] == par) continue; mx[0][v[a][0]] = v[a][1]; // DFS Recursive Call dfs_lca(v[a][0], a, lev + 1); } } // Function to find the ancestor function find_ancestor() { // Loop to set every 2^i distance for(let i = 1; i < 16; i++) { // Loop to calculate for // each node in the N-ary tree for(let j = 1; j < n + 1; j++) { dp[i][j] = dp[i - 1][dp[i - 1][j]]; // Storing maximum edge mx[i][j] = Math.max(mx[i - 1][j], mx[i - 1][dp[i - 1][j]]); } } } function getMax(a, b) { // Swaping if node a is at more depth // than node b because we will // always take at more depth if (level[b] < level[a]) { let temp = a; a = b; b = temp; } let ans = 0; // Difference between the // depth of the two given // nodes let diff = level[b] - level[a]; while (diff > 0) { let log = parseInt(Math.log(diff) / Math.log(2), 10); ans = Math.max(ans, mx[log][b]); // Changing Node B to its // parent at 2 ^ i distance b = dp[log][b]; // Subtracting distance by 2^i diff -= (1 << log); } // Take both a, b to its // lca and find maximum while (a == b) { i = parseInt(Math.log(level[a]) / Math.log(2), 10); // Loop to find the maximum 2^ith // parent the is different // for both a and b while (i > 0 && dp[i][a] == dp[i][b]) { i-=1; } // Updating ans ans = Math.max(ans, mx[i][a]); ans = Math.max(ans, mx[i][b]); // Changing value to // its parent a = dp[i][a]; b = dp[i][b]; } return ans*2 + 1; } // Function to compute the Least // common Ansector function compute_lca() { dfs_lca(1, 0, 0); find_ancestor(); } // Undirected tree n = 5; v[1].push(2); v[1].push(2); v[2].push(1); v[2].push(2); v[1].push(3); v[1].push(5); v[3].push(1); v[3].push(5); v[3].push(4); v[3].push(3); v[4].push(3); v[4].push(4); v[3].push(5); v[3].push(1); v[5].push(3); v[5].push(1); // Computing LCA compute_lca(); let queries= [[3, 5], [2, 3], [2,4]]; let q = 3; for(let i = 0; i <q; i++) { let max_edge = getMax(queries[i][0], queries[i][1]); document.write(max_edge + "</br>"); } // This code is contributed by suresh07.</script> 1 5 5 Time Complexity: O(N*logN).Auxiliary Space: O(N*logN). rutvik_56 abhishek0719kadiyan pankajsharmagfg suresh07 divyesh072019 deepakchowdary decode2207 surindertarika1234 simmytarika5 array-range-queries DFS n-ary-tree Algorithms Bit Magic Competitive Programming Dynamic Programming Tree Dynamic Programming Bit Magic DFS Tree Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation What is Hashing | A Complete Tutorial Understanding Time Complexity with Simple Examples CPU Scheduling in Operating Systems Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer How to swap two numbers without using a temporary variable?
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Apr, 2022" }, { "code": null, "e": 257, "s": 54, "text": "Given an N-ary tree with weighted edge and Q queries where each query contains two nodes of the tree. The task is to find the maximum weighted edge in the simple path between these two nodes.Examples: " }, { "code": null, "e": 528, "s": 257, "text": "Naive Approach: A simple solution is to traverse the whole tree for each query and find the path between the two nodes.Efficient Approach: The idea is to use binary lifting to pre-compute the maximum weighted edge from every node to every other node at distance of some " }, { "code": null, "e": 576, "s": 528, "text": ". We will store the maximum weighted edge till " }, { "code": null, "e": 584, "s": 576, "text": "level. " }, { "code": null, "e": 591, "s": 586, "text": "and " }, { "code": null, "e": 598, "s": 591, "text": "where " }, { "code": null, "e": 616, "s": 598, "text": "j is the node and" }, { "code": null, "e": 637, "s": 616, "text": "i is the distance of" }, { "code": null, "e": 672, "s": 637, "text": "dp[i][j] stores the parent of j at" }, { "code": null, "e": 714, "s": 672, "text": "distance if present, else it will store 0" }, { "code": null, "e": 789, "s": 714, "text": "mx[i][j] stores the maximum edge from node j to the parent of this node at" }, { "code": null, "e": 799, "s": 789, "text": "distance." }, { "code": null, "e": 857, "s": 799, "text": "We’ll do a depth-first search to find all the parents at " }, { "code": null, "e": 939, "s": 857, "text": "distance and their weight and then precompute parents and maximum edges at every " }, { "code": null, "e": 999, "s": 939, "text": "distance.Below is the implementation of the above approach:" }, { "code": null, "e": 1003, "s": 999, "text": "C++" }, { "code": null, "e": 1008, "s": 1003, "text": "Java" }, { "code": null, "e": 1016, "s": 1008, "text": "Python3" }, { "code": null, "e": 1019, "s": 1016, "text": "C#" }, { "code": null, "e": 1030, "s": 1019, "text": "Javascript" }, { "code": "// C++ implementation to find the// maximum weighted edge in the simple// path between two nodes in N-ary Tree #include <bits/stdc++.h> using namespace std; const int N = 100005; // Depths of Nodesvector<int> level(N);const int LG = 20; // Parent at every 2^i levelvector<vector<int> > dp(LG, vector<int>(N)); // Maximum node at every 2^i levelvector<vector<int> > mx(LG, vector<int>(N)); // Graph that stores destinations// and its weightvector<vector<pair<int, int> > > v(N);int n; // Function to traverse the nodes// using the Depth-First Search Traversalvoid dfs_lca(int a, int par, int lev){ dp[0][a] = par; level[a] = lev; for (auto i : v[a]) { // Condition to check if its // equal to its parent then skip if (i.first == par) continue; mx[0][i.first] = i.second; // DFS Recursive Call dfs_lca(i.first, a, lev + 1); }} // Function to find the ancestorvoid find_ancestor(){ // Loop to set every 2^i distance for (int i = 1; i < LG; i++) { // Loop to calculate for // each node in the N-ary tree for (int j = 1; j <= n; j++) { dp[i][j] = dp[i - 1][dp[i - 1][j]]; // Storing maximum edge mx[i][j] = max(mx[i - 1][j], mx[i - 1][dp[i - 1][j]]); } }} int getMax(int a, int b){ // Swaping if node a is at more depth // than node b because we will // always take at more depth if (level[b] < level[a]) swap(a, b); int ans = 0; // Difference between the depth of // the two given nodes int diff = level[b] - level[a]; while (diff > 0) { int log = log2(diff); ans = max(ans, mx[log][b]); // Changing Node B to its // parent at 2 ^ i distance b = dp[log][b]; // Subtracting distance by 2^i diff -= (1 << log); } // Take both a, b to its // lca and find maximum while (a != b) { int i = log2(level[a]); // Loop to find the 2^ith // parent that is different // for both a and b i.e below the lca while (i > 0 && dp[i][a] == dp[i][b]) i--; // Updating ans ans = max(ans, mx[i][a]); ans = max(ans, mx[i][b]); // Changing value to its parent a = dp[i][a]; b = dp[i][b]; } return ans;} // Function to compute the Least// common Ancestorvoid compute_lca(){ dfs_lca(1, 0, 0); find_ancestor();} // Driver Codeint main(){ // Undirected tree n = 5; v[1].push_back(make_pair(2, 2)); v[2].push_back(make_pair(1, 2)); v[1].push_back(make_pair(3, 5)); v[3].push_back(make_pair(1, 5)); v[3].push_back(make_pair(4, 3)); v[4].push_back(make_pair(3, 4)); v[3].push_back(make_pair(5, 1)); v[5].push_back(make_pair(3, 1)); // Computing LCA compute_lca(); int queries[][2] = { { 3, 5 }, { 2, 3 }, { 2, 4 } }; int q = 3; for (int i = 0; i < q; i++) { int max_edge = getMax(queries[i][0], queries[i][1]); cout << max_edge << endl; } return 0;}", "e": 4178, "s": 1030, "text": null }, { "code": "// Java implementation to find the// maximum weighted edge in the simple// path between two nodes in N-ary Treeimport java.util.*;import java.awt.Point;public class Main{ static int N = 100005; // Depths of Nodes static int[] level = new int[N]; static int LG = 20; // Parent at every 2^i level static int[][] dp = new int[LG][N]; // Maximum node at every 2^i level static int[][] mx = new int[LG][N]; // Graph that stores destinations // and its weight static Vector<Vector<Point>> v = new Vector<Vector<Point>>(); static int n = 0; // Function to traverse the // nodes using the Depth-First // Search Traversal static void dfs_lca(int a, int par, int lev) { dp[0][a] = par; level[a] = lev; for(int i = 0; i < v.get(a).size(); i++) { // Condition to check // if its equal to its // parent then skip if (v.get(a).get(i).x == par) continue; mx[0][v.get(a).get(i).x] = v.get(a).get(i).y; // DFS Recursive Call dfs_lca(v.get(a).get(i).x, a, lev + 1); } } // Function to find the ancestor static void find_ancestor() { // Loop to set every 2^i distance for(int i = 1; i < 16; i++) { // Loop to calculate for // each node in the N-ary tree for(int j = 1; j < n + 1; j++) { dp[i][j] = dp[i - 1][dp[i - 1][j]]; // Storing maximum edge mx[i][j] = Math.max(mx[i - 1][j], mx[i - 1][dp[i - 1][j]]); } } } static int getMax(int a, int b) { // Swaping if node a is at more depth // than node b because we will // always take at more depth if (level[b] < level[a]) { int temp = a; a = b; b = temp; } int ans = 0; // Difference between the // depth of the two given // nodes int diff = level[b] - level[a]; while (diff > 0) { int log = (int)(Math.log(diff) / Math.log(2)); ans = Math.max(ans, mx[log][b]); // Changing Node B to its // parent at 2 ^ i distance b = dp[log][b]; // Subtracting distance by 2^i diff -= (1 << log); } // Take both a, b to its // lca and find maximum while (a != b) { int i = (int)(Math.log(level[a]) / Math.log(2)); // Loop to find the maximum 2^ith // parent the is different // for both a and b while (i > 0 && dp[i][a] == dp[i][b]) { i-=1; } // Updating ans ans = Math.max(ans, mx[i][a]); ans = Math.max(ans, mx[i][b]); // Changing value to // its parent a = dp[i][a]; b = dp[i][b]; } return ans; } // Function to compute the Least // common Ancestor static void compute_lca() { dfs_lca(1, 0, 0); find_ancestor(); } public static void main(String[] args) { for(int i = 0; i < LG; i++) { for(int j = 0; j < N; j++) { dp[i][j] = 0; mx[i][j] = 0; } } for(int i = 0; i < N; i++) { v.add(new Vector<Point>()); } // Undirected tree v.get(1).add(new Point(2, 2)); v.get(2).add(new Point(1, 2)); v.get(1).add(new Point(3, 5)); v.get(3).add(new Point(1, 5)); v.get(3).add(new Point(4, 3)); v.get(4).add(new Point(3, 4)); v.get(3).add(new Point(5, 1)); v.get(5).add(new Point(3, 1)); // Computing LCA compute_lca(); int[][] queries = { { 3, 5 }, { 2, 3 }, { 2, 4 } }; int q = 3; for (int i = 0; i < q; i++) { int max_edge = getMax(queries[i][0], queries[i][1]); System.out.println(max_edge); } }} // This code is contributed by decode2207.", "e": 8439, "s": 4178, "text": null }, { "code": "# Python3 implementation to# find the maximum weighted# edge in the simple path# between two nodes in N-ary Treeimport mathN = 100005; # Depths of Nodeslevel = [0 for i in range(N)]LG = 20; # Parent at every 2^i leveldp = [[0 for j in range(N)] for i in range(LG)] # Maximum node at every 2^i levelmx = [[0 for j in range(N)] for i in range(LG)] # Graph that stores destinations# and its weightv = [[] for i in range(N)]n = 0 # Function to traverse the# nodes using the Depth-First# Search Traversaldef dfs_lca(a, par, lev): dp[0][a] = par; level[a] = lev; for i in v[a]: # Condition to check # if its equal to its # parent then skip if (i[0] == par): continue; mx[0][i[0]] = i[1]; # DFS Recursive Call dfs_lca(i[0], a, lev + 1); # Function to find the ancestordef find_ancestor(): # Loop to set every 2^i distance for i in range(1, 16): # Loop to calculate for # each node in the N-ary tree for j in range(1, n + 1): dp[i][j] = dp[i - 1][dp[i - 1][j]]; # Storing maximum edge mx[i][j] = max(mx[i - 1][j], mx[i - 1][dp[i - 1][j]]); def getMax(a, b): # Swaping if node a is at more depth # than node b because we will # always take at more depth if (level[b] < level[a]): a, b = b, a ans = 0; # Difference between the # depth of the two given # nodes diff = level[b] - level[a]; while (diff > 0): log = int(math.log2(diff)); ans = max(ans, mx[log][b]); # Changing Node B to its # parent at 2 ^ i distance b = dp[log][b]; # Subtracting distance by 2^i diff -= (1 << log); # Take both a, b to its # lca and find maximum while (a != b): i = int(math.log2(level[a])); # Loop to find the maximum 2^ith # parent the is different # for both a and b while (i > 0 and dp[i][a] == dp[i][b]): i-=1 # Updating ans ans = max(ans, mx[i][a]); ans = max(ans, mx[i][b]); # Changing value to # its parent a = dp[i][a]; b = dp[i][b]; return ans; # Function to compute the Least# common Ancestordef compute_lca(): dfs_lca(1, 0, 0); find_ancestor(); # Driver codeif __name__==\"__main__\": # Undirected tree n = 5; v[1].append([2, 2]); v[2].append([1, 2]); v[1].append([3, 5]); v[3].append([1, 5]); v[3].append([4, 3]); v[4].append([3, 4]); v[3].append([5, 1]); v[5].append([3, 1]); # Computing LCA compute_lca(); queries= [[3, 5], [2, 3], [2,4]] q = 3; for i in range(q): max_edge = getMax(queries[i][0], queries[i][1]); print(max_edge) # This code is contributed by Rutvik_56", "e": 11353, "s": 8439, "text": null }, { "code": "// C# implementation to find the// maximum weighted edge in the simple// path between two nodes in N-ary Treeusing System;using System.Collections.Generic;class GFG { static int N = 100005; // Depths of Nodes static int[] level = new int[N]; static int LG = 20; // Parent at every 2^i level static int[,] dp = new int[LG, N]; // Maximum node at every 2^i level static int[,] mx = new int[LG, N]; // Graph that stores destinations // and its weight static List<List<Tuple<int,int>>> v = new List<List<Tuple<int,int>>>(); static int n = 0; // Function to traverse the // nodes using the Depth-First // Search Traversal static void dfs_lca(int a, int par, int lev) { dp[0,a] = par; level[a] = lev; for(int i = 0; i < v[a].Count; i++) { // Condition to check // if its equal to its // parent then skip if (v[a][i].Item1 == par) continue; mx[0,v[a][i].Item1] = v[a][i].Item2; // DFS Recursive Call dfs_lca(v[a][i].Item1, a, lev + 1); } } // Function to find the ancestor static void find_ancestor() { // Loop to set every 2^i distance for(int i = 1; i < 16; i++) { // Loop to calculate for // each node in the N-ary tree for(int j = 1; j < n + 1; j++) { dp[i,j] = dp[i - 1,dp[i - 1,j]]; // Storing maximum edge mx[i,j] = Math.Max(mx[i - 1,j], mx[i - 1,dp[i - 1,j]]); } } } static int getMax(int a, int b) { // Swaping if node a is at more depth // than node b because we will // always take at more depth if (level[b] < level[a]) { int temp = a; a = b; b = temp; } int ans = 0; // Difference between the // depth of the two given // nodes int diff = level[b] - level[a]; while (diff > 0) { int log = (int)(Math.Log(diff) / Math.Log(2)); ans = Math.Max(ans, mx[log,b]); // Changing Node B to its // parent at 2 ^ i distance b = dp[log,b]; // Subtracting distance by 2^i diff -= (1 << log); } // Take both a, b to its // lca and find maximum while (a != b) { int i = (int)(Math.Log(level[a]) / Math.Log(2)); // Loop to find the maximum 2^ith // parent the is different // for both a and b while (i > 0 && dp[i,a] == dp[i,b]) { i-=1; } // Updating ans ans = Math.Max(ans, mx[i,a]); ans = Math.Max(ans, mx[i,b]); // Changing value to // its parent a = dp[i,a]; b = dp[i,b]; } return ans; } // Function to compute the Least // common Ancestor static void compute_lca() { dfs_lca(1, 0, 0); find_ancestor(); } static void Main() { for(int i = 0; i < LG; i++) { for(int j = 0; j < N; j++) { dp[i,j] = 0; mx[i,j] = 0; } } for(int i = 0; i < N; i++) { v.Add(new List<Tuple<int,int>>()); } // Undirected tree v[1].Add(new Tuple<int,int>(2, 2)); v[2].Add(new Tuple<int,int>(1, 2)); v[1].Add(new Tuple<int,int>(3, 5)); v[3].Add(new Tuple<int,int>(1, 5)); v[3].Add(new Tuple<int,int>(4, 3)); v[4].Add(new Tuple<int,int>(3, 4)); v[3].Add(new Tuple<int,int>(5, 1)); v[5].Add(new Tuple<int,int>(3, 1)); // Computing LCA compute_lca(); int[,] queries = { { 3, 5 }, { 2, 3 }, { 2, 4 } }; int q = 3; for (int i = 0; i < q; i++) { int max_edge = getMax(queries[i,0], queries[i,1]); Console.WriteLine(max_edge); } }} // This code is contributed by divyesh072019.", "e": 15430, "s": 11353, "text": null }, { "code": "<script> // Javascript implementation to find the // maximum weighted edge in the simple // path between two nodes in N-ary Tree let N = 100005; // Depths of Nodes let level = new Array(N); level.fill(0); let LG = 20; // Parent at every 2^i level let dp = new Array(LG); for(let i = 0; i < LG; i++) { dp[i] = new Array(N); for(let j = 0; j < N; j++) { dp[i][j] = 0; } } // Maximum node at every 2^i level let mx = new Array(LG); for(let i = 0; i < LG; i++) { mx[i] = new Array(N); for(let j = 0; j < N; j++) { mx[i][j] = 0; } } // Graph that stores destinations // and its weight let v = []; for(let i = 0; i < N; i++) { v.push([]); } let n = 0; // Function to traverse the // nodes using the Depth-First // Search Traversal function dfs_lca(a, par, lev) { dp[0][a] = par; level[a] = lev; for(let i = 0; i < 2; i++) { // Condition to check // if its equal to its // parent then skip if (v[a][0] == par) continue; mx[0][v[a][0]] = v[a][1]; // DFS Recursive Call dfs_lca(v[a][0], a, lev + 1); } } // Function to find the ancestor function find_ancestor() { // Loop to set every 2^i distance for(let i = 1; i < 16; i++) { // Loop to calculate for // each node in the N-ary tree for(let j = 1; j < n + 1; j++) { dp[i][j] = dp[i - 1][dp[i - 1][j]]; // Storing maximum edge mx[i][j] = Math.max(mx[i - 1][j], mx[i - 1][dp[i - 1][j]]); } } } function getMax(a, b) { // Swaping if node a is at more depth // than node b because we will // always take at more depth if (level[b] < level[a]) { let temp = a; a = b; b = temp; } let ans = 0; // Difference between the // depth of the two given // nodes let diff = level[b] - level[a]; while (diff > 0) { let log = parseInt(Math.log(diff) / Math.log(2), 10); ans = Math.max(ans, mx[log][b]); // Changing Node B to its // parent at 2 ^ i distance b = dp[log][b]; // Subtracting distance by 2^i diff -= (1 << log); } // Take both a, b to its // lca and find maximum while (a == b) { i = parseInt(Math.log(level[a]) / Math.log(2), 10); // Loop to find the maximum 2^ith // parent the is different // for both a and b while (i > 0 && dp[i][a] == dp[i][b]) { i-=1; } // Updating ans ans = Math.max(ans, mx[i][a]); ans = Math.max(ans, mx[i][b]); // Changing value to // its parent a = dp[i][a]; b = dp[i][b]; } return ans*2 + 1; } // Function to compute the Least // common Ansector function compute_lca() { dfs_lca(1, 0, 0); find_ancestor(); } // Undirected tree n = 5; v[1].push(2); v[1].push(2); v[2].push(1); v[2].push(2); v[1].push(3); v[1].push(5); v[3].push(1); v[3].push(5); v[3].push(4); v[3].push(3); v[4].push(3); v[4].push(4); v[3].push(5); v[3].push(1); v[5].push(3); v[5].push(1); // Computing LCA compute_lca(); let queries= [[3, 5], [2, 3], [2,4]]; let q = 3; for(let i = 0; i <q; i++) { let max_edge = getMax(queries[i][0], queries[i][1]); document.write(max_edge + \"</br>\"); } // This code is contributed by suresh07.</script>", "e": 19365, "s": 15430, "text": null }, { "code": null, "e": 19371, "s": 19365, "text": "1\n5\n5" }, { "code": null, "e": 19429, "s": 19373, "text": "Time Complexity: O(N*logN).Auxiliary Space: O(N*logN). " }, { "code": null, "e": 19439, "s": 19429, "text": "rutvik_56" }, { "code": null, "e": 19459, "s": 19439, "text": "abhishek0719kadiyan" }, { "code": null, "e": 19475, "s": 19459, "text": "pankajsharmagfg" }, { "code": null, "e": 19484, "s": 19475, "text": "suresh07" }, { "code": null, "e": 19498, "s": 19484, "text": "divyesh072019" }, { "code": null, "e": 19513, "s": 19498, "text": "deepakchowdary" }, { "code": null, "e": 19524, "s": 19513, "text": "decode2207" }, { "code": null, "e": 19543, "s": 19524, "text": "surindertarika1234" }, { "code": null, "e": 19556, "s": 19543, "text": "simmytarika5" }, { "code": null, "e": 19576, "s": 19556, "text": "array-range-queries" }, { "code": null, "e": 19580, "s": 19576, "text": "DFS" }, { "code": null, "e": 19591, "s": 19580, "text": "n-ary-tree" }, { "code": null, "e": 19602, "s": 19591, "text": "Algorithms" }, { "code": null, "e": 19612, "s": 19602, "text": "Bit Magic" }, { "code": null, "e": 19636, "s": 19612, "text": "Competitive Programming" }, { "code": null, "e": 19656, "s": 19636, "text": "Dynamic Programming" }, { "code": null, "e": 19661, "s": 19656, "text": "Tree" }, { "code": null, "e": 19681, "s": 19661, "text": "Dynamic Programming" }, { "code": null, "e": 19691, "s": 19681, "text": "Bit Magic" }, { "code": null, "e": 19695, "s": 19691, "text": "DFS" }, { "code": null, "e": 19700, "s": 19695, "text": "Tree" }, { "code": null, "e": 19711, "s": 19700, "text": "Algorithms" }, { "code": null, "e": 19809, "s": 19711, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 19834, "s": 19809, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 19883, "s": 19834, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 19921, "s": 19883, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 19972, "s": 19921, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 20008, "s": 19972, "text": "CPU Scheduling in Operating Systems" }, { "code": null, "e": 20035, "s": 20008, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 20081, "s": 20035, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 20149, "s": 20081, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 20178, "s": 20149, "text": "Count set bits in an integer" } ]
Software Engineering | Differences between defect, bug and failure
21 May, 2019 Generally, when the system/application does not act as per expectation or abnormally, we call it’s an error or it’s an fault and so on. Many of the newbies in Software Testing industry have confusion in using this, so let’s know what is the difference b/w defect, bug, error and failure. We will see these terms in detail one by one. Defect:The bugs introduced by programmer inside the code is called as Defect.Defect is defined as the deviation from the actual and expected result of application or software or in other words, defects are defined as any deviation or irregularity from the specifications mentioned in the product functional specification document. Defect is also solved by the developer in development phase or stage.Reasons for Defects:Any deviation from the customer requirements is called as defect.By giving wrong input may lead to defect.Any error in logic code may lead to defect.Bug:Sometimes most people are confused between defect and bug, they say that bug is the informal name of defect. Actually bugs are faults in system or application which impact on software functionality and performance. Usually bugs are found in unit testing by testers.There are different types of bugs, some of them are given below.Functional ErrorsCompilation ErrorsMissing commandsRun time ErrorsLogical errorsInappropriate error handlingAbove given these errors lead to bug.Failure:When a defect reaches the end customer, it is called as Failure.Once the product is completed and it is delivered to the customers and if the customer find any issues in product or software then it is the condition of failure of product.In other words, if an end user finds an issue in product then that particular issue is called as failure.Causes of Failure:Human errors or mistakes may lead to failure.Environmental conditionsThe way in which system is used. Defect:The bugs introduced by programmer inside the code is called as Defect.Defect is defined as the deviation from the actual and expected result of application or software or in other words, defects are defined as any deviation or irregularity from the specifications mentioned in the product functional specification document. Defect is also solved by the developer in development phase or stage.Reasons for Defects:Any deviation from the customer requirements is called as defect.By giving wrong input may lead to defect.Any error in logic code may lead to defect. The bugs introduced by programmer inside the code is called as Defect. Defect is defined as the deviation from the actual and expected result of application or software or in other words, defects are defined as any deviation or irregularity from the specifications mentioned in the product functional specification document. Defect is also solved by the developer in development phase or stage. Reasons for Defects: Any deviation from the customer requirements is called as defect. By giving wrong input may lead to defect. Any error in logic code may lead to defect. Bug:Sometimes most people are confused between defect and bug, they say that bug is the informal name of defect. Actually bugs are faults in system or application which impact on software functionality and performance. Usually bugs are found in unit testing by testers.There are different types of bugs, some of them are given below.Functional ErrorsCompilation ErrorsMissing commandsRun time ErrorsLogical errorsInappropriate error handlingAbove given these errors lead to bug. There are different types of bugs, some of them are given below. Functional Errors Compilation Errors Missing commands Run time Errors Logical errors Inappropriate error handling Above given these errors lead to bug. Failure:When a defect reaches the end customer, it is called as Failure.Once the product is completed and it is delivered to the customers and if the customer find any issues in product or software then it is the condition of failure of product.In other words, if an end user finds an issue in product then that particular issue is called as failure.Causes of Failure:Human errors or mistakes may lead to failure.Environmental conditionsThe way in which system is used. When a defect reaches the end customer, it is called as Failure. Once the product is completed and it is delivered to the customers and if the customer find any issues in product or software then it is the condition of failure of product.In other words, if an end user finds an issue in product then that particular issue is called as failure. Causes of Failure: Human errors or mistakes may lead to failure. Environmental conditions The way in which system is used. Flow of Bug to Defect: Example:Let’s see a defect by an example. a=7 b=5 ans=a*b print("Addition of {} and {} = {}.".format(a, b, ans)) When you compile and run this program you see the printed statement as below: Addition of 7 and 5=35 This is program of adding two numbers but the output is deviated from it’s actual result which is 12. Now we have detected a failure. As the failure has been detected a defect can be raised. evana pp_pankaj Difference Between Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Differences between JDK, JRE and JVM Difference between Process and Thread Difference between Clustered and Non-clustered index Types of Software Testing Software Engineering | COCOMO Model Software Engineering | White box Testing Unit Testing | Software Testing Software Engineering | Black box testing
[ { "code": null, "e": 28, "s": 0, "text": "\n21 May, 2019" }, { "code": null, "e": 362, "s": 28, "text": "Generally, when the system/application does not act as per expectation or abnormally, we call it’s an error or it’s an fault and so on. Many of the newbies in Software Testing industry have confusion in using this, so let’s know what is the difference b/w defect, bug, error and failure. We will see these terms in detail one by one." }, { "code": null, "e": 1879, "s": 362, "text": "Defect:The bugs introduced by programmer inside the code is called as Defect.Defect is defined as the deviation from the actual and expected result of application or software or in other words, defects are defined as any deviation or irregularity from the specifications mentioned in the product functional specification document. Defect is also solved by the developer in development phase or stage.Reasons for Defects:Any deviation from the customer requirements is called as defect.By giving wrong input may lead to defect.Any error in logic code may lead to defect.Bug:Sometimes most people are confused between defect and bug, they say that bug is the informal name of defect. Actually bugs are faults in system or application which impact on software functionality and performance. Usually bugs are found in unit testing by testers.There are different types of bugs, some of them are given below.Functional ErrorsCompilation ErrorsMissing commandsRun time ErrorsLogical errorsInappropriate error handlingAbove given these errors lead to bug.Failure:When a defect reaches the end customer, it is called as Failure.Once the product is completed and it is delivered to the customers and if the customer find any issues in product or software then it is the condition of failure of product.In other words, if an end user finds an issue in product then that particular issue is called as failure.Causes of Failure:Human errors or mistakes may lead to failure.Environmental conditionsThe way in which system is used." }, { "code": null, "e": 2449, "s": 1879, "text": "Defect:The bugs introduced by programmer inside the code is called as Defect.Defect is defined as the deviation from the actual and expected result of application or software or in other words, defects are defined as any deviation or irregularity from the specifications mentioned in the product functional specification document. Defect is also solved by the developer in development phase or stage.Reasons for Defects:Any deviation from the customer requirements is called as defect.By giving wrong input may lead to defect.Any error in logic code may lead to defect." }, { "code": null, "e": 2520, "s": 2449, "text": "The bugs introduced by programmer inside the code is called as Defect." }, { "code": null, "e": 2844, "s": 2520, "text": "Defect is defined as the deviation from the actual and expected result of application or software or in other words, defects are defined as any deviation or irregularity from the specifications mentioned in the product functional specification document. Defect is also solved by the developer in development phase or stage." }, { "code": null, "e": 2865, "s": 2844, "text": "Reasons for Defects:" }, { "code": null, "e": 2931, "s": 2865, "text": "Any deviation from the customer requirements is called as defect." }, { "code": null, "e": 2973, "s": 2931, "text": "By giving wrong input may lead to defect." }, { "code": null, "e": 3017, "s": 2973, "text": "Any error in logic code may lead to defect." }, { "code": null, "e": 3496, "s": 3017, "text": "Bug:Sometimes most people are confused between defect and bug, they say that bug is the informal name of defect. Actually bugs are faults in system or application which impact on software functionality and performance. Usually bugs are found in unit testing by testers.There are different types of bugs, some of them are given below.Functional ErrorsCompilation ErrorsMissing commandsRun time ErrorsLogical errorsInappropriate error handlingAbove given these errors lead to bug." }, { "code": null, "e": 3561, "s": 3496, "text": "There are different types of bugs, some of them are given below." }, { "code": null, "e": 3579, "s": 3561, "text": "Functional Errors" }, { "code": null, "e": 3598, "s": 3579, "text": "Compilation Errors" }, { "code": null, "e": 3615, "s": 3598, "text": "Missing commands" }, { "code": null, "e": 3631, "s": 3615, "text": "Run time Errors" }, { "code": null, "e": 3646, "s": 3631, "text": "Logical errors" }, { "code": null, "e": 3675, "s": 3646, "text": "Inappropriate error handling" }, { "code": null, "e": 3713, "s": 3675, "text": "Above given these errors lead to bug." }, { "code": null, "e": 4183, "s": 3713, "text": "Failure:When a defect reaches the end customer, it is called as Failure.Once the product is completed and it is delivered to the customers and if the customer find any issues in product or software then it is the condition of failure of product.In other words, if an end user finds an issue in product then that particular issue is called as failure.Causes of Failure:Human errors or mistakes may lead to failure.Environmental conditionsThe way in which system is used." }, { "code": null, "e": 4248, "s": 4183, "text": "When a defect reaches the end customer, it is called as Failure." }, { "code": null, "e": 4527, "s": 4248, "text": "Once the product is completed and it is delivered to the customers and if the customer find any issues in product or software then it is the condition of failure of product.In other words, if an end user finds an issue in product then that particular issue is called as failure." }, { "code": null, "e": 4546, "s": 4527, "text": "Causes of Failure:" }, { "code": null, "e": 4592, "s": 4546, "text": "Human errors or mistakes may lead to failure." }, { "code": null, "e": 4617, "s": 4592, "text": "Environmental conditions" }, { "code": null, "e": 4650, "s": 4617, "text": "The way in which system is used." }, { "code": null, "e": 4673, "s": 4650, "text": "Flow of Bug to Defect:" }, { "code": null, "e": 4715, "s": 4673, "text": "Example:Let’s see a defect by an example." }, { "code": null, "e": 4787, "s": 4715, "text": "a=7\nb=5\nans=a*b\nprint(\"Addition of {} and {} = {}.\".format(a, b, ans)) " }, { "code": null, "e": 4865, "s": 4787, "text": "When you compile and run this program you see the printed statement as below:" }, { "code": null, "e": 4889, "s": 4865, "text": "Addition of 7 and 5=35 " }, { "code": null, "e": 5080, "s": 4889, "text": "This is program of adding two numbers but the output is deviated from it’s actual result which is 12. Now we have detected a failure. As the failure has been detected a defect can be raised." }, { "code": null, "e": 5086, "s": 5080, "text": "evana" }, { "code": null, "e": 5096, "s": 5086, "text": "pp_pankaj" }, { "code": null, "e": 5115, "s": 5096, "text": "Difference Between" }, { "code": null, "e": 5136, "s": 5115, "text": "Software Engineering" }, { "code": null, "e": 5234, "s": 5136, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5295, "s": 5234, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5363, "s": 5295, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 5400, "s": 5363, "text": "Differences between JDK, JRE and JVM" }, { "code": null, "e": 5438, "s": 5400, "text": "Difference between Process and Thread" }, { "code": null, "e": 5491, "s": 5438, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 5517, "s": 5491, "text": "Types of Software Testing" }, { "code": null, "e": 5553, "s": 5517, "text": "Software Engineering | COCOMO Model" }, { "code": null, "e": 5594, "s": 5553, "text": "Software Engineering | White box Testing" }, { "code": null, "e": 5626, "s": 5594, "text": "Unit Testing | Software Testing" } ]
jQuery - Slideshow.js
Slideshow.js is a jQuery plugin for quickly and easily implementing slide show of images or videos into your website. A Simple of slide show example as shown below − <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "https://www.w3.org/1999/xhtml" xml:lang = "en" lang = "en"> <head> <meta http-equiv = "content-type" content = "text/html; charset = UTF-8" /> <link rel = "stylesheet" href = "css/supersized.css" type = "text/css" media = "screen" /> <link rel = "stylesheet" href = "theme/supersized.shutter.css" type = "text/css" media = "screen" /> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"> </script> <script type = "text/javascript" src =" js/jquery.easing.min.js"></script> <script type = "text/javascript" src =" js/supersized.3.2.7.min.js"></script> <script type = "text/javascript" src = "theme/supersized.shutter.min.js"></script> <script type = "text/javascript"> jQuery(function($){ $.supersized({ slideshow : 1, autoplay : 1, start_slide : 1, stop_loop : 0, random : 0, slide_interval : 3000, transition : 6, transition_speed : 1000, new_window : 1, pause_hover : 0, keyboard_nav : 1, performance : 1, image_protect : 1, min_width : 0, min_height : 0, vertical_center : 1, horizontal_center : 1, fit_always : 0, fit_portrait : 1, fit_landscape : 0, slide_links : 'blank', thumb_links : 1, thumbnail_navigation : 0, slides : [ { image : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/slides/kazvan-1.jpg', title : 'Sample demo', thumb : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/thumbs/kazvan-1.jpg', url : 'https://www.tutorialspoint.com' }, { image : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/slides/kazvan-3.jpg', title : 'Sample demo', thumb : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/thumbs/kazvan-3.jpg', url : 'https://www.tutorialspoint.com' }, { image : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/slides/wojno-1.jpg', title : 'Sample demo', thumb : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/thumbs/wojno-1.jpg', url : 'https://www.tutorialspoint.com' }, { image : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/slides/wojno-2.jpg', title : 'Sample demo', thumb : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/thumbs/wojno-2.jpg', url : 'https://www.tutorialspoint.com' }, { image : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/slides/wojno-3.jpg', title : 'Sample demo', thumb : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/thumbs/wojno-3.jpg', url : 'https://www.tutorialspoint.com'}, ], progress_bar : 1, mouse_scrub : 0 }); }); </script> </head> <style type = "text/css"> ul#demo-block{ margin:0 15px 15px 15px; } ul#demo-block li{ margin:0 0 10px 0; padding:10px; display:inline; float:left; clear:both; color:#aaa; background:url('img/bg-black.png'); font:11px Helvetica, Arial, sans-serif; } ul#demo-block li a{ color:#eee; font-weight:bold; } </style> <body> <div id = "prevthumb"></div> <div id = "nextthumb"></div> <a id = "prevslide" class = "load-item"></a> <a id = "nextslide" class = "load-item"></a> <div id = "thumb-tray" class = "load-item"> <div id = "thumb-back"></div> <div id = "thumb-forward"></div> </div> <div id = "progress-back" class = "load-item"> <div id = "progress-bar"></div> </div> <div id = "controls-wrapper" class = "load-item"> <div id = "controls"> <a id = "play-button"><img id = "pauseplay" src = "img/pause.png"/></a> <div id = "slidecounter"> <span class = "slidenumber"></span> / <span class = "totalslides"></span> </div> <div id = "slidecaption"></div> <a id = "tray-button"><img id = "tray-arrow" src = "img/button-tray-up.png"/></a> <ul id = "slide-list"></ul> </div> </div> </body> </html> This should produce following result −
[ { "code": null, "e": 2907, "s": 2789, "text": "Slideshow.js is a jQuery plugin for quickly and easily implementing slide show of images or videos into your website." }, { "code": null, "e": 2955, "s": 2907, "text": "A Simple of slide show example as shown below −" }, { "code": null, "e": 8521, "s": 2955, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n \"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"https://www.w3.org/1999/xhtml\" xml:lang = \"en\" lang = \"en\">\n \n <head>\n <meta http-equiv = \"content-type\" content = \"text/html; charset = UTF-8\" />\n\t\t\n <link rel = \"stylesheet\" href = \"css/supersized.css\" type = \"text/css\" \n media = \"screen\" />\n \n <link rel = \"stylesheet\" href = \"theme/supersized.shutter.css\" \n type = \"text/css\" media = \"screen\" />\n\t\t\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js\">\n </script>\n <script type = \"text/javascript\" src =\" js/jquery.easing.min.js\"></script>\n\t\t\n <script type = \"text/javascript\" src =\" js/supersized.3.2.7.min.js\"></script>\n <script type = \"text/javascript\" src = \"theme/supersized.shutter.min.js\"></script>\n\t\t\n <script type = \"text/javascript\">\n jQuery(function($){\n $.supersized({\n slideshow : 1,\t\t\t\n autoplay : 1,\t\t\t\n start_slide : 1,\t\t\t\n stop_loop : 0,\t\t\t\n random : 0,\t\t\t\n slide_interval : 3000,\t\t\n transition : 6, \t\t\t\n transition_speed : 1000,\t\t\n new_window : 1,\t\t\t\n pause_hover : 0,\t\t\t\n keyboard_nav : 1,\t\t\t\n performance : 1,\t\t\t\n image_protect : 1,\t\t\t\n \n min_width : 0,\t\t\t\n min_height : 0,\t\t\t\n vertical_center : 1,\t\t\t\n horizontal_center : 1,\t\t\t\n fit_always : 0,\t\t\t\n fit_portrait : 1,\t\t\t\n fit_landscape : 0,\t\t\t\n \n slide_links : 'blank',\t\n thumb_links : 1,\t\t\t\n thumbnail_navigation : 0,\t\t\t\n slides : \t\n [\t\t\t\n {\n image : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/slides/kazvan-1.jpg', \n title : 'Sample demo', \n thumb : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/thumbs/kazvan-1.jpg', \n url : 'https://www.tutorialspoint.com'\n },\n {\n image : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/slides/kazvan-3.jpg', \n title : 'Sample demo', \n thumb : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/thumbs/kazvan-3.jpg', \n url : 'https://www.tutorialspoint.com'\n },\n {\n image : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/slides/wojno-1.jpg', \n title : 'Sample demo', \n thumb : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/thumbs/wojno-1.jpg', \n url : 'https://www.tutorialspoint.com'\n },\n {\n image : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/slides/wojno-2.jpg', \n title : 'Sample demo', \n thumb : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/thumbs/wojno-2.jpg', \n url : 'https://www.tutorialspoint.com'\n },\n {\n image : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/slides/wojno-3.jpg', \n title : 'Sample demo', \n thumb : 'https://buildinternet.s3.amazonaws.com/projects/supersized/3.2/thumbs/wojno-3.jpg', \n url : 'https://www.tutorialspoint.com'},\n ],\n progress_bar :\t1,\t\t\t\n mouse_scrub :\t0\n });\n });\n </script>\n </head>\n\t\n <style type = \"text/css\">\n ul#demo-block{ margin:0 15px 15px 15px; }\n ul#demo-block li{ margin:0 0 10px 0; padding:10px; display:inline; \n float:left; clear:both; color:#aaa; background:url('img/bg-black.png'); \n font:11px Helvetica, Arial, sans-serif; }\n ul#demo-block li a{ color:#eee; font-weight:bold; }\n </style>\n\n <body>\n <div id = \"prevthumb\"></div>\n <div id = \"nextthumb\"></div>\n \n <a id = \"prevslide\" class = \"load-item\"></a>\n <a id = \"nextslide\" class = \"load-item\"></a>\n \n <div id = \"thumb-tray\" class = \"load-item\">\n <div id = \"thumb-back\"></div>\n <div id = \"thumb-forward\"></div>\n </div>\n \n <div id = \"progress-back\" class = \"load-item\">\n <div id = \"progress-bar\"></div>\n </div>\n \n <div id = \"controls-wrapper\" class = \"load-item\">\n <div id = \"controls\">\n <a id = \"play-button\"><img id = \"pauseplay\" src = \"img/pause.png\"/></a>\n\n <div id = \"slidecounter\">\n <span class = \"slidenumber\"></span> / <span class = \"totalslides\"></span>\n </div>\n\n <div id = \"slidecaption\"></div>\n\n <a id = \"tray-button\"><img id = \"tray-arrow\" src = \"img/button-tray-up.png\"/></a>\n\n <ul id = \"slide-list\"></ul>\n </div>\n </div>\n </body>\n</html>" } ]
Exception Handling with Method Overriding in Java
09 Aug, 2021 An Exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run-time, that disrupts the normal flow of the program’s instructions. Exception handling is used to handle runtime errors. It helps to maintain the normal flow of the program. In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature, and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class. Exception Handling with Method OverridingWhen Exception handling is involved with Method overriding, ambiguity occurs. The compiler gets confused as to which definition is to be followed. Types of problems: There are two types of problems associated with it which are as follows: Problem 1: If The SuperClass doesn’t declare an exceptionProblem 2: If The SuperClass declares an exception Problem 1: If The SuperClass doesn’t declare an exception Problem 2: If The SuperClass declares an exception Let us discuss different cases under these problems and perceived their outputs. Problem 1: If The SuperClass doesn’t declare an exception In this problem, two cases that will arise are as follows: Case 1: If SuperClass doesn’t declare any exception and subclass declare checked exception Case 2: If SuperClass doesn’t declare any exception and SubClass declare Unchecked exception Let us discuss the above two cases and interpret them with help of examples as follows: Case 1: If SuperClass doesn’t declare any exception and subclass declare checked exception. Example Java // Java Program to Illustrate Exception Handling// with Method Overriding// Where SuperClass does not declare any exception and// subclass declare checked exception // Importing required classesimport java.io.*; class SuperClass { // SuperClass doesn't declare any exception void method() { System.out.println("SuperClass"); }} // SuperClass inherited by the SubClassclass SubClass extends SuperClass { // method() declaring Checked Exception IOException void method() throws IOException { // IOException is of type Checked Exception // so the compiler will give Error System.out.println("SubClass"); } // Driver code public static void main(String args[]) { SuperClass s = new SubClass(); s.method(); }} Output: Case 2: If SuperClass doesn’t declare any exception and SubClass declare Unchecked exception Example Java // Java Program to Illustrate Exception Handling// with Method Overriding// Where SuperClass doesn't declare any exception and// SubClass declare Unchecked exception // Importing required classesimport java.io.*; class SuperClass { // SuperClass doesn't declare any exception void method() { System.out.println("SuperClass"); }} // SuperClass inherited by the SubClassclass SubClass extends SuperClass { // method() declaring Unchecked Exception ArithmeticException void method() throws ArithmeticException { // ArithmeticException is of type Unchecked Exception // so the compiler won't give any error System.out.println("SubClass"); } // Driver code public static void main(String args[]) { SuperClass s = new SubClass(); s.method(); }} SubClass Now dwelling onto the next problem associated with that is if The SuperClass declares an exception. In this problem 3 cases will arise as follows: Case 1: If SuperClass declares an exception and SubClass declares exceptions other than the child exception of the SuperClass declared Exception. Case 2: If SuperClass declares an exception and SubClass declares a child exception of the SuperClass declared Exception. Case 3: If SuperClass declares an exception and SubClass declares without exception. Now let us interpret these cases by implementing and interpreting with example. Case 1: If SuperClass declares an exception and SubClass declares exceptions other than the child exception of the SuperClass declared Exception. Example Java // Java Program to Illustrate Exception Handling// with Method Overriding// Where SuperClass declares an exception and// SubClass declares exceptions other than the child exception// of the SuperClass declared Exception. // Importing required classesimport java.io.*; class SuperClass { // SuperClass declares an exception void method() throws RuntimeException { System.out.println("SuperClass"); }} // SuperClass inherited by the SubClassclass SubClass extends SuperClass { // SubClass declaring an exception // which are not a child exception of RuntimeException void method() throws Exception { // Exception is not a child exception // of the RuntimeException // So the compiler will give an error System.out.println("SubClass"); } // Driver code public static void main(String args[]) { SuperClass s = new SubClass(); s.method(); }} Output: Case 2: If SuperClass declares an exception and SubClass declares a child exception of the SuperClass declared Exception. Example Java // Java Program to Illustrate Exception Handling// with Method Overriding// Where SuperClass declares an exception and// SubClass declares a child exception// of the SuperClass declared Exception // Importing required classesimport java.io.*; class SuperClass { // SuperClass declares an exception void method() throws RuntimeException { System.out.println("SuperClass"); }} // SuperClass inherited by the SubClassclass SubClass extends SuperClass { // SubClass declaring a child exception // of RuntimeException void method() throws ArithmeticException { // ArithmeticException is a child exception // of the RuntimeException // So the compiler won't give an error System.out.println("SubClass"); } // Driver code public static void main(String args[]) { SuperClass s = new SubClass(); s.method(); }} SubClass Case 3: If SuperClass declares an exception and SubClass declares without exception. Example Java // Java Program to Illustrate Exception Handling// with Method Overriding// Where SuperClass declares an exception and// SubClass declares without exception // Importing required classesimport java.io.*; class SuperClass { // SuperClass declares an exception void method() throws IOException { System.out.println("SuperClass"); }} // SuperClass inherited by the SubClassclass SubClass extends SuperClass { // SubClass declaring without exception void method() { System.out.println("SubClass"); } // Driver code public static void main(String args[]) { SuperClass s = new SubClass(); try { s.method(); } catch (IOException e) { e.printStackTrace(); } }} SubClass Conclusions: As perceived from above 3 examples in order to handle such exceptions, the following conclusions derived are as follows: If SuperClass does not declare an exception, then the SubClass can only declare unchecked exceptions, but not the checked exceptions. If SuperClass declares an exception, then the SubClass can only declare the same or child exceptions of the exception declared by the SuperClass and any new Runtime Exceptions, just not any new checked exceptions at the same level or higher. If SuperClass declares an exception, then the SubClass can declare without exception. sanjaygoyaljpr msca0816 varshagumber28 gabaa406 Java-Exception Handling Java-Exceptions Java-Object Oriented java-overriding Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Aug, 2021" }, { "code": null, "e": 786, "s": 52, "text": "An Exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run-time, that disrupts the normal flow of the program’s instructions. Exception handling is used to handle runtime errors. It helps to maintain the normal flow of the program. In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature, and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class." }, { "code": null, "e": 975, "s": 786, "text": "Exception Handling with Method OverridingWhen Exception handling is involved with Method overriding, ambiguity occurs. The compiler gets confused as to which definition is to be followed. " }, { "code": null, "e": 994, "s": 975, "text": "Types of problems:" }, { "code": null, "e": 1067, "s": 994, "text": "There are two types of problems associated with it which are as follows:" }, { "code": null, "e": 1176, "s": 1067, "text": "Problem 1: If The SuperClass doesn’t declare an exceptionProblem 2: If The SuperClass declares an exception" }, { "code": null, "e": 1235, "s": 1176, "text": "Problem 1: If The SuperClass doesn’t declare an exception" }, { "code": null, "e": 1286, "s": 1235, "text": "Problem 2: If The SuperClass declares an exception" }, { "code": null, "e": 1367, "s": 1286, "text": "Let us discuss different cases under these problems and perceived their outputs." }, { "code": null, "e": 1426, "s": 1367, "text": "Problem 1: If The SuperClass doesn’t declare an exception" }, { "code": null, "e": 1485, "s": 1426, "text": "In this problem, two cases that will arise are as follows:" }, { "code": null, "e": 1576, "s": 1485, "text": "Case 1: If SuperClass doesn’t declare any exception and subclass declare checked exception" }, { "code": null, "e": 1669, "s": 1576, "text": "Case 2: If SuperClass doesn’t declare any exception and SubClass declare Unchecked exception" }, { "code": null, "e": 1757, "s": 1669, "text": "Let us discuss the above two cases and interpret them with help of examples as follows:" }, { "code": null, "e": 1849, "s": 1757, "text": "Case 1: If SuperClass doesn’t declare any exception and subclass declare checked exception." }, { "code": null, "e": 1858, "s": 1849, "text": "Example " }, { "code": null, "e": 1863, "s": 1858, "text": "Java" }, { "code": "// Java Program to Illustrate Exception Handling// with Method Overriding// Where SuperClass does not declare any exception and// subclass declare checked exception // Importing required classesimport java.io.*; class SuperClass { // SuperClass doesn't declare any exception void method() { System.out.println(\"SuperClass\"); }} // SuperClass inherited by the SubClassclass SubClass extends SuperClass { // method() declaring Checked Exception IOException void method() throws IOException { // IOException is of type Checked Exception // so the compiler will give Error System.out.println(\"SubClass\"); } // Driver code public static void main(String args[]) { SuperClass s = new SubClass(); s.method(); }}", "e": 2600, "s": 1863, "text": null }, { "code": null, "e": 2608, "s": 2600, "text": "Output:" }, { "code": null, "e": 2701, "s": 2608, "text": "Case 2: If SuperClass doesn’t declare any exception and SubClass declare Unchecked exception" }, { "code": null, "e": 2710, "s": 2701, "text": "Example " }, { "code": null, "e": 2715, "s": 2710, "text": "Java" }, { "code": "// Java Program to Illustrate Exception Handling// with Method Overriding// Where SuperClass doesn't declare any exception and// SubClass declare Unchecked exception // Importing required classesimport java.io.*; class SuperClass { // SuperClass doesn't declare any exception void method() { System.out.println(\"SuperClass\"); }} // SuperClass inherited by the SubClassclass SubClass extends SuperClass { // method() declaring Unchecked Exception ArithmeticException void method() throws ArithmeticException { // ArithmeticException is of type Unchecked Exception // so the compiler won't give any error System.out.println(\"SubClass\"); } // Driver code public static void main(String args[]) { SuperClass s = new SubClass(); s.method(); }}", "e": 3537, "s": 2715, "text": null }, { "code": null, "e": 3546, "s": 3537, "text": "SubClass" }, { "code": null, "e": 3693, "s": 3546, "text": "Now dwelling onto the next problem associated with that is if The SuperClass declares an exception. In this problem 3 cases will arise as follows:" }, { "code": null, "e": 3839, "s": 3693, "text": "Case 1: If SuperClass declares an exception and SubClass declares exceptions other than the child exception of the SuperClass declared Exception." }, { "code": null, "e": 3961, "s": 3839, "text": "Case 2: If SuperClass declares an exception and SubClass declares a child exception of the SuperClass declared Exception." }, { "code": null, "e": 4046, "s": 3961, "text": "Case 3: If SuperClass declares an exception and SubClass declares without exception." }, { "code": null, "e": 4127, "s": 4046, "text": "Now let us interpret these cases by implementing and interpreting with example. " }, { "code": null, "e": 4273, "s": 4127, "text": "Case 1: If SuperClass declares an exception and SubClass declares exceptions other than the child exception of the SuperClass declared Exception." }, { "code": null, "e": 4282, "s": 4273, "text": "Example " }, { "code": null, "e": 4287, "s": 4282, "text": "Java" }, { "code": "// Java Program to Illustrate Exception Handling// with Method Overriding// Where SuperClass declares an exception and// SubClass declares exceptions other than the child exception// of the SuperClass declared Exception. // Importing required classesimport java.io.*; class SuperClass { // SuperClass declares an exception void method() throws RuntimeException { System.out.println(\"SuperClass\"); }} // SuperClass inherited by the SubClassclass SubClass extends SuperClass { // SubClass declaring an exception // which are not a child exception of RuntimeException void method() throws Exception { // Exception is not a child exception // of the RuntimeException // So the compiler will give an error System.out.println(\"SubClass\"); } // Driver code public static void main(String args[]) { SuperClass s = new SubClass(); s.method(); }}", "e": 5160, "s": 4287, "text": null }, { "code": null, "e": 5168, "s": 5160, "text": "Output:" }, { "code": null, "e": 5290, "s": 5168, "text": "Case 2: If SuperClass declares an exception and SubClass declares a child exception of the SuperClass declared Exception." }, { "code": null, "e": 5298, "s": 5290, "text": "Example" }, { "code": null, "e": 5303, "s": 5298, "text": "Java" }, { "code": "// Java Program to Illustrate Exception Handling// with Method Overriding// Where SuperClass declares an exception and// SubClass declares a child exception// of the SuperClass declared Exception // Importing required classesimport java.io.*; class SuperClass { // SuperClass declares an exception void method() throws RuntimeException { System.out.println(\"SuperClass\"); }} // SuperClass inherited by the SubClassclass SubClass extends SuperClass { // SubClass declaring a child exception // of RuntimeException void method() throws ArithmeticException { // ArithmeticException is a child exception // of the RuntimeException // So the compiler won't give an error System.out.println(\"SubClass\"); } // Driver code public static void main(String args[]) { SuperClass s = new SubClass(); s.method(); }}", "e": 6197, "s": 5303, "text": null }, { "code": null, "e": 6206, "s": 6197, "text": "SubClass" }, { "code": null, "e": 6291, "s": 6206, "text": "Case 3: If SuperClass declares an exception and SubClass declares without exception." }, { "code": null, "e": 6299, "s": 6291, "text": "Example" }, { "code": null, "e": 6304, "s": 6299, "text": "Java" }, { "code": "// Java Program to Illustrate Exception Handling// with Method Overriding// Where SuperClass declares an exception and// SubClass declares without exception // Importing required classesimport java.io.*; class SuperClass { // SuperClass declares an exception void method() throws IOException { System.out.println(\"SuperClass\"); }} // SuperClass inherited by the SubClassclass SubClass extends SuperClass { // SubClass declaring without exception void method() { System.out.println(\"SubClass\"); } // Driver code public static void main(String args[]) { SuperClass s = new SubClass(); try { s.method(); } catch (IOException e) { e.printStackTrace(); } }}", "e": 7040, "s": 6304, "text": null }, { "code": null, "e": 7049, "s": 7040, "text": "SubClass" }, { "code": null, "e": 7062, "s": 7049, "text": "Conclusions:" }, { "code": null, "e": 7184, "s": 7062, "text": "As perceived from above 3 examples in order to handle such exceptions, the following conclusions derived are as follows: " }, { "code": null, "e": 7318, "s": 7184, "text": "If SuperClass does not declare an exception, then the SubClass can only declare unchecked exceptions, but not the checked exceptions." }, { "code": null, "e": 7560, "s": 7318, "text": "If SuperClass declares an exception, then the SubClass can only declare the same or child exceptions of the exception declared by the SuperClass and any new Runtime Exceptions, just not any new checked exceptions at the same level or higher." }, { "code": null, "e": 7646, "s": 7560, "text": "If SuperClass declares an exception, then the SubClass can declare without exception." }, { "code": null, "e": 7661, "s": 7646, "text": "sanjaygoyaljpr" }, { "code": null, "e": 7670, "s": 7661, "text": "msca0816" }, { "code": null, "e": 7685, "s": 7670, "text": "varshagumber28" }, { "code": null, "e": 7694, "s": 7685, "text": "gabaa406" }, { "code": null, "e": 7718, "s": 7694, "text": "Java-Exception Handling" }, { "code": null, "e": 7734, "s": 7718, "text": "Java-Exceptions" }, { "code": null, "e": 7755, "s": 7734, "text": "Java-Object Oriented" }, { "code": null, "e": 7771, "s": 7755, "text": "java-overriding" }, { "code": null, "e": 7776, "s": 7771, "text": "Java" }, { "code": null, "e": 7781, "s": 7776, "text": "Java" }, { "code": null, "e": 7879, "s": 7781, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7894, "s": 7879, "text": "Stream In Java" }, { "code": null, "e": 7915, "s": 7894, "text": "Introduction to Java" }, { "code": null, "e": 7936, "s": 7915, "text": "Constructors in Java" }, { "code": null, "e": 7955, "s": 7936, "text": "Exceptions in Java" }, { "code": null, "e": 7972, "s": 7955, "text": "Generics in Java" }, { "code": null, "e": 8002, "s": 7972, "text": "Functional Interfaces in Java" }, { "code": null, "e": 8028, "s": 8002, "text": "Java Programming Examples" }, { "code": null, "e": 8044, "s": 8028, "text": "Strings in Java" }, { "code": null, "e": 8081, "s": 8044, "text": "Differences between JDK, JRE and JVM" } ]
How to create a bar chart and save in pptx using Python?
06 Jul, 2021 World Wide Web holds large amounts of data available that is consistently growing both in quantity and to a fine form. Python API allows us to collect data/information of interest from the World Wide Web. API is a very useful tool for data scientists, web developers, and even any casual person who wants to find and extract information programmatically. Well, most of the websites provide APIs to share data in a structured format, however, they typically restrict the data that is available and also might put a limit on how frequently it can be accessed. Additionally, a website developer might change, remove, or restrict the backend API. On other hand, there are websites that do not provide API to share the data. The website development team at any time can change, remove, or restrict backend API. In short, we cannot rely on APIs to access the online data we may want. Therefore, we may need to rely on web scraping techniques. When it comes to effective API, Python is usually the programming language of choice. It is easy to use a programming language that has a very rich ecosystem of tools for many tasks. If you program in other languages, you will find it easy to pick up Python and you may never go back. The Python Software Foundation has announced Python 2 will be phased out of development and support in 2020. For this reason, We will use Python 3 and Jupyter notebook through the post. To be more specific, my python version is : Python3 from platform import python_version print(python_version()) 3.6.10 Before attempting to access the content of a website by API or web crawling, we should always develop an understanding of the structure of our target website. The sitemap and robots.txt of a website help us with some vital information apart from external tools such as Google Search and WHOIS. Well, websites (most of them) define a robots.txt file to note the users about the restrictions, when accessing their website. However, these restrictions are guidelines only, and highly recommend respecting their guidelines. You should always validate and respect the contents inside the robots.txt to understand the structure of the website and minimize the chance of being blocked. The robots.txt file is a valuable resource to validate before taking a decision to write a web crawler program or to use an API. In this post, Now gather the JavaScript repositories with the highest stars from Developers Facebook famously known as Github, so let me first checkout their robots.txt file. The following content (first few lines only) is from the robots.txt file of the website – https://github.com/robots.txt. From the file it is clear, Github wants to use its contents using an API. One way of solving our problem is by putting our search criteria in the Github search box and pressing enter, however, it is a manual activity. Helpfully, Github exposes this search capability as an API we can consume from our own applications. Github’s Search API gives us access to the built-in search function. This includes the use of logical and scoping operators, like “or” and “user”. Before we jump into the code, there is something you should know about public repositories, private repositories, and access restrictions. Public repositories are usually open to the public with no restrictions while private repositories are restricted only to the owners and to the collaborators they choose. Step 1: Validating with cURL. Now let’s quickly validate the access to Github before putting the effort into writing an API. So to do that cURL, a simple command-line HTTP tool, is a perfect fit. cURL is usually installed on most of the Linux machines if not, you can easily do it using. – yum install curl For windows, get a copy from “https://curl.haxx.se/download.html”. Now run the command as shown below: The cURL has given us a lot of information: HTTP/1.1 200 OK – code When your request destination URL and associated parameters are correct, GitHub will respond with a 200 status(Success).X-RateLimit-Limit – The maximum number of requests you’re permitted to make per hour.X-RateLimit-Remaining – The number of requests remaining in the current rate limit window.X-RateLimit-Reset – the time at which the current rate limit window resets in UTC epoch seconds.“repository_search_url“: This is the one we will be using in this post to query the repositories. HTTP/1.1 200 OK – code When your request destination URL and associated parameters are correct, GitHub will respond with a 200 status(Success). X-RateLimit-Limit – The maximum number of requests you’re permitted to make per hour. X-RateLimit-Remaining – The number of requests remaining in the current rate limit window. X-RateLimit-Reset – the time at which the current rate limit window resets in UTC epoch seconds. “repository_search_url“: This is the one we will be using in this post to query the repositories. Step 2: Authentication Usually, there are a couple of ways to authenticate when making a request to the Github API – using username and passwords (HTTP Basic) and using OAuth tokens. The authentication details will not be covered in this post. Since Github allows us to access the public content without any authentication, we will stick to searching public repositories without API. It means that we are going to write an API that doesn’t require authentication, so we will be searching public repositories only. Step 3: Github Response with Python Python3 # 1 - importsimport requests # 2 - set the siteurlsite_url = 'https://api.github.com/search/repositories?q=language:javascript&sort=stars' # 3 - set the headersheaders = {'Accept': 'application/vnd.github.v3+json'} # 4 - call the url with headers and save the responseresponse = requests.get(site_url, headers=headers) # 5 - Get the responseprint(f"Response from {site_url} is {response.status_code} ") Output: We started with importing requests (if it’s missing installation using pip install requests) then assigning a variable site_url with the URL of our interest. If you wanted to search for JavaScript repositories with a sorting (descending) on maximum stars. Github is currently on the third version of its API, so defined headers for the API call that ask explicitly to use the 3rd version of the API. Feel free to always check out the latest version here – https://docs.github.com/en/free-pro-team@latest/developers/overview/about-githubs-apis. Then call get() and pass it the site_url and the header, the response object is assigned to the response variable. The response from Github is always a JSON. The response object has an attribute status_code, which tells whether the response is successful(200) or not. Step 4: Converting JSON response to Python dictionary Python3 response_json = response.json()print(f"keys in the Json file : {response_json.keys()}")print(f"Total javascript repositories in GitHub : {response_json['total_count']}" ) Output: As mentioned earlier, the response is JSON. Our JSON has three keys of which we can ignore “incomplete_results” for such a small API. A program output displayed the total repositories in Github returned for our search with response_json[‘total_count’]. Step 5: Looking at our first repository Python3 repositories = response_json['items']first_repo = repositories[0] print(f"Output \n *** Repository information keys total - {len(first_repo)} - values are -\n")for keys in sorted(first_repo.keys()): print(keys) print(f" *** Repository name - {first_repo['name']}, Owner - {first_repo['owner']['login']}, total watchers - {first_repo['watchers_count']} ") Output: The above code is self-explanatory. What we are doing is displaying all the keys inside the dictionary and then displaying information on our first repository. Step 6: Loop for more... We have looked at one repository, for more obviously we need to go through the loop. Python3 for repo_info in repositories: print(f"\n *** Repository Name: {repo_info['name']}") print(f" *** Repository Owner: {repo_info['owner']['login']}") print(f" *** Repository Description: {repo_info['description']}") Output: Step 7: Visualization with Plotly Time for visualization using the data we have now to show the popularity of JavaScript projects on Github. Digesting information visually is always helpful. Before using you need to install Plotly package. For installation run this command into the terminal. pip install plotly Code: Python3 # importsimport requestsfrom plotly.graph_objs import Barfrom plotly import offline # siteurl and headerssite_url = 'https://api.github.com/search/repositories?q=language:javascript&sort=stars'headers = {'Accept': 'application/vnd.github.v3+json'} # response and parsing the response.response = requests.get(site_url, headers=headers)response_json = response.json() repositories = response_json['items'] # loop the repositoriesrepo_names, repo_stars = [], []for repo_info in repositories: repo_names.append(repo_info['name']) repo_stars.append(repo_info['stargazers_count']) # graph plotting data_plots = [{'type' : 'bar', 'x':repo_names , 'y': repo_stars}]layout = {'title': 'GItHubs Most Popular Javascript Projects', 'xaxis': {'title': 'Repository'}, 'yaxis': {'title': 'Stars'}} # saving graph to a Most_Popular_JavaScript_Repos.pngfig = {'data': data_plots, 'layout': layout}offline.plot(fig, image = 'png', image_filename='Most_Popular_JavaScript_Repos') The above code when executed, will save the bar-chart to a png file – Most_Popular_JavaScript_Repos under the current repository. Step 8: Creating a Presentation... Introduction... Microsoft production especially Spreadsheets and PowerPoint presentations are ruling the world. So we are going to create a PowerPoint presentation with the Visualization graph we just created. For installing python-pptx run this code into the terminal: pip install python-pptx We will begin by creating our first slide with the title — ” Popular JavaScript Repositories in Github”. Python3 from pptx import Presentation # create an object pptppt = Presentation() # add a new slideslide = ppt.slides.add_slide(ppt.slide_layouts[0]) # Set the Text toslide.shapes.title.text = "Popular JavaScript Repositories in GitHub" # save the powerpointppt.save('Javascript_report.pptx') Output: We have first imported Presentation from ppt then create a ppt object using the Presentation class of ppt module. New slide is added with add_slide() method. The text is added using the slide.shapes. Step 9: Saving the chart to pptx. Now that the basics of creating a PowerPoint are covered in the above steps. Now let’s dive into the final piece of code to create a report. Python3 from pptx import Presentationfrom pptx.util import Inchesfrom datetime import date # create an Objectppt = Presentation()first_slide = ppt.slides.add_slide(ppt.slide_layouts[0]) # title (included date)title = "Popular JavaScript Repositories in GitHub - " + str(date.today()) # set the title on first slidefirst_slide.shapes[0].text_frame.paragraphs[0].text = title # slide 2 - set the imageimg = 'Most_Popular_JavaScript_Repos.png'second_slide = ppt.slide_layouts[1]slide2 = ppt.slides.add_slide(second_slide) # play with the image attributes if you are not OK with the height and widthpic = slide2.shapes.add_picture(img, left= Inches(2),top = Inches(1),height = Inches(5)) # save the powerpoint presentationppt.save('Javascript_report.pptx') Output: Finally, we will put all the above steps discussed in a single program. Python3 import requestsfrom plotly.graph_objs import Barfrom plotly import offlinefrom pptx import Presentationfrom pptx.util import Inchesfrom datetime import date def github_api(): # siteurl and headers site_url = 'https://api.github.com/search/repositories?q=language:javascript&sort=stars' headers = {'Accept': 'application/vnd.github.v3+json'} # response and parsing the response. response = requests.get(site_url, headers=headers) response_json = response.json() repositories = response_json['items'] # loop the repositories repo_names, repo_stars = [], [] for repo_info in repositories: repo_names.append(repo_info['name']) repo_stars.append(repo_info['stargazers_count']) # graph plotting data_plots = [{'type' : 'bar', 'x':repo_names , 'y': repo_stars}] layout = {'title': 'GItHubs Most Popular Javascript Projects', 'xaxis': {'title': 'Repository'}, 'yaxis': {'title': 'Stars'}} # saving graph to a Most_Popular_JavaScript_Repos.png fig = {'data': data_plots, 'layout': layout} offline.plot(fig, image = 'png', image_filename='Most_Popular_JavaScript_Repos') def create_pptx_report(): # create an Object ppt = Presentation() first_slide = ppt.slides.add_slide(ppt.slide_layouts[0]) # title (included date) title = "Popular JavaScript Repositories in GitHub - " + str(date.today()) # set the title on first slide first_slide.shapes[0].text_frame.paragraphs[0].text = title # slide 2 - set the image img = 'Most_Popular_JavaScript_Repos.png' second_slide = ppt.slide_layouts[1] slide2 = ppt.slides.add_slide(second_slide) # play with the image attributes if you are not OK with the height and width pic = slide2.shapes.add_picture(img, left= Inches(2),top = Inches(1),height = Inches(5)) # save the powerpoint presentation ppt.save('Javascript_report.pptx') if __name__ == '__main__': github_api() create_pptx_report() clintra gulshankumarar231 Data Visualization python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jul, 2021" }, { "code": null, "e": 383, "s": 28, "text": "World Wide Web holds large amounts of data available that is consistently growing both in quantity and to a fine form. Python API allows us to collect data/information of interest from the World Wide Web. API is a very useful tool for data scientists, web developers, and even any casual person who wants to find and extract information programmatically." }, { "code": null, "e": 671, "s": 383, "text": "Well, most of the websites provide APIs to share data in a structured format, however, they typically restrict the data that is available and also might put a limit on how frequently it can be accessed. Additionally, a website developer might change, remove, or restrict the backend API." }, { "code": null, "e": 965, "s": 671, "text": "On other hand, there are websites that do not provide API to share the data. The website development team at any time can change, remove, or restrict backend API. In short, we cannot rely on APIs to access the online data we may want. Therefore, we may need to rely on web scraping techniques." }, { "code": null, "e": 1250, "s": 965, "text": "When it comes to effective API, Python is usually the programming language of choice. It is easy to use a programming language that has a very rich ecosystem of tools for many tasks. If you program in other languages, you will find it easy to pick up Python and you may never go back." }, { "code": null, "e": 1480, "s": 1250, "text": "The Python Software Foundation has announced Python 2 will be phased out of development and support in 2020. For this reason, We will use Python 3 and Jupyter notebook through the post. To be more specific, my python version is :" }, { "code": null, "e": 1488, "s": 1480, "text": "Python3" }, { "code": "from platform import python_version print(python_version())", "e": 1549, "s": 1488, "text": null }, { "code": null, "e": 1556, "s": 1549, "text": "3.6.10" }, { "code": null, "e": 1850, "s": 1556, "text": "Before attempting to access the content of a website by API or web crawling, we should always develop an understanding of the structure of our target website. The sitemap and robots.txt of a website help us with some vital information apart from external tools such as Google Search and WHOIS." }, { "code": null, "e": 2235, "s": 1850, "text": "Well, websites (most of them) define a robots.txt file to note the users about the restrictions, when accessing their website. However, these restrictions are guidelines only, and highly recommend respecting their guidelines. You should always validate and respect the contents inside the robots.txt to understand the structure of the website and minimize the chance of being blocked." }, { "code": null, "e": 2364, "s": 2235, "text": "The robots.txt file is a valuable resource to validate before taking a decision to write a web crawler program or to use an API." }, { "code": null, "e": 2539, "s": 2364, "text": "In this post, Now gather the JavaScript repositories with the highest stars from Developers Facebook famously known as Github, so let me first checkout their robots.txt file." }, { "code": null, "e": 2660, "s": 2539, "text": "The following content (first few lines only) is from the robots.txt file of the website – https://github.com/robots.txt." }, { "code": null, "e": 2878, "s": 2660, "text": "From the file it is clear, Github wants to use its contents using an API. One way of solving our problem is by putting our search criteria in the Github search box and pressing enter, however, it is a manual activity." }, { "code": null, "e": 3126, "s": 2878, "text": "Helpfully, Github exposes this search capability as an API we can consume from our own applications. Github’s Search API gives us access to the built-in search function. This includes the use of logical and scoping operators, like “or” and “user”." }, { "code": null, "e": 3436, "s": 3126, "text": "Before we jump into the code, there is something you should know about public repositories, private repositories, and access restrictions. Public repositories are usually open to the public with no restrictions while private repositories are restricted only to the owners and to the collaborators they choose." }, { "code": null, "e": 3466, "s": 3436, "text": "Step 1: Validating with cURL." }, { "code": null, "e": 3744, "s": 3466, "text": "Now let’s quickly validate the access to Github before putting the effort into writing an API. So to do that cURL, a simple command-line HTTP tool, is a perfect fit. cURL is usually installed on most of the Linux machines if not, you can easily do it using. – yum install curl " }, { "code": null, "e": 3811, "s": 3744, "text": "For windows, get a copy from “https://curl.haxx.se/download.html”." }, { "code": null, "e": 3847, "s": 3811, "text": "Now run the command as shown below:" }, { "code": null, "e": 3891, "s": 3847, "text": "The cURL has given us a lot of information:" }, { "code": null, "e": 4403, "s": 3891, "text": "HTTP/1.1 200 OK – code When your request destination URL and associated parameters are correct, GitHub will respond with a 200 status(Success).X-RateLimit-Limit – The maximum number of requests you’re permitted to make per hour.X-RateLimit-Remaining – The number of requests remaining in the current rate limit window.X-RateLimit-Reset – the time at which the current rate limit window resets in UTC epoch seconds.“repository_search_url“: This is the one we will be using in this post to query the repositories." }, { "code": null, "e": 4547, "s": 4403, "text": "HTTP/1.1 200 OK – code When your request destination URL and associated parameters are correct, GitHub will respond with a 200 status(Success)." }, { "code": null, "e": 4633, "s": 4547, "text": "X-RateLimit-Limit – The maximum number of requests you’re permitted to make per hour." }, { "code": null, "e": 4724, "s": 4633, "text": "X-RateLimit-Remaining – The number of requests remaining in the current rate limit window." }, { "code": null, "e": 4821, "s": 4724, "text": "X-RateLimit-Reset – the time at which the current rate limit window resets in UTC epoch seconds." }, { "code": null, "e": 4919, "s": 4821, "text": "“repository_search_url“: This is the one we will be using in this post to query the repositories." }, { "code": null, "e": 4942, "s": 4919, "text": "Step 2: Authentication" }, { "code": null, "e": 5163, "s": 4942, "text": "Usually, there are a couple of ways to authenticate when making a request to the Github API – using username and passwords (HTTP Basic) and using OAuth tokens. The authentication details will not be covered in this post." }, { "code": null, "e": 5433, "s": 5163, "text": "Since Github allows us to access the public content without any authentication, we will stick to searching public repositories without API. It means that we are going to write an API that doesn’t require authentication, so we will be searching public repositories only." }, { "code": null, "e": 5469, "s": 5433, "text": "Step 3: Github Response with Python" }, { "code": null, "e": 5477, "s": 5469, "text": "Python3" }, { "code": "# 1 - importsimport requests # 2 - set the siteurlsite_url = 'https://api.github.com/search/repositories?q=language:javascript&sort=stars' # 3 - set the headersheaders = {'Accept': 'application/vnd.github.v3+json'} # 4 - call the url with headers and save the responseresponse = requests.get(site_url, headers=headers) # 5 - Get the responseprint(f\"Response from {site_url} is {response.status_code} \")", "e": 5880, "s": 5477, "text": null }, { "code": null, "e": 5889, "s": 5880, "text": " Output:" }, { "code": null, "e": 6145, "s": 5889, "text": "We started with importing requests (if it’s missing installation using pip install requests) then assigning a variable site_url with the URL of our interest. If you wanted to search for JavaScript repositories with a sorting (descending) on maximum stars." }, { "code": null, "e": 6433, "s": 6145, "text": "Github is currently on the third version of its API, so defined headers for the API call that ask explicitly to use the 3rd version of the API. Feel free to always check out the latest version here – https://docs.github.com/en/free-pro-team@latest/developers/overview/about-githubs-apis." }, { "code": null, "e": 6701, "s": 6433, "text": "Then call get() and pass it the site_url and the header, the response object is assigned to the response variable. The response from Github is always a JSON. The response object has an attribute status_code, which tells whether the response is successful(200) or not." }, { "code": null, "e": 6756, "s": 6701, "text": "Step 4: Converting JSON response to Python dictionary " }, { "code": null, "e": 6764, "s": 6756, "text": "Python3" }, { "code": "response_json = response.json()print(f\"keys in the Json file : {response_json.keys()}\")print(f\"Total javascript repositories in GitHub : {response_json['total_count']}\" )", "e": 6935, "s": 6764, "text": null }, { "code": null, "e": 6943, "s": 6935, "text": "Output:" }, { "code": null, "e": 7196, "s": 6943, "text": "As mentioned earlier, the response is JSON. Our JSON has three keys of which we can ignore “incomplete_results” for such a small API. A program output displayed the total repositories in Github returned for our search with response_json[‘total_count’]." }, { "code": null, "e": 7236, "s": 7196, "text": "Step 5: Looking at our first repository" }, { "code": null, "e": 7244, "s": 7236, "text": "Python3" }, { "code": "repositories = response_json['items']first_repo = repositories[0] print(f\"Output \\n *** Repository information keys total - {len(first_repo)} - values are -\\n\")for keys in sorted(first_repo.keys()): print(keys) print(f\" *** Repository name - {first_repo['name']}, Owner - {first_repo['owner']['login']}, total watchers - {first_repo['watchers_count']} \")", "e": 7615, "s": 7244, "text": null }, { "code": null, "e": 7624, "s": 7615, "text": "Output: " }, { "code": null, "e": 7784, "s": 7624, "text": "The above code is self-explanatory. What we are doing is displaying all the keys inside the dictionary and then displaying information on our first repository." }, { "code": null, "e": 7809, "s": 7784, "text": "Step 6: Loop for more..." }, { "code": null, "e": 7895, "s": 7809, "text": "We have looked at one repository, for more obviously we need to go through the loop. " }, { "code": null, "e": 7903, "s": 7895, "text": "Python3" }, { "code": "for repo_info in repositories: print(f\"\\n *** Repository Name: {repo_info['name']}\") print(f\" *** Repository Owner: {repo_info['owner']['login']}\") print(f\" *** Repository Description: {repo_info['description']}\")", "e": 8126, "s": 7903, "text": null }, { "code": null, "e": 8136, "s": 8126, "text": " Output: " }, { "code": null, "e": 8170, "s": 8136, "text": "Step 7: Visualization with Plotly" }, { "code": null, "e": 8327, "s": 8170, "text": "Time for visualization using the data we have now to show the popularity of JavaScript projects on Github. Digesting information visually is always helpful." }, { "code": null, "e": 8430, "s": 8327, "text": "Before using you need to install Plotly package. For installation run this command into the terminal. " }, { "code": null, "e": 8449, "s": 8430, "text": "pip install plotly" }, { "code": null, "e": 8456, "s": 8449, "text": "Code: " }, { "code": null, "e": 8464, "s": 8456, "text": "Python3" }, { "code": "# importsimport requestsfrom plotly.graph_objs import Barfrom plotly import offline # siteurl and headerssite_url = 'https://api.github.com/search/repositories?q=language:javascript&sort=stars'headers = {'Accept': 'application/vnd.github.v3+json'} # response and parsing the response.response = requests.get(site_url, headers=headers)response_json = response.json() repositories = response_json['items'] # loop the repositoriesrepo_names, repo_stars = [], []for repo_info in repositories: repo_names.append(repo_info['name']) repo_stars.append(repo_info['stargazers_count']) # graph plotting data_plots = [{'type' : 'bar', 'x':repo_names , 'y': repo_stars}]layout = {'title': 'GItHubs Most Popular Javascript Projects', 'xaxis': {'title': 'Repository'}, 'yaxis': {'title': 'Stars'}} # saving graph to a Most_Popular_JavaScript_Repos.pngfig = {'data': data_plots, 'layout': layout}offline.plot(fig, image = 'png', image_filename='Most_Popular_JavaScript_Repos')", "e": 9451, "s": 8464, "text": null }, { "code": null, "e": 9581, "s": 9451, "text": "The above code when executed, will save the bar-chart to a png file – Most_Popular_JavaScript_Repos under the current repository." }, { "code": null, "e": 9632, "s": 9581, "text": "Step 8: Creating a Presentation... Introduction..." }, { "code": null, "e": 9826, "s": 9632, "text": "Microsoft production especially Spreadsheets and PowerPoint presentations are ruling the world. So we are going to create a PowerPoint presentation with the Visualization graph we just created." }, { "code": null, "e": 9886, "s": 9826, "text": "For installing python-pptx run this code into the terminal:" }, { "code": null, "e": 9910, "s": 9886, "text": "pip install python-pptx" }, { "code": null, "e": 10015, "s": 9910, "text": "We will begin by creating our first slide with the title — ” Popular JavaScript Repositories in Github”." }, { "code": null, "e": 10023, "s": 10015, "text": "Python3" }, { "code": "from pptx import Presentation # create an object pptppt = Presentation() # add a new slideslide = ppt.slides.add_slide(ppt.slide_layouts[0]) # Set the Text toslide.shapes.title.text = \"Popular JavaScript Repositories in GitHub\" # save the powerpointppt.save('Javascript_report.pptx')", "e": 10307, "s": 10023, "text": null }, { "code": null, "e": 10315, "s": 10307, "text": "Output:" }, { "code": null, "e": 10515, "s": 10315, "text": "We have first imported Presentation from ppt then create a ppt object using the Presentation class of ppt module. New slide is added with add_slide() method. The text is added using the slide.shapes." }, { "code": null, "e": 10549, "s": 10515, "text": "Step 9: Saving the chart to pptx." }, { "code": null, "e": 10690, "s": 10549, "text": "Now that the basics of creating a PowerPoint are covered in the above steps. Now let’s dive into the final piece of code to create a report." }, { "code": null, "e": 10698, "s": 10690, "text": "Python3" }, { "code": "from pptx import Presentationfrom pptx.util import Inchesfrom datetime import date # create an Objectppt = Presentation()first_slide = ppt.slides.add_slide(ppt.slide_layouts[0]) # title (included date)title = \"Popular JavaScript Repositories in GitHub - \" + str(date.today()) # set the title on first slidefirst_slide.shapes[0].text_frame.paragraphs[0].text = title # slide 2 - set the imageimg = 'Most_Popular_JavaScript_Repos.png'second_slide = ppt.slide_layouts[1]slide2 = ppt.slides.add_slide(second_slide) # play with the image attributes if you are not OK with the height and widthpic = slide2.shapes.add_picture(img, left= Inches(2),top = Inches(1),height = Inches(5)) # save the powerpoint presentationppt.save('Javascript_report.pptx')", "e": 11444, "s": 10698, "text": null }, { "code": null, "e": 11453, "s": 11444, "text": "Output: " }, { "code": null, "e": 11526, "s": 11453, "text": "Finally, we will put all the above steps discussed in a single program. " }, { "code": null, "e": 11534, "s": 11526, "text": "Python3" }, { "code": "import requestsfrom plotly.graph_objs import Barfrom plotly import offlinefrom pptx import Presentationfrom pptx.util import Inchesfrom datetime import date def github_api(): # siteurl and headers site_url = 'https://api.github.com/search/repositories?q=language:javascript&sort=stars' headers = {'Accept': 'application/vnd.github.v3+json'} # response and parsing the response. response = requests.get(site_url, headers=headers) response_json = response.json() repositories = response_json['items'] # loop the repositories repo_names, repo_stars = [], [] for repo_info in repositories: repo_names.append(repo_info['name']) repo_stars.append(repo_info['stargazers_count']) # graph plotting data_plots = [{'type' : 'bar', 'x':repo_names , 'y': repo_stars}] layout = {'title': 'GItHubs Most Popular Javascript Projects', 'xaxis': {'title': 'Repository'}, 'yaxis': {'title': 'Stars'}} # saving graph to a Most_Popular_JavaScript_Repos.png fig = {'data': data_plots, 'layout': layout} offline.plot(fig, image = 'png', image_filename='Most_Popular_JavaScript_Repos') def create_pptx_report(): # create an Object ppt = Presentation() first_slide = ppt.slides.add_slide(ppt.slide_layouts[0]) # title (included date) title = \"Popular JavaScript Repositories in GitHub - \" + str(date.today()) # set the title on first slide first_slide.shapes[0].text_frame.paragraphs[0].text = title # slide 2 - set the image img = 'Most_Popular_JavaScript_Repos.png' second_slide = ppt.slide_layouts[1] slide2 = ppt.slides.add_slide(second_slide) # play with the image attributes if you are not OK with the height and width pic = slide2.shapes.add_picture(img, left= Inches(2),top = Inches(1),height = Inches(5)) # save the powerpoint presentation ppt.save('Javascript_report.pptx') if __name__ == '__main__': github_api() create_pptx_report()", "e": 13515, "s": 11534, "text": null }, { "code": null, "e": 13526, "s": 13518, "text": "clintra" }, { "code": null, "e": 13544, "s": 13526, "text": "gulshankumarar231" }, { "code": null, "e": 13563, "s": 13544, "text": "Data Visualization" }, { "code": null, "e": 13578, "s": 13563, "text": "python-utility" }, { "code": null, "e": 13585, "s": 13578, "text": "Python" } ]
Convert BST to Min Heap
14 Mar, 2022 Given a binary search tree which is also a complete binary tree. The problem is to convert the given BST into a Min Heap with the condition that all the values in the left subtree of a node should be less than all the values in the right subtree of the node. This condition is applied on all the nodes in the so converted Min Heap. Examples: Input : 4 / \ 2 6 / \ / \ 1 3 5 7 Output : 1 / \ 2 5 / \ / \ 3 4 6 7 The given BST has been transformed into a Min Heap. All the nodes in the Min Heap satisfies the given condition, that is, values in the left subtree of a node should be less than the values in the right subtree of the node. Create an array arr[] of size n, where n is the number of nodes in the given BST.Perform the inorder traversal of the BST and copy the node values in the arr[] in sorted order.Now perform the preorder traversal of the tree.While traversing the root during the preorder traversal, one by one copy the values from the array arr[] to the nodes. Create an array arr[] of size n, where n is the number of nodes in the given BST. Perform the inorder traversal of the BST and copy the node values in the arr[] in sorted order. Now perform the preorder traversal of the tree. While traversing the root during the preorder traversal, one by one copy the values from the array arr[] to the nodes. C++ Java Python3 C# Javascript // C++ implementation to convert the given// BST to Min Heap#include <bits/stdc++.h>using namespace std; // structure of a node of BSTstruct Node { int data; Node *left, *right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct Node* getNode(int data){ struct Node* newNode = new Node; newNode->data = data; newNode->left = newNode->right = NULL; return newNode;} // function prototype for preorder traversal// of the given treevoid preorderTraversal(Node*); // function for the inorder traversal of the tree// so as to store the node values in 'arr' in// sorted ordervoid inorderTraversal(Node* root, vector<int>& arr){ if (root == NULL) return; // first recur on left subtree inorderTraversal(root->left, arr); // then copy the data of the node arr.push_back(root->data); // now recur for right subtree inorderTraversal(root->right, arr);} // function to convert the given BST to MIN HEAP// performs preorder traversal of the treevoid BSTToMinHeap(Node* root, vector<int> arr, int* i){ if (root == NULL) return; // first copy data at index 'i' of 'arr' to // the node root->data = arr[++*i]; // then recur on left subtree BSTToMinHeap(root->left, arr, i); // now recur on right subtree BSTToMinHeap(root->right, arr, i);} // utility function to convert the given BST to// MIN HEAPvoid convertToMinHeapUtil(Node* root){ // vector to store the data of all the // nodes of the BST vector<int> arr; int i = -1; // inorder traversal to populate 'arr' inorderTraversal(root, arr); // BST to MIN HEAP conversion BSTToMinHeap(root, arr, &i);} // function for the preorder traversal of the treevoid preorderTraversal(Node* root){ if (!root) return; // first print the root's data cout << root->data << " "; // then recur on left subtree preorderTraversal(root->left); // now recur on right subtree preorderTraversal(root->right);} // Driver program to test aboveint main(){ // BST formation struct Node* root = getNode(4); root->left = getNode(2); root->right = getNode(6); root->left->left = getNode(1); root->left->right = getNode(3); root->right->left = getNode(5); root->right->right = getNode(7); convertToMinHeapUtil(root); cout << "Preorder Traversal:" << endl; preorderTraversal(root); return 0;} // Java implementation to convert the given// BST to Min Heapimport java.util.ArrayList; class Gfg { static class Node { int data; Node left, right; // Constructor Node() { this.data = 0; this.left = this.right = null; } Node(int data) { this.data = data; this.left = this.right = null; } } private static void preOrder(Node root) { if (root == null) return; System.out.print(root.data + " "); preOrder(root.left); preOrder(root.right); } private static void bstToArray(Node root, ArrayList<Integer> arr) { // ArrayLIst stores elements in inorder fashion if (root == null) return; bstToArray(root.left, arr); arr.add(root.data); bstToArray(root.right, arr); } static int index; private static void arrToMinHeap(Node root, ArrayList<Integer> arr) { if (root == null) return; root.data = arr.get(index++); arrToMinHeap(root.left, arr); arrToMinHeap(root.right, arr); } static void convertToMinHeap(Node root) { //initialize static index to zero index = 0; ArrayList<Integer> arr = new ArrayList<Integer>(); bstToArray(root, arr); arrToMinHeap(root, arr); } // Driver program to test above public static void main(String[] args) { // BST formation Node root = new Node(4); root.left = new Node(2); root.right = new Node(6); root.left.left = new Node(1); root.left.right = new Node(3); root.right.left = new Node(5); root.right.right = new Node(7); System.out.print( "Preorder Traversal Before Conversion :" + "\n"); preOrder(root); convertToMinHeap(root); System.out.print( "\nPreorder Traversal After Conversion :" + "\n"); preOrder(root); }} // Contributed by : @mahi_07 /*Tip : If interviewer ask not to use global index variableyou can use LinkedList Instead of ArrayList and useLinkedList's removeFirst() method So instead of this root.data = arr.get(index++); you can write root.data = list.removeFirst(); Do not forget to initialize list in converttoMinHeapfunction*/ # C++ implementation to convert the# given BST to Min Heap # structure of a node of BST class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # function for the inorder traversal# of the tree so as to store the node# values in 'arr' in sorted order def inorderTraversal(root, arr): if root == None: return # first recur on left subtree inorderTraversal(root.left, arr) # then copy the data of the node arr.append(root.data) # now recur for right subtree inorderTraversal(root.right, arr) # function to convert the given# BST to MIN HEAP performs preorder# traversal of the tree def BSTToMinHeap(root, arr, i): if root == None: return # first copy data at index 'i' of # 'arr' to the node i[0] += 1 root.data = arr[i[0]] # then recur on left subtree BSTToMinHeap(root.left, arr, i) # now recur on right subtree BSTToMinHeap(root.right, arr, i) # utility function to convert the# given BST to MIN HEAP def convertToMinHeapUtil(root): # vector to store the data of # all the nodes of the BST arr = [] i = [-1] # inorder traversal to populate 'arr' inorderTraversal(root, arr) # BST to MIN HEAP conversion BSTToMinHeap(root, arr, i) # function for the preorder traversal# of the tree def preorderTraversal(root): if root == None: return # first print the root's data print(root.data, end=" ") # then recur on left subtree preorderTraversal(root.left) # now recur on right subtree preorderTraversal(root.right) # Driver Codeif __name__ == '__main__': # BST formation root = Node(4) root.left = Node(2) root.right = Node(6) root.left.left = Node(1) root.left.right = Node(3) root.right.left = Node(5) root.right.right = Node(7) convertToMinHeapUtil(root) print("Preorder Traversal:") preorderTraversal(root) # This code is contributed# by PranchalK // C# implementation to convert the given// BST to Min Heapusing System;using System.Collections.Generic;public class GFG { // structure of a node of BST public class Node { public int data; public Node left, right; }; /* Helper function that allocates a new node with the given data and null left and right pointers. */ static Node getNode(int data) { Node newNode = new Node(); newNode.data = data; newNode.left = newNode.right = null; return newNode; } // function prototype for preorder traversal // of the given tree // function for the inorder traversal of the tree // so as to store the node values in 'arr' in // sorted order static void inorderTraversal(Node root) { if (root == null) return; // first recur on left subtree inorderTraversal(root.left); // then copy the data of the node arr.Add(root.data); // now recur for right subtree inorderTraversal(root.right); } // function to convert the given BST to MIN HEAP // performs preorder traversal of the tree static void BSTToMinHeap(Node root) { if (root == null) return; // first copy data at index 'i' of 'arr' to // the node root.data = arr[++i]; // then recur on left subtree BSTToMinHeap(root.left); // now recur on right subtree BSTToMinHeap(root.right); } static List<int> arr = new List<int>(); static int i; // utility function to convert the given BST to // MIN HEAP static void convertToMinHeapUtil(Node root) { // vector to store the data of all the // nodes of the BST i = -1; // inorder traversal to populate 'arr' inorderTraversal(root); // BST to MIN HEAP conversion BSTToMinHeap(root); } // function for the preorder traversal of the tree static void preorderTraversal(Node root) { if (root == null) return; // first print the root's data Console.Write(root.data + " "); // then recur on left subtree preorderTraversal(root.left); // now recur on right subtree preorderTraversal(root.right); } // Driver program to test above public static void Main(String[] args) { // BST formation Node root = getNode(4); root.left = getNode(2); root.right = getNode(6); root.left.left = getNode(1); root.left.right = getNode(3); root.right.left = getNode(5); root.right.right = getNode(7); convertToMinHeapUtil(root); Console.Write("Preorder Traversal:" + "\n"); preorderTraversal(root); }} // This code contributed by Rajput-Ji <script> // JavaScript implementation to convert the given // BST to Min Heap // structure of a node of BST class Node { constructor() { this.data = 0; this.left = null; this.right = null; } } /* Helper function that allocates a new node with the given data and null left and right pointers. */ function getNode(data) { var newNode = new Node(); newNode.data = data; newNode.left = newNode.right = null; return newNode; } // function prototype for preorder traversal // of the given tree // function for the inorder traversal of the tree // so as to store the node values in 'arr' in // sorted order function inorderTraversal(root) { if (root == null) return; // first recur on left subtree inorderTraversal(root.left); // then copy the data of the node arr.push(root.data); // now recur for right subtree inorderTraversal(root.right); } // function to convert the given BST to MIN HEAP // performs preorder traversal of the tree function BSTToMinHeap(root) { if (root == null) return; // first copy data at index 'i' of 'arr' to // the node root.data = arr[++i]; // then recur on left subtree BSTToMinHeap(root.left); // now recur on right subtree BSTToMinHeap(root.right); } var arr = []; var i; // utility function to convert the given BST to // MIN HEAP function convertToMinHeapUtil(root) { // vector to store the data of all the // nodes of the BST i = -1; // inorder traversal to populate 'arr' inorderTraversal(root); // BST to MIN HEAP conversion BSTToMinHeap(root); } // function for the preorder traversal of the tree function preorderTraversal(root) { if (root == null) { return; } // first print the root's data document.write(root.data + " "); // then recur on left subtree preorderTraversal(root.left); // now recur on right subtree preorderTraversal(root.right); } // Driver program to test above // BST formation var root = getNode(4); root.left = getNode(2); root.right = getNode(6); root.left.left = getNode(1); root.left.right = getNode(3); root.right.left = getNode(5); root.right.right = getNode(7); convertToMinHeapUtil(root); document.write("Preorder Traversal:" + "<br>"); preorderTraversal(root); </script> Output: Preorder Traversal: 1 2 3 4 5 6 7 Time Complexity: O(n) Auxiliary Space: O(n) This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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. PranchalKatiyar aashish1995 Rajput-Ji mahi_07 rdtank rahulchintawar Binary Search Tree Heap Binary Search Tree Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Binary Search Tree | Set 1 (Search and Insertion) AVL Tree | Set 1 (Insertion) Binary Search Tree | Set 2 (Delete) Find postorder traversal of BST from preorder traversal A program to check if a binary tree is BST or not HeapSort K'th Smallest/Largest Element in Unsorted Array | Set 1 Introduction to Data Structures Huffman Coding | Greedy Algo-3 Sliding Window Maximum (Maximum of all subarrays of size k)
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Mar, 2022" }, { "code": null, "e": 398, "s": 54, "text": "Given a binary search tree which is also a complete binary tree. The problem is to convert the given BST into a Min Heap with the condition that all the values in the left subtree of a node should be less than all the values in the right subtree of the node. This condition is applied on all the nodes in the so converted Min Heap. Examples: " }, { "code": null, "e": 845, "s": 398, "text": "Input : 4\n / \\\n 2 6\n / \\ / \\\n 1 3 5 7 \n\nOutput : 1\n / \\\n 2 5\n / \\ / \\\n 3 4 6 7 \n\nThe given BST has been transformed into a\nMin Heap.\nAll the nodes in the Min Heap satisfies the given\ncondition, that is, values in the left subtree of\na node should be less than the values in the right\nsubtree of the node. " }, { "code": null, "e": 1191, "s": 849, "text": "Create an array arr[] of size n, where n is the number of nodes in the given BST.Perform the inorder traversal of the BST and copy the node values in the arr[] in sorted order.Now perform the preorder traversal of the tree.While traversing the root during the preorder traversal, one by one copy the values from the array arr[] to the nodes." }, { "code": null, "e": 1273, "s": 1191, "text": "Create an array arr[] of size n, where n is the number of nodes in the given BST." }, { "code": null, "e": 1369, "s": 1273, "text": "Perform the inorder traversal of the BST and copy the node values in the arr[] in sorted order." }, { "code": null, "e": 1417, "s": 1369, "text": "Now perform the preorder traversal of the tree." }, { "code": null, "e": 1536, "s": 1417, "text": "While traversing the root during the preorder traversal, one by one copy the values from the array arr[] to the nodes." }, { "code": null, "e": 1542, "s": 1538, "text": "C++" }, { "code": null, "e": 1547, "s": 1542, "text": "Java" }, { "code": null, "e": 1555, "s": 1547, "text": "Python3" }, { "code": null, "e": 1558, "s": 1555, "text": "C#" }, { "code": null, "e": 1569, "s": 1558, "text": "Javascript" }, { "code": "// C++ implementation to convert the given// BST to Min Heap#include <bits/stdc++.h>using namespace std; // structure of a node of BSTstruct Node { int data; Node *left, *right;}; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct Node* getNode(int data){ struct Node* newNode = new Node; newNode->data = data; newNode->left = newNode->right = NULL; return newNode;} // function prototype for preorder traversal// of the given treevoid preorderTraversal(Node*); // function for the inorder traversal of the tree// so as to store the node values in 'arr' in// sorted ordervoid inorderTraversal(Node* root, vector<int>& arr){ if (root == NULL) return; // first recur on left subtree inorderTraversal(root->left, arr); // then copy the data of the node arr.push_back(root->data); // now recur for right subtree inorderTraversal(root->right, arr);} // function to convert the given BST to MIN HEAP// performs preorder traversal of the treevoid BSTToMinHeap(Node* root, vector<int> arr, int* i){ if (root == NULL) return; // first copy data at index 'i' of 'arr' to // the node root->data = arr[++*i]; // then recur on left subtree BSTToMinHeap(root->left, arr, i); // now recur on right subtree BSTToMinHeap(root->right, arr, i);} // utility function to convert the given BST to// MIN HEAPvoid convertToMinHeapUtil(Node* root){ // vector to store the data of all the // nodes of the BST vector<int> arr; int i = -1; // inorder traversal to populate 'arr' inorderTraversal(root, arr); // BST to MIN HEAP conversion BSTToMinHeap(root, arr, &i);} // function for the preorder traversal of the treevoid preorderTraversal(Node* root){ if (!root) return; // first print the root's data cout << root->data << \" \"; // then recur on left subtree preorderTraversal(root->left); // now recur on right subtree preorderTraversal(root->right);} // Driver program to test aboveint main(){ // BST formation struct Node* root = getNode(4); root->left = getNode(2); root->right = getNode(6); root->left->left = getNode(1); root->left->right = getNode(3); root->right->left = getNode(5); root->right->right = getNode(7); convertToMinHeapUtil(root); cout << \"Preorder Traversal:\" << endl; preorderTraversal(root); return 0;}", "e": 4009, "s": 1569, "text": null }, { "code": "// Java implementation to convert the given// BST to Min Heapimport java.util.ArrayList; class Gfg { static class Node { int data; Node left, right; // Constructor Node() { this.data = 0; this.left = this.right = null; } Node(int data) { this.data = data; this.left = this.right = null; } } private static void preOrder(Node root) { if (root == null) return; System.out.print(root.data + \" \"); preOrder(root.left); preOrder(root.right); } private static void bstToArray(Node root, ArrayList<Integer> arr) { // ArrayLIst stores elements in inorder fashion if (root == null) return; bstToArray(root.left, arr); arr.add(root.data); bstToArray(root.right, arr); } static int index; private static void arrToMinHeap(Node root, ArrayList<Integer> arr) { if (root == null) return; root.data = arr.get(index++); arrToMinHeap(root.left, arr); arrToMinHeap(root.right, arr); } static void convertToMinHeap(Node root) { //initialize static index to zero index = 0; ArrayList<Integer> arr = new ArrayList<Integer>(); bstToArray(root, arr); arrToMinHeap(root, arr); } // Driver program to test above public static void main(String[] args) { // BST formation Node root = new Node(4); root.left = new Node(2); root.right = new Node(6); root.left.left = new Node(1); root.left.right = new Node(3); root.right.left = new Node(5); root.right.right = new Node(7); System.out.print( \"Preorder Traversal Before Conversion :\" + \"\\n\"); preOrder(root); convertToMinHeap(root); System.out.print( \"\\nPreorder Traversal After Conversion :\" + \"\\n\"); preOrder(root); }} // Contributed by : @mahi_07 /*Tip : If interviewer ask not to use global index variableyou can use LinkedList Instead of ArrayList and useLinkedList's removeFirst() method So instead of this root.data = arr.get(index++); you can write root.data = list.removeFirst(); Do not forget to initialize list in converttoMinHeapfunction*/", "e": 6454, "s": 4009, "text": null }, { "code": "# C++ implementation to convert the# given BST to Min Heap # structure of a node of BST class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # function for the inorder traversal# of the tree so as to store the node# values in 'arr' in sorted order def inorderTraversal(root, arr): if root == None: return # first recur on left subtree inorderTraversal(root.left, arr) # then copy the data of the node arr.append(root.data) # now recur for right subtree inorderTraversal(root.right, arr) # function to convert the given# BST to MIN HEAP performs preorder# traversal of the tree def BSTToMinHeap(root, arr, i): if root == None: return # first copy data at index 'i' of # 'arr' to the node i[0] += 1 root.data = arr[i[0]] # then recur on left subtree BSTToMinHeap(root.left, arr, i) # now recur on right subtree BSTToMinHeap(root.right, arr, i) # utility function to convert the# given BST to MIN HEAP def convertToMinHeapUtil(root): # vector to store the data of # all the nodes of the BST arr = [] i = [-1] # inorder traversal to populate 'arr' inorderTraversal(root, arr) # BST to MIN HEAP conversion BSTToMinHeap(root, arr, i) # function for the preorder traversal# of the tree def preorderTraversal(root): if root == None: return # first print the root's data print(root.data, end=\" \") # then recur on left subtree preorderTraversal(root.left) # now recur on right subtree preorderTraversal(root.right) # Driver Codeif __name__ == '__main__': # BST formation root = Node(4) root.left = Node(2) root.right = Node(6) root.left.left = Node(1) root.left.right = Node(3) root.right.left = Node(5) root.right.right = Node(7) convertToMinHeapUtil(root) print(\"Preorder Traversal:\") preorderTraversal(root) # This code is contributed# by PranchalK", "e": 8463, "s": 6454, "text": null }, { "code": "// C# implementation to convert the given// BST to Min Heapusing System;using System.Collections.Generic;public class GFG { // structure of a node of BST public class Node { public int data; public Node left, right; }; /* Helper function that allocates a new node with the given data and null left and right pointers. */ static Node getNode(int data) { Node newNode = new Node(); newNode.data = data; newNode.left = newNode.right = null; return newNode; } // function prototype for preorder traversal // of the given tree // function for the inorder traversal of the tree // so as to store the node values in 'arr' in // sorted order static void inorderTraversal(Node root) { if (root == null) return; // first recur on left subtree inorderTraversal(root.left); // then copy the data of the node arr.Add(root.data); // now recur for right subtree inorderTraversal(root.right); } // function to convert the given BST to MIN HEAP // performs preorder traversal of the tree static void BSTToMinHeap(Node root) { if (root == null) return; // first copy data at index 'i' of 'arr' to // the node root.data = arr[++i]; // then recur on left subtree BSTToMinHeap(root.left); // now recur on right subtree BSTToMinHeap(root.right); } static List<int> arr = new List<int>(); static int i; // utility function to convert the given BST to // MIN HEAP static void convertToMinHeapUtil(Node root) { // vector to store the data of all the // nodes of the BST i = -1; // inorder traversal to populate 'arr' inorderTraversal(root); // BST to MIN HEAP conversion BSTToMinHeap(root); } // function for the preorder traversal of the tree static void preorderTraversal(Node root) { if (root == null) return; // first print the root's data Console.Write(root.data + \" \"); // then recur on left subtree preorderTraversal(root.left); // now recur on right subtree preorderTraversal(root.right); } // Driver program to test above public static void Main(String[] args) { // BST formation Node root = getNode(4); root.left = getNode(2); root.right = getNode(6); root.left.left = getNode(1); root.left.right = getNode(3); root.right.left = getNode(5); root.right.right = getNode(7); convertToMinHeapUtil(root); Console.Write(\"Preorder Traversal:\" + \"\\n\"); preorderTraversal(root); }} // This code contributed by Rajput-Ji", "e": 11282, "s": 8463, "text": null }, { "code": "<script> // JavaScript implementation to convert the given // BST to Min Heap // structure of a node of BST class Node { constructor() { this.data = 0; this.left = null; this.right = null; } } /* Helper function that allocates a new node with the given data and null left and right pointers. */ function getNode(data) { var newNode = new Node(); newNode.data = data; newNode.left = newNode.right = null; return newNode; } // function prototype for preorder traversal // of the given tree // function for the inorder traversal of the tree // so as to store the node values in 'arr' in // sorted order function inorderTraversal(root) { if (root == null) return; // first recur on left subtree inorderTraversal(root.left); // then copy the data of the node arr.push(root.data); // now recur for right subtree inorderTraversal(root.right); } // function to convert the given BST to MIN HEAP // performs preorder traversal of the tree function BSTToMinHeap(root) { if (root == null) return; // first copy data at index 'i' of 'arr' to // the node root.data = arr[++i]; // then recur on left subtree BSTToMinHeap(root.left); // now recur on right subtree BSTToMinHeap(root.right); } var arr = []; var i; // utility function to convert the given BST to // MIN HEAP function convertToMinHeapUtil(root) { // vector to store the data of all the // nodes of the BST i = -1; // inorder traversal to populate 'arr' inorderTraversal(root); // BST to MIN HEAP conversion BSTToMinHeap(root); } // function for the preorder traversal of the tree function preorderTraversal(root) { if (root == null) { return; } // first print the root's data document.write(root.data + \" \"); // then recur on left subtree preorderTraversal(root.left); // now recur on right subtree preorderTraversal(root.right); } // Driver program to test above // BST formation var root = getNode(4); root.left = getNode(2); root.right = getNode(6); root.left.left = getNode(1); root.left.right = getNode(3); root.right.left = getNode(5); root.right.right = getNode(7); convertToMinHeapUtil(root); document.write(\"Preorder Traversal:\" + \"<br>\"); preorderTraversal(root); </script>", "e": 13939, "s": 11282, "text": null }, { "code": null, "e": 13949, "s": 13939, "text": "Output: " }, { "code": null, "e": 13983, "s": 13949, "text": "Preorder Traversal:\n1 2 3 4 5 6 7" }, { "code": null, "e": 14451, "s": 13983, "text": "Time Complexity: O(n) Auxiliary Space: O(n) This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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": 14467, "s": 14451, "text": "PranchalKatiyar" }, { "code": null, "e": 14479, "s": 14467, "text": "aashish1995" }, { "code": null, "e": 14489, "s": 14479, "text": "Rajput-Ji" }, { "code": null, "e": 14497, "s": 14489, "text": "mahi_07" }, { "code": null, "e": 14504, "s": 14497, "text": "rdtank" }, { "code": null, "e": 14519, "s": 14504, "text": "rahulchintawar" }, { "code": null, "e": 14538, "s": 14519, "text": "Binary Search Tree" }, { "code": null, "e": 14543, "s": 14538, "text": "Heap" }, { "code": null, "e": 14562, "s": 14543, "text": "Binary Search Tree" }, { "code": null, "e": 14567, "s": 14562, "text": "Heap" }, { "code": null, "e": 14665, "s": 14567, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14715, "s": 14665, "text": "Binary Search Tree | Set 1 (Search and Insertion)" }, { "code": null, "e": 14744, "s": 14715, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 14780, "s": 14744, "text": "Binary Search Tree | Set 2 (Delete)" }, { "code": null, "e": 14836, "s": 14780, "text": "Find postorder traversal of BST from preorder traversal" }, { "code": null, "e": 14886, "s": 14836, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 14895, "s": 14886, "text": "HeapSort" }, { "code": null, "e": 14951, "s": 14895, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 14983, "s": 14951, "text": "Introduction to Data Structures" }, { "code": null, "e": 15014, "s": 14983, "text": "Huffman Coding | Greedy Algo-3" } ]
JavaScript Instanceof Operator
11 Sep, 2020 Below is the example of the Instanceof Operator. Example:<!DOCTYPE html> <html> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <p id="GFG"></p> <script> var a = ["Geeks", "for", "Geeks"]; document.getElementById("GFG").innerHTML = (a instanceof Array) + "<br>" + (a instanceof Number); </script> </center> </body> </html> <!DOCTYPE html> <html> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <p id="GFG"></p> <script> var a = ["Geeks", "for", "Geeks"]; document.getElementById("GFG").innerHTML = (a instanceof Array) + "<br>" + (a instanceof Number); </script> </center> </body> </html> Output: The instanceof operator in JavaScript is used to check the type of an object at run time. It returns a boolean value if true then it indicates that the object is an instance of a particular class and if false then it is not. Syntax: var gfg = objectName instanceof objectType Parameters:objectName: States the name of Object. Example-1: objectTypes. <!DOCTYPE html><html> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <p id="GFG"></p> <script> var fruits = ["Apple", "Mango", "Banana"]; document.getElementById("GFG").innerHTML = (fruits instanceof Array) + "<br>" + (fruits instanceof Object) + "<br>" + (fruits instanceof String) + "<br>" + (fruits instanceof Number); </script> </center></body> </html> Output: Example-2: Demonstrating that String and Date objects are also a type of Object (derived from Object). <!DOCTYPE html><html> <body> <h1 style="color:green">GeeksforGeeks</h1> <p id="GFG"></p> <script> var myString = new String(); var myDate = new Date(); console.log(myString instanceof Object); console.log(myString instanceof Date); console.log(myString instanceof String); console.log(myDate instanceof Date); console.log(myDate instanceof Object); console.log(myDate instanceof String); </script></body> </html> Output Supported Browsers: Google Chrome Firefox Edge Opera Apple Safari javascript-operators Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Sep, 2020" }, { "code": null, "e": 77, "s": 28, "text": "Below is the example of the Instanceof Operator." }, { "code": null, "e": 469, "s": 77, "text": "Example:<!DOCTYPE html> <html> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <p id=\"GFG\"></p> <script> var a = [\"Geeks\", \"for\", \"Geeks\"]; document.getElementById(\"GFG\").innerHTML = (a instanceof Array) + \"<br>\" + (a instanceof Number); </script> </center> </body> </html> " }, { "code": "<!DOCTYPE html> <html> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <p id=\"GFG\"></p> <script> var a = [\"Geeks\", \"for\", \"Geeks\"]; document.getElementById(\"GFG\").innerHTML = (a instanceof Array) + \"<br>\" + (a instanceof Number); </script> </center> </body> </html> ", "e": 853, "s": 469, "text": null }, { "code": null, "e": 861, "s": 853, "text": "Output:" }, { "code": null, "e": 1086, "s": 861, "text": "The instanceof operator in JavaScript is used to check the type of an object at run time. It returns a boolean value if true then it indicates that the object is an instance of a particular class and if false then it is not." }, { "code": null, "e": 1094, "s": 1086, "text": "Syntax:" }, { "code": null, "e": 1137, "s": 1094, "text": "var gfg = objectName instanceof objectType" }, { "code": null, "e": 1187, "s": 1137, "text": "Parameters:objectName: States the name of Object." }, { "code": null, "e": 1211, "s": 1187, "text": "Example-1: objectTypes." }, { "code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <p id=\"GFG\"></p> <script> var fruits = [\"Apple\", \"Mango\", \"Banana\"]; document.getElementById(\"GFG\").innerHTML = (fruits instanceof Array) + \"<br>\" + (fruits instanceof Object) + \"<br>\" + (fruits instanceof String) + \"<br>\" + (fruits instanceof Number); </script> </center></body> </html>", "e": 1704, "s": 1211, "text": null }, { "code": null, "e": 1712, "s": 1704, "text": "Output:" }, { "code": null, "e": 1815, "s": 1712, "text": "Example-2: Demonstrating that String and Date objects are also a type of Object (derived from Object)." }, { "code": "<!DOCTYPE html><html> <body> <h1 style=\"color:green\">GeeksforGeeks</h1> <p id=\"GFG\"></p> <script> var myString = new String(); var myDate = new Date(); console.log(myString instanceof Object); console.log(myString instanceof Date); console.log(myString instanceof String); console.log(myDate instanceof Date); console.log(myDate instanceof Object); console.log(myDate instanceof String); </script></body> </html>", "e": 2304, "s": 1815, "text": null }, { "code": null, "e": 2311, "s": 2304, "text": "Output" }, { "code": null, "e": 2331, "s": 2311, "text": "Supported Browsers:" }, { "code": null, "e": 2345, "s": 2331, "text": "Google Chrome" }, { "code": null, "e": 2353, "s": 2345, "text": "Firefox" }, { "code": null, "e": 2358, "s": 2353, "text": "Edge" }, { "code": null, "e": 2364, "s": 2358, "text": "Opera" }, { "code": null, "e": 2377, "s": 2364, "text": "Apple Safari" }, { "code": null, "e": 2398, "s": 2377, "text": "javascript-operators" }, { "code": null, "e": 2405, "s": 2398, "text": "Picked" }, { "code": null, "e": 2416, "s": 2405, "text": "JavaScript" }, { "code": null, "e": 2433, "s": 2416, "text": "Web Technologies" } ]
C# | Abstract Classes
08 Jun, 2022 Abstraction in C# is the process to hide the internal details and show only the functionality. The abstract modifier indicates the incomplete implementation. The keyword abstract is used before the class or method to declare the class or method as abstract. Also, the abstract modifier can be used with indexers, events, and properties. Example: public abstract void geek(); // this indicates the method 'geek()' is abstract abstract class gfg // this indicates the class 'gfg' is abstract Abstract Method: A method that is declared abstract, has no “body” and is declared inside the abstract class only. An abstract method must be implemented in all non-abstract classes using the override keyword. After overriding, the abstract method is in the non-Abstract class. We can derive this class in another class, and again we can override the same abstract method with it. Syntax: public abstract void geek(); // the method 'geek()' is abstract Abstract Class: This is the way to achieve the abstraction in C#. An Abstract class is never intended to be instantiated directly. An abstract class can also be created without any abstract methods, We can mark a class abstract even if doesn’t have any abstract method. The Abstract classes are typically used to define a base class in the class hierarchy. Or in other words, an abstract class is an incomplete class or a special class we can’t be instantiated. The purpose of an abstract class is to provide a blueprint for derived classes and set some rules that the derived classes must implement when they inherit an abstract class. We can use an abstract class as a base class and all derived classes must implement abstract definitions. Syntax: abstract class gfg{} // class 'gfg' is abstract Important Points: Generally, we use abstract class at the time of inheritance. A user must use the override keyword before the method is declared as abstract in the child class, the abstract class is used to inherit in the child class. An abstract class cannot be inherited by structures. It can contain constructors or destructors. It can implement functions with non-Abstract methods. It cannot support multiple inheritances. It can’t be static. Example 1: Program to show the working of an abstract class C# // C# program to show the// working of abstract classusing System; // abstract class 'GeeksForGeeks'public abstract class GeeksForGeeks { // abstract method 'gfg()' public abstract void gfg(); } // class 'GeeksForGeeks' inherit// in child class 'Geek1'public class Geek1 : GeeksForGeeks{ // abstract method 'gfg()' // declare here with // 'override' keyword public override void gfg() { Console.WriteLine("class Geek1"); }} // class 'GeeksForGeeks' inherit in// another child class 'Geek2'public class Geek2 : GeeksForGeeks{ // same as the previous class public override void gfg() { Console.WriteLine("class Geek2"); }} // Driver Classpublic class main_method { // Main Method public static void Main() { // 'g' is object of class // 'GeeksForGeeks' class ' // GeeksForGeeks' cannot // be instantiate GeeksForGeeks g; // instantiate class 'Geek1' g = new Geek1(); // call 'gfg()' of class 'Geek1' g.gfg(); // instantiate class 'Geek2' g = new Geek2(); // call 'gfg()' of class 'Geek2' g.gfg(); }} class Geek1 class Geek2 Example 2: Program to calculate the area of a square using abstract class and abstract method C# // C# program to calculate the area// of a Square using abstract class// and abstract methodusing System; // declare class 'AreaClass'// as abstractabstract class AreaClass{ // declare method // 'Area' as abstract abstract public int Area();} // class 'AreaClass' inherit// in child class 'Square'class Square : AreaClass{ int side = 0; // constructor public Square(int n) { side = n; } // the abstract method // 'Area' is overridden here public override int Area() { return side * side; }} class gfg { // Main Method public static void Main() { Square s = new Square(6); Console.WriteLine("Area = " + s.Area()); }} Area = 36 Following are some important observations about abstract classes in C# 1) An Abstract class does not mean that it only contains abstract methods. An Abstract class can also contain non-abstract methods also. Syntax: abstract class gfg { public void geek() { Console.WriteLine("'geek()' is non-abstract method"); } } Example: C# // C# program to show the working of// the non-abstract method in the// abstract classusing System; abstract class AbstractClass { // Non abstract method public int AddTwoNumbers(int Num1, int Num2) { return Num1 + Num2; } // An abstract method which // overridden in the derived class public abstract int MultiplyTwoNumbers(int Num1, int Num2); } // Child Class of AbstractClassclass Derived : AbstractClass { // implementing the abstract // method 'MultiplyTwoNumbers' // using override keyword, public override int MultiplyTwoNumbers(int Num1, int Num2) { return Num1 * Num2; }} // Driver Classclass geek { // Main Method public static void Main() { // Instance of the derived class Derived d = new Derived(); Console.WriteLine("Addition : {0}\nMultiplication :{1}", d.AddTwoNumbers(4, 6), d.MultiplyTwoNumbers(6, 4)); }} Addition : 10 Multiplication :24 2) Abstract class can also work with get and set accessors. Example: C# // C# program to show the working// of abstract class with the// get and set accessorsusing System; abstract class absClass { protected int myNumber; public abstract int numbers { get; set; }} class absDerived : absClass { // Implementing abstract properties public override int numbers { get { return myNumber; } set { myNumber = value; } }} // Driver Classclass geek { // Main Method public static void Main() { absDerived d = new absDerived(); d.numbers = 5; Console.WriteLine(d.numbers); }} 5 mahanteshng Ambika Goyal saikatt1999 CSharp-OOP Picked Technical Scripter 2018 C# Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Multiple inheritance using interfaces Introduction to .NET Framework C# | Delegates Differences Between .NET Core and .NET Framework C# | Data Types C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method C# | Arrays Extension Method in C#
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jun, 2022" }, { "code": null, "e": 392, "s": 54, "text": "Abstraction in C# is the process to hide the internal details and show only the functionality. The abstract modifier indicates the incomplete implementation. The keyword abstract is used before the class or method to declare the class or method as abstract. Also, the abstract modifier can be used with indexers, events, and properties. " }, { "code": null, "e": 402, "s": 392, "text": "Example: " }, { "code": null, "e": 548, "s": 402, "text": "public abstract void geek();\n// this indicates the method 'geek()' is abstract\n \nabstract class gfg\n// this indicates the class 'gfg' is abstract" }, { "code": null, "e": 929, "s": 548, "text": "Abstract Method: A method that is declared abstract, has no “body” and is declared inside the abstract class only. An abstract method must be implemented in all non-abstract classes using the override keyword. After overriding, the abstract method is in the non-Abstract class. We can derive this class in another class, and again we can override the same abstract method with it." }, { "code": null, "e": 938, "s": 929, "text": "Syntax: " }, { "code": null, "e": 1002, "s": 938, "text": "public abstract void geek();\n// the method 'geek()' is abstract" }, { "code": null, "e": 1746, "s": 1002, "text": "Abstract Class: This is the way to achieve the abstraction in C#. An Abstract class is never intended to be instantiated directly. An abstract class can also be created without any abstract methods, We can mark a class abstract even if doesn’t have any abstract method. The Abstract classes are typically used to define a base class in the class hierarchy. Or in other words, an abstract class is an incomplete class or a special class we can’t be instantiated. The purpose of an abstract class is to provide a blueprint for derived classes and set some rules that the derived classes must implement when they inherit an abstract class. We can use an abstract class as a base class and all derived classes must implement abstract definitions. " }, { "code": null, "e": 1756, "s": 1746, "text": "Syntax: " }, { "code": null, "e": 1804, "s": 1756, "text": "abstract class gfg{}\n// class 'gfg' is abstract" }, { "code": null, "e": 1823, "s": 1804, "text": "Important Points: " }, { "code": null, "e": 1884, "s": 1823, "text": "Generally, we use abstract class at the time of inheritance." }, { "code": null, "e": 2041, "s": 1884, "text": "A user must use the override keyword before the method is declared as abstract in the child class, the abstract class is used to inherit in the child class." }, { "code": null, "e": 2094, "s": 2041, "text": "An abstract class cannot be inherited by structures." }, { "code": null, "e": 2138, "s": 2094, "text": "It can contain constructors or destructors." }, { "code": null, "e": 2192, "s": 2138, "text": "It can implement functions with non-Abstract methods." }, { "code": null, "e": 2233, "s": 2192, "text": "It cannot support multiple inheritances." }, { "code": null, "e": 2253, "s": 2233, "text": "It can’t be static." }, { "code": null, "e": 2313, "s": 2253, "text": "Example 1: Program to show the working of an abstract class" }, { "code": null, "e": 2316, "s": 2313, "text": "C#" }, { "code": "// C# program to show the// working of abstract classusing System; // abstract class 'GeeksForGeeks'public abstract class GeeksForGeeks { // abstract method 'gfg()' public abstract void gfg(); } // class 'GeeksForGeeks' inherit// in child class 'Geek1'public class Geek1 : GeeksForGeeks{ // abstract method 'gfg()' // declare here with // 'override' keyword public override void gfg() { Console.WriteLine(\"class Geek1\"); }} // class 'GeeksForGeeks' inherit in// another child class 'Geek2'public class Geek2 : GeeksForGeeks{ // same as the previous class public override void gfg() { Console.WriteLine(\"class Geek2\"); }} // Driver Classpublic class main_method { // Main Method public static void Main() { // 'g' is object of class // 'GeeksForGeeks' class ' // GeeksForGeeks' cannot // be instantiate GeeksForGeeks g; // instantiate class 'Geek1' g = new Geek1(); // call 'gfg()' of class 'Geek1' g.gfg(); // instantiate class 'Geek2' g = new Geek2(); // call 'gfg()' of class 'Geek2' g.gfg(); }}", "e": 3510, "s": 2316, "text": null }, { "code": null, "e": 3534, "s": 3510, "text": "class Geek1\nclass Geek2" }, { "code": null, "e": 3630, "s": 3536, "text": "Example 2: Program to calculate the area of a square using abstract class and abstract method" }, { "code": null, "e": 3633, "s": 3630, "text": "C#" }, { "code": "// C# program to calculate the area// of a Square using abstract class// and abstract methodusing System; // declare class 'AreaClass'// as abstractabstract class AreaClass{ // declare method // 'Area' as abstract abstract public int Area();} // class 'AreaClass' inherit// in child class 'Square'class Square : AreaClass{ int side = 0; // constructor public Square(int n) { side = n; } // the abstract method // 'Area' is overridden here public override int Area() { return side * side; }} class gfg { // Main Method public static void Main() { Square s = new Square(6); Console.WriteLine(\"Area = \" + s.Area()); }}", "e": 4332, "s": 3633, "text": null }, { "code": null, "e": 4343, "s": 4332, "text": "Area = 36" }, { "code": null, "e": 4553, "s": 4345, "text": "Following are some important observations about abstract classes in C# 1) An Abstract class does not mean that it only contains abstract methods. An Abstract class can also contain non-abstract methods also." }, { "code": null, "e": 4563, "s": 4553, "text": "Syntax: " }, { "code": null, "e": 4683, "s": 4563, "text": "abstract class gfg\n{\n public void geek()\n {\n Console.WriteLine(\"'geek()' is non-abstract method\");\n }\n}" }, { "code": null, "e": 4692, "s": 4683, "text": "Example:" }, { "code": null, "e": 4695, "s": 4692, "text": "C#" }, { "code": "// C# program to show the working of// the non-abstract method in the// abstract classusing System; abstract class AbstractClass { // Non abstract method public int AddTwoNumbers(int Num1, int Num2) { return Num1 + Num2; } // An abstract method which // overridden in the derived class public abstract int MultiplyTwoNumbers(int Num1, int Num2); } // Child Class of AbstractClassclass Derived : AbstractClass { // implementing the abstract // method 'MultiplyTwoNumbers' // using override keyword, public override int MultiplyTwoNumbers(int Num1, int Num2) { return Num1 * Num2; }} // Driver Classclass geek { // Main Method public static void Main() { // Instance of the derived class Derived d = new Derived(); Console.WriteLine(\"Addition : {0}\\nMultiplication :{1}\", d.AddTwoNumbers(4, 6), d.MultiplyTwoNumbers(6, 4)); }}", "e": 5693, "s": 4695, "text": null }, { "code": null, "e": 5726, "s": 5693, "text": "Addition : 10\nMultiplication :24" }, { "code": null, "e": 5788, "s": 5728, "text": "2) Abstract class can also work with get and set accessors." }, { "code": null, "e": 5797, "s": 5788, "text": "Example:" }, { "code": null, "e": 5800, "s": 5797, "text": "C#" }, { "code": "// C# program to show the working// of abstract class with the// get and set accessorsusing System; abstract class absClass { protected int myNumber; public abstract int numbers { get; set; }} class absDerived : absClass { // Implementing abstract properties public override int numbers { get { return myNumber; } set { myNumber = value; } }} // Driver Classclass geek { // Main Method public static void Main() { absDerived d = new absDerived(); d.numbers = 5; Console.WriteLine(d.numbers); }}", "e": 6434, "s": 5800, "text": null }, { "code": null, "e": 6436, "s": 6434, "text": "5" }, { "code": null, "e": 6450, "s": 6438, "text": "mahanteshng" }, { "code": null, "e": 6463, "s": 6450, "text": "Ambika Goyal" }, { "code": null, "e": 6475, "s": 6463, "text": "saikatt1999" }, { "code": null, "e": 6486, "s": 6475, "text": "CSharp-OOP" }, { "code": null, "e": 6493, "s": 6486, "text": "Picked" }, { "code": null, "e": 6517, "s": 6493, "text": "Technical Scripter 2018" }, { "code": null, "e": 6520, "s": 6517, "text": "C#" }, { "code": null, "e": 6539, "s": 6520, "text": "Technical Scripter" }, { "code": null, "e": 6637, "s": 6539, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6665, "s": 6637, "text": "C# Dictionary with examples" }, { "code": null, "e": 6708, "s": 6665, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 6739, "s": 6708, "text": "Introduction to .NET Framework" }, { "code": null, "e": 6754, "s": 6739, "text": "C# | Delegates" }, { "code": null, "e": 6803, "s": 6754, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 6819, "s": 6803, "text": "C# | Data Types" }, { "code": null, "e": 6859, "s": 6819, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 6881, "s": 6859, "text": "C# | Replace() Method" }, { "code": null, "e": 6893, "s": 6881, "text": "C# | Arrays" } ]
How to set time timezone and synchronize system clock using timedatectl command
Do you know how to set Time, Timezone from Linux Command Line? If not, then the timedatectl command helps you to set time and Timezone and it comes as a part of systemd system and service manager. This article describes “How to Set Time, Timezone and Synchronize System Clock using timedatectl Command” To display time and current date on Linux, use the following command – $ timedatectl status The sample output should be like this – Local time: Fri 2016-03-11 11:23:54 IST Universal time: Fri 2016-03-11 05:53:54 UTC Timezone: Asia/Kolkata (IST, +0530) NTP enabled: yes NTP synchronized: no RTC in local TZ: no DST active: n/a System time is managed through Timezone. To get Timezone of your system, use the following command – $ timedatectl The sample output should be like this – Local time: Fri 2016-03-11 11:30:12 IST Universal time: Fri 2016-03-11 06:00:12 UTC Timezone: Asia/Kolkata (IST, +0530) NTP enabled: yes NTP synchronized: no RTC in local TZ: no DST active: n/a To get the available timezones, use the following command – $ timedatectl list-timezones The sample output should be like this – Africa/Abidjan Africa/Accra Africa/Addis_Ababa Africa/Algiers Africa/Asmara Africa/Bamako Africa/Bangui Africa/Banjul Africa/Bissau Africa/Blantyre Africa/Brazzaville Africa/Bujumbura Africa/Cairo Africa/Casablanca Africa/Ceuta Africa/Conakry Africa/Dakar Africa/Dar_es_Salaam Africa/Djibouti Africa/Douala ..................... To set your local timezone in Linux, use the following command- $ timedatectl set-timezone “Asia/Kolkata” To verify the above command result, use the following command – $ timedatectl The sample output should be like this – Local time: Fri 2016-03-11 11:42:22 IST Universal time: Fri 2016-03-11 06:12:22 UTC RTC time: Fri 2016-03-11 11:42:29 Timezone: Asia/Kolkata (IST, +0530) NTP enabled: yes NTP synchronized: no RTC in local TZ: no DST active: n/a To set our time zone according to UTF, use the following command – $ timedatectl set-timezone UTC To verify above command result, use the following command – $ timedatectl The sample output should be like this – Local time: Fri 2016-03-11 06:15:58 UTC Universal time: Fri 2016-03-11 06:15:58 UTC Timezone: UTC (UTC, +0000) NTP enabled: yes NTP synchronized: no RTC in local TZ: no DST active: n/a To set Time and Date, use the following command – $ timedatectl set-time 15:58:30 To verify the above command result, use the following command – $ timedatectl The sample output should be like this – Local time: Fri 2016-03-11 15:58:40 IST Universal time: Fri 2016-03-11 10:28:40 UTC Timezone: Asia/Kolkata (IST, +0530) NTP enabled: yes NTP synchronized: no RTC in local TZ: no DST active: n/a To set date from command line, use the following command – $ timedatectl set-time 2015-11-20 To verify the above command result, use the following command- $ timedatectl The sample output should be like this – Local time: Fri 2015-11-20 00:00:06 IST Universal time: Thu 2015-11-19 18:30:06 UTC Timezone: Asia/Kolkata (IST, +0530) NTP enabled: yes NTP synchronized: no RTC in local TZ: no DST active: n/a To set both date and time, use the following command- $ sudo timedatectl set-time "2014-11-08 06:40:00" To verify the above command result, use the following command – $ timedatectl The sample output should be like this – Local time: Sat 2014-11-08 06:40:11 IST Universal time: Sat 2014-11-08 01:10:11 UTC Timezone: Asia/Kolkata (IST, +0530) NTP enabled: yes NTP synchronized: no RTC in local TZ: no DST active: n/a To Display Hardware Clock Date and Time, use the following command – # hwclock The sample output should be like this – # hwclock Friday 11 March 2016 12:25:56 PM IST -0.594257 seconds To copy system time to hardware time, use the following command- # hwclock --systohc To verify it, use the following commands- # hwclock (for hardware date and time) # date (for system date and time) The sample output should be like this – # hwclock Friday 11 March 2016 01:53:03 PM IST -0.359815 seconds # date Fri Mar 11 13:53:05 IST 2016 In the above result, both hardware clock and system clock has the same result. NTP stands for Network Time Protocol which is an internet protocol is used to synchronize approach clock between computers. The timedatectl utility makes it possible for to routinely sync your Linux system clock with remote servers utilizing NTP. To start automatic time synchronization with remote NTP server, use the following command- # timedatectl set-ntp true To disable NTP time synchronization, use the following command – # timedatectl set-ntp false Congratulations! Now, you know “How to Set Time, Timezone and Synchronize System Clock Using timedatectl Command”. We’ll learn more about these types of commands in our next Linux post. Keep reading!
[ { "code": null, "e": 1490, "s": 1187, "text": "Do you know how to set Time, Timezone from Linux Command Line? If not, then the timedatectl command helps you to set time and Timezone and it comes as a part of systemd system and service manager. This article describes “How to Set Time, Timezone and Synchronize System Clock using timedatectl Command”" }, { "code": null, "e": 1561, "s": 1490, "text": "To display time and current date on Linux, use the following command –" }, { "code": null, "e": 1582, "s": 1561, "text": "$ timedatectl status" }, { "code": null, "e": 1622, "s": 1582, "text": "The sample output should be like this –" }, { "code": null, "e": 1844, "s": 1622, "text": " Local time: Fri 2016-03-11 11:23:54 IST\n Universal time: Fri 2016-03-11 05:53:54 UTC\n Timezone: Asia/Kolkata (IST, +0530)\n NTP enabled: yes\nNTP synchronized: no\n RTC in local TZ: no\n DST active: n/a" }, { "code": null, "e": 1945, "s": 1844, "text": "System time is managed through Timezone. To get Timezone of your system, use the following command –" }, { "code": null, "e": 1959, "s": 1945, "text": "$ timedatectl" }, { "code": null, "e": 1999, "s": 1959, "text": "The sample output should be like this –" }, { "code": null, "e": 2221, "s": 1999, "text": " Local time: Fri 2016-03-11 11:30:12 IST\n Universal time: Fri 2016-03-11 06:00:12 UTC\n Timezone: Asia/Kolkata (IST, +0530)\n NTP enabled: yes\nNTP synchronized: no\n RTC in local TZ: no\n DST active: n/a" }, { "code": null, "e": 2281, "s": 2221, "text": "To get the available timezones, use the following command –" }, { "code": null, "e": 2310, "s": 2281, "text": "$ timedatectl list-timezones" }, { "code": null, "e": 2350, "s": 2310, "text": "The sample output should be like this –" }, { "code": null, "e": 2679, "s": 2350, "text": "Africa/Abidjan\nAfrica/Accra\nAfrica/Addis_Ababa\nAfrica/Algiers\nAfrica/Asmara\nAfrica/Bamako\nAfrica/Bangui\nAfrica/Banjul\nAfrica/Bissau\nAfrica/Blantyre\nAfrica/Brazzaville\nAfrica/Bujumbura\nAfrica/Cairo\nAfrica/Casablanca\nAfrica/Ceuta\nAfrica/Conakry\nAfrica/Dakar\nAfrica/Dar_es_Salaam\nAfrica/Djibouti\nAfrica/Douala\n....................." }, { "code": null, "e": 2743, "s": 2679, "text": "To set your local timezone in Linux, use the following command-" }, { "code": null, "e": 2785, "s": 2743, "text": "$ timedatectl set-timezone “Asia/Kolkata”" }, { "code": null, "e": 2849, "s": 2785, "text": "To verify the above command result, use the following command –" }, { "code": null, "e": 2863, "s": 2849, "text": "$ timedatectl" }, { "code": null, "e": 2903, "s": 2863, "text": "The sample output should be like this –" }, { "code": null, "e": 3167, "s": 2903, "text": " Local time: Fri 2016-03-11 11:42:22 IST\n Universal time: Fri 2016-03-11 06:12:22 UTC\n RTC time: Fri 2016-03-11 11:42:29\n Timezone: Asia/Kolkata (IST, +0530)\n NTP enabled: yes\nNTP synchronized: no\n RTC in local TZ: no\n DST active: n/a" }, { "code": null, "e": 3234, "s": 3167, "text": "To set our time zone according to UTF, use the following command –" }, { "code": null, "e": 3265, "s": 3234, "text": "$ timedatectl set-timezone UTC" }, { "code": null, "e": 3325, "s": 3265, "text": "To verify above command result, use the following command –" }, { "code": null, "e": 3339, "s": 3325, "text": "$ timedatectl" }, { "code": null, "e": 3379, "s": 3339, "text": "The sample output should be like this –" }, { "code": null, "e": 3592, "s": 3379, "text": " Local time: Fri 2016-03-11 06:15:58 UTC\n Universal time: Fri 2016-03-11 06:15:58 UTC\n Timezone: UTC (UTC, +0000)\n NTP enabled: yes\nNTP synchronized: no\n RTC in local TZ: no\n DST active: n/a" }, { "code": null, "e": 3642, "s": 3592, "text": "To set Time and Date, use the following command –" }, { "code": null, "e": 3674, "s": 3642, "text": "$ timedatectl set-time 15:58:30" }, { "code": null, "e": 3738, "s": 3674, "text": "To verify the above command result, use the following command –" }, { "code": null, "e": 3752, "s": 3738, "text": "$ timedatectl" }, { "code": null, "e": 3792, "s": 3752, "text": "The sample output should be like this –" }, { "code": null, "e": 4014, "s": 3792, "text": " Local time: Fri 2016-03-11 15:58:40 IST\n Universal time: Fri 2016-03-11 10:28:40 UTC\n Timezone: Asia/Kolkata (IST, +0530)\n NTP enabled: yes\nNTP synchronized: no\n RTC in local TZ: no\n DST active: n/a" }, { "code": null, "e": 4073, "s": 4014, "text": "To set date from command line, use the following command –" }, { "code": null, "e": 4107, "s": 4073, "text": "$ timedatectl set-time 2015-11-20" }, { "code": null, "e": 4170, "s": 4107, "text": "To verify the above command result, use the following command-" }, { "code": null, "e": 4184, "s": 4170, "text": "$ timedatectl" }, { "code": null, "e": 4224, "s": 4184, "text": "The sample output should be like this –" }, { "code": null, "e": 4500, "s": 4224, "text": " Local time: Fri 2015-11-20 00:00:06 IST\n Universal time: Thu 2015-11-19 18:30:06 UTC\n Timezone: Asia/Kolkata (IST, +0530)\n NTP enabled: yes\nNTP synchronized: no\n RTC in local TZ: no\n DST active: n/a To set both date and time, use the following command-" }, { "code": null, "e": 4550, "s": 4500, "text": "$ sudo timedatectl set-time \"2014-11-08 06:40:00\"" }, { "code": null, "e": 4614, "s": 4550, "text": "To verify the above command result, use the following command –" }, { "code": null, "e": 4628, "s": 4614, "text": "$ timedatectl" }, { "code": null, "e": 4668, "s": 4628, "text": "The sample output should be like this –" }, { "code": null, "e": 4890, "s": 4668, "text": " Local time: Sat 2014-11-08 06:40:11 IST\n Universal time: Sat 2014-11-08 01:10:11 UTC\n Timezone: Asia/Kolkata (IST, +0530)\n NTP enabled: yes\nNTP synchronized: no\n RTC in local TZ: no\n DST active: n/a" }, { "code": null, "e": 4959, "s": 4890, "text": "To Display Hardware Clock Date and Time, use the following command –" }, { "code": null, "e": 4969, "s": 4959, "text": "# hwclock" }, { "code": null, "e": 5009, "s": 4969, "text": "The sample output should be like this –" }, { "code": null, "e": 5074, "s": 5009, "text": "# hwclock\nFriday 11 March 2016 12:25:56 PM IST -0.594257 seconds" }, { "code": null, "e": 5139, "s": 5074, "text": "To copy system time to hardware time, use the following command-" }, { "code": null, "e": 5159, "s": 5139, "text": "# hwclock --systohc" }, { "code": null, "e": 5201, "s": 5159, "text": "To verify it, use the following commands-" }, { "code": null, "e": 5274, "s": 5201, "text": "# hwclock (for hardware date and time)\n# date (for system date and time)" }, { "code": null, "e": 5314, "s": 5274, "text": "The sample output should be like this –" }, { "code": null, "e": 5415, "s": 5314, "text": "# hwclock\nFriday 11 March 2016 01:53:03 PM IST -0.359815 seconds\n# date\nFri Mar 11 13:53:05 IST 2016" }, { "code": null, "e": 5494, "s": 5415, "text": "In the above result, both hardware clock and system clock has the same result." }, { "code": null, "e": 5832, "s": 5494, "text": "NTP stands for Network Time Protocol which is an internet protocol is used to synchronize approach clock between computers. The timedatectl utility makes it possible for to routinely sync your Linux system clock with remote servers utilizing NTP. To start automatic time synchronization with remote NTP server, use the following command-" }, { "code": null, "e": 5859, "s": 5832, "text": "# timedatectl set-ntp true" }, { "code": null, "e": 5924, "s": 5859, "text": "To disable NTP time synchronization, use the following command –" }, { "code": null, "e": 5952, "s": 5924, "text": "# timedatectl set-ntp false" }, { "code": null, "e": 6152, "s": 5952, "text": "Congratulations! Now, you know “How to Set Time, Timezone and Synchronize System Clock Using timedatectl Command”. We’ll learn more about these types of commands in our next Linux post. Keep reading!" } ]
How to Create a Chatbot in Android with BrainShop API?
14 Dec, 2021 We have seen many apps and websites in which we will get to see a chatbot where we can chat along with the chatbot and can easily get solutions for our questions answered from the chatbot. In this article, we will take a look at building a chatbot in Android. Creating a ChatBot App in Android | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersCreating a ChatBot App in Android | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 48:49•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=7_Cc36c7EW0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> We will be building a simple application in which we will be building a simple chatbot where we can ask a question to our bot and the bot will answer our questions. Below is the video in which we will get to see what we are going to build in this article. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Add the below dependency in your build.gradle file Navigate to the app > Gradle Scripts > build.gradle file and add the below dependency to it in the dependencies section. implementation ‘com.android.volley:volley:1.1.1’ After adding this dependency sync your project and now move towards the AndroidManifest.xml part. Step 3: Adding permissions to the internet in the AndroidManifest.xml file Navigate to the app > AndroidManifest.xml and add the below code to it. XML <!--permissions for internet--><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> Step 4: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout 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" tools:context=".MainActivity"> <!--recycler view to display our chats--> <androidx.recyclerview.widget.RecyclerView android:id="@+id/idRVChats" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@id/idLLMessage" /> <LinearLayout android:id="@+id/idLLMessage" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:orientation="horizontal" android:weightSum="5"> <!--edit text to enter message--> <EditText android:id="@+id/idEdtMessage" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="4" android:hint="Enter Message" /> <!--button to send message--> <ImageButton android:id="@+id/idIBSend" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_weight="1" android:background="@color/purple_200" android:src="@android:drawable/ic_menu_send" android:tint="@color/white" /> </LinearLayout> </RelativeLayout> Step 5: Creating a Modal class for storing our messages Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as MessageModal and add the below code to it. Comments are added inside the code to understand the code in more detail. Java public class MessageModal { // string to store our message and sender private String message; private String sender; // constructor. public MessageModal(String message, String sender) { this.message = message; this.sender = sender; } // getter and setter methods. public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getSender() { return sender; } public void setSender(String sender) { this.sender = sender; }} Step 6: Creating a layout file for user messages Icons used in this file are present in the drawable folder. Navigate to the app > res > layout > Right-click on it > New > layout resource file and name the file as user_msg and add the below code to it. XML <?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end" android:layout_margin="5dp" android:elevation="8dp" app:cardCornerRadius="8dp"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <!--text view for displaying user message--> <TextView android:id="@+id/idTVUser" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_margin="5dp" android:padding="3dp" android:text="User message" android:textColor="@color/black" /> <!--we are displaying user icon--> <ImageView android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="10dp" android:src="@drawable/ic_user" /> </LinearLayout> </androidx.cardview.widget.CardView> Step 7: Create a layout file for bot messages Icons used in this file are present in the drawable folder. Navigate to the app > res > layout > Right-click on it > New > layout resource file and name the file as bot_msg and add the below code to it. XML <?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="start" android:layout_margin="5dp" android:elevation="8dp" app:cardCornerRadius="8dp"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <!--below widget is for image of bot--> <ImageView android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="10dp" android:src="@drawable/ic_bot" /> <!--below widget is for displaying message of bot--> <TextView android:id="@+id/idTVBot" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_margin="5dp" android:padding="3dp" android:text="Bot message" android:textColor="@color/black" /> </LinearLayout> </androidx.cardview.widget.CardView> Step 8: Working with the Adapter class For setting data to our items of Chat RecyclerView we have to create an Adapter class. Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name your class as MessageRVAdapter and add the below code to it. Comments are added inside the code to understand the code in more detail. Java import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class MessageRVAdapter extends RecyclerView.Adapter { // variable for our array list and context. private ArrayList<MessageModal> messageModalArrayList; private Context context; // constructor class. public MessageRVAdapter(ArrayList<MessageModal> messageModalArrayList, Context context) { this.messageModalArrayList = messageModalArrayList; this.context = context; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view; // below code is to switch our // layout type along with view holder. switch (viewType) { case 0: // below line we are inflating user message layout. view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_msg, parent, false); return new UserViewHolder(view); case 1: // below line we are inflating bot message layout. view = LayoutInflater.from(parent.getContext()).inflate(R.layout.bot_msg, parent, false); return new BotViewHolder(view); } return null; } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { // this method is use to set data to our layout file. MessageModal modal = messageModalArrayList.get(position); switch (modal.getSender()) { case "user": // below line is to set the text to our text view of user layout ((UserViewHolder) holder).userTV.setText(modal.getMessage()); break; case "bot": // below line is to set the text to our text view of bot layout ((BotViewHolder) holder).botTV.setText(modal.getMessage()); break; } } @Override public int getItemCount() { // return the size of array list return messageModalArrayList.size(); } @Override public int getItemViewType(int position) { // below line of code is to set position. switch (messageModalArrayList.get(position).getSender()) { case "user": return 0; case "bot": return 1; default: return -1; } } public static class UserViewHolder extends RecyclerView.ViewHolder { // creating a variable // for our text view. TextView userTV; public UserViewHolder(@NonNull View itemView) { super(itemView); // initializing with id. userTV = itemView.findViewById(R.id.idTVUser); } } public static class BotViewHolder extends RecyclerView.ViewHolder { // creating a variable // for our text view. TextView botTV; public BotViewHolder(@NonNull View itemView) { super(itemView); // initializing with id. botTV = itemView.findViewById(R.id.idTVBot); } }} Step 9: Generating API key for using the chatbot service Go to Brainshop.ai generate your simple account with your username and password. Simply create your account on this website. After creating a new account you will get to see the below screen. After creating your account you have to request a new password from the request password option and enter your email address. After adding your email address you have to add the password to your account. Now we are good to go to generate our API key. Follow the above steps to Generate a new brain for your chatbot. After generating your bot now we will get the API URL for this brain. Navigate to the settings tab inside your created brain you will get to see your bot details as shown below. Note: Now we will be using this API URL only inside the MainActivity.java file. Step 10: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.view.View;import android.widget.EditText;import android.widget.ImageButton;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonObjectRequest;import com.android.volley.toolbox.Volley; import org.json.JSONException;import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // creating variables for our // widgets in xml file. private RecyclerView chatsRV; private ImageButton sendMsgIB; private EditText userMsgEdt; private final String USER_KEY = "user"; private final String BOT_KEY = "bot"; // creating a variable for // our volley request queue. private RequestQueue mRequestQueue; // creating a variable for array list and adapter class. private ArrayList<MessageModal> messageModalArrayList; private MessageRVAdapter messageRVAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // on below line we are initializing all our views. chatsRV = findViewById(R.id.idRVChats); sendMsgIB = findViewById(R.id.idIBSend); userMsgEdt = findViewById(R.id.idEdtMessage); // below line is to initialize our request queue. mRequestQueue = Volley.newRequestQueue(MainActivity.this); mRequestQueue.getCache().clear(); // creating a new array list messageModalArrayList = new ArrayList<>(); // adding on click listener for send message button. sendMsgIB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // checking if the message entered // by user is empty or not. if (userMsgEdt.getText().toString().isEmpty()) { // if the edit text is empty display a toast message. Toast.makeText(MainActivity.this, "Please enter your message..", Toast.LENGTH_SHORT).show(); return; } // calling a method to send message // to our bot to get response. sendMessage(userMsgEdt.getText().toString()); // below line we are setting text in our edit text as empty userMsgEdt.setText(""); } }); // on below line we are initialing our adapter class and passing our array list to it. messageRVAdapter = new MessageRVAdapter(messageModalArrayList, this); // below line we are creating a variable for our linear layout manager. LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, RecyclerView.VERTICAL, false); // below line is to set layout // manager to our recycler view. chatsRV.setLayoutManager(linearLayoutManager); // below line we are setting // adapter to our recycler view. chatsRV.setAdapter(messageRVAdapter); } private void sendMessage(String userMsg) { // below line is to pass message to our // array list which is entered by the user. messageModalArrayList.add(new MessageModal(userMsg, USER_KEY)); messageRVAdapter.notifyDataSetChanged(); // url for our brain // make sure to add mshape for uid. // make sure to add your url. String url = "Enter you API URL here" + userMsg; // creating a variable for our request queue. RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // on below line we are making a json object request for a get request and passing our url . JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { // in on response method we are extracting data // from json response and adding this response to our array list. String botResponse = response.getString("cnt"); messageModalArrayList.add(new MessageModal(botResponse, BOT_KEY)); // notifying our adapter as data changed. messageRVAdapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); // handling error response from bot. messageModalArrayList.add(new MessageModal("No response", BOT_KEY)); messageRVAdapter.notifyDataSetChanged(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error handling. messageModalArrayList.add(new MessageModal("Sorry no response found", BOT_KEY)); Toast.makeText(MainActivity.this, "No response from the bot..", Toast.LENGTH_SHORT).show(); } }); // at last adding json object // request to our queue. queue.add(jsonObjectRequest); }} Now run your app and see the output of the app. Check out the project on the below link: https://github.com/ChinmayMunje/GFG-Bot sagar0719kumar android Technical Scripter 2020 Android Java Machine Learning Technical Scripter Java Android Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Android SDK and it's Components Flutter - Custom Bottom Navigation Bar Arrays in Java Arrays.sort() in Java with examples Split() String method in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Dec, 2021" }, { "code": null, "e": 315, "s": 54, "text": "We have seen many apps and websites in which we will get to see a chatbot where we can chat along with the chatbot and can easily get solutions for our questions answered from the chatbot. In this article, we will take a look at building a chatbot in Android. " }, { "code": null, "e": 1200, "s": 315, "text": "Creating a ChatBot App in Android | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersCreating a ChatBot App in Android | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 48:49•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=7_Cc36c7EW0\" 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": 1624, "s": 1200, "text": "We will be building a simple application in which we will be building a simple chatbot where we can ask a question to our bot and the bot will answer our questions. Below is the video in which we will get to see what we are going to build in this article. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 1653, "s": 1624, "text": "Step 1: Create a New Project" }, { "code": null, "e": 1815, "s": 1653, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 1874, "s": 1815, "text": "Step 2: Add the below dependency in your build.gradle file" }, { "code": null, "e": 1997, "s": 1874, "text": "Navigate to the app > Gradle Scripts > build.gradle file and add the below dependency to it in the dependencies section. " }, { "code": null, "e": 2046, "s": 1997, "text": "implementation ‘com.android.volley:volley:1.1.1’" }, { "code": null, "e": 2146, "s": 2046, "text": "After adding this dependency sync your project and now move towards the AndroidManifest.xml part. " }, { "code": null, "e": 2221, "s": 2146, "text": "Step 3: Adding permissions to the internet in the AndroidManifest.xml file" }, { "code": null, "e": 2294, "s": 2221, "text": "Navigate to the app > AndroidManifest.xml and add the below code to it. " }, { "code": null, "e": 2298, "s": 2294, "text": "XML" }, { "code": "<!--permissions for internet--><uses-permission android:name=\"android.permission.INTERNET\" /><uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" />", "e": 2466, "s": 2298, "text": null }, { "code": null, "e": 2514, "s": 2466, "text": "Step 4: Working with the activity_main.xml file" }, { "code": null, "e": 2657, "s": 2514, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 2661, "s": 2657, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout 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\" tools:context=\".MainActivity\"> <!--recycler view to display our chats--> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/idRVChats\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_above=\"@id/idLLMessage\" /> <LinearLayout android:id=\"@+id/idLLMessage\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_alignParentBottom=\"true\" android:orientation=\"horizontal\" android:weightSum=\"5\"> <!--edit text to enter message--> <EditText android:id=\"@+id/idEdtMessage\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_weight=\"4\" android:hint=\"Enter Message\" /> <!--button to send message--> <ImageButton android:id=\"@+id/idIBSend\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_vertical\" android:layout_weight=\"1\" android:background=\"@color/purple_200\" android:src=\"@android:drawable/ic_menu_send\" android:tint=\"@color/white\" /> </LinearLayout> </RelativeLayout>", "e": 4197, "s": 2661, "text": null }, { "code": null, "e": 4253, "s": 4197, "text": "Step 5: Creating a Modal class for storing our messages" }, { "code": null, "e": 4477, "s": 4253, "text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as MessageModal and add the below code to it. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 4482, "s": 4477, "text": "Java" }, { "code": "public class MessageModal { // string to store our message and sender private String message; private String sender; // constructor. public MessageModal(String message, String sender) { this.message = message; this.sender = sender; } // getter and setter methods. public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getSender() { return sender; } public void setSender(String sender) { this.sender = sender; }}", "e": 5068, "s": 4482, "text": null }, { "code": null, "e": 5117, "s": 5068, "text": "Step 6: Creating a layout file for user messages" }, { "code": null, "e": 5322, "s": 5117, "text": "Icons used in this file are present in the drawable folder. Navigate to the app > res > layout > Right-click on it > New > layout resource file and name the file as user_msg and add the below code to it. " }, { "code": null, "e": 5326, "s": 5322, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"end\" android:layout_margin=\"5dp\" android:elevation=\"8dp\" app:cardCornerRadius=\"8dp\"> <LinearLayout android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\"> <!--text view for displaying user message--> <TextView android:id=\"@+id/idTVUser\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_vertical\" android:layout_margin=\"5dp\" android:padding=\"3dp\" android:text=\"User message\" android:textColor=\"@color/black\" /> <!--we are displaying user icon--> <ImageView android:layout_width=\"50dp\" android:layout_height=\"50dp\" android:layout_margin=\"10dp\" android:src=\"@drawable/ic_user\" /> </LinearLayout> </androidx.cardview.widget.CardView>", "e": 6572, "s": 5326, "text": null }, { "code": null, "e": 6619, "s": 6572, "text": "Step 7: Create a layout file for bot messages " }, { "code": null, "e": 6823, "s": 6619, "text": "Icons used in this file are present in the drawable folder. Navigate to the app > res > layout > Right-click on it > New > layout resource file and name the file as bot_msg and add the below code to it. " }, { "code": null, "e": 6827, "s": 6823, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"start\" android:layout_margin=\"5dp\" android:elevation=\"8dp\" app:cardCornerRadius=\"8dp\"> <LinearLayout android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\"> <!--below widget is for image of bot--> <ImageView android:layout_width=\"50dp\" android:layout_height=\"50dp\" android:layout_margin=\"10dp\" android:src=\"@drawable/ic_bot\" /> <!--below widget is for displaying message of bot--> <TextView android:id=\"@+id/idTVBot\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_vertical\" android:layout_margin=\"5dp\" android:padding=\"3dp\" android:text=\"Bot message\" android:textColor=\"@color/black\" /> </LinearLayout> </androidx.cardview.widget.CardView>", "e": 8097, "s": 6827, "text": null }, { "code": null, "e": 8136, "s": 8097, "text": "Step 8: Working with the Adapter class" }, { "code": null, "e": 8460, "s": 8136, "text": "For setting data to our items of Chat RecyclerView we have to create an Adapter class. Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name your class as MessageRVAdapter and add the below code to it. Comments are added inside the code to understand the code in more detail. " }, { "code": null, "e": 8465, "s": 8460, "text": "Java" }, { "code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class MessageRVAdapter extends RecyclerView.Adapter { // variable for our array list and context. private ArrayList<MessageModal> messageModalArrayList; private Context context; // constructor class. public MessageRVAdapter(ArrayList<MessageModal> messageModalArrayList, Context context) { this.messageModalArrayList = messageModalArrayList; this.context = context; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view; // below code is to switch our // layout type along with view holder. switch (viewType) { case 0: // below line we are inflating user message layout. view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_msg, parent, false); return new UserViewHolder(view); case 1: // below line we are inflating bot message layout. view = LayoutInflater.from(parent.getContext()).inflate(R.layout.bot_msg, parent, false); return new BotViewHolder(view); } return null; } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { // this method is use to set data to our layout file. MessageModal modal = messageModalArrayList.get(position); switch (modal.getSender()) { case \"user\": // below line is to set the text to our text view of user layout ((UserViewHolder) holder).userTV.setText(modal.getMessage()); break; case \"bot\": // below line is to set the text to our text view of bot layout ((BotViewHolder) holder).botTV.setText(modal.getMessage()); break; } } @Override public int getItemCount() { // return the size of array list return messageModalArrayList.size(); } @Override public int getItemViewType(int position) { // below line of code is to set position. switch (messageModalArrayList.get(position).getSender()) { case \"user\": return 0; case \"bot\": return 1; default: return -1; } } public static class UserViewHolder extends RecyclerView.ViewHolder { // creating a variable // for our text view. TextView userTV; public UserViewHolder(@NonNull View itemView) { super(itemView); // initializing with id. userTV = itemView.findViewById(R.id.idTVUser); } } public static class BotViewHolder extends RecyclerView.ViewHolder { // creating a variable // for our text view. TextView botTV; public BotViewHolder(@NonNull View itemView) { super(itemView); // initializing with id. botTV = itemView.findViewById(R.id.idTVBot); } }}", "e": 11780, "s": 8465, "text": null }, { "code": null, "e": 11837, "s": 11780, "text": "Step 9: Generating API key for using the chatbot service" }, { "code": null, "e": 12281, "s": 11837, "text": "Go to Brainshop.ai generate your simple account with your username and password. Simply create your account on this website. After creating a new account you will get to see the below screen. After creating your account you have to request a new password from the request password option and enter your email address. After adding your email address you have to add the password to your account. Now we are good to go to generate our API key. " }, { "code": null, "e": 12524, "s": 12281, "text": "Follow the above steps to Generate a new brain for your chatbot. After generating your bot now we will get the API URL for this brain. Navigate to the settings tab inside your created brain you will get to see your bot details as shown below." }, { "code": null, "e": 12605, "s": 12524, "text": "Note: Now we will be using this API URL only inside the MainActivity.java file. " }, { "code": null, "e": 12654, "s": 12605, "text": "Step 10: Working with the MainActivity.java file" }, { "code": null, "e": 12844, "s": 12654, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 12849, "s": 12844, "text": "Java" }, { "code": "import android.os.Bundle;import android.view.View;import android.widget.EditText;import android.widget.ImageButton;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonObjectRequest;import com.android.volley.toolbox.Volley; import org.json.JSONException;import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // creating variables for our // widgets in xml file. private RecyclerView chatsRV; private ImageButton sendMsgIB; private EditText userMsgEdt; private final String USER_KEY = \"user\"; private final String BOT_KEY = \"bot\"; // creating a variable for // our volley request queue. private RequestQueue mRequestQueue; // creating a variable for array list and adapter class. private ArrayList<MessageModal> messageModalArrayList; private MessageRVAdapter messageRVAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // on below line we are initializing all our views. chatsRV = findViewById(R.id.idRVChats); sendMsgIB = findViewById(R.id.idIBSend); userMsgEdt = findViewById(R.id.idEdtMessage); // below line is to initialize our request queue. mRequestQueue = Volley.newRequestQueue(MainActivity.this); mRequestQueue.getCache().clear(); // creating a new array list messageModalArrayList = new ArrayList<>(); // adding on click listener for send message button. sendMsgIB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // checking if the message entered // by user is empty or not. if (userMsgEdt.getText().toString().isEmpty()) { // if the edit text is empty display a toast message. Toast.makeText(MainActivity.this, \"Please enter your message..\", Toast.LENGTH_SHORT).show(); return; } // calling a method to send message // to our bot to get response. sendMessage(userMsgEdt.getText().toString()); // below line we are setting text in our edit text as empty userMsgEdt.setText(\"\"); } }); // on below line we are initialing our adapter class and passing our array list to it. messageRVAdapter = new MessageRVAdapter(messageModalArrayList, this); // below line we are creating a variable for our linear layout manager. LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, RecyclerView.VERTICAL, false); // below line is to set layout // manager to our recycler view. chatsRV.setLayoutManager(linearLayoutManager); // below line we are setting // adapter to our recycler view. chatsRV.setAdapter(messageRVAdapter); } private void sendMessage(String userMsg) { // below line is to pass message to our // array list which is entered by the user. messageModalArrayList.add(new MessageModal(userMsg, USER_KEY)); messageRVAdapter.notifyDataSetChanged(); // url for our brain // make sure to add mshape for uid. // make sure to add your url. String url = \"Enter you API URL here\" + userMsg; // creating a variable for our request queue. RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // on below line we are making a json object request for a get request and passing our url . JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { // in on response method we are extracting data // from json response and adding this response to our array list. String botResponse = response.getString(\"cnt\"); messageModalArrayList.add(new MessageModal(botResponse, BOT_KEY)); // notifying our adapter as data changed. messageRVAdapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); // handling error response from bot. messageModalArrayList.add(new MessageModal(\"No response\", BOT_KEY)); messageRVAdapter.notifyDataSetChanged(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error handling. messageModalArrayList.add(new MessageModal(\"Sorry no response found\", BOT_KEY)); Toast.makeText(MainActivity.this, \"No response from the bot..\", Toast.LENGTH_SHORT).show(); } }); // at last adding json object // request to our queue. queue.add(jsonObjectRequest); }}", "e": 18371, "s": 12849, "text": null }, { "code": null, "e": 18420, "s": 18371, "text": "Now run your app and see the output of the app. " }, { "code": null, "e": 18501, "s": 18420, "text": "Check out the project on the below link: https://github.com/ChinmayMunje/GFG-Bot" }, { "code": null, "e": 18516, "s": 18501, "text": "sagar0719kumar" }, { "code": null, "e": 18524, "s": 18516, "text": "android" }, { "code": null, "e": 18548, "s": 18524, "text": "Technical Scripter 2020" }, { "code": null, "e": 18556, "s": 18548, "text": "Android" }, { "code": null, "e": 18561, "s": 18556, "text": "Java" }, { "code": null, "e": 18578, "s": 18561, "text": "Machine Learning" }, { "code": null, "e": 18597, "s": 18578, "text": "Technical Scripter" }, { "code": null, "e": 18602, "s": 18597, "text": "Java" }, { "code": null, "e": 18610, "s": 18602, "text": "Android" }, { "code": null, "e": 18627, "s": 18610, "text": "Machine Learning" }, { "code": null, "e": 18725, "s": 18627, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 18794, "s": 18725, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 18825, "s": 18794, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 18868, "s": 18825, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 18900, "s": 18868, "text": "Android SDK and it's Components" }, { "code": null, "e": 18939, "s": 18900, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 18954, "s": 18939, "text": "Arrays in Java" }, { "code": null, "e": 18990, "s": 18954, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 19034, "s": 18990, "text": "Split() String method in Java with examples" }, { "code": null, "e": 19059, "s": 19034, "text": "Reverse a string in Java" } ]
How to Create a TreeSet with a List in Java?
31 Aug, 2021 TreeSet is an implementation of the SortedSet interface in Java that uses a Tree for storage. TreeSet can be created from List by passing the List to the TreeSet constructor in Java or we can traverse complete List and adding each element of the List to the TreeSet. Example: Input : List = [a, b, c] Output: TreeSet = [a, b, c] Input : List = [1, 2, 3] Output: TreeSet = [1, 2, 3] Approach 1: Create a List object.Enter multiple inputs in the List.Create a TreeSet Object.Initialize object with a constructor and pass List object in it.Print the Treeset. Create a List object. Enter multiple inputs in the List. Create a TreeSet Object. Initialize object with a constructor and pass List object in it. Print the Treeset. Below is the implementation of the above approach: Java // Java Program to Create a TreeSet with a Listimport java.util.ArrayList;import java.util.List;import java.util.TreeSet; public class ExampleTreeSet { public static void main(String a[]) { // Create new List List<String> fruitlist = new ArrayList<String>(); fruitlist.add("Mango"); fruitlist.add("Apple"); fruitlist.add("Grape"); fruitlist.add("Papaya"); // Printing ArrayList System.out.println("Fruit List : " + fruitlist); // Create a TreeSet with the list TreeSet<String> tree_set = new TreeSet<String>(fruitlist); // Print TreeSet System.out.println("TreeSet from List : " + tree_set); }} Fruit List : [Mango, Apple, Grape, Papaya] TreeSet from List : [Apple, Grape, Mango, Papaya] Time Complexity: O(N) Approach 2: Create a List object.Enter multiple inputs in the List.Create a TreeSet Object.Start List traversal and add that element in the TreeSet.After complete traversal, Print the Treeset. Create a List object. Enter multiple inputs in the List. Create a TreeSet Object. Start List traversal and add that element in the TreeSet. After complete traversal, Print the Treeset. Below is the implementation of the above approach: Java // Java Program to Create a TreeSet with a Listimport java.util.ArrayList;import java.util.List;import java.util.TreeSet; public class ExampleTreeSet { public static void main(String a[]) { // Create new List List<String> fruitlist = new ArrayList<String>(); fruitlist.add("Mango"); fruitlist.add("Apple"); fruitlist.add("Grape"); fruitlist.add("Papaya"); // Printing ArrayList System.out.println("Fruit List : " + fruitlist); // Create a TreeSet TreeSet<String> tree_set = new TreeSet<String>(); // Add each element in the TreeSet for (String i : fruitlist) tree_set.add(i); // Print TreeSet System.out.println("TreeSet from List : " + tree_set); }} Fruit List : [Mango, Apple, Grape, Papaya] TreeSet from List : [Apple, Grape, Mango, Papaya] Time Complexity: O(N) as5853535 java-list java-treeset Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n31 Aug, 2021" }, { "code": null, "e": 322, "s": 54, "text": "TreeSet is an implementation of the SortedSet interface in Java that uses a Tree for storage. TreeSet can be created from List by passing the List to the TreeSet constructor in Java or we can traverse complete List and adding each element of the List to the TreeSet. " }, { "code": null, "e": 331, "s": 322, "text": "Example:" }, { "code": null, "e": 438, "s": 331, "text": "Input : List = [a, b, c]\nOutput: TreeSet = [a, b, c]\n\nInput : List = [1, 2, 3]\nOutput: TreeSet = [1, 2, 3]" }, { "code": null, "e": 450, "s": 438, "text": "Approach 1:" }, { "code": null, "e": 612, "s": 450, "text": "Create a List object.Enter multiple inputs in the List.Create a TreeSet Object.Initialize object with a constructor and pass List object in it.Print the Treeset." }, { "code": null, "e": 634, "s": 612, "text": "Create a List object." }, { "code": null, "e": 669, "s": 634, "text": "Enter multiple inputs in the List." }, { "code": null, "e": 694, "s": 669, "text": "Create a TreeSet Object." }, { "code": null, "e": 759, "s": 694, "text": "Initialize object with a constructor and pass List object in it." }, { "code": null, "e": 778, "s": 759, "text": "Print the Treeset." }, { "code": null, "e": 829, "s": 778, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 834, "s": 829, "text": "Java" }, { "code": "// Java Program to Create a TreeSet with a Listimport java.util.ArrayList;import java.util.List;import java.util.TreeSet; public class ExampleTreeSet { public static void main(String a[]) { // Create new List List<String> fruitlist = new ArrayList<String>(); fruitlist.add(\"Mango\"); fruitlist.add(\"Apple\"); fruitlist.add(\"Grape\"); fruitlist.add(\"Papaya\"); // Printing ArrayList System.out.println(\"Fruit List : \" + fruitlist); // Create a TreeSet with the list TreeSet<String> tree_set = new TreeSet<String>(fruitlist); // Print TreeSet System.out.println(\"TreeSet from List : \" + tree_set); }}", "e": 1562, "s": 834, "text": null }, { "code": null, "e": 1655, "s": 1562, "text": "Fruit List : [Mango, Apple, Grape, Papaya]\nTreeSet from List : [Apple, Grape, Mango, Papaya]" }, { "code": null, "e": 1677, "s": 1655, "text": "Time Complexity: O(N)" }, { "code": null, "e": 1690, "s": 1677, "text": "Approach 2: " }, { "code": null, "e": 1871, "s": 1690, "text": "Create a List object.Enter multiple inputs in the List.Create a TreeSet Object.Start List traversal and add that element in the TreeSet.After complete traversal, Print the Treeset." }, { "code": null, "e": 1893, "s": 1871, "text": "Create a List object." }, { "code": null, "e": 1928, "s": 1893, "text": "Enter multiple inputs in the List." }, { "code": null, "e": 1953, "s": 1928, "text": "Create a TreeSet Object." }, { "code": null, "e": 2011, "s": 1953, "text": "Start List traversal and add that element in the TreeSet." }, { "code": null, "e": 2056, "s": 2011, "text": "After complete traversal, Print the Treeset." }, { "code": null, "e": 2107, "s": 2056, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 2112, "s": 2107, "text": "Java" }, { "code": "// Java Program to Create a TreeSet with a Listimport java.util.ArrayList;import java.util.List;import java.util.TreeSet; public class ExampleTreeSet { public static void main(String a[]) { // Create new List List<String> fruitlist = new ArrayList<String>(); fruitlist.add(\"Mango\"); fruitlist.add(\"Apple\"); fruitlist.add(\"Grape\"); fruitlist.add(\"Papaya\"); // Printing ArrayList System.out.println(\"Fruit List : \" + fruitlist); // Create a TreeSet TreeSet<String> tree_set = new TreeSet<String>(); // Add each element in the TreeSet for (String i : fruitlist) tree_set.add(i); // Print TreeSet System.out.println(\"TreeSet from List : \" + tree_set); }}", "e": 2911, "s": 2112, "text": null }, { "code": null, "e": 3004, "s": 2911, "text": "Fruit List : [Mango, Apple, Grape, Papaya]\nTreeSet from List : [Apple, Grape, Mango, Papaya]" }, { "code": null, "e": 3026, "s": 3004, "text": "Time Complexity: O(N)" }, { "code": null, "e": 3038, "s": 3028, "text": "as5853535" }, { "code": null, "e": 3048, "s": 3038, "text": "java-list" }, { "code": null, "e": 3061, "s": 3048, "text": "java-treeset" }, { "code": null, "e": 3068, "s": 3061, "text": "Picked" }, { "code": null, "e": 3073, "s": 3068, "text": "Java" }, { "code": null, "e": 3087, "s": 3073, "text": "Java Programs" }, { "code": null, "e": 3092, "s": 3087, "text": "Java" } ]
JavaScript | Convert an array to JSON
21 May, 2019 Here is a need to convert an array into a JSON_Object. To do so we are going to use a few of the most preferred techniques. First, we need to know a few methods. 1) Object.assign() methodThis method copies the values of all properties owned by enumerables from source objects(one or more) to a target object.Syntax: Object.assign(target, ...sources) Parameters: target: It specifies the target object. sources: It specifies the source object(s). 2)-JSON.stringify() methodUse of JSON is to exchange data to/from a web server. While sending data to web server, the data need to be string.This method converts the javascript Object(array in this case) into JSON_string.Syntax: JSON.stringify(Javascript Object) Parameters: Javascript Object: It specifies the JavaScript object. Example 1:This example converts the JS array to JSON String using JSON.stringify() method. <!DOCTYPE html> <html> <head> <title> JavaScript | Convert array to JSON. </title> </head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 16px;"> </p> <button onclick = "gfg_Run()"> Convert </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var array = [34, 24, 31, 48]; el_up.innerHTML = "Array = [" +array+"]";; function gfg_Run(){ el_down.innerHTML = "JSON_String = '"+JSON.stringify(array)+"'"; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2:This example converts the JS array to JSON Object using Object.assign() method. <!DOCTYPE html> <html> <head> <title> JavaScript | Convert array to JSON. </title> </head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 16px;"> </p> <button onclick = "gfg_Run()"> Convert </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var array = [34, 24, 31, 48]; el_up.innerHTML = "Array = [" +array+"]";; function gfg_Run(){ el_down.innerHTML = "JSON Object = "+JSON.stringify(Object.assign({}, array)); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: JSON JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners How to get character array from string in JavaScript? Node.js | fs.writeFileSync() Method JavaScript | Promises How to filter object array based on attributes? How to Use the JavaScript Fetch API to Get Data?
[ { "code": null, "e": 28, "s": 0, "text": "\n21 May, 2019" }, { "code": null, "e": 190, "s": 28, "text": "Here is a need to convert an array into a JSON_Object. To do so we are going to use a few of the most preferred techniques. First, we need to know a few methods." }, { "code": null, "e": 344, "s": 190, "text": "1) Object.assign() methodThis method copies the values of all properties owned by enumerables from source objects(one or more) to a target object.Syntax:" }, { "code": null, "e": 379, "s": 344, "text": "Object.assign(target, ...sources)\n" }, { "code": null, "e": 391, "s": 379, "text": "Parameters:" }, { "code": null, "e": 431, "s": 391, "text": "target: It specifies the target object." }, { "code": null, "e": 475, "s": 431, "text": "sources: It specifies the source object(s)." }, { "code": null, "e": 704, "s": 475, "text": "2)-JSON.stringify() methodUse of JSON is to exchange data to/from a web server. While sending data to web server, the data need to be string.This method converts the javascript Object(array in this case) into JSON_string.Syntax:" }, { "code": null, "e": 739, "s": 704, "text": "JSON.stringify(Javascript Object)\n" }, { "code": null, "e": 751, "s": 739, "text": "Parameters:" }, { "code": null, "e": 806, "s": 751, "text": "Javascript Object: It specifies the JavaScript object." }, { "code": null, "e": 897, "s": 806, "text": "Example 1:This example converts the JS array to JSON String using JSON.stringify() method." }, { "code": "<!DOCTYPE html> <html> <head> <title> JavaScript | Convert array to JSON. </title> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 16px;\"> </p> <button onclick = \"gfg_Run()\"> Convert </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var array = [34, 24, 31, 48]; el_up.innerHTML = \"Array = [\" +array+\"]\";; function gfg_Run(){ el_down.innerHTML = \"JSON_String = '\"+JSON.stringify(array)+\"'\"; } </script> </body> </html>", "e": 1818, "s": 897, "text": null }, { "code": null, "e": 1826, "s": 1818, "text": "Output:" }, { "code": null, "e": 1857, "s": 1826, "text": "Before clicking on the button:" }, { "code": null, "e": 1887, "s": 1857, "text": "After clicking on the button:" }, { "code": null, "e": 1977, "s": 1887, "text": "Example 2:This example converts the JS array to JSON Object using Object.assign() method." }, { "code": "<!DOCTYPE html> <html> <head> <title> JavaScript | Convert array to JSON. </title> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 16px;\"> </p> <button onclick = \"gfg_Run()\"> Convert </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var array = [34, 24, 31, 48]; el_up.innerHTML = \"Array = [\" +array+\"]\";; function gfg_Run(){ el_down.innerHTML = \"JSON Object = \"+JSON.stringify(Object.assign({}, array)); } </script> </body> </html>", "e": 2923, "s": 1977, "text": null }, { "code": null, "e": 2931, "s": 2923, "text": "Output:" }, { "code": null, "e": 2962, "s": 2931, "text": "Before clicking on the button:" }, { "code": null, "e": 2992, "s": 2962, "text": "After clicking on the button:" }, { "code": null, "e": 2997, "s": 2992, "text": "JSON" }, { "code": null, "e": 3008, "s": 2997, "text": "JavaScript" }, { "code": null, "e": 3106, "s": 3008, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3167, "s": 3106, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3239, "s": 3167, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3279, "s": 3239, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3320, "s": 3279, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3362, "s": 3320, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3416, "s": 3362, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 3452, "s": 3416, "text": "Node.js | fs.writeFileSync() Method" }, { "code": null, "e": 3474, "s": 3452, "text": "JavaScript | Promises" }, { "code": null, "e": 3522, "s": 3474, "text": "How to filter object array based on attributes?" } ]
Python PyQt5 – How to change font and size of Status Bar Message
26 Mar, 2020 We can set message to a Status Bar by using showMessage() method. In this article, we will see how to change the font and the size of StatusBar message. In order to do this we will use setFont() method. Syntax : self.statusBar().setFont(QFont(font_name, font_size)) Argument : It take two argument :1. Font name it can be ‘Arial’, ’Times’ etc.2. Size to be set in integer. Action performed : It changes the font and size of message Code : from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Python") # setting the geometry of window self.setGeometry(60, 60, 600, 400) # setting status bar message self.statusBar().showMessage("Times Font") # setting border self.statusBar().setStyleSheet("border :3px solid black;") # setting font and size self.statusBar().setFont(QFont('Times', 15)) # creating a label widget self.label_1 = QLabel("Status bar", self) # moving position self.label_1.move(100, 100) # setting up the border self.label_1.setStyleSheet("border :1px solid blue;") # resizing label self.label_1.adjustSize() # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2020" }, { "code": null, "e": 231, "s": 28, "text": "We can set message to a Status Bar by using showMessage() method. In this article, we will see how to change the font and the size of StatusBar message. In order to do this we will use setFont() method." }, { "code": null, "e": 294, "s": 231, "text": "Syntax : self.statusBar().setFont(QFont(font_name, font_size))" }, { "code": null, "e": 401, "s": 294, "text": "Argument : It take two argument :1. Font name it can be ‘Arial’, ’Times’ etc.2. Size to be set in integer." }, { "code": null, "e": 460, "s": 401, "text": "Action performed : It changes the font and size of message" }, { "code": null, "e": 467, "s": 460, "text": "Code :" }, { "code": "from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Python\") # setting the geometry of window self.setGeometry(60, 60, 600, 400) # setting status bar message self.statusBar().showMessage(\"Times Font\") # setting border self.statusBar().setStyleSheet(\"border :3px solid black;\") # setting font and size self.statusBar().setFont(QFont('Times', 15)) # creating a label widget self.label_1 = QLabel(\"Status bar\", self) # moving position self.label_1.move(100, 100) # setting up the border self.label_1.setStyleSheet(\"border :1px solid blue;\") # resizing label self.label_1.adjustSize() # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 1545, "s": 467, "text": null }, { "code": null, "e": 1554, "s": 1545, "text": "Output :" }, { "code": null, "e": 1565, "s": 1554, "text": "Python-gui" }, { "code": null, "e": 1577, "s": 1565, "text": "Python-PyQt" }, { "code": null, "e": 1584, "s": 1577, "text": "Python" } ]
How to Install i3 Window Manager in Linux?
29 Jan, 2021 In this article, we will see How to install i3 windows manager in Linux. i3 window manager is a tiling window manager for advanced users and developers. It is extremely lightweight and fast. It is a text-oriented and keyboard-oriented window manager. It is an easy and quick way to switch between workspaces. Features: It is a simple and lightweight application It does not take more space and highly customizable It has more Shortcut-controlled Before Installing just update your system sudo apt update Now for installing the i3 tiling manager sudo apt install i3 For Arch Linux: sudo pacman -S i3 After installing we want to restart the system and click on the small gear wheel-like icon (like settings icon) by clicking we want to select i3 option out of many like in the below image Once after clicking i3 and logging in we will be prompted to either generate a config file that will be saved in our home directory /.config.i3/config or use the default method which will save the /etc/i3 directory. So now we will look at the first option where you will get a prompt like in the below image hit ENTER in order to place the configuration file in our home directory. After the above step now we want to define the i3 wm modifier key also known as a mod key which can be a Windows Logo key or Alt key. Now use the up arrow or down arrow to select our preference modifier key. Like in the below-given image Now after completing these steps it saves us a blank screen with the status bar at the lower part of the screen like in the below image i3 window status bar So these are the complete steps to install and configure the i3 Window Manager. So I hope this article helps you in enriching your skills. Picked How To Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Set Git Username and Password in GitBash? How to Install and Use NVM on Windows? How to Install Jupyter Notebook on MacOS? How to Install Python Packages for AWS Lambda Layers? How to Add External JAR File to an IntelliJ IDEA Project? Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux cut command in Linux with examples cp command in Linux with examples
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jan, 2021" }, { "code": null, "e": 337, "s": 28, "text": "In this article, we will see How to install i3 windows manager in Linux. i3 window manager is a tiling window manager for advanced users and developers. It is extremely lightweight and fast. It is a text-oriented and keyboard-oriented window manager. It is an easy and quick way to switch between workspaces." }, { "code": null, "e": 347, "s": 337, "text": "Features:" }, { "code": null, "e": 390, "s": 347, "text": "It is a simple and lightweight application" }, { "code": null, "e": 442, "s": 390, "text": "It does not take more space and highly customizable" }, { "code": null, "e": 474, "s": 442, "text": "It has more Shortcut-controlled" }, { "code": null, "e": 517, "s": 474, "text": "Before Installing just update your system " }, { "code": null, "e": 533, "s": 517, "text": "sudo apt update" }, { "code": null, "e": 575, "s": 533, "text": "Now for installing the i3 tiling manager " }, { "code": null, "e": 596, "s": 575, "text": "sudo apt install i3 " }, { "code": null, "e": 612, "s": 596, "text": "For Arch Linux:" }, { "code": null, "e": 630, "s": 612, "text": "sudo pacman -S i3" }, { "code": null, "e": 819, "s": 630, "text": "After installing we want to restart the system and click on the small gear wheel-like icon (like settings icon) by clicking we want to select i3 option out of many like in the below image " }, { "code": null, "e": 1035, "s": 819, "text": "Once after clicking i3 and logging in we will be prompted to either generate a config file that will be saved in our home directory /.config.i3/config or use the default method which will save the /etc/i3 directory." }, { "code": null, "e": 1201, "s": 1035, "text": "So now we will look at the first option where you will get a prompt like in the below image hit ENTER in order to place the configuration file in our home directory." }, { "code": null, "e": 1440, "s": 1201, "text": "After the above step now we want to define the i3 wm modifier key also known as a mod key which can be a Windows Logo key or Alt key. Now use the up arrow or down arrow to select our preference modifier key. Like in the below-given image " }, { "code": null, "e": 1577, "s": 1440, "text": "Now after completing these steps it saves us a blank screen with the status bar at the lower part of the screen like in the below image " }, { "code": null, "e": 1599, "s": 1577, "text": "i3 window status bar " }, { "code": null, "e": 1738, "s": 1599, "text": "So these are the complete steps to install and configure the i3 Window Manager. So I hope this article helps you in enriching your skills." }, { "code": null, "e": 1745, "s": 1738, "text": "Picked" }, { "code": null, "e": 1752, "s": 1745, "text": "How To" }, { "code": null, "e": 1763, "s": 1752, "text": "Linux-Unix" }, { "code": null, "e": 1861, "s": 1763, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1910, "s": 1861, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 1949, "s": 1910, "text": "How to Install and Use NVM on Windows?" }, { "code": null, "e": 1991, "s": 1949, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 2045, "s": 1991, "text": "How to Install Python Packages for AWS Lambda Layers?" }, { "code": null, "e": 2103, "s": 2045, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 2143, "s": 2103, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 2183, "s": 2143, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 2210, "s": 2183, "text": "grep command in Unix/Linux" }, { "code": null, "e": 2245, "s": 2210, "text": "cut command in Linux with examples" } ]
Range and Coefficient of range of Array
18 May, 2022 Given an array arr of integer elements, the task is to find the range and coefficient of range of the given array where: Range: Difference between the maximum value and the minimum value in the distribution. Coefficient of Range: (Max – Min) / (Max + Min).Examples: Input: arr[] = {15, 16, 10, 9, 6, 7, 17} Output: Range : 11 Coefficient of Range : 0.478261 Max = 17, Min = 6 Range = Max – Min = 17 – 6 = 11 Coefficient of Range = (Max – Min) / (Max + Min) = 11 / 23 = 0.478261Input: arr[] = {5, 10, 15} Output: Range : 10 Coefficient of Range : 0.5 Approach: Find the maximum and minimum element from the given array and calculate the range and the coefficient of range as follows: Range = Max – Min Coefficient of Range = (Max – Min) / (Max + Min) Below is the implementation of the above approach: C++ C Java Python3 C# PHP Javascript // C++ implementation to find// Range and coefficient of range#include <iostream>#include <numeric>using namespace std; // Function to return the minimum element from the arrayfloat getMin(float arr[], int n){ float res = arr[0]; for (int i = 1; i < n; i++) res = min(res, arr[i]); return res;} // Function to return the maximum element from the arrayfloat getMax(float arr[], int n){ float res = arr[0]; for (int i = 1; i < n; i++) res = max(res, arr[i]); return res;} // Function to print the Range and// Coefficient of Range in the given arrayvoid findRangeAndCoefficient(float arr[], int n){ float max = getMax(arr, n); float min = getMin(arr, n); float range = max - min; float coeffOfRange = range / (max + min); cout << "Range : " << range << endl; cout << "Coefficient of Range : " << coeffOfRange;} // Driver codeint main(){ float arr[] = { 5, 10, 15 }; int n = sizeof(arr) / sizeof(arr[0]); findRangeAndCoefficient(arr, n); return 0;} // C implementation to find// Range and coefficient of range#include <stdio.h> int min(int a,int b){ int min = a; if(min > b) min = b; return min;} int max(int a,int b){ int max = a; if(max < b) max = b; return max;} // Function to return the minimum element from the arrayfloat getMin(float arr[], int n){ float res = arr[0]; for (int i = 1; i < n; i++) res = min(res, arr[i]); return res;} // Function to return the maximum element from the arrayfloat getMax(float arr[], int n){ float res = arr[0]; for (int i = 1; i < n; i++) res = max(res, arr[i]); return res;} // Function to print the Range and// Coefficient of Range in the given arrayvoid findRangeAndCoefficient(float arr[], int n){ float max = getMax(arr, n); float min = getMin(arr, n); float range = max - min; float coeffOfRange = range / (max + min); printf("Range : %f\n",range); printf("Coefficient of Range : %f\n",coeffOfRange);} // Driver codeint main(){ float arr[] = { 5, 10, 15 }; int n = sizeof(arr) / sizeof(arr[0]); findRangeAndCoefficient(arr, n); return 0;} // This code is contributed by kothavvsaakash. // Java implementation to find// Range and coefficient of range import java.io.*; class GFG { // Function to return the minimum element from the arraystatic float getMin(float arr[], int n){ float res = arr[0]; for (int i = 1; i < n; i++) res = Math.min(res, arr[i]); return res;} // Function to return the maximum element from the arraystatic float getMax(float arr[], int n){ float res = arr[0]; for (int i = 1; i < n; i++) res = Math.max(res, arr[i]); return res;} // Function to print the Range and// Coefficient of Range in the given arraystatic void findRangeAndCoefficient(float arr[], int n){ float max = getMax(arr, n); float min = getMin(arr, n); float range = max - min; float coeffOfRange = range / (max + min); System.out.println("Range : " + range ); System.out.println("Coefficient of Range : " + coeffOfRange);} // Driver code public static void main (String[] args) { float arr[] = { 5, 10, 15 }; int n = arr.length; findRangeAndCoefficient(arr, n); }} # Python 3 implementation to find# Range and coefficient of range # Function to return the minimum# element from the arraydef getMin(arr, n): res = arr[0] for i in range(1, n, 1): res = min(res, arr[i]) return res # Function to return the maximum# element from the arraydef getMax(arr, n): res = arr[0] for i in range(1, n, 1): res = max(res, arr[i]) return res # Function to print the Range and# Coefficient of Range in the given arraydef findRangeAndCoefficient(arr, n): max = getMax(arr, n) min = getMin(arr, n) range = max - min coeffOfRange = range / (max + min) print("Range :", range) print("Coefficient of Range :", coeffOfRange) # Driver codeif __name__ == '__main__': arr = [5, 10, 15] n = len(arr) findRangeAndCoefficient(arr, n) # This code is contributed by# Surendra_Gangwar // C# implementation to find// Range and coefficient of range using System; public class GFG{ // Function to return the minimum element from the arraystatic float getMin(float []arr, int n){ float res = arr[0]; for (int i = 1; i < n; i++) res = Math.Min(res, arr[i]); return res;} // Function to return the maximum element from the arraystatic float getMax(float []arr, int n){ float res = arr[0]; for (int i = 1; i < n; i++) res = Math.Max(res, arr[i]); return res;} // Function to print the Range and// Coefficient of Range in the given arraystatic void findRangeAndCoefficient(float []arr, int n){ float max = getMax(arr, n); float min = getMin(arr, n); float range = max - min; float coeffOfRange = range / (max + min); Console.WriteLine ("Range : " + range ); Console.WriteLine ("Coefficient of Range : " + coeffOfRange);} // Driver code static public void Main (){ float []arr = { 5, 10, 15 }; int n = arr.Length; findRangeAndCoefficient(arr, n); }//This code is contributed by akt_mit. } <?php// PHP implementation to find// Range and coefficient of range// Function to return the minimum// element from the arrayfunction getMin($arr, $n){ $res = $arr[0]; for ($i = 1; $i < $n; $i++) $res = min($res, $arr[$i]); return $res;} // Function to return the maximum// element from the arrayfunction getMax($arr, $n){ $res = $arr[0]; for ($i = 1; $i < $n; $i++) $res = max($res, $arr[$i]); return $res;} // Function to print the Range and// Coefficient of Range in the given arrayfunction findRangeAndCoefficient($arr, $n){ $max = getMax($arr, $n); $min = getMin($arr, $n); $range = $max - $min; $coeffOfRange = $range / ($max + $min); echo "Range : ", $range, "\n"; echo "Coefficient of Range : ", $coeffOfRange;} // Driver code$arr = array( 5, 10, 15 );$n = sizeof($arr);findRangeAndCoefficient($arr, $n); // This code is contributed by jit_t?> <script> // Javascript implementation to find // Range and coefficient of range // Function to return the minimum // element from the array function getMin(arr, n) { let res = arr[0]; for (let i = 1; i < n; i++) res = Math.min(res, arr[i]); return res; } // Function to return the maximum // element from the array function getMax(arr, n) { let res = arr[0]; for (let i = 1; i < n; i++) res = Math.max(res, arr[i]); return res; } // Function to print the Range and // Coefficient of Range in the given array function findRangeAndCoefficient(arr, n) { let max = getMax(arr, n); let min = getMin(arr, n); let range = max - min; let coeffOfRange = range / (max + min); document.write("Range : " + range + "</br>"); document.write("Coefficient of Range : " + coeffOfRange + "</br>"); } let arr = [ 5, 10, 15 ]; let n = arr.length; findRangeAndCoefficient(arr, n); </script> Range : 10 Coefficient of Range : 0.5 Time complexity : O(n) Auxiliary Space: O(1) VishalBachchas jit_t SURENDRA_GANGWAR mukesh07 pankajsharmagfg kothavvsaakash Technical Scripter 2018 Arrays Data Structures School Programming Technical Scripter Data Structures Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array What is Data Structure: Types, Classifications and Applications Chocolate Distribution Problem DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation Introduction to Data Structures Doubly Linked List | Set 1 (Introduction and Insertion) What is Priority Queue | Introduction to Priority Queue
[ { "code": null, "e": 53, "s": 25, "text": "\n18 May, 2022" }, { "code": null, "e": 321, "s": 53, "text": "Given an array arr of integer elements, the task is to find the range and coefficient of range of the given array where: Range: Difference between the maximum value and the minimum value in the distribution. Coefficient of Range: (Max – Min) / (Max + Min).Examples: " }, { "code": null, "e": 607, "s": 321, "text": "Input: arr[] = {15, 16, 10, 9, 6, 7, 17} Output: Range : 11 Coefficient of Range : 0.478261 Max = 17, Min = 6 Range = Max – Min = 17 – 6 = 11 Coefficient of Range = (Max – Min) / (Max + Min) = 11 / 23 = 0.478261Input: arr[] = {5, 10, 15} Output: Range : 10 Coefficient of Range : 0.5 " }, { "code": null, "e": 744, "s": 609, "text": "Approach: Find the maximum and minimum element from the given array and calculate the range and the coefficient of range as follows: " }, { "code": null, "e": 762, "s": 744, "text": "Range = Max – Min" }, { "code": null, "e": 811, "s": 762, "text": "Coefficient of Range = (Max – Min) / (Max + Min)" }, { "code": null, "e": 863, "s": 811, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 867, "s": 863, "text": "C++" }, { "code": null, "e": 869, "s": 867, "text": "C" }, { "code": null, "e": 874, "s": 869, "text": "Java" }, { "code": null, "e": 882, "s": 874, "text": "Python3" }, { "code": null, "e": 885, "s": 882, "text": "C#" }, { "code": null, "e": 889, "s": 885, "text": "PHP" }, { "code": null, "e": 900, "s": 889, "text": "Javascript" }, { "code": "// C++ implementation to find// Range and coefficient of range#include <iostream>#include <numeric>using namespace std; // Function to return the minimum element from the arrayfloat getMin(float arr[], int n){ float res = arr[0]; for (int i = 1; i < n; i++) res = min(res, arr[i]); return res;} // Function to return the maximum element from the arrayfloat getMax(float arr[], int n){ float res = arr[0]; for (int i = 1; i < n; i++) res = max(res, arr[i]); return res;} // Function to print the Range and// Coefficient of Range in the given arrayvoid findRangeAndCoefficient(float arr[], int n){ float max = getMax(arr, n); float min = getMin(arr, n); float range = max - min; float coeffOfRange = range / (max + min); cout << \"Range : \" << range << endl; cout << \"Coefficient of Range : \" << coeffOfRange;} // Driver codeint main(){ float arr[] = { 5, 10, 15 }; int n = sizeof(arr) / sizeof(arr[0]); findRangeAndCoefficient(arr, n); return 0;}", "e": 1907, "s": 900, "text": null }, { "code": "// C implementation to find// Range and coefficient of range#include <stdio.h> int min(int a,int b){ int min = a; if(min > b) min = b; return min;} int max(int a,int b){ int max = a; if(max < b) max = b; return max;} // Function to return the minimum element from the arrayfloat getMin(float arr[], int n){ float res = arr[0]; for (int i = 1; i < n; i++) res = min(res, arr[i]); return res;} // Function to return the maximum element from the arrayfloat getMax(float arr[], int n){ float res = arr[0]; for (int i = 1; i < n; i++) res = max(res, arr[i]); return res;} // Function to print the Range and// Coefficient of Range in the given arrayvoid findRangeAndCoefficient(float arr[], int n){ float max = getMax(arr, n); float min = getMin(arr, n); float range = max - min; float coeffOfRange = range / (max + min); printf(\"Range : %f\\n\",range); printf(\"Coefficient of Range : %f\\n\",coeffOfRange);} // Driver codeint main(){ float arr[] = { 5, 10, 15 }; int n = sizeof(arr) / sizeof(arr[0]); findRangeAndCoefficient(arr, n); return 0;} // This code is contributed by kothavvsaakash.", "e": 3064, "s": 1907, "text": null }, { "code": "// Java implementation to find// Range and coefficient of range import java.io.*; class GFG { // Function to return the minimum element from the arraystatic float getMin(float arr[], int n){ float res = arr[0]; for (int i = 1; i < n; i++) res = Math.min(res, arr[i]); return res;} // Function to return the maximum element from the arraystatic float getMax(float arr[], int n){ float res = arr[0]; for (int i = 1; i < n; i++) res = Math.max(res, arr[i]); return res;} // Function to print the Range and// Coefficient of Range in the given arraystatic void findRangeAndCoefficient(float arr[], int n){ float max = getMax(arr, n); float min = getMin(arr, n); float range = max - min; float coeffOfRange = range / (max + min); System.out.println(\"Range : \" + range ); System.out.println(\"Coefficient of Range : \" + coeffOfRange);} // Driver code public static void main (String[] args) { float arr[] = { 5, 10, 15 }; int n = arr.length; findRangeAndCoefficient(arr, n); }}", "e": 4114, "s": 3064, "text": null }, { "code": "# Python 3 implementation to find# Range and coefficient of range # Function to return the minimum# element from the arraydef getMin(arr, n): res = arr[0] for i in range(1, n, 1): res = min(res, arr[i]) return res # Function to return the maximum# element from the arraydef getMax(arr, n): res = arr[0] for i in range(1, n, 1): res = max(res, arr[i]) return res # Function to print the Range and# Coefficient of Range in the given arraydef findRangeAndCoefficient(arr, n): max = getMax(arr, n) min = getMin(arr, n) range = max - min coeffOfRange = range / (max + min) print(\"Range :\", range) print(\"Coefficient of Range :\", coeffOfRange) # Driver codeif __name__ == '__main__': arr = [5, 10, 15] n = len(arr) findRangeAndCoefficient(arr, n) # This code is contributed by# Surendra_Gangwar", "e": 4962, "s": 4114, "text": null }, { "code": "// C# implementation to find// Range and coefficient of range using System; public class GFG{ // Function to return the minimum element from the arraystatic float getMin(float []arr, int n){ float res = arr[0]; for (int i = 1; i < n; i++) res = Math.Min(res, arr[i]); return res;} // Function to return the maximum element from the arraystatic float getMax(float []arr, int n){ float res = arr[0]; for (int i = 1; i < n; i++) res = Math.Max(res, arr[i]); return res;} // Function to print the Range and// Coefficient of Range in the given arraystatic void findRangeAndCoefficient(float []arr, int n){ float max = getMax(arr, n); float min = getMin(arr, n); float range = max - min; float coeffOfRange = range / (max + min); Console.WriteLine (\"Range : \" + range ); Console.WriteLine (\"Coefficient of Range : \" + coeffOfRange);} // Driver code static public void Main (){ float []arr = { 5, 10, 15 }; int n = arr.Length; findRangeAndCoefficient(arr, n); }//This code is contributed by akt_mit. }", "e": 6037, "s": 4962, "text": null }, { "code": "<?php// PHP implementation to find// Range and coefficient of range// Function to return the minimum// element from the arrayfunction getMin($arr, $n){ $res = $arr[0]; for ($i = 1; $i < $n; $i++) $res = min($res, $arr[$i]); return $res;} // Function to return the maximum// element from the arrayfunction getMax($arr, $n){ $res = $arr[0]; for ($i = 1; $i < $n; $i++) $res = max($res, $arr[$i]); return $res;} // Function to print the Range and// Coefficient of Range in the given arrayfunction findRangeAndCoefficient($arr, $n){ $max = getMax($arr, $n); $min = getMin($arr, $n); $range = $max - $min; $coeffOfRange = $range / ($max + $min); echo \"Range : \", $range, \"\\n\"; echo \"Coefficient of Range : \", $coeffOfRange;} // Driver code$arr = array( 5, 10, 15 );$n = sizeof($arr);findRangeAndCoefficient($arr, $n); // This code is contributed by jit_t?>", "e": 6963, "s": 6037, "text": null }, { "code": "<script> // Javascript implementation to find // Range and coefficient of range // Function to return the minimum // element from the array function getMin(arr, n) { let res = arr[0]; for (let i = 1; i < n; i++) res = Math.min(res, arr[i]); return res; } // Function to return the maximum // element from the array function getMax(arr, n) { let res = arr[0]; for (let i = 1; i < n; i++) res = Math.max(res, arr[i]); return res; } // Function to print the Range and // Coefficient of Range in the given array function findRangeAndCoefficient(arr, n) { let max = getMax(arr, n); let min = getMin(arr, n); let range = max - min; let coeffOfRange = range / (max + min); document.write(\"Range : \" + range + \"</br>\"); document.write(\"Coefficient of Range : \" + coeffOfRange + \"</br>\"); } let arr = [ 5, 10, 15 ]; let n = arr.length; findRangeAndCoefficient(arr, n); </script>", "e": 8023, "s": 6963, "text": null }, { "code": null, "e": 8061, "s": 8023, "text": "Range : 10\nCoefficient of Range : 0.5" }, { "code": null, "e": 8110, "s": 8063, "text": "Time complexity : O(n) Auxiliary Space: O(1) " }, { "code": null, "e": 8125, "s": 8110, "text": "VishalBachchas" }, { "code": null, "e": 8131, "s": 8125, "text": "jit_t" }, { "code": null, "e": 8148, "s": 8131, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 8157, "s": 8148, "text": "mukesh07" }, { "code": null, "e": 8173, "s": 8157, "text": "pankajsharmagfg" }, { "code": null, "e": 8188, "s": 8173, "text": "kothavvsaakash" }, { "code": null, "e": 8212, "s": 8188, "text": "Technical Scripter 2018" }, { "code": null, "e": 8219, "s": 8212, "text": "Arrays" }, { "code": null, "e": 8235, "s": 8219, "text": "Data Structures" }, { "code": null, "e": 8254, "s": 8235, "text": "School Programming" }, { "code": null, "e": 8273, "s": 8254, "text": "Technical Scripter" }, { "code": null, "e": 8289, "s": 8273, "text": "Data Structures" }, { "code": null, "e": 8296, "s": 8289, "text": "Arrays" }, { "code": null, "e": 8394, "s": 8296, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8426, "s": 8394, "text": "Introduction to Data Structures" }, { "code": null, "e": 8451, "s": 8426, "text": "Window Sliding Technique" }, { "code": null, "e": 8498, "s": 8451, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 8562, "s": 8498, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 8593, "s": 8562, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 8618, "s": 8593, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 8667, "s": 8618, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 8699, "s": 8667, "text": "Introduction to Data Structures" }, { "code": null, "e": 8755, "s": 8699, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" } ]
XML - Tree Structure
An XML document is always descriptive. The tree structure is often referred to as XML Tree and plays an important role to describe any XML document easily. The tree structure contains root (parent) elements, child elements and so on. By using tree structure, you can get to know all succeeding branches and sub-branches starting from the root. The parsing starts at the root, then moves down the first branch to an element, take the first branch from there, and so on to the leaf nodes. Following example demonstrates simple XML tree structure − <?xml version = "1.0"?> <Company> <Employee> <FirstName>Tanmay</FirstName> <LastName>Patil</LastName> <ContactNo>1234567890</ContactNo> <Email>[email protected]</Email> <Address> <City>Bangalore</City> <State>Karnataka</State> <Zip>560212</Zip> </Address> </Employee> </Company> Following tree structure represents the above XML document − In the above diagram, there is a root element named as <company>. Inside that, there is one more element <Employee>. Inside the employee element, there are five branches named <FirstName>, <LastName>, <ContactNo>, <Email>, and <Address>. Inside the <Address> element, there are three sub-branches, named <City> <State> and <Zip>.
[ { "code": null, "e": 2251, "s": 2095, "text": "An XML document is always descriptive. The tree structure is often referred to as XML Tree and plays an important role to describe any XML document easily." }, { "code": null, "e": 2582, "s": 2251, "text": "The tree structure contains root (parent) elements, child elements and so on. By using tree structure, you can get to know all succeeding branches and sub-branches starting from the root. The parsing starts at the root, then moves down the first branch to an element, take the first branch from there, and so on to the leaf nodes." }, { "code": null, "e": 2641, "s": 2582, "text": "Following example demonstrates simple XML tree structure −" }, { "code": null, "e": 2991, "s": 2641, "text": "<?xml version = \"1.0\"?>\n<Company>\n <Employee>\n <FirstName>Tanmay</FirstName>\n <LastName>Patil</LastName>\n <ContactNo>1234567890</ContactNo>\n <Email>[email protected]</Email>\n <Address>\n <City>Bangalore</City>\n <State>Karnataka</State>\n <Zip>560212</Zip>\n </Address>\n </Employee>\n</Company>" }, { "code": null, "e": 3052, "s": 2991, "text": "Following tree structure represents the above XML document −" } ]
PHP | Variables
21 Jun, 2022 Variables Variables in a program are used to store some values or data that can be used later in a program. The variables are also like containers that store character values, numeric values, memory addresses, and strings. PHP has its own way of declaring and storing variables. There are a few rules, that need to be followed and facts that need to be kept in mind while dealing with variables in PHP: Any variables declared in PHP must begin with a dollar sign ($), followed by the variable name. A variable can have long descriptive names (like $factorial, $even_nos) or short names (like $n or $f or $x) A variable name can only contain alphanumeric characters and underscores (i.e., ‘a-z’, ‘A-Z’, ‘0-9, and ‘_’) in their name. Even it cannot start with a number. A constant is used as a variable for a simple value that cannot be changed. It is also case-sensitive. Assignment of variables is done with the assignment operator, “equal to (=)”. The variable names are on the left of equal and the expression or values are to the right of the assignment operator ‘=’. One must keep in mind that variable names in PHP names must start with a letter or underscore and no numbers. PHP is a loosely typed language, and we do not require to declare the data types of variables, rather PHP assumes it automatically by analyzing the values. The same happens while conversion. No variables are declared before they are used. It automatically converts types from one type to another whenever required. PHP variables are case-sensitive, i.e., $sum and $SUM are treated differently. Data types used by PHP to declare or construct variables: Integers Doubles NULL Strings Booleans Arrays Objects Resources Example: PHP <?php // These are all valid declarations$val = 5;$val2 = 2;$x_Y = "gfg";$_X = "GeeksforGeeks"; // This is an invalid declaration as it// begins with a number$10_ val = 56; // This is also invalid as it contains// special character other than _$f.d = "num"; ?> Variable Scopes Scope of a variable is defined as its extent in a program within which it can be accessed, i.e. the scope of a variable is the portion of the program within which it is visible or can be accessed. Depending on the scopes, PHP has three variable scopes: Local variables: The variables declared within a function are called local variables to that function and have their scope only in that particular function. In simple words, it cannot be accessed outside that function. Any declaration of a variable outside the function with the same name as that of the one within the function is a completely different variable. We will learn about functions in detail in later articles. For now, consider a function as a block of statements. Example: PHP <?php $num = 60; function local_var(){ // This $num is local to this function // the variable $num outside this function // is a completely different variable $num = 50; echo "local num = $num \n";} local_var(); // $num outside function local_var() is a// completely different Variable than that of// inside local_var()echo "Variable num outside local_var() is $num \n"; ?> Output: local num = 50 Variable num outside local_var() is 60 Global variables: The variables declared outside a function are called global variables. These variables can be accessed directly outside a function. To get access within a function we need to use the “global” keyword before the variable to refer to the global variable. Example: PHP <?php $num = 20; // function to demonstrate use of global variablefunction global_var(){ // we have to use global keyword before // the variable $num to access within // the function global $num; echo "Variable num inside function : $num \n";} global_var(); echo "Variable num outside function : $num \n"; ?> Output: Variable num inside function : 20 Variable num outside function : 20 Static variable: It is the characteristic of PHP to delete the variable, once it completes its execution and the memory is freed. But sometimes we need to store the variables even after the completion of function execution. To do this we use the static keywords and the variables are then called static variables. PHP associates a data type depending on the value for the variable. Example: PHP <?php // function to demonstrate static variablesfunction static_var(){ // static variable static $num = 5; $sum = 2; $sum++; $num++; echo $num, "\n"; echo $sum, "\n";} // first function callstatic_var(); // second function callstatic_var(); ?> Output: 6 3 7 3 You must have noticed that $num regularly increments even after the first function call but $sum doesn’t. This is because $sum is not static, and its memory is freed after the execution of the first function call. Variable Variables:- PHP allows us to use dynamic variable names, called variable variables. Variable variables are simply variables whose names are dynamically created by another variable’s value. Example: PHP <?php $a = 'hello'; //hello is value of variable $a $$a = 'World'; //$($a) is equals to $(hello) echo $hello; //$hello is World i.e. $hello is new variable with value 'World'?> Output: World This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. geetanjali16 cd_pandey luizashaikh1 PHP-basics PHP PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? PHP in_array() Function How to delete an array element based on key in PHP? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to pop an alert message box using PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime Comparing two dates in PHP
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jun, 2022" }, { "code": null, "e": 62, "s": 52, "text": "Variables" }, { "code": null, "e": 457, "s": 62, "text": "Variables in a program are used to store some values or data that can be used later in a program. The variables are also like containers that store character values, numeric values, memory addresses, and strings. PHP has its own way of declaring and storing variables. There are a few rules, that need to be followed and facts that need to be kept in mind while dealing with variables in PHP: " }, { "code": null, "e": 553, "s": 457, "text": "Any variables declared in PHP must begin with a dollar sign ($), followed by the variable name." }, { "code": null, "e": 662, "s": 553, "text": "A variable can have long descriptive names (like $factorial, $even_nos) or short names (like $n or $f or $x)" }, { "code": null, "e": 822, "s": 662, "text": "A variable name can only contain alphanumeric characters and underscores (i.e., ‘a-z’, ‘A-Z’, ‘0-9, and ‘_’) in their name. Even it cannot start with a number." }, { "code": null, "e": 925, "s": 822, "text": "A constant is used as a variable for a simple value that cannot be changed. It is also case-sensitive." }, { "code": null, "e": 1125, "s": 925, "text": "Assignment of variables is done with the assignment operator, “equal to (=)”. The variable names are on the left of equal and the expression or values are to the right of the assignment operator ‘=’." }, { "code": null, "e": 1235, "s": 1125, "text": "One must keep in mind that variable names in PHP names must start with a letter or underscore and no numbers." }, { "code": null, "e": 1550, "s": 1235, "text": "PHP is a loosely typed language, and we do not require to declare the data types of variables, rather PHP assumes it automatically by analyzing the values. The same happens while conversion. No variables are declared before they are used. It automatically converts types from one type to another whenever required." }, { "code": null, "e": 1629, "s": 1550, "text": "PHP variables are case-sensitive, i.e., $sum and $SUM are treated differently." }, { "code": null, "e": 1687, "s": 1629, "text": "Data types used by PHP to declare or construct variables:" }, { "code": null, "e": 1696, "s": 1687, "text": "Integers" }, { "code": null, "e": 1704, "s": 1696, "text": "Doubles" }, { "code": null, "e": 1709, "s": 1704, "text": "NULL" }, { "code": null, "e": 1717, "s": 1709, "text": "Strings" }, { "code": null, "e": 1726, "s": 1717, "text": "Booleans" }, { "code": null, "e": 1733, "s": 1726, "text": "Arrays" }, { "code": null, "e": 1741, "s": 1733, "text": "Objects" }, { "code": null, "e": 1751, "s": 1741, "text": "Resources" }, { "code": null, "e": 1762, "s": 1751, "text": "Example: " }, { "code": null, "e": 1766, "s": 1762, "text": "PHP" }, { "code": "<?php // These are all valid declarations$val = 5;$val2 = 2;$x_Y = \"gfg\";$_X = \"GeeksforGeeks\"; // This is an invalid declaration as it// begins with a number$10_ val = 56; // This is also invalid as it contains// special character other than _$f.d = \"num\"; ?>", "e": 2028, "s": 1766, "text": null }, { "code": null, "e": 2044, "s": 2028, "text": "Variable Scopes" }, { "code": null, "e": 2299, "s": 2044, "text": "Scope of a variable is defined as its extent in a program within which it can be accessed, i.e. the scope of a variable is the portion of the program within which it is visible or can be accessed. Depending on the scopes, PHP has three variable scopes: " }, { "code": null, "e": 2779, "s": 2299, "text": "Local variables: The variables declared within a function are called local variables to that function and have their scope only in that particular function. In simple words, it cannot be accessed outside that function. Any declaration of a variable outside the function with the same name as that of the one within the function is a completely different variable. We will learn about functions in detail in later articles. For now, consider a function as a block of statements. " }, { "code": null, "e": 2790, "s": 2779, "text": "Example: " }, { "code": null, "e": 2794, "s": 2790, "text": "PHP" }, { "code": "<?php $num = 60; function local_var(){ // This $num is local to this function // the variable $num outside this function // is a completely different variable $num = 50; echo \"local num = $num \\n\";} local_var(); // $num outside function local_var() is a// completely different Variable than that of// inside local_var()echo \"Variable num outside local_var() is $num \\n\"; ?>", "e": 3185, "s": 2794, "text": null }, { "code": null, "e": 3194, "s": 3185, "text": "Output: " }, { "code": null, "e": 3250, "s": 3194, "text": "local num = 50 \nVariable num outside local_var() is 60 " }, { "code": null, "e": 3521, "s": 3250, "text": "Global variables: The variables declared outside a function are called global variables. These variables can be accessed directly outside a function. To get access within a function we need to use the “global” keyword before the variable to refer to the global variable." }, { "code": null, "e": 3532, "s": 3521, "text": "Example: " }, { "code": null, "e": 3536, "s": 3532, "text": "PHP" }, { "code": "<?php $num = 20; // function to demonstrate use of global variablefunction global_var(){ // we have to use global keyword before // the variable $num to access within // the function global $num; echo \"Variable num inside function : $num \\n\";} global_var(); echo \"Variable num outside function : $num \\n\"; ?>", "e": 3865, "s": 3536, "text": null }, { "code": null, "e": 3875, "s": 3865, "text": "Output: " }, { "code": null, "e": 3946, "s": 3875, "text": "Variable num inside function : 20 \nVariable num outside function : 20 " }, { "code": null, "e": 4330, "s": 3946, "text": "Static variable: It is the characteristic of PHP to delete the variable, once it completes its execution and the memory is freed. But sometimes we need to store the variables even after the completion of function execution. To do this we use the static keywords and the variables are then called static variables. PHP associates a data type depending on the value for the variable. " }, { "code": null, "e": 4341, "s": 4330, "text": "Example: " }, { "code": null, "e": 4345, "s": 4341, "text": "PHP" }, { "code": "<?php // function to demonstrate static variablesfunction static_var(){ // static variable static $num = 5; $sum = 2; $sum++; $num++; echo $num, \"\\n\"; echo $sum, \"\\n\";} // first function callstatic_var(); // second function callstatic_var(); ?>", "e": 4623, "s": 4345, "text": null }, { "code": null, "e": 4632, "s": 4623, "text": "Output: " }, { "code": null, "e": 4640, "s": 4632, "text": "6\n3\n7\n3" }, { "code": null, "e": 4856, "s": 4640, "text": "You must have noticed that $num regularly increments even after the first function call but $sum doesn’t. This is because $sum is not static, and its memory is freed after the execution of the first function call. " }, { "code": null, "e": 4877, "s": 4856, "text": "Variable Variables:-" }, { "code": null, "e": 4949, "s": 4877, "text": "PHP allows us to use dynamic variable names, called variable variables." }, { "code": null, "e": 5054, "s": 4949, "text": "Variable variables are simply variables whose names are dynamically created by another variable’s value." }, { "code": null, "e": 5063, "s": 5054, "text": "Example:" }, { "code": null, "e": 5067, "s": 5063, "text": "PHP" }, { "code": "<?php $a = 'hello'; //hello is value of variable $a $$a = 'World'; //$($a) is equals to $(hello) echo $hello; //$hello is World i.e. $hello is new variable with value 'World'?>", "e": 5250, "s": 5067, "text": null }, { "code": null, "e": 5258, "s": 5250, "text": "Output:" }, { "code": null, "e": 5264, "s": 5258, "text": "World" }, { "code": null, "e": 5689, "s": 5264, "text": "This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. " }, { "code": null, "e": 5702, "s": 5689, "text": "geetanjali16" }, { "code": null, "e": 5712, "s": 5702, "text": "cd_pandey" }, { "code": null, "e": 5725, "s": 5712, "text": "luizashaikh1" }, { "code": null, "e": 5736, "s": 5725, "text": "PHP-basics" }, { "code": null, "e": 5740, "s": 5736, "text": "PHP" }, { "code": null, "e": 5744, "s": 5740, "text": "PHP" }, { "code": null, "e": 5842, "s": 5744, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5887, "s": 5842, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 5911, "s": 5887, "text": "PHP in_array() Function" }, { "code": null, "e": 5963, "s": 5911, "text": "How to delete an array element based on key in PHP?" }, { "code": null, "e": 6013, "s": 5963, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 6053, "s": 6013, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 6097, "s": 6053, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 6158, "s": 6097, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 6208, "s": 6158, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 6253, "s": 6208, "text": "PHP | Converting string to Date and DateTime" } ]
How to Create a PHP Docker Container? - GeeksforGeeks
05 Nov, 2020 PHP is one of the widely used programming languages across several organizations mostly used for creating web architectures and back-end applications. Most of the big tech giants still rely on PHP for their back-end applications and are also increasingly adopting developer tools such as Docker. Thus, it becomes very important to learn how to access and use PHP inside Docker Containers. Docker provides regularly updated PHP Images that can be pulled straight from the Dockerhub and can be customized using Dockerfiles. The Docker PHP Image allows you to build and run PHP applications and to access such applications on your localhost, you can use the -p flag to connect and publish ports. In this article, we will discuss how to create a PHP Docker Container with the help of the Apache server. Create a simple PHP file that will be served once we run the container. Let’s name the file app.php. PHP <?php echo ?Welcome to GeeksForGeeks?;?> We will pull the PHP Image and Copy the files to the following directory. FROM php:7.0-apache COPY . /var/www/php Your directory structure should look like this. To build the Docker Image, you can use the Docker Build Command. sudo docker build -t php-demo . To verify that the image has been built, you can list all the Images. sudo docker images You can use the following command to run the Docker Container. sudo docker run -p 80:80 php-demo You can see that our PHP application is being served at IP address 172.17.0.4. Docker Container linux Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments ML | Stochastic Gradient Descent (SGD) Copying Files to and from Docker Containers Principal Component Analysis with Python ML | Principal Component Analysis(PCA) ML | Types of Learning – Supervised Learning Q-Learning in Python Classifying data using Support Vector Machines(SVMs) in Python Getting Started with System Design Deep Learning | Introduction to Long Short Term Memory Learning Model Building in Scikit-learn : A Python Machine Learning Library
[ { "code": null, "e": 24148, "s": 24120, "text": "\n05 Nov, 2020" }, { "code": null, "e": 24841, "s": 24148, "text": "PHP is one of the widely used programming languages across several organizations mostly used for creating web architectures and back-end applications. Most of the big tech giants still rely on PHP for their back-end applications and are also increasingly adopting developer tools such as Docker. Thus, it becomes very important to learn how to access and use PHP inside Docker Containers. Docker provides regularly updated PHP Images that can be pulled straight from the Dockerhub and can be customized using Dockerfiles. The Docker PHP Image allows you to build and run PHP applications and to access such applications on your localhost, you can use the -p flag to connect and publish ports." }, { "code": null, "e": 24947, "s": 24841, "text": "In this article, we will discuss how to create a PHP Docker Container with the help of the Apache server." }, { "code": null, "e": 25049, "s": 24947, "text": "Create a simple PHP file that will be served once we run the container. Let’s name the file app.php. " }, { "code": null, "e": 25053, "s": 25049, "text": "PHP" }, { "code": "<?php echo ?Welcome to GeeksForGeeks?;?>", "e": 25095, "s": 25053, "text": null }, { "code": null, "e": 25169, "s": 25095, "text": "We will pull the PHP Image and Copy the files to the following directory." }, { "code": null, "e": 25215, "s": 25169, "text": "FROM php:7.0-apache \nCOPY . /var/www/php\n\n" }, { "code": null, "e": 25263, "s": 25215, "text": "Your directory structure should look like this." }, { "code": null, "e": 25328, "s": 25263, "text": "To build the Docker Image, you can use the Docker Build Command." }, { "code": null, "e": 25362, "s": 25328, "text": "sudo docker build -t php-demo .\n\n" }, { "code": null, "e": 25432, "s": 25362, "text": "To verify that the image has been built, you can list all the Images." }, { "code": null, "e": 25453, "s": 25432, "text": "sudo docker images\n\n" }, { "code": null, "e": 25516, "s": 25453, "text": "You can use the following command to run the Docker Container." }, { "code": null, "e": 25552, "s": 25516, "text": "sudo docker run -p 80:80 php-demo\n\n" }, { "code": null, "e": 25631, "s": 25552, "text": "You can see that our PHP application is being served at IP address 172.17.0.4." }, { "code": null, "e": 25648, "s": 25631, "text": "Docker Container" }, { "code": null, "e": 25654, "s": 25648, "text": "linux" }, { "code": null, "e": 25680, "s": 25654, "text": "Advanced Computer Subject" }, { "code": null, "e": 25778, "s": 25680, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25787, "s": 25778, "text": "Comments" }, { "code": null, "e": 25800, "s": 25787, "text": "Old Comments" }, { "code": null, "e": 25839, "s": 25800, "text": "ML | Stochastic Gradient Descent (SGD)" }, { "code": null, "e": 25883, "s": 25839, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 25924, "s": 25883, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 25963, "s": 25924, "text": "ML | Principal Component Analysis(PCA)" }, { "code": null, "e": 26008, "s": 25963, "text": "ML | Types of Learning – Supervised Learning" }, { "code": null, "e": 26029, "s": 26008, "text": "Q-Learning in Python" }, { "code": null, "e": 26092, "s": 26029, "text": "Classifying data using Support Vector Machines(SVMs) in Python" }, { "code": null, "e": 26127, "s": 26092, "text": "Getting Started with System Design" }, { "code": null, "e": 26182, "s": 26127, "text": "Deep Learning | Introduction to Long Short Term Memory" } ]
Crystal Reports - Creating Variables
A Variable is used to assign different values to an object unlike constant which is fixed. When you assign a value to a variable, it maintains that value till you assign a new value to it. Before using variables, it is necessary to define them in a report. When you declare a variable in Crystal Report you need to assign a name to it, however this name shouldn’t be the same as any other function, operator, etc. A variable can be a number type, string type, date type, Boolean type, range type or an array type. A variable can hold a value of single type, like if you declare it as a number it can’t be used to hold string values later. Local Stringvar Customer_Lastname Local numbervar Sales_percentage The keyword for declaring the variable has ‘var’ at the end and it is true for all variable types. You can also assign an initial value to a variable with declaration or in separate syntax. Local NumberVar Z; //Declare Z to be a Number variable Z := 30; //Assign the value of 30 to Z To use Variables in formulas, its scope is defined. Variable scope can be of three types − Local Global Shared This defines that a variable in one formula can be used in other formula. Local variables are declared using the local keyword followed by the type and followed by the variable name as in the above examples. Local variables are restricted to a single formula. This means that you cannot access the value of a local variable in one formula from a different formula. //Formula 1 Local NumberVar Z; Z := 30; //Formula 2 EvaluateAfter ({@Formula A}) Local NumberVar Z; Z := z + 5; In the above example, Formula 2 will return a value 5 as Z is declared as local number variable in formula 1 so it will take default value for variable Z in formula 2. Global variables are used throughout the main report. Their value is available to all formulas that declare the variable, except for those in sub reports. Global StringVar Z; It is recommended that you use global variable only when local variables do not suffice. Since global variables share their values throughout the main report, you cannot declare a global variable in one formula with one type and then declare a global variable with the same name in a different formula with a different type. Shared variables are used throughout the main report and all of its sub reports. Shared variables are even more general than global variables. To use a shared variable, declare it in a formula in the main report − Shared NumberVar Z := 10; To use shared variables, it must be declared and assigned a value before it can be used in the main report and subreports. 37 Lectures 2 hours Neha Gupta 61 Lectures 4.5 hours Sasha Miller 31 Lectures 32 mins Prof Krishna N Sharma 35 Lectures 2 hours Prof Krishna N Sharma 24 Lectures 2 hours Prof Krishna N Sharma Print Add Notes Bookmark this page
[ { "code": null, "e": 3227, "s": 2970, "text": "A Variable is used to assign different values to an object unlike constant which is fixed. When you assign a value to a variable, it maintains that value till you assign a new value to it. Before using variables, it is necessary to define them in a report." }, { "code": null, "e": 3609, "s": 3227, "text": "When you declare a variable in Crystal Report you need to assign a name to it, however this name shouldn’t be the same as any other function, operator, etc. A variable can be a number type, string type, date type, Boolean type, range type or an array type. A variable can hold a value of single type, like if you declare it as a number it can’t be used to hold string values later." }, { "code": null, "e": 3677, "s": 3609, "text": "Local Stringvar Customer_Lastname\nLocal numbervar Sales_percentage\n" }, { "code": null, "e": 3867, "s": 3677, "text": "The keyword for declaring the variable has ‘var’ at the end and it is true for all variable types. You can also assign an initial value to a variable with declaration or in separate syntax." }, { "code": null, "e": 3972, "s": 3867, "text": "Local NumberVar Z; //Declare Z to be a Number variable\nZ := 30; //Assign the value of 30 to Z\n" }, { "code": null, "e": 4063, "s": 3972, "text": "To use Variables in formulas, its scope is defined. Variable scope can be of three types −" }, { "code": null, "e": 4069, "s": 4063, "text": "Local" }, { "code": null, "e": 4076, "s": 4069, "text": "Global" }, { "code": null, "e": 4083, "s": 4076, "text": "Shared" }, { "code": null, "e": 4157, "s": 4083, "text": "This defines that a variable in one formula can be used in other formula." }, { "code": null, "e": 4291, "s": 4157, "text": "Local variables are declared using the local keyword followed by the type and followed by the variable name as in the above examples." }, { "code": null, "e": 4448, "s": 4291, "text": "Local variables are restricted to a single formula. This means that you cannot access the value of a local variable in one formula from a different formula." }, { "code": null, "e": 4561, "s": 4448, "text": "//Formula 1\nLocal NumberVar Z;\nZ := 30;\n\n//Formula 2\nEvaluateAfter ({@Formula A})\nLocal NumberVar Z;\nZ := z + 5;" }, { "code": null, "e": 4729, "s": 4561, "text": "In the above example, Formula 2 will return a value 5 as Z is declared as local number variable in formula 1 so it will take default value for variable Z in formula 2." }, { "code": null, "e": 4884, "s": 4729, "text": "Global variables are used throughout the main report. Their value is available to all formulas that declare the variable, except for those in sub reports." }, { "code": null, "e": 4905, "s": 4884, "text": "Global StringVar Z;\n" }, { "code": null, "e": 4994, "s": 4905, "text": "It is recommended that you use global variable only when local variables do not suffice." }, { "code": null, "e": 5230, "s": 4994, "text": "Since global variables share their values throughout the main report, you cannot declare a global variable in one formula with one type and then declare a global variable with the same name in a different formula with a different type." }, { "code": null, "e": 5373, "s": 5230, "text": "Shared variables are used throughout the main report and all of its sub reports. Shared variables are even more general than global variables." }, { "code": null, "e": 5444, "s": 5373, "text": "To use a shared variable, declare it in a formula in the main report −" }, { "code": null, "e": 5471, "s": 5444, "text": "Shared NumberVar Z := 10;\n" }, { "code": null, "e": 5594, "s": 5471, "text": "To use shared variables, it must be declared and assigned a value before it can be used in the main report and subreports." }, { "code": null, "e": 5627, "s": 5594, "text": "\n 37 Lectures \n 2 hours \n" }, { "code": null, "e": 5639, "s": 5627, "text": " Neha Gupta" }, { "code": null, "e": 5674, "s": 5639, "text": "\n 61 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5688, "s": 5674, "text": " Sasha Miller" }, { "code": null, "e": 5720, "s": 5688, "text": "\n 31 Lectures \n 32 mins\n" }, { "code": null, "e": 5743, "s": 5720, "text": " Prof Krishna N Sharma" }, { "code": null, "e": 5776, "s": 5743, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 5799, "s": 5776, "text": " Prof Krishna N Sharma" }, { "code": null, "e": 5832, "s": 5799, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 5855, "s": 5832, "text": " Prof Krishna N Sharma" }, { "code": null, "e": 5862, "s": 5855, "text": " Print" }, { "code": null, "e": 5873, "s": 5862, "text": " Add Notes" } ]
How to shift a column in a Pandas DataFrame?
We can use the shift() method in Pandas to shift the columns of a DataFrame without having to rewrite the whole DataFrame. shift() takes the following parameters shift(self, periods=1, freq=None, axis=0, fill_value=None) periods Number of periods to shift. It can take a negative number too. axis It takes a Boolean value; 0 if you want to shift index and 1 if you want to shift column fill_value It will replace the missing value. Let's take an example and see how to use this shift() method. Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df. Print the input DataFrame, df. Select a column and shift it by using df["column_name]=df.column_name.shift() Print the updated DataFrame. import pandas as pd df = pd.DataFrame( dict( name=['John', 'Jacob', 'Tom', 'Tim', 'Ally'], marks=[89, 23, 100, 56, 90], subjects=["Math", "Physics", "Chemistry", "Biology", "English"] ) ) print "Input DataFrame is:\n", df df["name"] = df.name.shift(1) print "After shifting column name by 1:\n", df df["marks"] = df.marks.shift(2) print "After shifting column marks by 2:\n", df df["subjects"] = df.subjects.shift(-1) print "After shifting column subjects by -1:\n", df Input DataFrame is: name marks subjects 0 John 89 Math 1 Jacob 23 Physics 2 Tom 100 Chemistry 3 Tim 56 Biology 4 Ally 90 English After shifting column name by 1: name marks subjects 0 NaN 89 Math 1 John 23 Physics 2 Jacob 100 Chemistry 3 Tom 56 Biology 4 Tim 90 English After shifting column marks by 2: name marks subjects 0 NaN 100 Math 1 John 100 Physics 2 Jacob 89 Chemistry 3 Tom 23 Biology 4 Tim 100 English After shifting column subjects by -1: name marks subjects 0 NaN 100 Physics 1 John 100 Chemistry 2 Jacob 89 Biology 3 Tom 23 English 4 Tim 100 NaN
[ { "code": null, "e": 1224, "s": 1062, "text": "We can use the shift() method in Pandas to shift the columns of a DataFrame without having to rewrite the whole DataFrame. shift() takes the following parameters" }, { "code": null, "e": 1283, "s": 1224, "text": "shift(self, periods=1, freq=None, axis=0, fill_value=None)" }, { "code": null, "e": 1355, "s": 1283, "text": "periods Number of periods to shift. It can take a negative number too." }, { "code": null, "e": 1450, "s": 1355, "text": "axis It takes a Boolean value; 0 if you want to shift index and 1 if you want to shift column" }, { "code": null, "e": 1497, "s": 1450, "text": "fill_value It will replace the missing value." }, { "code": null, "e": 1559, "s": 1497, "text": "Let's take an example and see how to use this shift() method." }, { "code": null, "e": 1643, "s": 1559, "text": "Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df." }, { "code": null, "e": 1674, "s": 1643, "text": "Print the input DataFrame, df." }, { "code": null, "e": 1752, "s": 1674, "text": "Select a column and shift it by using df[\"column_name]=df.column_name.shift()" }, { "code": null, "e": 1781, "s": 1752, "text": "Print the updated DataFrame." }, { "code": null, "e": 2280, "s": 1781, "text": "import pandas as pd\n\ndf = pd.DataFrame(\n dict(\n name=['John', 'Jacob', 'Tom', 'Tim', 'Ally'],\n marks=[89, 23, 100, 56, 90],\n subjects=[\"Math\", \"Physics\", \"Chemistry\", \"Biology\", \"English\"]\n )\n)\n\nprint \"Input DataFrame is:\\n\", df\n\ndf[\"name\"] = df.name.shift(1)\nprint \"After shifting column name by 1:\\n\", df\n\ndf[\"marks\"] = df.marks.shift(2)\nprint \"After shifting column marks by 2:\\n\", df\n\ndf[\"subjects\"] = df.subjects.shift(-1)\nprint \"After shifting column subjects by -1:\\n\", df" }, { "code": null, "e": 3099, "s": 2280, "text": "Input DataFrame is:\n name marks subjects\n0 John 89 Math\n1 Jacob 23 Physics\n2 Tom 100 Chemistry\n3 Tim 56 Biology\n4 Ally 90 English\n\nAfter shifting column name by 1:\n name marks subjects\n0 NaN 89 Math\n1 John 23 Physics\n2 Jacob 100 Chemistry\n3 Tom 56 Biology\n4 Tim 90 English\n\nAfter shifting column marks by 2:\n name marks subjects\n0 NaN 100 Math\n1 John 100 Physics\n2 Jacob 89 Chemistry\n3 Tom 23 Biology\n4 Tim 100 English\n\nAfter shifting column subjects by -1:\n name marks subjects\n0 NaN 100 Physics\n1 John 100 Chemistry\n2 Jacob 89 Biology\n3 Tom 23 English\n4 Tim 100 NaN" } ]
R Lang: Zero to Hero. A guide for statistical computing and... | by Vihar Kurama | Towards Data Science
A guide for statistical computing and graphics. R is a computing environment that combines a programming language called S, that implements the idea of programming with data. It has powerful numerical analysis tools for linear algebra, differential equations, and stochastics. R Programming lets you learn about data visualisations by offering a set of inbuilt functions and libraries. There are many graphical front-ends for R. At present, the best of these appears to be RStudio. Before learning about these, however, you should learn a little about R itself. R is flexible.R is powerful.R is not just a statistics computing package; it’s a programming language.R is designed to operate the way that problems are designed for.R is efficient in handling data and storage facility. R is flexible. R is powerful. R is not just a statistics computing package; it’s a programming language. R is designed to operate the way that problems are designed for. R is efficient in handling data and storage facility. The snippets of code that are written in the R language are always available to the user, so a small change to the task usually requires only a minor change to the code — a difference that can be carried out in a lesser amount of time. To download R, please choose your preferred CRAN mirror. RStudio makes R easier to use. It includes a code editor, debugging & visualisation tools. It is an (IDE) which includes a console, syntax-highlighting editor that supports direct code execution, as well as tools for plotting, history, debugging and workspace management. Download R-Studio from the following link. www.rstudio.com After installing R on your machine, then start the R interactive Shell by hitting R in the terminal or shell. The default prompt is ‘>’, which on UNIX might be the same as the shell prompt, and so it may appear that nothing is happening, it will be waiting for the user for the instruction. You can use the R Shell as a calculator, you can just play with from doing simple math to advance Machine Learning Algorithms. To quit the R program the command is > q() This will exit from the R Shell you can also save the workspace session by hitting “y” after exiting if to wish to continue without saving just hit “n”, which brings you back to the terminal/shell. Lets’s get started with printing “Hello World!” in the R interactive Shell. In R we use print() function to return the String given in the argument. $R> print("Hello World!")[1] "Hello World!"> As we know every programming language needs comments, R supports comments, which are ignored by the interpreter. This it how we use comments in R. # This is a comment in R# print("This doesn't work") In programming, a variable is nothing more than a name for something. A variable in R can store an atomic vector, group of atomic vectors or a combination of many R objects. R names are case sensitive. To create names for the data structures, we have to follow the following rules: Note: Names that begin with . are considered system names and are not always visible using the ls()-function. Now let’s see how we declare variables in R a <- 3 This line of code declares a variable “a” and assigns it to the value 3. typeof() function returns the datatype of the variable. type(a)[1] "double" Numeric (real or decimal): Decimal values are called numerics in R. It is the default computational data type. Integer: In order to create an integer variable in R, we invoke the as integer function. Character: A character object is used to represent string values in R. We convert objects into character values with the as character() function. Logical: A logical value is often created via comparison between variables. Complex: A complex value in R is defined via the pure imaginary value i. A code snippet explaining datatypes. To execute R files from the shell we use the command “ Rscript filename.R ” [1] 3[1] "double"[1] "Stark"[1] "character"[1] TRUE[1] "logical"[1] 1+4i[1] "complex" Note: Strings in R Language are Characters. All the basic operations like addition, subtraction, division, multiplication. Etc Can be performed in R. [1] 6[1] 1[1] 315[1] 8.333333[1] 3[1] 1[1] 125 A vector is the most commonly used data structure in R . It is a sequence of data elements of the same basic type. Members in a vector are officially called components. A vector can be a vector of elements that are most commonly character, logical, integer or numeric. We use vector() function to create an empty vector, the below snippet show’s how we declare a vector. x <- vector()> character(5)[1] "" "" "" "" "" Lists in R lang act as containers. They are generic vector containing other objects. Unlike atomic vectors, the variables of a list are not limited to a single mode and can include any mixture of data types. A list can contain other lists. This makes them unique from atomic vectors. Lists in R are created using list() function. my_list <- list("Red", TRUE, 51.23) [1] "Red"[[2]][1] TRUE[[3]][1] 51.23[[1]][1] 1[[2]][1] 2[[3]][1] 3[[4]][1] "Sun"[[5]][1] "Mon"[[6]][1] "Tue" Matrices are special types of Vectors in R. A matrix is a collection of data elements arranged in a two-dimensional rectangular layout. Matrices have rows and columns. Now let’s create a 2x2 matrix, we use matrix function and send the rows and columns as parameters. The number of rows will be nrow, the number of columns will be ncol. my_matrix <- matrix(nrow = 2, ncol = 2) [,1] [,2] [,3] [,4][1,] 59.0 22.3 31.2 9.5[2,] 55.0 19.7 30.4 13.8[3,] 53.5 20.8 30.6 14.8[4,] 55.0 20.3 30.3 15.2[5,] 52.5 20.8 30.3 15.5[6,] 57.5 21.5 30.8 15.6[7,] 53.0 20.6 32.5 15.6[8,] 55.0 21.5 34.0 15.7 Dataframes are on of the most used data structures in R Language. The data is represented in a tabular format which has number of rows and columns. We usually read csv files into a data frame to do that we use read.csv() function or read.table() function and send the csv file name as an argument. We can also create a data frame using data.frame() function. > df <- data.frame(id = letters[1:5], x = 1:10, y = rnorm(10))> df> ## id x y> ## 1 a 1 -1.37593> ## 2 b 2 0.47094> ## 3 c 3 -0.16046> ## 4 d 4 -1.36914> ## 5 e 5 0.39763 These are few import functions we apply to a data frame to draw minimal conclusions. head() — see first 6 rows tail() — see last 6 rows dim() — see dimensions nrow() — number of rows ncol() — number of columns str() — structure of each column Factors are pretty much integers that have labels on them. While factors look (and often behave) like character vectors, they are actually integers under the hood, and you need to be careful when treating them like strings. Some string methods will coerce factors to strings, while others will throw an error. Factors can be created with factor(). Input is generally a character vector. > x <- factor(c("yes", "no", "no", "yes", "yes"))> x[1] yes no no yes yesLevels: no yes# table(x) will return a frequency table. These allow you to control the flow of execution of a script typically inside of a function. Common ones include: if, elseforwhilerepeatbreak if, else for while repeat break We always need the ability to check the conditions and change the behavior of the program accordingly. The conditional statements give us the ability; the simplest form is the ‘if’ statement. if (condition) { # do something} else { # do something else} Example, x is less than 10 The for loop in R has the ability to iterate over items of any sequence such as list or vectors. for (i in 1:5) { print(i)} This is how we declare for loop in R, it takes the iterable variable(i) and iterates until the range given (10, here) 12345 Few ways of implementing for loops. [1] NA[1] NA[1] NA[1] NA[1] "apples"[1] "oranges"[1] "bananas"[1] "strawberries"[1] "apples"[1] "oranges"[1] "bananas"[1] "strawberries"[1] "apples"[1] "oranges"[1] "bananas"[1] "strawberries" A while loop statement in R lang repeatedly executes a target statement as long as the given condition is true. Unlike the for loop, the while loop will not run n times, but until a defined condition is met. Syntax of While loop while(condition){ statements iteration} Here’s an example of how we can implement a simple while loop, 12345 A repeat loop is used to iterate over a block of code multiple number of times.There is no condition check in repeat loop to exit the loop. Syntax for repeat and break repeat{ condition statements break} Now let’s print first five numbers using repeat and break. [1] 1[1] 2[1] 3[1] 4[1] 5 The main use of a function in any programming language is reusability. They are the set of statements organised together to perform a specific task. There are various inbuilt functions in R. Some of the inbuilt functions in R are sum(), min(), max(),mean(), etc. Syntax for declaring a function in R function_name <- function(arg_1, arg_2, ...) { function body } Now let’s create a function to print cubes of numbers in sequence. 216 Visualising the data is one of the vital solutions for decision making. R Programming language offers a one of the best set of inbuilt function and libraries (such as ggplot2, leaflet, lattice) for creating data stories and visualisation. Now, let’s create a simple line plot using ggplot2 in RStudio, to do that we need to install the ggplot2 package, you will find the console in the left corner. Run the command install.packages(“package_name”). > install.packages("ggplot2") We will now import a inbuilt dataset(mpg), and plot a simple graph. About mpg dataset: It’s a fuel economy data from 1999 and 2008 for 38 popular models of car. A data frame with 234 rows and 11 variablesdispl — engine displacement, in litreshwy — highway miles per gallon A data frame with 234 rows and 11 variables displ — engine displacement, in litres hwy — highway miles per gallon Thanks for reading! Code for this article can be found here by AaqilShaik. Thanks for reading. If you found this story helpful, please click the below 👏 to spread the love.
[ { "code": null, "e": 219, "s": 171, "text": "A guide for statistical computing and graphics." }, { "code": null, "e": 733, "s": 219, "text": "R is a computing environment that combines a programming language called S, that implements the idea of programming with data. It has powerful numerical analysis tools for linear algebra, differential equations, and stochastics. R Programming lets you learn about data visualisations by offering a set of inbuilt functions and libraries. There are many graphical front-ends for R. At present, the best of these appears to be RStudio. Before learning about these, however, you should learn a little about R itself." }, { "code": null, "e": 953, "s": 733, "text": "R is flexible.R is powerful.R is not just a statistics computing package; it’s a programming language.R is designed to operate the way that problems are designed for.R is efficient in handling data and storage facility." }, { "code": null, "e": 968, "s": 953, "text": "R is flexible." }, { "code": null, "e": 983, "s": 968, "text": "R is powerful." }, { "code": null, "e": 1058, "s": 983, "text": "R is not just a statistics computing package; it’s a programming language." }, { "code": null, "e": 1123, "s": 1058, "text": "R is designed to operate the way that problems are designed for." }, { "code": null, "e": 1177, "s": 1123, "text": "R is efficient in handling data and storage facility." }, { "code": null, "e": 1413, "s": 1177, "text": "The snippets of code that are written in the R language are always available to the user, so a small change to the task usually requires only a minor change to the code — a difference that can be carried out in a lesser amount of time." }, { "code": null, "e": 1470, "s": 1413, "text": "To download R, please choose your preferred CRAN mirror." }, { "code": null, "e": 1742, "s": 1470, "text": "RStudio makes R easier to use. It includes a code editor, debugging & visualisation tools. It is an (IDE) which includes a console, syntax-highlighting editor that supports direct code execution, as well as tools for plotting, history, debugging and workspace management." }, { "code": null, "e": 1785, "s": 1742, "text": "Download R-Studio from the following link." }, { "code": null, "e": 1801, "s": 1785, "text": "www.rstudio.com" }, { "code": null, "e": 2092, "s": 1801, "text": "After installing R on your machine, then start the R interactive Shell by hitting R in the terminal or shell. The default prompt is ‘>’, which on UNIX might be the same as the shell prompt, and so it may appear that nothing is happening, it will be waiting for the user for the instruction." }, { "code": null, "e": 2219, "s": 2092, "text": "You can use the R Shell as a calculator, you can just play with from doing simple math to advance Machine Learning Algorithms." }, { "code": null, "e": 2256, "s": 2219, "text": "To quit the R program the command is" }, { "code": null, "e": 2262, "s": 2256, "text": "> q()" }, { "code": null, "e": 2460, "s": 2262, "text": "This will exit from the R Shell you can also save the workspace session by hitting “y” after exiting if to wish to continue without saving just hit “n”, which brings you back to the terminal/shell." }, { "code": null, "e": 2536, "s": 2460, "text": "Lets’s get started with printing “Hello World!” in the R interactive Shell." }, { "code": null, "e": 2609, "s": 2536, "text": "In R we use print() function to return the String given in the argument." }, { "code": null, "e": 2654, "s": 2609, "text": "$R> print(\"Hello World!\")[1] \"Hello World!\">" }, { "code": null, "e": 2767, "s": 2654, "text": "As we know every programming language needs comments, R supports comments, which are ignored by the interpreter." }, { "code": null, "e": 2801, "s": 2767, "text": "This it how we use comments in R." }, { "code": null, "e": 2854, "s": 2801, "text": "# This is a comment in R# print(\"This doesn't work\")" }, { "code": null, "e": 3136, "s": 2854, "text": "In programming, a variable is nothing more than a name for something. A variable in R can store an atomic vector, group of atomic vectors or a combination of many R objects. R names are case sensitive. To create names for the data structures, we have to follow the following rules:" }, { "code": null, "e": 3246, "s": 3136, "text": "Note: Names that begin with . are considered system names and are not always visible using the ls()-function." }, { "code": null, "e": 3290, "s": 3246, "text": "Now let’s see how we declare variables in R" }, { "code": null, "e": 3297, "s": 3290, "text": "a <- 3" }, { "code": null, "e": 3370, "s": 3297, "text": "This line of code declares a variable “a” and assigns it to the value 3." }, { "code": null, "e": 3426, "s": 3370, "text": "typeof() function returns the datatype of the variable." }, { "code": null, "e": 3446, "s": 3426, "text": "type(a)[1] \"double\"" }, { "code": null, "e": 3557, "s": 3446, "text": "Numeric (real or decimal): Decimal values are called numerics in R. It is the default computational data type." }, { "code": null, "e": 3646, "s": 3557, "text": "Integer: In order to create an integer variable in R, we invoke the as integer function." }, { "code": null, "e": 3792, "s": 3646, "text": "Character: A character object is used to represent string values in R. We convert objects into character values with the as character() function." }, { "code": null, "e": 3868, "s": 3792, "text": "Logical: A logical value is often created via comparison between variables." }, { "code": null, "e": 3941, "s": 3868, "text": "Complex: A complex value in R is defined via the pure imaginary value i." }, { "code": null, "e": 3978, "s": 3941, "text": "A code snippet explaining datatypes." }, { "code": null, "e": 4054, "s": 3978, "text": "To execute R files from the shell we use the command “ Rscript filename.R ”" }, { "code": null, "e": 4140, "s": 4054, "text": "[1] 3[1] \"double\"[1] \"Stark\"[1] \"character\"[1] TRUE[1] \"logical\"[1] 1+4i[1] \"complex\"" }, { "code": null, "e": 4184, "s": 4140, "text": "Note: Strings in R Language are Characters." }, { "code": null, "e": 4290, "s": 4184, "text": "All the basic operations like addition, subtraction, division, multiplication. Etc Can be performed in R." }, { "code": null, "e": 4337, "s": 4290, "text": "[1] 6[1] 1[1] 315[1] 8.333333[1] 3[1] 1[1] 125" }, { "code": null, "e": 4606, "s": 4337, "text": "A vector is the most commonly used data structure in R . It is a sequence of data elements of the same basic type. Members in a vector are officially called components. A vector can be a vector of elements that are most commonly character, logical, integer or numeric." }, { "code": null, "e": 4708, "s": 4606, "text": "We use vector() function to create an empty vector, the below snippet show’s how we declare a vector." }, { "code": null, "e": 4754, "s": 4708, "text": "x <- vector()> character(5)[1] \"\" \"\" \"\" \"\" \"\"" }, { "code": null, "e": 5038, "s": 4754, "text": "Lists in R lang act as containers. They are generic vector containing other objects. Unlike atomic vectors, the variables of a list are not limited to a single mode and can include any mixture of data types. A list can contain other lists. This makes them unique from atomic vectors." }, { "code": null, "e": 5084, "s": 5038, "text": "Lists in R are created using list() function." }, { "code": null, "e": 5120, "s": 5084, "text": "my_list <- list(\"Red\", TRUE, 51.23)" }, { "code": null, "e": 5229, "s": 5120, "text": "[1] \"Red\"[[2]][1] TRUE[[3]][1] 51.23[[1]][1] 1[[2]][1] 2[[3]][1] 3[[4]][1] \"Sun\"[[5]][1] \"Mon\"[[6]][1] \"Tue\"" }, { "code": null, "e": 5397, "s": 5229, "text": "Matrices are special types of Vectors in R. A matrix is a collection of data elements arranged in a two-dimensional rectangular layout. Matrices have rows and columns." }, { "code": null, "e": 5565, "s": 5397, "text": "Now let’s create a 2x2 matrix, we use matrix function and send the rows and columns as parameters. The number of rows will be nrow, the number of columns will be ncol." }, { "code": null, "e": 5605, "s": 5565, "text": "my_matrix <- matrix(nrow = 2, ncol = 2)" }, { "code": null, "e": 5822, "s": 5605, "text": " [,1] [,2] [,3] [,4][1,] 59.0 22.3 31.2 9.5[2,] 55.0 19.7 30.4 13.8[3,] 53.5 20.8 30.6 14.8[4,] 55.0 20.3 30.3 15.2[5,] 52.5 20.8 30.3 15.5[6,] 57.5 21.5 30.8 15.6[7,] 53.0 20.6 32.5 15.6[8,] 55.0 21.5 34.0 15.7" }, { "code": null, "e": 5970, "s": 5822, "text": "Dataframes are on of the most used data structures in R Language. The data is represented in a tabular format which has number of rows and columns." }, { "code": null, "e": 6120, "s": 5970, "text": "We usually read csv files into a data frame to do that we use read.csv() function or read.table() function and send the csv file name as an argument." }, { "code": null, "e": 6181, "s": 6120, "text": "We can also create a data frame using data.frame() function." }, { "code": null, "e": 6380, "s": 6181, "text": "> df <- data.frame(id = letters[1:5], x = 1:10, y = rnorm(10))> df> ## id x y> ## 1 a 1 -1.37593> ## 2 b 2 0.47094> ## 3 c 3 -0.16046> ## 4 d 4 -1.36914> ## 5 e 5 0.39763" }, { "code": null, "e": 6465, "s": 6380, "text": "These are few import functions we apply to a data frame to draw minimal conclusions." }, { "code": null, "e": 6491, "s": 6465, "text": "head() — see first 6 rows" }, { "code": null, "e": 6516, "s": 6491, "text": "tail() — see last 6 rows" }, { "code": null, "e": 6539, "s": 6516, "text": "dim() — see dimensions" }, { "code": null, "e": 6563, "s": 6539, "text": "nrow() — number of rows" }, { "code": null, "e": 6590, "s": 6563, "text": "ncol() — number of columns" }, { "code": null, "e": 6623, "s": 6590, "text": "str() — structure of each column" }, { "code": null, "e": 6933, "s": 6623, "text": "Factors are pretty much integers that have labels on them. While factors look (and often behave) like character vectors, they are actually integers under the hood, and you need to be careful when treating them like strings. Some string methods will coerce factors to strings, while others will throw an error." }, { "code": null, "e": 7010, "s": 6933, "text": "Factors can be created with factor(). Input is generally a character vector." }, { "code": null, "e": 7141, "s": 7010, "text": "> x <- factor(c(\"yes\", \"no\", \"no\", \"yes\", \"yes\"))> x[1] yes no no yes yesLevels: no yes# table(x) will return a frequency table." }, { "code": null, "e": 7255, "s": 7141, "text": "These allow you to control the flow of execution of a script typically inside of a function. Common ones include:" }, { "code": null, "e": 7283, "s": 7255, "text": "if, elseforwhilerepeatbreak" }, { "code": null, "e": 7292, "s": 7283, "text": "if, else" }, { "code": null, "e": 7296, "s": 7292, "text": "for" }, { "code": null, "e": 7302, "s": 7296, "text": "while" }, { "code": null, "e": 7309, "s": 7302, "text": "repeat" }, { "code": null, "e": 7315, "s": 7309, "text": "break" }, { "code": null, "e": 7507, "s": 7315, "text": "We always need the ability to check the conditions and change the behavior of the program accordingly. The conditional statements give us the ability; the simplest form is the ‘if’ statement." }, { "code": null, "e": 7574, "s": 7507, "text": "if (condition) { # do something} else { # do something else}" }, { "code": null, "e": 7583, "s": 7574, "text": "Example," }, { "code": null, "e": 7601, "s": 7583, "text": "x is less than 10" }, { "code": null, "e": 7698, "s": 7601, "text": "The for loop in R has the ability to iterate over items of any sequence such as list or vectors." }, { "code": null, "e": 7728, "s": 7698, "text": "for (i in 1:5) { print(i)}" }, { "code": null, "e": 7846, "s": 7728, "text": "This is how we declare for loop in R, it takes the iterable variable(i) and iterates until the range given (10, here)" }, { "code": null, "e": 7852, "s": 7846, "text": "12345" }, { "code": null, "e": 7888, "s": 7852, "text": "Few ways of implementing for loops." }, { "code": null, "e": 8081, "s": 7888, "text": "[1] NA[1] NA[1] NA[1] NA[1] \"apples\"[1] \"oranges\"[1] \"bananas\"[1] \"strawberries\"[1] \"apples\"[1] \"oranges\"[1] \"bananas\"[1] \"strawberries\"[1] \"apples\"[1] \"oranges\"[1] \"bananas\"[1] \"strawberries\"" }, { "code": null, "e": 8289, "s": 8081, "text": "A while loop statement in R lang repeatedly executes a target statement as long as the given condition is true. Unlike the for loop, the while loop will not run n times, but until a defined condition is met." }, { "code": null, "e": 8310, "s": 8289, "text": "Syntax of While loop" }, { "code": null, "e": 8356, "s": 8310, "text": "while(condition){ statements iteration}" }, { "code": null, "e": 8419, "s": 8356, "text": "Here’s an example of how we can implement a simple while loop," }, { "code": null, "e": 8425, "s": 8419, "text": "12345" }, { "code": null, "e": 8565, "s": 8425, "text": "A repeat loop is used to iterate over a block of code multiple number of times.There is no condition check in repeat loop to exit the loop." }, { "code": null, "e": 8593, "s": 8565, "text": "Syntax for repeat and break" }, { "code": null, "e": 8646, "s": 8593, "text": "repeat{ condition statements break}" }, { "code": null, "e": 8705, "s": 8646, "text": "Now let’s print first five numbers using repeat and break." }, { "code": null, "e": 8731, "s": 8705, "text": "[1] 1[1] 2[1] 3[1] 4[1] 5" }, { "code": null, "e": 8994, "s": 8731, "text": "The main use of a function in any programming language is reusability. They are the set of statements organised together to perform a specific task. There are various inbuilt functions in R. Some of the inbuilt functions in R are sum(), min(), max(),mean(), etc." }, { "code": null, "e": 9031, "s": 8994, "text": "Syntax for declaring a function in R" }, { "code": null, "e": 9097, "s": 9031, "text": "function_name <- function(arg_1, arg_2, ...) { function body }" }, { "code": null, "e": 9164, "s": 9097, "text": "Now let’s create a function to print cubes of numbers in sequence." }, { "code": null, "e": 9168, "s": 9164, "text": "216" }, { "code": null, "e": 9407, "s": 9168, "text": "Visualising the data is one of the vital solutions for decision making. R Programming language offers a one of the best set of inbuilt function and libraries (such as ggplot2, leaflet, lattice) for creating data stories and visualisation." }, { "code": null, "e": 9617, "s": 9407, "text": "Now, let’s create a simple line plot using ggplot2 in RStudio, to do that we need to install the ggplot2 package, you will find the console in the left corner. Run the command install.packages(“package_name”)." }, { "code": null, "e": 9647, "s": 9617, "text": "> install.packages(\"ggplot2\")" }, { "code": null, "e": 9715, "s": 9647, "text": "We will now import a inbuilt dataset(mpg), and plot a simple graph." }, { "code": null, "e": 9808, "s": 9715, "text": "About mpg dataset: It’s a fuel economy data from 1999 and 2008 for 38 popular models of car." }, { "code": null, "e": 9920, "s": 9808, "text": "A data frame with 234 rows and 11 variablesdispl — engine displacement, in litreshwy — highway miles per gallon" }, { "code": null, "e": 9964, "s": 9920, "text": "A data frame with 234 rows and 11 variables" }, { "code": null, "e": 10003, "s": 9964, "text": "displ — engine displacement, in litres" }, { "code": null, "e": 10034, "s": 10003, "text": "hwy — highway miles per gallon" }, { "code": null, "e": 10054, "s": 10034, "text": "Thanks for reading!" }, { "code": null, "e": 10109, "s": 10054, "text": "Code for this article can be found here by AaqilShaik." } ]
Fetch specific field values in MongoDB
To fetch specific field values, use inoperator.Thein selects the documents where the value of a field equals any value in the specified array. Let us first create a collection with documents − > db.indexesDemo.createIndex({"StudentFirstName":1}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.indexesDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5e06de4d25ddae1f53b621dd") } > db.indexesDemo.insertOne({"StudentFirstName":"Chris","StudentLastName":"Brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5e06de5825ddae1f53b621de") } > db.indexesDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Doe"}); { "acknowledged" : true, "insertedId" : ObjectId("5e06de6725ddae1f53b621df") } > db.indexesDemo.insertOne({"StudentFirstName":"David","StudentLastName":"Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5e06de7225ddae1f53b621e0") } Following is the query to display all documents from a collection with the help of find() method − > db.indexesDemo.find(); This will produce the following output − { "_id" : ObjectId("5e06de4d25ddae1f53b621dd"), "StudentFirstName" : "John", "StudentLastName" : "Smith" } { "_id" : ObjectId("5e06de5825ddae1f53b621de"), "StudentFirstName" : "Chris", "StudentLastName" : "Brown" } { "_id" : ObjectId("5e06de6725ddae1f53b621df"), "StudentFirstName" : "John", "StudentLastName" : "Doe" } { "_id" : ObjectId("5e06de7225ddae1f53b621e0"), "StudentFirstName" : "David", "StudentLastName" : "Miller" } Following is the query to indexes − > db.indexesDemo.find( ... { StudentFirstName: { $in: [ "John", "David" ] } }, ... { _id: 0, StudentLastName: 0 } ... ); This will produce the following output − { "StudentFirstName" : "David" } { "StudentFirstName" : "John" } { "StudentFirstName" : "John" }
[ { "code": null, "e": 1205, "s": 1062, "text": "To fetch specific field values, use inoperator.Thein selects the documents where the value of a field equals any value in the specified array." }, { "code": null, "e": 1255, "s": 1205, "text": "Let us first create a collection with documents −" }, { "code": null, "e": 2095, "s": 1255, "text": "> db.indexesDemo.createIndex({\"StudentFirstName\":1});\n{\n \"createdCollectionAutomatically\" : true,\n \"numIndexesBefore\" : 1,\n \"numIndexesAfter\" : 2,\n \"ok\" : 1\n}\n> db.indexesDemo.insertOne({\"StudentFirstName\":\"John\",\"StudentLastName\":\"Smith\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e06de4d25ddae1f53b621dd\")\n}\n> db.indexesDemo.insertOne({\"StudentFirstName\":\"Chris\",\"StudentLastName\":\"Brown\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e06de5825ddae1f53b621de\")\n}\n> db.indexesDemo.insertOne({\"StudentFirstName\":\"John\",\"StudentLastName\":\"Doe\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e06de6725ddae1f53b621df\")\n}\n> db.indexesDemo.insertOne({\"StudentFirstName\":\"David\",\"StudentLastName\":\"Miller\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e06de7225ddae1f53b621e0\")\n}" }, { "code": null, "e": 2194, "s": 2095, "text": "Following is the query to display all documents from a collection with the help of find() method −" }, { "code": null, "e": 2219, "s": 2194, "text": "> db.indexesDemo.find();" }, { "code": null, "e": 2260, "s": 2219, "text": "This will produce the following output −" }, { "code": null, "e": 2689, "s": 2260, "text": "{ \"_id\" : ObjectId(\"5e06de4d25ddae1f53b621dd\"), \"StudentFirstName\" : \"John\", \"StudentLastName\" : \"Smith\" }\n{ \"_id\" : ObjectId(\"5e06de5825ddae1f53b621de\"), \"StudentFirstName\" : \"Chris\", \"StudentLastName\" : \"Brown\" }\n{ \"_id\" : ObjectId(\"5e06de6725ddae1f53b621df\"), \"StudentFirstName\" : \"John\", \"StudentLastName\" : \"Doe\" }\n{ \"_id\" : ObjectId(\"5e06de7225ddae1f53b621e0\"), \"StudentFirstName\" : \"David\", \"StudentLastName\" : \"Miller\" }" }, { "code": null, "e": 2725, "s": 2689, "text": "Following is the query to indexes −" }, { "code": null, "e": 2846, "s": 2725, "text": "> db.indexesDemo.find(\n... { StudentFirstName: { $in: [ \"John\", \"David\" ] } },\n... { _id: 0, StudentLastName: 0 }\n... );" }, { "code": null, "e": 2887, "s": 2846, "text": "This will produce the following output −" }, { "code": null, "e": 2984, "s": 2887, "text": "{ \"StudentFirstName\" : \"David\" }\n{ \"StudentFirstName\" : \"John\" }\n{ \"StudentFirstName\" : \"John\" }" } ]
Count strings having sum of ASCII values of characters equal to a Prime or Armstrong Number - GeeksforGeeks
05 Jul, 2021 Given an array arr[] of size N containing strings, the task is to count the number of strings having sum of ASCII values of characters equal to an Armstrong Number number or a Prime Number. Examples: Input: arr[] = {“hello”, “nace”}Output:Number of Armstrong Strings are: 1Number of Prime Strings are: 0Explanation: Sum of ASCII values of characters of each string is: {532, 407}, out of which 407 is an Armstrong Number, and none of them is a Prime Number.Hence, the armstrong valued string is “nace”. Input: arr[] = {“geeksforgeeks”, “a”, “computer”, “science”, “portal”, “for”, “geeks”}Output:Number of Armstrong Strings are: 0Number of Prime Strings are: 2 Explanation: Sum of ASCII values of characters of each string is: {1381, 97, 879, 730, 658, 327, 527}, out of which 1381 and 97 are Prime Numbers, and none of them is an Armstrong Number.Hence, prime valued strings are “geeksforgeeks” and “a”. Approach: This problem can be solved by calculating the ASCII value of each string. Follow the steps below to solve this problem: Initialize two variables, countPrime and countArmstrong as 0, to store the count of Prime and Armstrong valued strings. Iterate over the range of indices [0, N – 1] using a variable, say i and perform the following steps: Store the sum of ASCII values of characters of the current string arr[i] in a variable, say val.If the number val is an Armstrong Number, increment countArmstrong by 1.If the number val is a Prime Number, increment countPrime by 1. Store the sum of ASCII values of characters of the current string arr[i] in a variable, say val. If the number val is an Armstrong Number, increment countArmstrong by 1. If the number val is a Prime Number, increment countPrime by 1. Print the values of countPrime and countArmstrong as the result. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if a// number is prime numberbool isPrime(int num){ // Define a flag variable bool flag = false; if (num > 1) { // Check for factors of num for(int i = 2; i < num; i++) { // If factor is found, // set flag to True and // break out of loop if ((num % i) == 0) { flag = true; break; } } } // Check if flag is True if (flag) return false; else return true;} // Function to calculate// order of the number xint order(int x){ int n = 0; while (x != 0) { n = n + 1; x = x / 10; } return n;} // Function to check whether the given// number is Armstrong number or notbool isArmstrong(int x){ int n = order(x); int temp = x; int sum1 = 0; while (temp != 0) { int r = temp % 10; sum1 = sum1 + pow(r, n); temp = temp / 10; } // If the condition satisfies return (sum1 == x);} // Function to count// Armstrong valued stringsint count_armstrong(vector<string> li){ // Stores the count of // Armstrong valued strings int c = 0; // Iterate over the list for(string ele : li) { // Store the value // of the string int val = 0; // Find value of the string for(char che:ele) val += che; // Check if it an Armstrong number if (isArmstrong(val)) c += 1; } return c;} // Function to count// prime valued stringsint count_prime(vector<string> li){ // Store the count of // prime valued strings int c = 0; // Iterate over the list for(string ele:li) { // Store the value // of the string int val = 0; // Find value of the string for(char che : ele) val += che; // Check if it // is a Prime Number if (isPrime(val)) c += 1; } return c;} // Driver codeint main(){ vector<string> arr = { "geeksforgeeks", "a", "computer", "science", "portal", "for", "geeks"}; // Function Call cout << "Number of Armstrong Strings are: " << count_armstrong(arr) << endl; cout << "Number of Prime Strings are: " << count_prime(arr) << endl;} // This code is contributed by mohit kumar 29 // Java program for the above approachimport java.io.*; class GFG { // Function to check if a // number is prime number static boolean isPrime(int num) { // Define a flag variable boolean flag = false; if (num > 1) { // Check for factors of num for (int i = 2; i < num; i++) { // If factor is found, // set flag to True and // break out of loop if ((num % i) == 0) { flag = true; break; } } } // Check if flag is True if (flag) return false; else return true; } // Function to calculate // order of the number x static int order(int x) { int n = 0; while (x != 0) { n = n + 1; x = x / 10; } return n; } // Function to check whether the given // number is Armstrong number or not static boolean isArmstrong(int x) { int n = order(x); int temp = x; int sum1 = 0; while (temp != 0) { int r = temp % 10; sum1 = sum1 + (int)(Math.pow(r, n)); temp = temp / 10; } // If the condition satisfies return (sum1 == x); } // Function to count // Armstrong valued strings static int count_armstrong(String[] li) { // Stores the count of // Armstrong valued strings int c = 0; // Iterate over the list for(String ele : li) { // Store the value // of the string int val = 0; // Find value of the string for(char che : ele.toCharArray()) val += che; // Check if it an Armstrong number if (isArmstrong(val)) c += 1; } return c; } // Function to count // prime valued strings static int count_prime(String[] li) { // Store the count of // prime valued strings int c = 0; // Iterate over the list for(String ele : li) { // Store the value // of the string int val = 0; // Find value of the string for(char che : ele.toCharArray()) val += che; // Check if it // is a Prime Number if (isPrime(val)) c += 1; } return c; } // Driver code public static void main (String[] args) { String[] arr = { "geeksforgeeks", "a", "computer", "science", "portal", "for", "geeks" }; // Function Call System.out.println( "Number of Armstrong Strings are: " + count_armstrong(arr)); System.out.println("Number of Prime Strings are: " + count_prime(arr)); }} // This code is contributed by patel2127. # Python program for the above approach # Function to check if a# number is prime numberdef isPrime(num): # Define a flag variable flag = False if num > 1: # Check for factors of num for i in range(2, num): # If factor is found, # set flag to True and # break out of loop if (num % i) == 0: flag = True break # Check if flag is True if flag: return False else: return True # Function to calculate# order of the number xdef order(x): n = 0 while (x != 0): n = n + 1 x = x // 10 return n # Function to check whether the given# number is Armstrong number or notdef isArmstrong(x): n = order(x) temp = x sum1 = 0 while (temp != 0): r = temp % 10 sum1 = sum1 + r**n temp = temp // 10 # If the condition satisfies return (sum1 == x) # Function to count# Armstrong valued stringsdef count_armstrong(li): # Stores the count of # Armstrong valued strings c = 0 # Iterate over the list for ele in li: # Store the value # of the string val = 0 # Find value of the string for che in ele: val += ord(che) # Check if it an Armstrong number if isArmstrong(val): c += 1 return c # Function to count# prime valued stringsdef count_prime(li): # Store the count of # prime valued strings c = 0 # Iterate over the list for ele in li: # Store the value # of the string val = 0 # Find value of the string for che in ele: val += ord(che) # Check if it # is a Prime Number if isPrime(val): c += 1 return c # Driver codearr = ["geeksforgeeks", "a", "computer", "science", "portal", "for", "geeks"] # Function Callprint("Number of Armstrong Strings are:", count_armstrong(arr))print("Number of Prime Strings are:", count_prime(arr)) // C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to check if a // number is prime number static bool isPrime(int num) { // Define a flag variable bool flag = false; if (num > 1) { // Check for factors of num for (int i = 2; i < num; i++) { // If factor is found, // set flag to True and // break out of loop if ((num % i) == 0) { flag = true; break; } } } // Check if flag is True if (flag) return false; else return true; } // Function to calculate // order of the number x static int order(int x) { int n = 0; while (x != 0) { n = n + 1; x = x / 10; } return n; } // Function to check whether the given // number is Armstrong number or not static bool isArmstrong(int x) { int n = order(x); int temp = x; int sum1 = 0; while (temp != 0) { int r = temp % 10; sum1 = sum1 + (int)(Math.Pow(r, n)); temp = temp / 10; } // If the condition satisfies return (sum1 == x); } // Function to count // Armstrong valued strings static int count_armstrong(string[] li) { // Stores the count of // Armstrong valued strings int c = 0; // Iterate over the list foreach(string ele in li) { // Store the value // of the string int val = 0; // Find value of the string foreach(char che in ele) val += che; // Check if it an Armstrong number if (isArmstrong(val)) c += 1; } return c; } // Function to count // prime valued strings static int count_prime(string[] li) { // Store the count of // prime valued strings int c = 0; // Iterate over the list foreach(string ele in li) { // Store the value // of the string int val = 0; // Find value of the string foreach(char che in ele) val += che; // Check if it // is a Prime Number if (isPrime(val)) c += 1; } return c; } // Driver code public static void Main() { string[] arr = { "geeksforgeeks", "a", "computer", "science", "portal", "for", "geeks" }; // Function Call Console.WriteLine( "Number of Armstrong Strings are: " + count_armstrong(arr)); Console.WriteLine("Number of Prime Strings are: " + count_prime(arr)); }} // This code is contributed by ukasp. <script> // JavaScript program for the above approach // Function to check if a// number is prime numberfunction isPrime(num) { // Define a flag variable let flag = false; if (num > 1) { // Check for factors of num for (let i = 2; i < num; i++) { // If factor is found, // set flag to True and // break out of loop if ((num % i) == 0) { flag = true; break; } } } // Check if flag is True if (flag) return false; else return true;} // Function to calculate// order of the number xfunction order(x) { let n = 0; while (x != 0) { n = n + 1; x = x / 10; } return n;} // Function to check whether the given// number is Armstrong number or notfunction isArmstrong(x) { let n = order(x); let temp = x; let sum1 = 0; while (temp != 0) { let r = temp % 10; sum1 = sum1 + Math.pow(r, n); temp = temp / 10; } // If the condition satisfies return (sum1 == x);} // Function to count// Armstrong valued stringsfunction count_armstrong(li) { // Stores the count of // Armstrong valued strings let c = 0; // Iterate over the list for (let ele of li) { // Store the value // of the string let val = 0; // Find value of the string for (let che of ele) val += che.charCodeAt(0); // Check if it an Armstrong number if (isArmstrong(val)) c += 1; } return c;} // Function to count// prime valued stringsfunction count_prime(li) { // Store the count of // prime valued strings let c = 0; // Iterate over the list for (let ele of li) { // Store the value // of the string let val = 0; // Find value of the string for (let che of ele) val += che.charCodeAt(0); // Check if it // is a Prime Number if (isPrime(val)) c += 1; } return c;} // Driver code let arr = ["geeksforgeeks", "a", "computer", "science", "portal", "for", "geeks"]; // Function Calldocument.write("Number of Armstrong Strings are: " + count_armstrong(arr) + "<br>");document.write("Number of Prime Strings are: " + count_prime(arr) + "<br>"); // This code is contributed by gfgking </script> Number of Armstrong Strings are: 0 Number of Prime Strings are: 2 Time Complexity: O(N*M), where M is the length of the longest string in the array arr[]Auxiliary Space: O(1) mohit kumar 29 ukasp gfgking patel2127 ASCII Numbers Prime Number Arrays Mathematical Strings Arrays Strings Mathematical Prime Number Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 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": 26067, "s": 26039, "text": "\n05 Jul, 2021" }, { "code": null, "e": 26257, "s": 26067, "text": "Given an array arr[] of size N containing strings, the task is to count the number of strings having sum of ASCII values of characters equal to an Armstrong Number number or a Prime Number." }, { "code": null, "e": 26267, "s": 26257, "text": "Examples:" }, { "code": null, "e": 26570, "s": 26267, "text": "Input: arr[] = {“hello”, “nace”}Output:Number of Armstrong Strings are: 1Number of Prime Strings are: 0Explanation: Sum of ASCII values of characters of each string is: {532, 407}, out of which 407 is an Armstrong Number, and none of them is a Prime Number.Hence, the armstrong valued string is “nace”." }, { "code": null, "e": 26972, "s": 26570, "text": "Input: arr[] = {“geeksforgeeks”, “a”, “computer”, “science”, “portal”, “for”, “geeks”}Output:Number of Armstrong Strings are: 0Number of Prime Strings are: 2 Explanation: Sum of ASCII values of characters of each string is: {1381, 97, 879, 730, 658, 327, 527}, out of which 1381 and 97 are Prime Numbers, and none of them is an Armstrong Number.Hence, prime valued strings are “geeksforgeeks” and “a”." }, { "code": null, "e": 27102, "s": 26972, "text": "Approach: This problem can be solved by calculating the ASCII value of each string. Follow the steps below to solve this problem:" }, { "code": null, "e": 27222, "s": 27102, "text": "Initialize two variables, countPrime and countArmstrong as 0, to store the count of Prime and Armstrong valued strings." }, { "code": null, "e": 27556, "s": 27222, "text": "Iterate over the range of indices [0, N – 1] using a variable, say i and perform the following steps: Store the sum of ASCII values of characters of the current string arr[i] in a variable, say val.If the number val is an Armstrong Number, increment countArmstrong by 1.If the number val is a Prime Number, increment countPrime by 1." }, { "code": null, "e": 27653, "s": 27556, "text": "Store the sum of ASCII values of characters of the current string arr[i] in a variable, say val." }, { "code": null, "e": 27726, "s": 27653, "text": "If the number val is an Armstrong Number, increment countArmstrong by 1." }, { "code": null, "e": 27790, "s": 27726, "text": "If the number val is a Prime Number, increment countPrime by 1." }, { "code": null, "e": 27855, "s": 27790, "text": "Print the values of countPrime and countArmstrong as the result." }, { "code": null, "e": 27906, "s": 27855, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27910, "s": 27906, "text": "C++" }, { "code": null, "e": 27915, "s": 27910, "text": "Java" }, { "code": null, "e": 27923, "s": 27915, "text": "Python3" }, { "code": null, "e": 27926, "s": 27923, "text": "C#" }, { "code": null, "e": 27937, "s": 27926, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if a// number is prime numberbool isPrime(int num){ // Define a flag variable bool flag = false; if (num > 1) { // Check for factors of num for(int i = 2; i < num; i++) { // If factor is found, // set flag to True and // break out of loop if ((num % i) == 0) { flag = true; break; } } } // Check if flag is True if (flag) return false; else return true;} // Function to calculate// order of the number xint order(int x){ int n = 0; while (x != 0) { n = n + 1; x = x / 10; } return n;} // Function to check whether the given// number is Armstrong number or notbool isArmstrong(int x){ int n = order(x); int temp = x; int sum1 = 0; while (temp != 0) { int r = temp % 10; sum1 = sum1 + pow(r, n); temp = temp / 10; } // If the condition satisfies return (sum1 == x);} // Function to count// Armstrong valued stringsint count_armstrong(vector<string> li){ // Stores the count of // Armstrong valued strings int c = 0; // Iterate over the list for(string ele : li) { // Store the value // of the string int val = 0; // Find value of the string for(char che:ele) val += che; // Check if it an Armstrong number if (isArmstrong(val)) c += 1; } return c;} // Function to count// prime valued stringsint count_prime(vector<string> li){ // Store the count of // prime valued strings int c = 0; // Iterate over the list for(string ele:li) { // Store the value // of the string int val = 0; // Find value of the string for(char che : ele) val += che; // Check if it // is a Prime Number if (isPrime(val)) c += 1; } return c;} // Driver codeint main(){ vector<string> arr = { \"geeksforgeeks\", \"a\", \"computer\", \"science\", \"portal\", \"for\", \"geeks\"}; // Function Call cout << \"Number of Armstrong Strings are: \" << count_armstrong(arr) << endl; cout << \"Number of Prime Strings are: \" << count_prime(arr) << endl;} // This code is contributed by mohit kumar 29", "e": 30445, "s": 27937, "text": null }, { "code": "// Java program for the above approachimport java.io.*; class GFG { // Function to check if a // number is prime number static boolean isPrime(int num) { // Define a flag variable boolean flag = false; if (num > 1) { // Check for factors of num for (int i = 2; i < num; i++) { // If factor is found, // set flag to True and // break out of loop if ((num % i) == 0) { flag = true; break; } } } // Check if flag is True if (flag) return false; else return true; } // Function to calculate // order of the number x static int order(int x) { int n = 0; while (x != 0) { n = n + 1; x = x / 10; } return n; } // Function to check whether the given // number is Armstrong number or not static boolean isArmstrong(int x) { int n = order(x); int temp = x; int sum1 = 0; while (temp != 0) { int r = temp % 10; sum1 = sum1 + (int)(Math.pow(r, n)); temp = temp / 10; } // If the condition satisfies return (sum1 == x); } // Function to count // Armstrong valued strings static int count_armstrong(String[] li) { // Stores the count of // Armstrong valued strings int c = 0; // Iterate over the list for(String ele : li) { // Store the value // of the string int val = 0; // Find value of the string for(char che : ele.toCharArray()) val += che; // Check if it an Armstrong number if (isArmstrong(val)) c += 1; } return c; } // Function to count // prime valued strings static int count_prime(String[] li) { // Store the count of // prime valued strings int c = 0; // Iterate over the list for(String ele : li) { // Store the value // of the string int val = 0; // Find value of the string for(char che : ele.toCharArray()) val += che; // Check if it // is a Prime Number if (isPrime(val)) c += 1; } return c; } // Driver code public static void main (String[] args) { String[] arr = { \"geeksforgeeks\", \"a\", \"computer\", \"science\", \"portal\", \"for\", \"geeks\" }; // Function Call System.out.println( \"Number of Armstrong Strings are: \" + count_armstrong(arr)); System.out.println(\"Number of Prime Strings are: \" + count_prime(arr)); }} // This code is contributed by patel2127.", "e": 33429, "s": 30445, "text": null }, { "code": "# Python program for the above approach # Function to check if a# number is prime numberdef isPrime(num): # Define a flag variable flag = False if num > 1: # Check for factors of num for i in range(2, num): # If factor is found, # set flag to True and # break out of loop if (num % i) == 0: flag = True break # Check if flag is True if flag: return False else: return True # Function to calculate# order of the number xdef order(x): n = 0 while (x != 0): n = n + 1 x = x // 10 return n # Function to check whether the given# number is Armstrong number or notdef isArmstrong(x): n = order(x) temp = x sum1 = 0 while (temp != 0): r = temp % 10 sum1 = sum1 + r**n temp = temp // 10 # If the condition satisfies return (sum1 == x) # Function to count# Armstrong valued stringsdef count_armstrong(li): # Stores the count of # Armstrong valued strings c = 0 # Iterate over the list for ele in li: # Store the value # of the string val = 0 # Find value of the string for che in ele: val += ord(che) # Check if it an Armstrong number if isArmstrong(val): c += 1 return c # Function to count# prime valued stringsdef count_prime(li): # Store the count of # prime valued strings c = 0 # Iterate over the list for ele in li: # Store the value # of the string val = 0 # Find value of the string for che in ele: val += ord(che) # Check if it # is a Prime Number if isPrime(val): c += 1 return c # Driver codearr = [\"geeksforgeeks\", \"a\", \"computer\", \"science\", \"portal\", \"for\", \"geeks\"] # Function Callprint(\"Number of Armstrong Strings are:\", count_armstrong(arr))print(\"Number of Prime Strings are:\", count_prime(arr))", "e": 35482, "s": 33429, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to check if a // number is prime number static bool isPrime(int num) { // Define a flag variable bool flag = false; if (num > 1) { // Check for factors of num for (int i = 2; i < num; i++) { // If factor is found, // set flag to True and // break out of loop if ((num % i) == 0) { flag = true; break; } } } // Check if flag is True if (flag) return false; else return true; } // Function to calculate // order of the number x static int order(int x) { int n = 0; while (x != 0) { n = n + 1; x = x / 10; } return n; } // Function to check whether the given // number is Armstrong number or not static bool isArmstrong(int x) { int n = order(x); int temp = x; int sum1 = 0; while (temp != 0) { int r = temp % 10; sum1 = sum1 + (int)(Math.Pow(r, n)); temp = temp / 10; } // If the condition satisfies return (sum1 == x); } // Function to count // Armstrong valued strings static int count_armstrong(string[] li) { // Stores the count of // Armstrong valued strings int c = 0; // Iterate over the list foreach(string ele in li) { // Store the value // of the string int val = 0; // Find value of the string foreach(char che in ele) val += che; // Check if it an Armstrong number if (isArmstrong(val)) c += 1; } return c; } // Function to count // prime valued strings static int count_prime(string[] li) { // Store the count of // prime valued strings int c = 0; // Iterate over the list foreach(string ele in li) { // Store the value // of the string int val = 0; // Find value of the string foreach(char che in ele) val += che; // Check if it // is a Prime Number if (isPrime(val)) c += 1; } return c; } // Driver code public static void Main() { string[] arr = { \"geeksforgeeks\", \"a\", \"computer\", \"science\", \"portal\", \"for\", \"geeks\" }; // Function Call Console.WriteLine( \"Number of Armstrong Strings are: \" + count_armstrong(arr)); Console.WriteLine(\"Number of Prime Strings are: \" + count_prime(arr)); }} // This code is contributed by ukasp.", "e": 38427, "s": 35482, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to check if a// number is prime numberfunction isPrime(num) { // Define a flag variable let flag = false; if (num > 1) { // Check for factors of num for (let i = 2; i < num; i++) { // If factor is found, // set flag to True and // break out of loop if ((num % i) == 0) { flag = true; break; } } } // Check if flag is True if (flag) return false; else return true;} // Function to calculate// order of the number xfunction order(x) { let n = 0; while (x != 0) { n = n + 1; x = x / 10; } return n;} // Function to check whether the given// number is Armstrong number or notfunction isArmstrong(x) { let n = order(x); let temp = x; let sum1 = 0; while (temp != 0) { let r = temp % 10; sum1 = sum1 + Math.pow(r, n); temp = temp / 10; } // If the condition satisfies return (sum1 == x);} // Function to count// Armstrong valued stringsfunction count_armstrong(li) { // Stores the count of // Armstrong valued strings let c = 0; // Iterate over the list for (let ele of li) { // Store the value // of the string let val = 0; // Find value of the string for (let che of ele) val += che.charCodeAt(0); // Check if it an Armstrong number if (isArmstrong(val)) c += 1; } return c;} // Function to count// prime valued stringsfunction count_prime(li) { // Store the count of // prime valued strings let c = 0; // Iterate over the list for (let ele of li) { // Store the value // of the string let val = 0; // Find value of the string for (let che of ele) val += che.charCodeAt(0); // Check if it // is a Prime Number if (isPrime(val)) c += 1; } return c;} // Driver code let arr = [\"geeksforgeeks\", \"a\", \"computer\", \"science\", \"portal\", \"for\", \"geeks\"]; // Function Calldocument.write(\"Number of Armstrong Strings are: \" + count_armstrong(arr) + \"<br>\");document.write(\"Number of Prime Strings are: \" + count_prime(arr) + \"<br>\"); // This code is contributed by gfgking </script>", "e": 40789, "s": 38427, "text": null }, { "code": null, "e": 40855, "s": 40789, "text": "Number of Armstrong Strings are: 0\nNumber of Prime Strings are: 2" }, { "code": null, "e": 40964, "s": 40855, "text": "Time Complexity: O(N*M), where M is the length of the longest string in the array arr[]Auxiliary Space: O(1)" }, { "code": null, "e": 40979, "s": 40964, "text": "mohit kumar 29" }, { "code": null, "e": 40985, "s": 40979, "text": "ukasp" }, { "code": null, "e": 40993, "s": 40985, "text": "gfgking" }, { "code": null, "e": 41003, "s": 40993, "text": "patel2127" }, { "code": null, "e": 41009, "s": 41003, "text": "ASCII" }, { "code": null, "e": 41017, "s": 41009, "text": "Numbers" }, { "code": null, "e": 41030, "s": 41017, "text": "Prime Number" }, { "code": null, "e": 41037, "s": 41030, "text": "Arrays" }, { "code": null, "e": 41050, "s": 41037, "text": "Mathematical" }, { "code": null, "e": 41058, "s": 41050, "text": "Strings" }, { "code": null, "e": 41065, "s": 41058, "text": "Arrays" }, { "code": null, "e": 41073, "s": 41065, "text": "Strings" }, { "code": null, "e": 41086, "s": 41073, "text": "Mathematical" }, { "code": null, "e": 41099, "s": 41086, "text": "Prime Number" }, { "code": null, "e": 41107, "s": 41099, "text": "Numbers" }, { "code": null, "e": 41205, "s": 41107, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41236, "s": 41205, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 41261, "s": 41236, "text": "Window Sliding Technique" }, { "code": null, "e": 41299, "s": 41261, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 41320, "s": 41299, "text": "Next Greater Element" }, { "code": null, "e": 41378, "s": 41320, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 41408, "s": 41378, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 41468, "s": 41408, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 41483, "s": 41468, "text": "C++ Data Types" }, { "code": null, "e": 41526, "s": 41483, "text": "Set in C++ Standard Template Library (STL)" } ]
Python - Difference in keys of two dictionaries
Two python dictionaries may contain some common keys between them. In this article we will find how to get the difference in the keys present in two given dictionaries. Here we take two dictionaries and apply set function to them. Then we subtract the two sets to get the difference. We do it both ways, by subtracting second dictionary from first and next subtracting first dictionary form second. Those keys which are not common are listed in the result set. Live Demo dictA = {'1': 'Mon', '2': 'Tue', '3': 'Wed'} print("1st Distionary:\n",dictA) dictB = {'3': 'Wed', '4': 'Thu','5':'Fri'} print("1st Distionary:\n",dictB) res1 = set(dictA) - set(dictB) res2 = set(dictB) - set(dictA) print("\nThe difference in keys between both the dictionaries:") print(res1,res2) Running the above code gives us the following result − 1st Distionary: {'1': 'Mon', '2': 'Tue', '3': 'Wed'} 1st Distionary: {'3': 'Wed', '4': 'Thu', '5': 'Fri'} The difference in keys between both the dictionaries: {'2', '1'} {'4', '5'} In another approach we can use a for loop to iterate through the keys of one dictionary and check for its presence using the in clause in the second dictionary. Live Demo dictA = {'1': 'Mon', '2': 'Tue', '3': 'Wed'} print("1st Distionary:\n",dictA) dictB = {'3': 'Wed', '4': 'Thu','5':'Fri'} print("1st Distionary:\n",dictB) print("\nThe keys in 1st dictionary but not in the second:") for key in dictA.keys(): if not key in dictB: print(key) Running the above code gives us the following result − 1st Distionary: {'1': 'Mon', '2': 'Tue', '3': 'Wed'} 1st Distionary: {'3': 'Wed', '4': 'Thu', '5': 'Fri'} The keys in 1st dictionary but not in the second: 1 2
[ { "code": null, "e": 1231, "s": 1062, "text": "Two python dictionaries may contain some common keys between them. In this article we will find how to get the difference in the keys present in two given dictionaries." }, { "code": null, "e": 1523, "s": 1231, "text": "Here we take two dictionaries and apply set function to them. Then we subtract the two sets to get the difference. We do it both ways, by subtracting second dictionary from first and next subtracting first dictionary form second. Those keys which are not common are listed in the result set." }, { "code": null, "e": 1534, "s": 1523, "text": " Live Demo" }, { "code": null, "e": 1833, "s": 1534, "text": "dictA = {'1': 'Mon', '2': 'Tue', '3': 'Wed'}\nprint(\"1st Distionary:\\n\",dictA)\ndictB = {'3': 'Wed', '4': 'Thu','5':'Fri'}\nprint(\"1st Distionary:\\n\",dictB)\n\nres1 = set(dictA) - set(dictB)\nres2 = set(dictB) - set(dictA)\nprint(\"\\nThe difference in keys between both the dictionaries:\")\nprint(res1,res2)" }, { "code": null, "e": 1888, "s": 1833, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2070, "s": 1888, "text": "1st Distionary:\n{'1': 'Mon', '2': 'Tue', '3': 'Wed'}\n1st Distionary:\n{'3': 'Wed', '4': 'Thu', '5': 'Fri'}\nThe difference in keys between both the dictionaries:\n{'2', '1'} {'4', '5'}" }, { "code": null, "e": 2231, "s": 2070, "text": "In another approach we can use a for loop to iterate through the keys of one dictionary and check for its presence using the in clause in the second dictionary." }, { "code": null, "e": 2242, "s": 2231, "text": " Live Demo" }, { "code": null, "e": 2524, "s": 2242, "text": "dictA = {'1': 'Mon', '2': 'Tue', '3': 'Wed'}\nprint(\"1st Distionary:\\n\",dictA)\ndictB = {'3': 'Wed', '4': 'Thu','5':'Fri'}\nprint(\"1st Distionary:\\n\",dictB)\n\nprint(\"\\nThe keys in 1st dictionary but not in the second:\")\nfor key in dictA.keys():\n if not key in dictB:\n print(key)" }, { "code": null, "e": 2579, "s": 2524, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2740, "s": 2579, "text": "1st Distionary:\n{'1': 'Mon', '2': 'Tue', '3': 'Wed'}\n1st Distionary:\n{'3': 'Wed', '4': 'Thu', '5': 'Fri'}\n\nThe keys in 1st dictionary but not in the second:\n1\n2" } ]
Establishing JDBC Connection in Java - GeeksforGeeks
22 Apr, 2022 Before establishing a connection between the front end i.e your Java Program and the back end i.e the database we should learn what precisely a JDBC is and why it came to existence. Now let us discuss what exactly JDBC stands for and will ease out with the help of real-life illustration to get it working. What is JDBC? JDBC is an acronym for Java Database Connectivity. It’s an advancement for ODBC ( Open Database Connectivity ). JDBC is a standard API specification developed in order to move data from frontend to backend. This API consists of classes and interfaces written in Java. It basically acts as an interface (not the one we use in Java) or channel between your Java program and databases i.e it establishes a link between the two so that a programmer could send data from Java code and store it in the database for future use. Illustration: Working of JDBC co-relating with real-time Why JDBC Came into Existence? As previously told JDBC is an advancement for ODBC, ODBC being platform-dependent had a lot of drawbacks. ODBC API was written in C, C++, Python, Core Java and as we know above languages (except Java and some part of Python )are platform dependent. Therefore to remove dependence, JDBC was developed by a database vendor which consisted of classes and interfaces written in Java. Steps For Connectivity Between Java Program and Database Import the PackagesLoad the drivers using the forName() method Register the drivers using DriverManager Establish a connection using the Connection class objectCreate a statementExecute the queryCLose the connections Import the Packages Load the drivers using the forName() method Register the drivers using DriverManager Establish a connection using the Connection class object Create a statement Execute the query CLose the connections Let us discuss these steps in brief before implementing by writing suitable code to illustrate connectivity steps for JDBC/ Step 1: Import the Packages Step 2: Loading the drivers In order to begin with, you first need to load the driver or register it before using it in the program. Registration is to be done once in your program. You can register a driver in one of two ways mentioned below as follows: 2-A Class.forName() Here we load the driver’s class file into memory at the runtime. No need of using new or create objects. The following example uses Class.forName() to load the Oracle driver as shown below as follows: Class.forName(“oracle.jdbc.driver.OracleDriver”); 2-B DriverManager.registerDriver() DriverManager is a Java inbuilt class with a static member register. Here we call the constructor of the driver class at compile time. The following example uses DriverManager.registerDriver()to register the Oracle driver as shown below: DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()) Step 4: Establish a connection using the Connection class object After loading the driver, establish connections via as shown below as follows: Connection con = DriverManager.getConnection(url,user,password) user: Username from which your SQL command prompt can be accessed. password: password from which the SQL command prompt can be accessed. con: It is a reference to the Connection interface. Url : Uniform Resource Locator which is created as shown below: String url = “ jdbc:oracle:thin:@localhost:1521:xe” Where oracle is the database used, thin is the driver used, @localhost is the IP Address where a database is stored, 1521 is the port number and xe is the service provider. All 3 parameters above are of String type and are to be declared by the programmer before calling the function. Use of this can be referred from the final code. Step 5: Create a statement Once a connection is established you can interact with the database. The JDBCStatement, CallableStatement, and PreparedStatement interfaces define the methods that enable you to send SQL commands and receive data from your database. Use of JDBC Statement is as follows: Statement st = con.createStatement(); Note: Here, con is a reference to Connection interface used in previous step . Step 6: Execute the query Now comes the most important part i.e executing the query. The query here is an SQL Query. Now we know we can have multiple types of queries. Some of them are as follows: The query for updating/inserting table in a database. The query for retrieving data. The executeQuery() method of the Statement interface is used to execute queries of retrieving values from the database. This method returns the object of ResultSet that can be used to get all the records of a table. The executeUpdate(sql query) method of the Statement interface is used to execute queries of updating/inserting. Pseodo Code: int m = st.executeUpdate(sql); if (m==1) System.out.println("inserted successfully : "+sql); else System.out.println("insertion failed"); Here sql is SQL query of the type String Step 7: Closing the connections So finally we have sent the data to the specified location and now we are on the verge of completing of our task. By closing the connection, objects of Statement and ResultSet will be closed automatically. The close() method of the Connection interface is used to close the connection. It is as shown below as follows: con.close(); Example: Java // Java Program to Establish Connection in JDBC // Importing databaseimport java.sql.*;// Importing required classesimport java.util.*; // Main classclass Main { // Main driver method public static void main(String a[]) { // Creating the connection using Oracle DB // Note: url syntax is standard, so do grasp String url = "jdbc:oracle:thin:@localhost:1521:xe"; // Username and password to access DB // Custom initialization String user = "system"; String pass = "12345"; // Entering the data Scanner k = new Scanner(System.in); System.out.println("enter name"); String name = k.next(); System.out.println("enter roll no"); int roll = k.nextInt(); System.out.println("enter class"); String cls = k.next(); // Inserting data using SQL query String sql = "insert into student1 values('" + name + "'," + roll + ",'" + cls + "')"; // Connection class object Connection con = null; // Try block to check for exceptions try { // Registering drivers DriverManager.registerDriver( new oracle.jdbc.OracleDriver()); // Reference to connection interface con = DriverManager.getConnection(url, user, pass); // Creating a statement Statement st = con.createStatement(); // Executing query int m = st.executeUpdate(sql); if (m == 1) System.out.println( "inserted successfully : " + sql); else System.out.println("insertion failed"); // Closing the connections con.close(); } // Catch block to handle exceptions catch (Exception ex) { // Display message when exceptions occurs System.err.println(ex); } }} Output: This article is contributed by Shreya Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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. solankimayank clintra zack_aayush JDBC Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Interfaces in Java Set in Java Collections in Java Multithreading in Java Initializing a List in Java Queue Interface In Java Inheritance in Java Constructors in Java Different ways of Reading a text file in Java Stream In Java
[ { "code": null, "e": 24188, "s": 24160, "text": "\n22 Apr, 2022" }, { "code": null, "e": 24497, "s": 24188, "text": "Before establishing a connection between the front end i.e your Java Program and the back end i.e the database we should learn what precisely a JDBC is and why it came to existence. Now let us discuss what exactly JDBC stands for and will ease out with the help of real-life illustration to get it working. " }, { "code": null, "e": 24512, "s": 24497, "text": "What is JDBC? " }, { "code": null, "e": 25033, "s": 24512, "text": "JDBC is an acronym for Java Database Connectivity. It’s an advancement for ODBC ( Open Database Connectivity ). JDBC is a standard API specification developed in order to move data from frontend to backend. This API consists of classes and interfaces written in Java. It basically acts as an interface (not the one we use in Java) or channel between your Java program and databases i.e it establishes a link between the two so that a programmer could send data from Java code and store it in the database for future use." }, { "code": null, "e": 25090, "s": 25033, "text": "Illustration: Working of JDBC co-relating with real-time" }, { "code": null, "e": 25121, "s": 25090, "text": "Why JDBC Came into Existence? " }, { "code": null, "e": 25502, "s": 25121, "text": "As previously told JDBC is an advancement for ODBC, ODBC being platform-dependent had a lot of drawbacks. ODBC API was written in C, C++, Python, Core Java and as we know above languages (except Java and some part of Python )are platform dependent. Therefore to remove dependence, JDBC was developed by a database vendor which consisted of classes and interfaces written in Java. " }, { "code": null, "e": 25559, "s": 25502, "text": "Steps For Connectivity Between Java Program and Database" }, { "code": null, "e": 25776, "s": 25559, "text": "Import the PackagesLoad the drivers using the forName() method Register the drivers using DriverManager Establish a connection using the Connection class objectCreate a statementExecute the queryCLose the connections" }, { "code": null, "e": 25796, "s": 25776, "text": "Import the Packages" }, { "code": null, "e": 25841, "s": 25796, "text": "Load the drivers using the forName() method " }, { "code": null, "e": 25883, "s": 25841, "text": "Register the drivers using DriverManager " }, { "code": null, "e": 25940, "s": 25883, "text": "Establish a connection using the Connection class object" }, { "code": null, "e": 25959, "s": 25940, "text": "Create a statement" }, { "code": null, "e": 25977, "s": 25959, "text": "Execute the query" }, { "code": null, "e": 25999, "s": 25977, "text": "CLose the connections" }, { "code": null, "e": 26123, "s": 25999, "text": "Let us discuss these steps in brief before implementing by writing suitable code to illustrate connectivity steps for JDBC/" }, { "code": null, "e": 26151, "s": 26123, "text": "Step 1: Import the Packages" }, { "code": null, "e": 26180, "s": 26151, "text": "Step 2: Loading the drivers " }, { "code": null, "e": 26407, "s": 26180, "text": "In order to begin with, you first need to load the driver or register it before using it in the program. Registration is to be done once in your program. You can register a driver in one of two ways mentioned below as follows:" }, { "code": null, "e": 26427, "s": 26407, "text": "2-A Class.forName()" }, { "code": null, "e": 26628, "s": 26427, "text": "Here we load the driver’s class file into memory at the runtime. No need of using new or create objects. The following example uses Class.forName() to load the Oracle driver as shown below as follows:" }, { "code": null, "e": 26678, "s": 26628, "text": "Class.forName(“oracle.jdbc.driver.OracleDriver”);" }, { "code": null, "e": 26713, "s": 26678, "text": "2-B DriverManager.registerDriver()" }, { "code": null, "e": 26952, "s": 26713, "text": "DriverManager is a Java inbuilt class with a static member register. Here we call the constructor of the driver class at compile time. The following example uses DriverManager.registerDriver()to register the Oracle driver as shown below: " }, { "code": null, "e": 27021, "s": 26952, "text": " DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())" }, { "code": null, "e": 27087, "s": 27021, "text": " Step 4: Establish a connection using the Connection class object" }, { "code": null, "e": 27167, "s": 27087, "text": "After loading the driver, establish connections via as shown below as follows: " }, { "code": null, "e": 27231, "s": 27167, "text": "Connection con = DriverManager.getConnection(url,user,password)" }, { "code": null, "e": 27298, "s": 27231, "text": "user: Username from which your SQL command prompt can be accessed." }, { "code": null, "e": 27368, "s": 27298, "text": "password: password from which the SQL command prompt can be accessed." }, { "code": null, "e": 27420, "s": 27368, "text": "con: It is a reference to the Connection interface." }, { "code": null, "e": 27484, "s": 27420, "text": "Url : Uniform Resource Locator which is created as shown below:" }, { "code": null, "e": 27536, "s": 27484, "text": "String url = “ jdbc:oracle:thin:@localhost:1521:xe”" }, { "code": null, "e": 27870, "s": 27536, "text": "Where oracle is the database used, thin is the driver used, @localhost is the IP Address where a database is stored, 1521 is the port number and xe is the service provider. All 3 parameters above are of String type and are to be declared by the programmer before calling the function. Use of this can be referred from the final code." }, { "code": null, "e": 27898, "s": 27870, "text": "Step 5: Create a statement " }, { "code": null, "e": 28169, "s": 27898, "text": "Once a connection is established you can interact with the database. The JDBCStatement, CallableStatement, and PreparedStatement interfaces define the methods that enable you to send SQL commands and receive data from your database. Use of JDBC Statement is as follows: " }, { "code": null, "e": 28207, "s": 28169, "text": "Statement st = con.createStatement();" }, { "code": null, "e": 28286, "s": 28207, "text": "Note: Here, con is a reference to Connection interface used in previous step ." }, { "code": null, "e": 28313, "s": 28286, "text": "Step 6: Execute the query " }, { "code": null, "e": 28485, "s": 28313, "text": "Now comes the most important part i.e executing the query. The query here is an SQL Query. Now we know we can have multiple types of queries. Some of them are as follows: " }, { "code": null, "e": 28539, "s": 28485, "text": "The query for updating/inserting table in a database." }, { "code": null, "e": 28570, "s": 28539, "text": "The query for retrieving data." }, { "code": null, "e": 28899, "s": 28570, "text": "The executeQuery() method of the Statement interface is used to execute queries of retrieving values from the database. This method returns the object of ResultSet that can be used to get all the records of a table. The executeUpdate(sql query) method of the Statement interface is used to execute queries of updating/inserting." }, { "code": null, "e": 28912, "s": 28899, "text": "Pseodo Code:" }, { "code": null, "e": 29058, "s": 28912, "text": "int m = st.executeUpdate(sql);\nif (m==1)\n System.out.println(\"inserted successfully : \"+sql);\nelse\n System.out.println(\"insertion failed\");" }, { "code": null, "e": 29099, "s": 29058, "text": "Here sql is SQL query of the type String" }, { "code": null, "e": 29132, "s": 29099, "text": "Step 7: Closing the connections " }, { "code": null, "e": 29451, "s": 29132, "text": "So finally we have sent the data to the specified location and now we are on the verge of completing of our task. By closing the connection, objects of Statement and ResultSet will be closed automatically. The close() method of the Connection interface is used to close the connection. It is as shown below as follows:" }, { "code": null, "e": 29465, "s": 29451, "text": " con.close();" }, { "code": null, "e": 29474, "s": 29465, "text": "Example:" }, { "code": null, "e": 29479, "s": 29474, "text": "Java" }, { "code": "// Java Program to Establish Connection in JDBC // Importing databaseimport java.sql.*;// Importing required classesimport java.util.*; // Main classclass Main { // Main driver method public static void main(String a[]) { // Creating the connection using Oracle DB // Note: url syntax is standard, so do grasp String url = \"jdbc:oracle:thin:@localhost:1521:xe\"; // Username and password to access DB // Custom initialization String user = \"system\"; String pass = \"12345\"; // Entering the data Scanner k = new Scanner(System.in); System.out.println(\"enter name\"); String name = k.next(); System.out.println(\"enter roll no\"); int roll = k.nextInt(); System.out.println(\"enter class\"); String cls = k.next(); // Inserting data using SQL query String sql = \"insert into student1 values('\" + name + \"',\" + roll + \",'\" + cls + \"')\"; // Connection class object Connection con = null; // Try block to check for exceptions try { // Registering drivers DriverManager.registerDriver( new oracle.jdbc.OracleDriver()); // Reference to connection interface con = DriverManager.getConnection(url, user, pass); // Creating a statement Statement st = con.createStatement(); // Executing query int m = st.executeUpdate(sql); if (m == 1) System.out.println( \"inserted successfully : \" + sql); else System.out.println(\"insertion failed\"); // Closing the connections con.close(); } // Catch block to handle exceptions catch (Exception ex) { // Display message when exceptions occurs System.err.println(ex); } }}", "e": 31456, "s": 29479, "text": null }, { "code": null, "e": 31464, "s": 31456, "text": "Output:" }, { "code": null, "e": 31885, "s": 31464, "text": "This article is contributed by Shreya Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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": 31899, "s": 31885, "text": "solankimayank" }, { "code": null, "e": 31907, "s": 31899, "text": "clintra" }, { "code": null, "e": 31919, "s": 31907, "text": "zack_aayush" }, { "code": null, "e": 31924, "s": 31919, "text": "JDBC" }, { "code": null, "e": 31929, "s": 31924, "text": "Java" }, { "code": null, "e": 31934, "s": 31929, "text": "Java" }, { "code": null, "e": 32032, "s": 31934, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32041, "s": 32032, "text": "Comments" }, { "code": null, "e": 32054, "s": 32041, "text": "Old Comments" }, { "code": null, "e": 32073, "s": 32054, "text": "Interfaces in Java" }, { "code": null, "e": 32085, "s": 32073, "text": "Set in Java" }, { "code": null, "e": 32105, "s": 32085, "text": "Collections in Java" }, { "code": null, "e": 32128, "s": 32105, "text": "Multithreading in Java" }, { "code": null, "e": 32156, "s": 32128, "text": "Initializing a List in Java" }, { "code": null, "e": 32180, "s": 32156, "text": "Queue Interface In Java" }, { "code": null, "e": 32200, "s": 32180, "text": "Inheritance in Java" }, { "code": null, "e": 32221, "s": 32200, "text": "Constructors in Java" }, { "code": null, "e": 32267, "s": 32221, "text": "Different ways of Reading a text file in Java" } ]
Building WhatsApp bot on Python - GeeksforGeeks
31 Aug, 2021 A WhatsApp bot is application software that is able to carry on communication with humans in a spoken or written manner. And today we are going to learn how we can create a WhatsApp bot using python. First, let’s see the requirements for building the WhatsApp bot using python language. A Twilio account and a smartphone with an active phone number and WhatsApp installed. Must have Python 3.9 or newer installed in the system. Flask: We will be using a flask to create a web application that responds to incoming WhatsApp messages with it. ngrok: Ngrok will help us to connect the Flask application running on your system to a public URL that Twilio can connect to. This is necessary for the development version of the chatbot because your computer is likely behind a router or firewall, so it isn’t directly reachable on the Internet. Step 1: Set up the Twilio account using the Twilio WhatsApp API. Go to this link and click on signup and start building button and fill in your details and verify your email ID and mobile number. Sign up After login, select the Develop option from the left menu and then further select the Messaging subject then select the Try it out option, and in the last click on Send a WhatsApp message. This will open up a new webpage for setting up the WhatsApp Sandbox. Setup Whatsapp messaging Step 2: Configure the Twilio WhatsApp Sandbox by sending a message to this WhatsApp number with the secrete unique security code as shown in the below images: Send the code as below format to the following number: +14155238886 secret code : join <secret-code> Setup Sandbox Now, send the secret code to the above WhatsApp message and you will receive a confirmation message as below: Confirmation message Step 3: Open up the terminal and run the following command to create a directory for the bot, to create a virtual environment for python, to install all the necessary packages. To create the directory and navigate to that directory: mkdir geeks-bot && cd geeks-bot To create and activate the python virtual environment: python3 -m venv geek-bot-env && source geek-bot-env/bin/activate To install Twilio, flask and requests: pip3 install twilio flask requests Here are the above commands in just one line : mkdir geek-bot && cd geek-bot && python3 -m venv geek-bot-env && source geek-bot-env/bin/activate && pip3 install twilio flask requests Output: Setting up folder structure Step 1: Import the necessary files needed to run this flask app. Python3 from flask import Flask, requestimport requestsfrom twilio.twiml.messaging_response import MessagingResponse Step 2: Receiving message entered by the user and sending the response. We can access the user response that is coming in the payload of the POST request with a key of ’Body’. Python3 from flask import request incoming_msg = request.values.get('Body', '').lower() To send messages/respond to the user, we are going to use MessagingResponse() function from Twilio. Python3 from twilio.twiml.messaging_response import MessagingResponse response = MessagingResponse()msg = response.message()msg.body('this is the response/reply from the bot.) Step 3: So now we will build the chatbot logic, we are going to ask the user to enter a topic that he/she want to learn then we send the message to the bot, and the bot will search the query and respond with the most relevant article from geeksfogeeks to the user. Python3 # chatbot logicdef bot(): # user input user_msg = request.values.get('Body', '').lower() # creating object of MessagingResponse response = MessagingResponse() # User Query q = user_msg + "geeksforgeeks.org" # list to store urls result = [] # searching and storing urls for i in search(q, tld='co.in', num=6, stop=6, pause=2): result.append(i) # displaying result msg = response.message(f"--- Result for '{user_msg}' are ---") msg = response.message(result[0]) msg = response.message(result[1]) msg = response.message(result[2]) msg = response.message(result[3]) msg = response.message(result[4]) return str(response) Here, in this function, using user_msg will receive the user response/query. Then we are using google search to fetch the first 5 links from the Google search with the user query and storing them into a list called result. After that, are simply sending the first 5 links to the user using the Twilio messaging service. To run the bot will follow these steps: Firstly, run the above script using the following command: python3 main2.py Output: Running the bot script Secondly, open up another terminal window and run the following command to start the ngrok server. ngrok http 5000 Output: And third and last step we have to do is to set up the forwarding URL in the WhatsApp Sandbox Settings. Navigate to the following link and paste the forwarding URL in the selected location and click on save. Link: https://www.twilio.com/console/sms/whatsapp/sandbox Setup URL in Twilio Here, we have imported all the necessary libraries that we’re going to use during the execution of the chatbot then we are creating a function called a bot, where we are going to implement our chatbot logic. In the bot function, firstly, we are fetching the response made by the user using WhatsApp and saving it into a variable called user_msg. After that we have created an object of MessagingResponse(), we need that for sending the reply to the user using WhatsApp. We are appending user query with the word “geeksforgeeks.org” because we have made this bot with respect to a user who might have the study-related queries and he/she can ask any doubt related to studies. After that, we have created a list called result where we are going to save the URLs that we have to send to the user. We are using the google search library for googling purposes. Using for loop, we are fetching the first 5 article links and saving them into the result. Using response.message() function we are simply sending the result back to the user through WhatsApp. Python3 from flask import Flaskfrom googlesearch import searchimport requestsfrom twilio.twiml.messaging_response import MessagingResponse app = Flask(__name__) @app.route("/", methods=["POST"]) # chatbot logicdef bot(): # user input user_msg = request.values.get('Body', '').lower() # creating object of MessagingResponse response = MessagingResponse() # User Query q = user_msg + "geeksforgeeks.org" # list to store urls result = [] # searching and storing urls for i in search(q, tld='co.in', num=6, stop=6, pause=2): result.append(i) # displaying result msg = response.message(f"--- Result for '{user_msg}' are ---") msg = response.message(result[0]) msg = response.message(result[1]) msg = response.message(result[2]) msg = response.message(result[3]) msg = response.message(result[4]) return str(response) if __name__ == "__main__": app.run() Output: Picked Python-projects 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 ? 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 Defaultdict in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n31 Aug, 2021" }, { "code": null, "e": 25934, "s": 25647, "text": "A WhatsApp bot is application software that is able to carry on communication with humans in a spoken or written manner. And today we are going to learn how we can create a WhatsApp bot using python. First, let’s see the requirements for building the WhatsApp bot using python language." }, { "code": null, "e": 26020, "s": 25934, "text": "A Twilio account and a smartphone with an active phone number and WhatsApp installed." }, { "code": null, "e": 26075, "s": 26020, "text": "Must have Python 3.9 or newer installed in the system." }, { "code": null, "e": 26188, "s": 26075, "text": "Flask: We will be using a flask to create a web application that responds to incoming WhatsApp messages with it." }, { "code": null, "e": 26484, "s": 26188, "text": "ngrok: Ngrok will help us to connect the Flask application running on your system to a public URL that Twilio can connect to. This is necessary for the development version of the chatbot because your computer is likely behind a router or firewall, so it isn’t directly reachable on the Internet." }, { "code": null, "e": 26549, "s": 26484, "text": "Step 1: Set up the Twilio account using the Twilio WhatsApp API." }, { "code": null, "e": 26680, "s": 26549, "text": "Go to this link and click on signup and start building button and fill in your details and verify your email ID and mobile number." }, { "code": null, "e": 26688, "s": 26680, "text": "Sign up" }, { "code": null, "e": 26946, "s": 26688, "text": "After login, select the Develop option from the left menu and then further select the Messaging subject then select the Try it out option, and in the last click on Send a WhatsApp message. This will open up a new webpage for setting up the WhatsApp Sandbox." }, { "code": null, "e": 26971, "s": 26946, "text": "Setup Whatsapp messaging" }, { "code": null, "e": 27130, "s": 26971, "text": "Step 2: Configure the Twilio WhatsApp Sandbox by sending a message to this WhatsApp number with the secrete unique security code as shown in the below images:" }, { "code": null, "e": 27198, "s": 27130, "text": "Send the code as below format to the following number: +14155238886" }, { "code": null, "e": 27231, "s": 27198, "text": "secret code : join <secret-code>" }, { "code": null, "e": 27245, "s": 27231, "text": "Setup Sandbox" }, { "code": null, "e": 27355, "s": 27245, "text": "Now, send the secret code to the above WhatsApp message and you will receive a confirmation message as below:" }, { "code": null, "e": 27376, "s": 27355, "text": "Confirmation message" }, { "code": null, "e": 27553, "s": 27376, "text": "Step 3: Open up the terminal and run the following command to create a directory for the bot, to create a virtual environment for python, to install all the necessary packages." }, { "code": null, "e": 27610, "s": 27553, "text": "To create the directory and navigate to that directory:" }, { "code": null, "e": 27642, "s": 27610, "text": "mkdir geeks-bot && cd geeks-bot" }, { "code": null, "e": 27697, "s": 27642, "text": "To create and activate the python virtual environment:" }, { "code": null, "e": 27762, "s": 27697, "text": "python3 -m venv geek-bot-env && source geek-bot-env/bin/activate" }, { "code": null, "e": 27802, "s": 27762, "text": "To install Twilio, flask and requests: " }, { "code": null, "e": 27837, "s": 27802, "text": "pip3 install twilio flask requests" }, { "code": null, "e": 27884, "s": 27837, "text": "Here are the above commands in just one line :" }, { "code": null, "e": 28020, "s": 27884, "text": "mkdir geek-bot && cd geek-bot && python3 -m venv geek-bot-env && source geek-bot-env/bin/activate && pip3 install twilio flask requests" }, { "code": null, "e": 28028, "s": 28020, "text": "Output:" }, { "code": null, "e": 28056, "s": 28028, "text": "Setting up folder structure" }, { "code": null, "e": 28121, "s": 28056, "text": "Step 1: Import the necessary files needed to run this flask app." }, { "code": null, "e": 28129, "s": 28121, "text": "Python3" }, { "code": "from flask import Flask, requestimport requestsfrom twilio.twiml.messaging_response import MessagingResponse", "e": 28238, "s": 28129, "text": null }, { "code": null, "e": 28414, "s": 28238, "text": "Step 2: Receiving message entered by the user and sending the response. We can access the user response that is coming in the payload of the POST request with a key of ’Body’." }, { "code": null, "e": 28422, "s": 28414, "text": "Python3" }, { "code": "from flask import request incoming_msg = request.values.get('Body', '').lower()", "e": 28503, "s": 28422, "text": null }, { "code": null, "e": 28603, "s": 28503, "text": "To send messages/respond to the user, we are going to use MessagingResponse() function from Twilio." }, { "code": null, "e": 28611, "s": 28603, "text": "Python3" }, { "code": "from twilio.twiml.messaging_response import MessagingResponse response = MessagingResponse()msg = response.message()msg.body('this is the response/reply from the bot.)", "e": 28781, "s": 28611, "text": null }, { "code": null, "e": 29046, "s": 28781, "text": "Step 3: So now we will build the chatbot logic, we are going to ask the user to enter a topic that he/she want to learn then we send the message to the bot, and the bot will search the query and respond with the most relevant article from geeksfogeeks to the user." }, { "code": null, "e": 29054, "s": 29046, "text": "Python3" }, { "code": "# chatbot logicdef bot(): # user input user_msg = request.values.get('Body', '').lower() # creating object of MessagingResponse response = MessagingResponse() # User Query q = user_msg + \"geeksforgeeks.org\" # list to store urls result = [] # searching and storing urls for i in search(q, tld='co.in', num=6, stop=6, pause=2): result.append(i) # displaying result msg = response.message(f\"--- Result for '{user_msg}' are ---\") msg = response.message(result[0]) msg = response.message(result[1]) msg = response.message(result[2]) msg = response.message(result[3]) msg = response.message(result[4]) return str(response)", "e": 29749, "s": 29054, "text": null }, { "code": null, "e": 30070, "s": 29749, "text": "Here, in this function, using user_msg will receive the user response/query. Then we are using google search to fetch the first 5 links from the Google search with the user query and storing them into a list called result. After that, are simply sending the first 5 links to the user using the Twilio messaging service." }, { "code": null, "e": 30110, "s": 30070, "text": "To run the bot will follow these steps:" }, { "code": null, "e": 30169, "s": 30110, "text": "Firstly, run the above script using the following command:" }, { "code": null, "e": 30186, "s": 30169, "text": "python3 main2.py" }, { "code": null, "e": 30194, "s": 30186, "text": "Output:" }, { "code": null, "e": 30217, "s": 30194, "text": "Running the bot script" }, { "code": null, "e": 30316, "s": 30217, "text": "Secondly, open up another terminal window and run the following command to start the ngrok server." }, { "code": null, "e": 30332, "s": 30316, "text": "ngrok http 5000" }, { "code": null, "e": 30340, "s": 30332, "text": "Output:" }, { "code": null, "e": 30548, "s": 30340, "text": "And third and last step we have to do is to set up the forwarding URL in the WhatsApp Sandbox Settings. Navigate to the following link and paste the forwarding URL in the selected location and click on save." }, { "code": null, "e": 30606, "s": 30548, "text": "Link: https://www.twilio.com/console/sms/whatsapp/sandbox" }, { "code": null, "e": 30626, "s": 30606, "text": "Setup URL in Twilio" }, { "code": null, "e": 31675, "s": 30626, "text": "Here, we have imported all the necessary libraries that we’re going to use during the execution of the chatbot then we are creating a function called a bot, where we are going to implement our chatbot logic. In the bot function, firstly, we are fetching the response made by the user using WhatsApp and saving it into a variable called user_msg. After that we have created an object of MessagingResponse(), we need that for sending the reply to the user using WhatsApp. We are appending user query with the word “geeksforgeeks.org” because we have made this bot with respect to a user who might have the study-related queries and he/she can ask any doubt related to studies. After that, we have created a list called result where we are going to save the URLs that we have to send to the user. We are using the google search library for googling purposes. Using for loop, we are fetching the first 5 article links and saving them into the result. Using response.message() function we are simply sending the result back to the user through WhatsApp." }, { "code": null, "e": 31683, "s": 31675, "text": "Python3" }, { "code": "from flask import Flaskfrom googlesearch import searchimport requestsfrom twilio.twiml.messaging_response import MessagingResponse app = Flask(__name__) @app.route(\"/\", methods=[\"POST\"]) # chatbot logicdef bot(): # user input user_msg = request.values.get('Body', '').lower() # creating object of MessagingResponse response = MessagingResponse() # User Query q = user_msg + \"geeksforgeeks.org\" # list to store urls result = [] # searching and storing urls for i in search(q, tld='co.in', num=6, stop=6, pause=2): result.append(i) # displaying result msg = response.message(f\"--- Result for '{user_msg}' are ---\") msg = response.message(result[0]) msg = response.message(result[1]) msg = response.message(result[2]) msg = response.message(result[3]) msg = response.message(result[4]) return str(response) if __name__ == \"__main__\": app.run()", "e": 32613, "s": 31683, "text": null }, { "code": null, "e": 32621, "s": 32613, "text": "Output:" }, { "code": null, "e": 32628, "s": 32621, "text": "Picked" }, { "code": null, "e": 32644, "s": 32628, "text": "Python-projects" }, { "code": null, "e": 32659, "s": 32644, "text": "python-utility" }, { "code": null, "e": 32666, "s": 32659, "text": "Python" }, { "code": null, "e": 32764, "s": 32666, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32796, "s": 32764, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32838, "s": 32796, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 32880, "s": 32838, "text": "Check if element exists in list in Python" }, { "code": null, "e": 32936, "s": 32880, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 32963, "s": 32936, "text": "Python Classes and Objects" }, { "code": null, "e": 32994, "s": 32963, "text": "Python | os.path.join() method" }, { "code": null, "e": 33023, "s": 32994, "text": "Create a directory in Python" }, { "code": null, "e": 33045, "s": 33023, "text": "Defaultdict in Python" }, { "code": null, "e": 33081, "s": 33045, "text": "Python | Pandas dataframe.groupby()" } ]
Print all the cycles in an undirected graph in C++
In this problem, we are given an undirected graph and we have to print all the cycles that are formed in the graph. Undirected Graph is a graph that is connected together. All the edges of the unidirectional graph are bidirectional. It is also known as an undirected network. Cycle in a graph data structure is a graph in which all vertices form a cycle. Let’s see an example to understand the problem better − Graph- Output- Cycle 1: 2 3 4 5 Cycle 2: 6 7 8 For this, we will make use of a few properties of the graph. You need to use graph coloring method and color all the vertices which occur in a cyclic graph. Also, if a vertex is partially visited, it will give rise to a cyclic graph. So, we will color this vertex and all next vertex till the same is reached again. Step 1: call DFS traversal for the graph which can color the vertices. Step 2: If a partially visited vertex is found, backtrack till the vertex is reached again and mark all vertices in the path with a counter which is cycle number. Step 3: After completion of traversal, iterate for cyclic edge and push them into a separate adjacency list. Step 4: Print the cycles number wise from the adjacency list. #include <bits/stdc++.h> using namespace std; const int N = 100000; vector<int> graph[N]; vector<int> cycles[N]; void DFSCycle(int u, int p, int color[], int mark[], int par[], int&amp; cyclenumber){ if (color[u] == 2) { return; } if (color[u] == 1) { cyclenumber++; int cur = p; mark[cur] = cyclenumber; while (cur != u) { cur = par[cur]; mark[cur] = cyclenumber; } return; } par[u] = p; color[u] = 1; for (int v : graph[u]) { if (v == par[u]) { continue; } DFSCycle(v, u, color, mark, par, cyclenumber); } color[u] = 2; } void insert(int u, int v){ graph[u].push_back(v); graph[v].push_back(u); } void printCycles(int edges, int mark[], int&amp; cyclenumber){ for (int i = 1; i <= edges; i++) { if (mark[i] != 0) cycles[mark[i]].push_back(i); } for (int i = 1; i <= cyclenumber; i++) { cout << "Cycle " << i << ": "; for (int x : cycles[i]) cout << x << " "; cout << endl; } } int main(){ insert(1, 2); insert(2, 3); insert(3, 4); insert(4, 5); insert(5, 2); insert(5, 6); insert(6, 7); insert(7, 8); insert(6, 8); int color[N]; int par[N]; int mark[N]; int cyclenumber = 0; cout<<"Cycles in the Graph are :\n"; int edges = 13; DFSCycle(1, 0, color, mark, par, cyclenumber); printCycles(edges, mark, cyclenumber); } Cycles in the Graph are − Cycle 1: 2 3 4 5 Cycle 2: 6 7 8
[ { "code": null, "e": 1178, "s": 1062, "text": "In this problem, we are given an undirected graph and we have to print all the cycles that are formed in the graph." }, { "code": null, "e": 1338, "s": 1178, "text": "Undirected Graph is a graph that is connected together. All the edges of the unidirectional graph are bidirectional. It is also known as an undirected network." }, { "code": null, "e": 1417, "s": 1338, "text": "Cycle in a graph data structure is a graph in which all vertices form a cycle." }, { "code": null, "e": 1473, "s": 1417, "text": "Let’s see an example to understand the problem better −" }, { "code": null, "e": 1480, "s": 1473, "text": "Graph-" }, { "code": null, "e": 1488, "s": 1480, "text": "Output-" }, { "code": null, "e": 1520, "s": 1488, "text": "Cycle 1: 2 3 4 5\nCycle 2: 6 7 8" }, { "code": null, "e": 1836, "s": 1520, "text": "For this, we will make use of a few properties of the graph. You need to use graph coloring method and color all the vertices which occur in a cyclic graph. Also, if a vertex is partially visited, it will give rise to a cyclic graph. So, we will color this vertex and all next vertex till the same is reached again." }, { "code": null, "e": 2241, "s": 1836, "text": "Step 1: call DFS traversal for the graph which can color the vertices.\nStep 2: If a partially visited vertex is found, backtrack till the vertex is\nreached again and mark all vertices in the path with a counter which is cycle number.\nStep 3: After completion of traversal, iterate for cyclic edge and push them\ninto a separate adjacency list.\nStep 4: Print the cycles number wise from the adjacency list." }, { "code": null, "e": 3684, "s": 2241, "text": "#include <bits/stdc++.h>\nusing namespace std;\nconst int N = 100000;\nvector<int> graph[N];\nvector<int> cycles[N];\nvoid DFSCycle(int u, int p, int color[], int mark[], int par[], int&amp; cyclenumber){\n if (color[u] == 2) {\n return;\n }\n if (color[u] == 1) {\n cyclenumber++;\n int cur = p;\n mark[cur] = cyclenumber;\n while (cur != u) {\n cur = par[cur];\n mark[cur] = cyclenumber;\n }\n return;\n }\n par[u] = p;\n color[u] = 1;\n for (int v : graph[u]) {\n if (v == par[u]) {\n continue;\n }\n DFSCycle(v, u, color, mark, par, cyclenumber);\n }\n color[u] = 2;\n}\nvoid insert(int u, int v){\n graph[u].push_back(v);\n graph[v].push_back(u);\n}\nvoid printCycles(int edges, int mark[], int&amp; cyclenumber){\n for (int i = 1; i <= edges; i++) {\n if (mark[i] != 0)\n cycles[mark[i]].push_back(i);\n }\n for (int i = 1; i <= cyclenumber; i++) {\n cout << \"Cycle \" << i << \": \";\n for (int x : cycles[i])\n cout << x << \" \";\n cout << endl;\n }\n}\nint main(){\n insert(1, 2);\n insert(2, 3);\n insert(3, 4);\n insert(4, 5);\n insert(5, 2);\n insert(5, 6);\n insert(6, 7);\n insert(7, 8);\n insert(6, 8);\n int color[N];\n int par[N];\n int mark[N];\n int cyclenumber = 0;\n cout<<\"Cycles in the Graph are :\\n\";\n int edges = 13;\n DFSCycle(1, 0, color, mark, par, cyclenumber);\n printCycles(edges, mark, cyclenumber);\n}" }, { "code": null, "e": 3710, "s": 3684, "text": "Cycles in the Graph are −" }, { "code": null, "e": 3742, "s": 3710, "text": "Cycle 1: 2 3 4 5\nCycle 2: 6 7 8" } ]
Java Program for Anagram Substring Search
Following is an example for Anagram Substring Search in Java − Live Demo public class Demo{ static final int max_val = 256; static boolean compare_vals(char my_arr_1[], char my_arr_2[]){ for (int i = 0; i < max_val; i++) if (my_arr_1[i] != my_arr_2[i]) return false; return true; } static void search_subs(String my_pattern, String my_text){ int pat_len = my_pattern.length(); int txt_len = my_text.length(); char[] count_pat = new char[max_val]; char[] count_txt = new char[max_val]; for (int i = 0; i < pat_len; i++){ (count_pat[my_pattern.charAt(i)])++; (count_txt[my_text.charAt(i)])++; } for (int i = pat_len; i < txt_len; i++){ if (compare_vals(count_pat, count_txt)) System.out.println("The element was found at index " + (i - pat_len)); (count_txt[my_text.charAt(i)])++; count_txt[my_text.charAt(i-pat_len)]--; } if (compare_vals(count_pat, count_txt)) System.out.println("The element was found at index " + (txt_len - pat_len)); } public static void main(String args[]){ String my_text = "ABNFGHABNJGH"; String my_pattern = "NFGH"; search_subs(my_pattern, my_text); } } The element was found at index 2 A class named Demo defines a constant value and a Boolean function that takes in two arrays. It iterates over both the arrays till the constant value is reached. It returns true or false depending on whether the elements in the array that compared were compared were equal or unequal. Another static function takes in the text and the pattern that needs to be checked for in the text and iterate over the pattern and string. Both the counts of pattern and string are incremented. Again a ‘for’ loop is run and the counts of both the pattern and text are compared. If they are equal, the index is displayed. Otherwise, a relevant message is displayed. In the main class, the pattern and the text are defined and the function is called.
[ { "code": null, "e": 1125, "s": 1062, "text": "Following is an example for Anagram Substring Search in Java −" }, { "code": null, "e": 1136, "s": 1125, "text": " Live Demo" }, { "code": null, "e": 2319, "s": 1136, "text": "public class Demo{\n static final int max_val = 256;\n static boolean compare_vals(char my_arr_1[], char my_arr_2[]){\n for (int i = 0; i < max_val; i++)\n if (my_arr_1[i] != my_arr_2[i])\n return false;\n return true;\n }\n static void search_subs(String my_pattern, String my_text){\n int pat_len = my_pattern.length();\n int txt_len = my_text.length();\n char[] count_pat = new char[max_val];\n char[] count_txt = new char[max_val];\n for (int i = 0; i < pat_len; i++){\n (count_pat[my_pattern.charAt(i)])++;\n (count_txt[my_text.charAt(i)])++;\n }\n for (int i = pat_len; i < txt_len; i++){\n if (compare_vals(count_pat, count_txt))\n System.out.println(\"The element was found at index \" + (i - pat_len));\n (count_txt[my_text.charAt(i)])++;\n count_txt[my_text.charAt(i-pat_len)]--;\n }\n if (compare_vals(count_pat, count_txt))\n System.out.println(\"The element was found at index \" + (txt_len - pat_len));\n }\n public static void main(String args[]){\n String my_text = \"ABNFGHABNJGH\";\n String my_pattern = \"NFGH\";\n search_subs(my_pattern, my_text);\n }\n}" }, { "code": null, "e": 2352, "s": 2319, "text": "The element was found at index 2" }, { "code": null, "e": 2637, "s": 2352, "text": "A class named Demo defines a constant value and a Boolean function that takes in two arrays. It iterates over both the arrays till the constant value is reached. It returns true or false depending on whether the elements in the array that compared were compared were equal or unequal." }, { "code": null, "e": 3087, "s": 2637, "text": "Another static function takes in the text and the pattern that needs to be checked for in the text and iterate over the pattern and string. Both the counts of pattern and string are incremented. Again a ‘for’ loop is run and the counts of both the pattern and text are compared. If they are equal, the index is displayed. Otherwise, a relevant message is displayed. In the main class, the pattern and the text are defined and the function is called." } ]
Apex - Batch Processing
In this chapter, we will understand Batch Processing in Apex. Consider a scenario wherein, we will process large number of records on daily basis, probably the cleaning of data or maybe deleting some unused data. Batch Apex is asynchronous execution of Apex code, specially designed for processing the large number of records and has greater flexibility in governor limits than the synchronous code. When you want to process large number of records on daily basis or even on specific time of interval then you can go for Batch Apex. When you want to process large number of records on daily basis or even on specific time of interval then you can go for Batch Apex. Also, when you want an operation to be asynchronous then you can implement the Batch Apex. Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically invoked at runtime using Apex. Batch Apex operates over small batches of records, covering your entire record set and breaking the processing down to manageable chunks of data. Also, when you want an operation to be asynchronous then you can implement the Batch Apex. Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically invoked at runtime using Apex. Batch Apex operates over small batches of records, covering your entire record set and breaking the processing down to manageable chunks of data. When we are using the Batch Apex, we must implement the Salesforce-provided interface Database.Batchable, and then invoke the class programmatically. You can monitor the class by following these steps − To monitor or stop the execution of the batch Apex Batch job, go to Setup → Monitoring → Apex Jobs or Jobs → Apex Jobs. Database.Batchable interface has the following three methods that need to be implemented − Start Execute Finish Let us now understand each method in detail. The Start method is one of the three methods of the Database.Batchable interface. Syntax global void execute(Database.BatchableContext BC, list<sobject<) {} This method will be called at the starting of the Batch Job and collects the data on which the Batch job will be operating. Consider the following points to understand the method − Use the Database.QueryLocator object when you are using a simple query to generate the scope of objects used in the batch job. In this case, the SOQL data row limit will be bypassed. Use the Database.QueryLocator object when you are using a simple query to generate the scope of objects used in the batch job. In this case, the SOQL data row limit will be bypassed. Use the iterable object when you have complex criteria to process the records. Database.QueryLocator determines the scope of records which should be processed. Use the iterable object when you have complex criteria to process the records. Database.QueryLocator determines the scope of records which should be processed. Let us now understand the Execute method of the Database.Batchable interface. Syntax global void execute(Database.BatchableContext BC, list<sobject<) {} where, list<sObject< is returned by the Database.QueryLocator method. This method gets called after the Start method and does all the processing required for Batch Job. We will now discuss the Finish method of the Database.Batchable interface. Syntax global void finish(Database.BatchableContext BC) {} This method gets called at the end and you can do some finishing activities like sending an email with information about the batch job records processed and status. Let us consider an example of our existing Chemical Company and assume that we have requirement to update the Customer Status and Customer Description field of Customer Records which have been marked as Active and which have created Date as today. This should be done on daily basis and an email should be sent to a User about the status of the Batch Processing. Update the Customer Status as 'Processed' and Customer Description as 'Updated Via Batch Job'. // Batch Job for Processing the Records global class CustomerProessingBatch implements Database.Batchable<sobject> { global String [] email = new String[] {'[email protected]'}; // Add here your email address here // Start Method global Database.Querylocator start (Database.BatchableContext BC) { return Database.getQueryLocator('Select id, Name, APEX_Customer_Status__c, APEX_Customer_Decscription__c From APEX_Customer__c WHERE createdDate = today AND APEX_Active__c = true'); // Query which will be determine the scope of Records fetching the same } // Execute method global void execute (Database.BatchableContext BC, List<sobject> scope) { List<apex_customer__c> customerList = new List<apex_customer__c>(); List<apex_customer__c> updtaedCustomerList = new List<apex_customer__c>(); // List to hold updated customer for (sObject objScope: scope) { APEX_Customer__c newObjScope = (APEX_Customer__c)objScope ; // type casting from generic sOject to APEX_Customer__c newObjScope.APEX_Customer_Decscription__c = 'Updated Via Batch Job'; newObjScope.APEX_Customer_Status__c = 'Processed'; updtaedCustomerList.add(newObjScope); // Add records to the List System.debug('Value of UpdatedCustomerList '+updtaedCustomerList); } if (updtaedCustomerList != null && updtaedCustomerList.size()>0) { // Check if List is empty or not Database.update(updtaedCustomerList); System.debug('List Size ' + updtaedCustomerList.size()); // Update the Records } } // Finish Method global void finish(Database.BatchableContext BC) { Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); // Below code will fetch the job Id AsyncApexJob a = [Select a.TotalJobItems, a.Status, a.NumberOfErrors, a.JobType, a.JobItemsProcessed, a.ExtendedStatus, a.CreatedById, a.CompletedDate From AsyncApexJob a WHERE id = :BC.getJobId()]; // get the job Id System.debug('$$$ Jobid is'+BC.getJobId()); // below code will send an email to User about the status mail.setToAddresses(email); mail.setReplyTo('[email protected]'); // Add here your email address mail.setSenderDisplayName('Apex Batch Processing Module'); mail.setSubject('Batch Processing '+a.Status); mail.setPlainTextBody('The Batch Apex job processed' + a.TotalJobItems+'batches with '+a.NumberOfErrors+'failures'+'Job Item processed are'+a.JobItemsProcessed); Messaging.sendEmail(new Messaging.Singleemailmessage [] {mail}); } } To execute this code, first save it and then paste the following code in Execute anonymous. This will create the object of class and Database.execute method will execute the Batch job. Once the job is completed then an email will be sent to the specified email address. Make sure that you have a customer record which has Active as checked. // Paste in Developer Console CustomerProessingBatch objClass = new CustomerProessingBatch(); Database.executeBatch (objClass); Once this class is executed, then check the email address you have provided where you will receive the email with information. Also, you can check the status of the batch job via the Monitoring page and steps as provided above. If you check the debug logs, then you can find the List size which indicates how many records have been processed. Limitations We can only have 5 batch job processing at a time. This is one of the limitations of Batch Apex. You can schedule the Apex class via Apex detail page as given below − Step 1 − Go to Setup ⇒ Apex Classes, Click on Apex Classes. Step 2 − Click on the Schedule Apex button. Step 3 − Provide details. You can schedule the Apex Batch Job using Schedulable Interface as given below − // Batch Job for Processing the Records global class CustomerProessingBatch implements Database.Batchable<sobject> { global String [] email = new String[] {'[email protected]'}; // Add here your email address here // Start Method global Database.Querylocator start (Database.BatchableContext BC) { return Database.getQueryLocator('Select id, Name, APEX_Customer_Status__c, APEX_Customer_Decscription__c From APEX_Customer__c WHERE createdDate = today AND APEX_Active__c = true'); // Query which will be determine the scope of Records fetching the same } // Execute method global void execute (Database.BatchableContext BC, List<sobject> scope) { List<apex_customer__c> customerList = new List<apex_customer__c>(); List<apex_customer__c> updtaedCustomerList = new List<apex_customer__c>();//List to hold updated customer for (sObject objScope: scope) { APEX_Customer__c newObjScope = (APEX_Customer__c)objScope ;//type casting from generic sOject to APEX_Customer__c newObjScope.APEX_Customer_Decscription__c = 'Updated Via Batch Job'; newObjScope.APEX_Customer_Status__c = 'Processed'; updtaedCustomerList.add(newObjScope);//Add records to the List System.debug('Value of UpdatedCustomerList '+updtaedCustomerList); } if (updtaedCustomerList != null && updtaedCustomerList.size()>0) { // Check if List is empty or not Database.update(updtaedCustomerList); System.debug('List Size' + updtaedCustomerList.size()); // Update the Records } } // Finish Method global void finish(Database.BatchableContext BC) { Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); // Below code will fetch the job Id AsyncApexJob a = [Select a.TotalJobItems, a.Status, a.NumberOfErrors, a.JobType, a.JobItemsProcessed, a.ExtendedStatus, a.CreatedById, a.CompletedDate From AsyncApexJob a WHERE id = :BC.getJobId()];//get the job Id System.debug('$$$ Jobid is'+BC.getJobId()); // below code will send an email to User about the status mail.setToAddresses(email); mail.setReplyTo('[email protected]');//Add here your email address mail.setSenderDisplayName('Apex Batch Processing Module'); mail.setSubject('Batch Processing '+a.Status); mail.setPlainTextBody('The Batch Apex job processed' + a.TotalJobItems+'batches with '+a.NumberOfErrors+'failures'+'Job Item processed are'+a.JobItemsProcessed); Messaging.sendEmail(new Messaging.Singleemailmessage [] {mail}); } // Scheduler Method to scedule the class global void execute(SchedulableContext sc) { CustomerProessingBatch conInstance = new CustomerProessingBatch(); database.executebatch(conInstance,100); } } // Paste in Developer Console CustomerProessingBatch objClass = new CustomerProcessingBatch(); Database.executeBatch (objClass); 14 Lectures 2 hours Vijay Thapa 7 Lectures 2 hours Uplatz 29 Lectures 6 hours Ramnarayan Ramakrishnan 49 Lectures 3 hours Ali Saleh Ali 10 Lectures 4 hours Soham Ghosh 48 Lectures 4.5 hours GUHARAJANM Print Add Notes Bookmark this page
[ { "code": null, "e": 2265, "s": 2052, "text": "In this chapter, we will understand Batch Processing in Apex. Consider a scenario wherein, we will process large number of records on daily basis, probably the cleaning of data or maybe deleting some unused data." }, { "code": null, "e": 2452, "s": 2265, "text": "Batch Apex is asynchronous execution of Apex code, specially designed for processing the large number of records and has greater flexibility in governor limits than the synchronous code." }, { "code": null, "e": 2585, "s": 2452, "text": "When you want to process large number of records on daily basis or even on specific time of interval then you can go for Batch Apex." }, { "code": null, "e": 2718, "s": 2585, "text": "When you want to process large number of records on daily basis or even on specific time of interval then you can go for Batch Apex." }, { "code": null, "e": 3102, "s": 2718, "text": "Also, when you want an operation to be asynchronous then you can implement the Batch Apex. Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically invoked at runtime using Apex. Batch Apex operates over small batches of records, covering your entire record set and breaking the processing down to manageable chunks of data." }, { "code": null, "e": 3486, "s": 3102, "text": "Also, when you want an operation to be asynchronous then you can implement the Batch Apex. Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically invoked at runtime using Apex. Batch Apex operates over small batches of records, covering your entire record set and breaking the processing down to manageable chunks of data." }, { "code": null, "e": 3636, "s": 3486, "text": "When we are using the Batch Apex, we must implement the Salesforce-provided interface Database.Batchable, and then invoke the class programmatically." }, { "code": null, "e": 3689, "s": 3636, "text": "You can monitor the class by following these steps −" }, { "code": null, "e": 3809, "s": 3689, "text": "To monitor or stop the execution of the batch Apex Batch job, go to Setup → Monitoring → Apex Jobs or Jobs → Apex Jobs." }, { "code": null, "e": 3900, "s": 3809, "text": "Database.Batchable interface has the following three methods that need to be implemented −" }, { "code": null, "e": 3906, "s": 3900, "text": "Start" }, { "code": null, "e": 3914, "s": 3906, "text": "Execute" }, { "code": null, "e": 3921, "s": 3914, "text": "Finish" }, { "code": null, "e": 3966, "s": 3921, "text": "Let us now understand each method in detail." }, { "code": null, "e": 4048, "s": 3966, "text": "The Start method is one of the three methods of the Database.Batchable interface." }, { "code": null, "e": 4055, "s": 4048, "text": "Syntax" }, { "code": null, "e": 4124, "s": 4055, "text": "global void execute(Database.BatchableContext BC, list<sobject<) {}\n" }, { "code": null, "e": 4248, "s": 4124, "text": "This method will be called at the starting of the Batch Job and collects the data on which the Batch job will be operating." }, { "code": null, "e": 4305, "s": 4248, "text": "Consider the following points to understand the method −" }, { "code": null, "e": 4488, "s": 4305, "text": "Use the Database.QueryLocator object when you are using a simple query to generate the scope of objects used in the batch job. In this case, the SOQL data row limit will be bypassed." }, { "code": null, "e": 4671, "s": 4488, "text": "Use the Database.QueryLocator object when you are using a simple query to generate the scope of objects used in the batch job. In this case, the SOQL data row limit will be bypassed." }, { "code": null, "e": 4831, "s": 4671, "text": "Use the iterable object when you have complex criteria to process the records. Database.QueryLocator determines the scope of records which should be processed." }, { "code": null, "e": 4991, "s": 4831, "text": "Use the iterable object when you have complex criteria to process the records. Database.QueryLocator determines the scope of records which should be processed." }, { "code": null, "e": 5069, "s": 4991, "text": "Let us now understand the Execute method of the Database.Batchable interface." }, { "code": null, "e": 5076, "s": 5069, "text": "Syntax" }, { "code": null, "e": 5145, "s": 5076, "text": "global void execute(Database.BatchableContext BC, list<sobject<) {}\n" }, { "code": null, "e": 5215, "s": 5145, "text": "where, list<sObject< is returned by the Database.QueryLocator method." }, { "code": null, "e": 5314, "s": 5215, "text": "This method gets called after the Start method and does all the processing required for Batch Job." }, { "code": null, "e": 5389, "s": 5314, "text": "We will now discuss the Finish method of the Database.Batchable interface." }, { "code": null, "e": 5396, "s": 5389, "text": "Syntax" }, { "code": null, "e": 5449, "s": 5396, "text": "global void finish(Database.BatchableContext BC) {}\n" }, { "code": null, "e": 5614, "s": 5449, "text": "This method gets called at the end and you can do some finishing activities like sending an email with information about the batch job records processed and status." }, { "code": null, "e": 6072, "s": 5614, "text": "Let us consider an example of our existing Chemical Company and assume that we have requirement to update the Customer Status and Customer Description field of Customer Records which have been marked as Active and which have created Date as today. This should be done on daily basis and an email should be sent to a User about the status of the Batch Processing. Update the Customer Status as 'Processed' and Customer Description as 'Updated Via Batch Job'." }, { "code": null, "e": 8783, "s": 6072, "text": "// Batch Job for Processing the Records\nglobal class CustomerProessingBatch implements Database.Batchable<sobject> {\n global String [] email = new String[] {'[email protected]'};\n // Add here your email address here\n \n // Start Method\n global Database.Querylocator start (Database.BatchableContext BC) {\n return Database.getQueryLocator('Select id, Name, APEX_Customer_Status__c,\n APEX_Customer_Decscription__c From APEX_Customer__c WHERE createdDate = today\n AND APEX_Active__c = true');\n // Query which will be determine the scope of Records fetching the same\n }\n \n // Execute method\n global void execute (Database.BatchableContext BC, List<sobject> scope) {\n List<apex_customer__c> customerList = new List<apex_customer__c>();\n List<apex_customer__c> updtaedCustomerList = new List<apex_customer__c>();\n \n // List to hold updated customer\n for (sObject objScope: scope) {\n APEX_Customer__c newObjScope = (APEX_Customer__c)objScope ;\n \n // type casting from generic sOject to APEX_Customer__c\n newObjScope.APEX_Customer_Decscription__c = 'Updated Via Batch Job';\n newObjScope.APEX_Customer_Status__c = 'Processed';\n updtaedCustomerList.add(newObjScope); // Add records to the List\n System.debug('Value of UpdatedCustomerList '+updtaedCustomerList);\n }\n \n if (updtaedCustomerList != null && updtaedCustomerList.size()>0) {\n // Check if List is empty or not\n Database.update(updtaedCustomerList); System.debug('List Size '\n + updtaedCustomerList.size());\n // Update the Records\n }\n }\n \n // Finish Method\n global void finish(Database.BatchableContext BC) {\n Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();\n \n // Below code will fetch the job Id\n AsyncApexJob a = [Select a.TotalJobItems, a.Status, a.NumberOfErrors,\n a.JobType, a.JobItemsProcessed, a.ExtendedStatus, a.CreatedById,\n a.CompletedDate From AsyncApexJob a WHERE id = :BC.getJobId()];\n \n // get the job Id\n System.debug('$$$ Jobid is'+BC.getJobId());\n \n // below code will send an email to User about the status\n mail.setToAddresses(email);\n mail.setReplyTo('[email protected]'); // Add here your email address\n mail.setSenderDisplayName('Apex Batch Processing Module');\n mail.setSubject('Batch Processing '+a.Status);\n mail.setPlainTextBody('The Batch Apex job processed'\n + a.TotalJobItems+'batches with '+a.NumberOfErrors+'failures'+'Job Item\n processed are'+a.JobItemsProcessed);\n Messaging.sendEmail(new Messaging.Singleemailmessage [] {mail});\n }\n}" }, { "code": null, "e": 9124, "s": 8783, "text": "To execute this code, first save it and then paste the following code in Execute anonymous. This will create the object of class and Database.execute method will execute the Batch job. Once the job is completed then an email will be sent to the specified email address. Make sure that you have a customer record which has Active as checked." }, { "code": null, "e": 9252, "s": 9124, "text": "// Paste in Developer Console\nCustomerProessingBatch objClass = new CustomerProessingBatch();\nDatabase.executeBatch (objClass);" }, { "code": null, "e": 9480, "s": 9252, "text": "Once this class is executed, then check the email address you have provided where you will receive the email with information. Also, you can check the status of the batch job via the Monitoring page and steps as provided above." }, { "code": null, "e": 9595, "s": 9480, "text": "If you check the debug logs, then you can find the List size which indicates how many records have been processed." }, { "code": null, "e": 9607, "s": 9595, "text": "Limitations" }, { "code": null, "e": 9704, "s": 9607, "text": "We can only have 5 batch job processing at a time. This is one of the limitations of Batch Apex." }, { "code": null, "e": 9774, "s": 9704, "text": "You can schedule the Apex class via Apex detail page as given below −" }, { "code": null, "e": 9834, "s": 9774, "text": "Step 1 − Go to Setup ⇒ Apex Classes, Click on Apex Classes." }, { "code": null, "e": 9878, "s": 9834, "text": "Step 2 − Click on the Schedule Apex button." }, { "code": null, "e": 9904, "s": 9878, "text": "Step 3 − Provide details." }, { "code": null, "e": 9985, "s": 9904, "text": "You can schedule the Apex Batch Job using Schedulable Interface as given below −" }, { "code": null, "e": 13014, "s": 9985, "text": "// Batch Job for Processing the Records\nglobal class CustomerProessingBatch implements Database.Batchable<sobject> {\n global String [] email = new String[] {'[email protected]'};\n // Add here your email address here\n \n // Start Method\n global Database.Querylocator start (Database.BatchableContext BC) {\n return Database.getQueryLocator('Select id, Name, APEX_Customer_Status__c,\n APEX_Customer_Decscription__c From APEX_Customer__c WHERE createdDate = today\n AND APEX_Active__c = true');\n // Query which will be determine the scope of Records fetching the same\n }\n \n // Execute method\n global void execute (Database.BatchableContext BC, List<sobject> scope) {\n List<apex_customer__c> customerList = new List<apex_customer__c>();\n List<apex_customer__c> updtaedCustomerList = new\n List<apex_customer__c>();//List to hold updated customer\n \n for (sObject objScope: scope) {\n APEX_Customer__c newObjScope = (APEX_Customer__c)objScope ;//type\n casting from generic sOject to APEX_Customer__c\n newObjScope.APEX_Customer_Decscription__c = 'Updated Via Batch Job';\n newObjScope.APEX_Customer_Status__c = 'Processed';\n updtaedCustomerList.add(newObjScope);//Add records to the List\n System.debug('Value of UpdatedCustomerList '+updtaedCustomerList);\n }\n \n if (updtaedCustomerList != null && updtaedCustomerList.size()>0) {\n // Check if List is empty or not\n Database.update(updtaedCustomerList); System.debug('List Size'\n + updtaedCustomerList.size());\n // Update the Records\n }\n }\n \n // Finish Method\n global void finish(Database.BatchableContext BC) {\n Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();\n \n // Below code will fetch the job Id\n AsyncApexJob a = [Select a.TotalJobItems, a.Status, a.NumberOfErrors,\n a.JobType, a.JobItemsProcessed, a.ExtendedStatus, a.CreatedById,\n a.CompletedDate From AsyncApexJob a WHERE id = :BC.getJobId()];//get the job Id\n System.debug('$$$ Jobid is'+BC.getJobId());\n \n // below code will send an email to User about the status\n mail.setToAddresses(email);\n mail.setReplyTo('[email protected]');//Add here your email address\n mail.setSenderDisplayName('Apex Batch Processing Module');\n mail.setSubject('Batch Processing '+a.Status);\n mail.setPlainTextBody('The Batch Apex job processed' \n + a.TotalJobItems+'batches with '+a.NumberOfErrors+'failures'+'Job Item\n processed are'+a.JobItemsProcessed);\n Messaging.sendEmail(new Messaging.Singleemailmessage [] {mail});\n }\n \n // Scheduler Method to scedule the class\n global void execute(SchedulableContext sc) {\n CustomerProessingBatch conInstance = new CustomerProessingBatch();\n database.executebatch(conInstance,100);\n }\n}\n\n// Paste in Developer Console\nCustomerProessingBatch objClass = new CustomerProcessingBatch();\nDatabase.executeBatch (objClass);" }, { "code": null, "e": 13047, "s": 13014, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 13060, "s": 13047, "text": " Vijay Thapa" }, { "code": null, "e": 13092, "s": 13060, "text": "\n 7 Lectures \n 2 hours \n" }, { "code": null, "e": 13100, "s": 13092, "text": " Uplatz" }, { "code": null, "e": 13133, "s": 13100, "text": "\n 29 Lectures \n 6 hours \n" }, { "code": null, "e": 13158, "s": 13133, "text": " Ramnarayan Ramakrishnan" }, { "code": null, "e": 13191, "s": 13158, "text": "\n 49 Lectures \n 3 hours \n" }, { "code": null, "e": 13206, "s": 13191, "text": " Ali Saleh Ali" }, { "code": null, "e": 13239, "s": 13206, "text": "\n 10 Lectures \n 4 hours \n" }, { "code": null, "e": 13252, "s": 13239, "text": " Soham Ghosh" }, { "code": null, "e": 13287, "s": 13252, "text": "\n 48 Lectures \n 4.5 hours \n" }, { "code": null, "e": 13299, "s": 13287, "text": " GUHARAJANM" }, { "code": null, "e": 13306, "s": 13299, "text": " Print" }, { "code": null, "e": 13317, "s": 13306, "text": " Add Notes" } ]
How to use email input type in HTML?
The email input type is used in HTML using the <input type="email">. Using this, allow the users to add an e-mail address. On some browsers, the email entered will be validated i.e. if you miss @ and. (period), while adding e-mail, then it won’t submit the form and will show an error i.e. “Please enter an email address”. Use the multiple Boolean attributes, if you want to allow adding more than one email address. Note − The input type email is not supported in Internet Explorer 9 and earlier. You can try to run the following code to learn how to use email input type in HTML − <!DOCTYPE html> <html> <head> <title>HTML input email</title> </head> <body> <form action = "" method = "get"> Details:<br><br> Student Name<br><input type = "name" name = "sname"><br> Student E-mail<br><input type = "email" name = "email"><br> <input type = "submit" value = "Submit"> </form> </body> </html>
[ { "code": null, "e": 1385, "s": 1062, "text": "The email input type is used in HTML using the <input type=\"email\">. Using this, allow the users to add an e-mail address. On some browsers, the email entered will be validated i.e. if you miss @ and. (period), while adding e-mail, then it won’t submit the form and will show an error i.e. “Please enter an email address”." }, { "code": null, "e": 1479, "s": 1385, "text": "Use the multiple Boolean attributes, if you want to allow adding more than one email address." }, { "code": null, "e": 1560, "s": 1479, "text": "Note − The input type email is not supported in Internet Explorer 9 and earlier." }, { "code": null, "e": 1645, "s": 1560, "text": "You can try to run the following code to learn how to use email input type in HTML −" }, { "code": null, "e": 2022, "s": 1645, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML input email</title>\n </head>\n\n <body>\n <form action = \"\" method = \"get\">\n Details:<br><br>\n Student Name<br><input type = \"name\" name = \"sname\"><br>\n Student E-mail<br><input type = \"email\" name = \"email\"><br>\n <input type = \"submit\" value = \"Submit\">\n </form>\n </body>\n</html>" } ]
Create “Interactive Globe + Earthquake Plot in Python with Plotly | by Ryota Kiuchi | Towards Data Science | Towards Data Science
How Does It Look? Enjoy in here! Through creating this interactive plot, you can get the following ideas.- Deeper insights and more realistic application example to use Plotly- Especially, handle with the spherical plot in which Matplotlib poorly handle with- Get familiar with the global data characterized by latitude and longitude through the topography and earthquake data- The most important point is that visualizing earthquake distribution in this post makes you imagine where most of the earthquakes occurred (which is along the plate boundary). We need to install Plotly via pip: pip install plotly Or if you want to install via Anaconda: conda install plotly - macOS 10.14 Mojave- Python 3.6 (Anaconda)- Jupyter notebook 1. Create the Interactive Globe2. Plot the Global Earthquake Distribution on the Interactive Globe 1–1. Download and import the topography data1–2. Convert geographical coordinates (latitude/longitude) into spherical coordinates to plot on the sphere.(Plotly Chart Studio: Heatmap plot on a spherical map)1–3. Create the map using Plotly The 1 arc-minute global relief model of Earth’s surface (ETOPO1 Global Relief Model) is published by NOAA (National Oceanic and Atmospheric Administration). Download the ETOPO1 data from here.* In here, we use the “ETOPO1_Ice_g_gdal.grd” file which is a grid-registered netCDF file of ETOPO1 Ice Surface. Firstly, importing the values of latitude, longitude, and topography from the downloaded NetCDF file using the Etopo function. Input: longitude (lon_area) and latitude (lat_area) based on the selected area, and resolution.Output: mesh shape longitude (lon), latitude (lat) within the selected area, and topography (topo) based on resolution.* resolution has to be in degree unit and the highest resolution will be 0.0167 degree To make the spherical plot using the imported longitude (lon) and latitude (lat) data, we convert these data into the spherical coordinates. The idea is not complicated. Just converting from the orthogonal coordinate to the spherical coordinate using the basic math functional form. How to make it in Python? See details described at Plotly Chart Studio: Heatmap plot on a spherical map Here we plot the interactive Globe using the data of latitude, longitude described as the spherical coordinated, and topography. Firstly, we call the Etopo function defined in Step. 1 to read the array of longitude (lon_topo), latitude (lat_topo), and topography (topo) covering the whole globe. If the resolution is too high, the size of data becomes huge due to the 3-dimensional data. Here we adopt 0.8 degrees as the value of resolution. And then, converting to the spherical coordinates using the created function of mapping_map_to_sphere We also need to define the color scale of the topography we plot. The color scale in this example is defined as follows: We prepare the plot using Plotly as follows: To make our plot more brilliant, the axes are removed as follows: Figure title (‘3D spherical topography map’), font (‘Courier New’), and its associated settings are described here. Note that, black and white are selected as the background and font color, respectively, to make our globe being in the universe: Finally, we create the plot and export as an HTML file.Once you create the HTML file, you can check your plot using the Web browser (Google Chrome, Safari, ...) in the local environment. Demo In the above plot, the topography data was displayed as the color without any three-dimensional shapes. Here we create those shapes by converting xs, ys, and zs. The following code describes how to create and make the figure just like what we did in the previous plot: Demo 2–1. Prepare the earthquake data2–2. Prepare plate boundary plot and convert coordinates2–3. Plot the earthquake distribution on the interactive globe created above In this post, we download the earthquake data from the U.S. Geological Survey (USGS) website. This earthquake catalog data includes the dates, location parameters (longitude, latitude, and depth), magnitudes that describe the size of the earthquake, and so on. You can select the earthquake by filtering these parameters. I would recommend downloading only for larger magnitude events (e.g. M > 5) due to the huge numbers of earthquakes you have to handle (For a given frequency of magnitude 4.0 or larger events there will be 10 times as many magnitude 3.0 or larger quakes and 100 times as many magnitude 2.0 or larger quakes ! — Gutenberg-Richter law) In this post, I downloaded the catalog based on the following options: M > 5Date between 2000/1/1 to 2020/8/31Worldwide region M > 5 Date between 2000/1/1 to 2020/8/31 Worldwide region Here we import the earthquake data downloaded above using pandas. And then create NumPy arrays for five parameters we will use (date, longitude, latitude, depth, magnitude). Three location parameters (longitude, latitude, and depth) are used as the x, y, and z, and magnitude is used for the plot size. For the plot color, we create two cases using depth, and Timefrom_RefYears (years since 2000) which is calculated using np.datetime64 and np.timedelta64 function. Here we convert earthquake longitude and latitude to the spherical coordinates as described in 1–2, and create a color bar used for depth and Timefrom_RefYears. For a color bar, we adopt matplotlib color bar and convert to Plotly format. Firstly, we slightly change the location parameters using depth to create a three-dimensional effect for the earthquake plot. Although earthquakes occur under the ground (of course!), we plot the earthquake distribution above the interactive globe to make them visible. In this post, we will plot the earthquake distribution on the interactive globe created in Step 1. However, in order to make an earthquake distribution more clear, we also plot this distribution on just a simple plate boundaries map. In this step, we prepare that plate boundary map. This procedure is already clearly explained in these posts: Plotly chart_studio posted by Dreamshot: https://plot.ly/~Dreamshot/9152 Using these new location parameters, we make the three different ways of Plotly function as follows: 3D earthquake distribution on the interactive globe with the color of depth 3D earthquake distribution on the interactive globe with the color of years since 2000 3D earthquake distribution on the plate boundary plot The color describes earthquake depths ranging from 0 (red) to 700 km (blue) Demo The color describes how many years passed since 2000 from 0 year (red) to 20 years (blue) Demo Firstly, we create an inner black sphere to hide inside of the globe: Then create the 3D plot using the plate boundary data we prepared at 2.2: Demo Thanks for reading this article and hope you enjoy your own plot. I’m happy to get any comments from all of you!
[ { "code": null, "e": 190, "s": 172, "text": "How Does It Look?" }, { "code": null, "e": 205, "s": 190, "text": "Enjoy in here!" }, { "code": null, "e": 726, "s": 205, "text": "Through creating this interactive plot, you can get the following ideas.- Deeper insights and more realistic application example to use Plotly- Especially, handle with the spherical plot in which Matplotlib poorly handle with- Get familiar with the global data characterized by latitude and longitude through the topography and earthquake data- The most important point is that visualizing earthquake distribution in this post makes you imagine where most of the earthquakes occurred (which is along the plate boundary)." }, { "code": null, "e": 761, "s": 726, "text": "We need to install Plotly via pip:" }, { "code": null, "e": 780, "s": 761, "text": "pip install plotly" }, { "code": null, "e": 820, "s": 780, "text": "Or if you want to install via Anaconda:" }, { "code": null, "e": 841, "s": 820, "text": "conda install plotly" }, { "code": null, "e": 903, "s": 841, "text": "- macOS 10.14 Mojave- Python 3.6 (Anaconda)- Jupyter notebook" }, { "code": null, "e": 1002, "s": 903, "text": "1. Create the Interactive Globe2. Plot the Global Earthquake Distribution on the Interactive Globe" }, { "code": null, "e": 1241, "s": 1002, "text": "1–1. Download and import the topography data1–2. Convert geographical coordinates (latitude/longitude) into spherical coordinates to plot on the sphere.(Plotly Chart Studio: Heatmap plot on a spherical map)1–3. Create the map using Plotly" }, { "code": null, "e": 1546, "s": 1241, "text": "The 1 arc-minute global relief model of Earth’s surface (ETOPO1 Global Relief Model) is published by NOAA (National Oceanic and Atmospheric Administration). Download the ETOPO1 data from here.* In here, we use the “ETOPO1_Ice_g_gdal.grd” file which is a grid-registered netCDF file of ETOPO1 Ice Surface." }, { "code": null, "e": 1673, "s": 1546, "text": "Firstly, importing the values of latitude, longitude, and topography from the downloaded NetCDF file using the Etopo function." }, { "code": null, "e": 1974, "s": 1673, "text": "Input: longitude (lon_area) and latitude (lat_area) based on the selected area, and resolution.Output: mesh shape longitude (lon), latitude (lat) within the selected area, and topography (topo) based on resolution.* resolution has to be in degree unit and the highest resolution will be 0.0167 degree" }, { "code": null, "e": 2257, "s": 1974, "text": "To make the spherical plot using the imported longitude (lon) and latitude (lat) data, we convert these data into the spherical coordinates. The idea is not complicated. Just converting from the orthogonal coordinate to the spherical coordinate using the basic math functional form." }, { "code": null, "e": 2361, "s": 2257, "text": "How to make it in Python? See details described at Plotly Chart Studio: Heatmap plot on a spherical map" }, { "code": null, "e": 2490, "s": 2361, "text": "Here we plot the interactive Globe using the data of latitude, longitude described as the spherical coordinated, and topography." }, { "code": null, "e": 2803, "s": 2490, "text": "Firstly, we call the Etopo function defined in Step. 1 to read the array of longitude (lon_topo), latitude (lat_topo), and topography (topo) covering the whole globe. If the resolution is too high, the size of data becomes huge due to the 3-dimensional data. Here we adopt 0.8 degrees as the value of resolution." }, { "code": null, "e": 2905, "s": 2803, "text": "And then, converting to the spherical coordinates using the created function of mapping_map_to_sphere" }, { "code": null, "e": 3026, "s": 2905, "text": "We also need to define the color scale of the topography we plot. The color scale in this example is defined as follows:" }, { "code": null, "e": 3071, "s": 3026, "text": "We prepare the plot using Plotly as follows:" }, { "code": null, "e": 3137, "s": 3071, "text": "To make our plot more brilliant, the axes are removed as follows:" }, { "code": null, "e": 3253, "s": 3137, "text": "Figure title (‘3D spherical topography map’), font (‘Courier New’), and its associated settings are described here." }, { "code": null, "e": 3382, "s": 3253, "text": "Note that, black and white are selected as the background and font color, respectively, to make our globe being in the universe:" }, { "code": null, "e": 3569, "s": 3382, "text": "Finally, we create the plot and export as an HTML file.Once you create the HTML file, you can check your plot using the Web browser (Google Chrome, Safari, ...) in the local environment." }, { "code": null, "e": 3574, "s": 3569, "text": "Demo" }, { "code": null, "e": 3843, "s": 3574, "text": "In the above plot, the topography data was displayed as the color without any three-dimensional shapes. Here we create those shapes by converting xs, ys, and zs. The following code describes how to create and make the figure just like what we did in the previous plot:" }, { "code": null, "e": 3848, "s": 3843, "text": "Demo" }, { "code": null, "e": 4013, "s": 3848, "text": "2–1. Prepare the earthquake data2–2. Prepare plate boundary plot and convert coordinates2–3. Plot the earthquake distribution on the interactive globe created above" }, { "code": null, "e": 4668, "s": 4013, "text": "In this post, we download the earthquake data from the U.S. Geological Survey (USGS) website. This earthquake catalog data includes the dates, location parameters (longitude, latitude, and depth), magnitudes that describe the size of the earthquake, and so on. You can select the earthquake by filtering these parameters. I would recommend downloading only for larger magnitude events (e.g. M > 5) due to the huge numbers of earthquakes you have to handle (For a given frequency of magnitude 4.0 or larger events there will be 10 times as many magnitude 3.0 or larger quakes and 100 times as many magnitude 2.0 or larger quakes ! — Gutenberg-Richter law)" }, { "code": null, "e": 4739, "s": 4668, "text": "In this post, I downloaded the catalog based on the following options:" }, { "code": null, "e": 4795, "s": 4739, "text": "M > 5Date between 2000/1/1 to 2020/8/31Worldwide region" }, { "code": null, "e": 4801, "s": 4795, "text": "M > 5" }, { "code": null, "e": 4836, "s": 4801, "text": "Date between 2000/1/1 to 2020/8/31" }, { "code": null, "e": 4853, "s": 4836, "text": "Worldwide region" }, { "code": null, "e": 5319, "s": 4853, "text": "Here we import the earthquake data downloaded above using pandas. And then create NumPy arrays for five parameters we will use (date, longitude, latitude, depth, magnitude). Three location parameters (longitude, latitude, and depth) are used as the x, y, and z, and magnitude is used for the plot size. For the plot color, we create two cases using depth, and Timefrom_RefYears (years since 2000) which is calculated using np.datetime64 and np.timedelta64 function." }, { "code": null, "e": 5557, "s": 5319, "text": "Here we convert earthquake longitude and latitude to the spherical coordinates as described in 1–2, and create a color bar used for depth and Timefrom_RefYears. For a color bar, we adopt matplotlib color bar and convert to Plotly format." }, { "code": null, "e": 5827, "s": 5557, "text": "Firstly, we slightly change the location parameters using depth to create a three-dimensional effect for the earthquake plot. Although earthquakes occur under the ground (of course!), we plot the earthquake distribution above the interactive globe to make them visible." }, { "code": null, "e": 6171, "s": 5827, "text": "In this post, we will plot the earthquake distribution on the interactive globe created in Step 1. However, in order to make an earthquake distribution more clear, we also plot this distribution on just a simple plate boundaries map. In this step, we prepare that plate boundary map. This procedure is already clearly explained in these posts:" }, { "code": null, "e": 6244, "s": 6171, "text": "Plotly chart_studio posted by Dreamshot: https://plot.ly/~Dreamshot/9152" }, { "code": null, "e": 6345, "s": 6244, "text": "Using these new location parameters, we make the three different ways of Plotly function as follows:" }, { "code": null, "e": 6421, "s": 6345, "text": "3D earthquake distribution on the interactive globe with the color of depth" }, { "code": null, "e": 6508, "s": 6421, "text": "3D earthquake distribution on the interactive globe with the color of years since 2000" }, { "code": null, "e": 6562, "s": 6508, "text": "3D earthquake distribution on the plate boundary plot" }, { "code": null, "e": 6638, "s": 6562, "text": "The color describes earthquake depths ranging from 0 (red) to 700 km (blue)" }, { "code": null, "e": 6643, "s": 6638, "text": "Demo" }, { "code": null, "e": 6733, "s": 6643, "text": "The color describes how many years passed since 2000 from 0 year (red) to 20 years (blue)" }, { "code": null, "e": 6738, "s": 6733, "text": "Demo" }, { "code": null, "e": 6808, "s": 6738, "text": "Firstly, we create an inner black sphere to hide inside of the globe:" }, { "code": null, "e": 6882, "s": 6808, "text": "Then create the 3D plot using the plate boundary data we prepared at 2.2:" }, { "code": null, "e": 6887, "s": 6882, "text": "Demo" } ]
How to print Unicode character in C++?
To print the Unicode characters, the process is very similar to the actual printing process in C++. We can put the Unicode value with the prefix \u. Thus we can successfully print the Unicode character. Note: If the console does not support Unicode, then you cannot get the correct result. Here we have used the Linux system to solve this problem. #include <iostream> using namespace std; int main() { cout << "Character: \u092E\n"; cout << "Character: \u0938\n"; cout << "Character: \u0915\n"; } Character: म Character: म Character: म
[ { "code": null, "e": 1162, "s": 1062, "text": "To print the Unicode characters, the process is very similar to the actual printing process in C++." }, { "code": null, "e": 1265, "s": 1162, "text": "We can put the Unicode value with the prefix \\u. Thus we can successfully print the Unicode character." }, { "code": null, "e": 1410, "s": 1265, "text": "Note: If the console does not support Unicode, then you cannot get the correct result. Here we have used the Linux system to solve this problem." }, { "code": null, "e": 1568, "s": 1410, "text": "#include <iostream>\nusing namespace std;\nint main() {\n cout << \"Character: \\u092E\\n\";\n cout << \"Character: \\u0938\\n\";\n cout << \"Character: \\u0915\\n\";\n}" }, { "code": null, "e": 1607, "s": 1568, "text": "Character: म\nCharacter: म\nCharacter: म" } ]
Kth Smallest Number in Multiplication Table | Practice | GeeksforGeeks
Given three integers M, N and K. Consider a grid of M * N, where mat[i][j] = i * j (1 based index). The task is to return the Kth smallest element in the M * N multiplication table. Example 1: Input: M = 3, N = 3 K = 5 Output: 3 Explanation: The 5th smallest element is 3. Example 2: Input: M = 2, N = 3 K = 6 Output: 6 Your Task: You don't need to read input or print anything. Your task is to complete the function KthSmallest() which takes three integers as input and returns an integer as output. Expected Time Complexity: O(M * log(M * N)) Expected Auxiliary Space: O(1) Constraints: 1 <= M, N <= 3 * 104 1 <= K <= M * N +1 0ehxmsy49h3ayafg2srpmc30s5h21xtq6mdt7g472 months ago bool small(int x,int m,int n, int k){ int co=0; for(int i=1;i<=m;i++){ co+=min(x/i,n); } return co>=k; } int KthSmallest(int m, int n, int k) { //Write your code here int low=1,high=m*n; while(low<high){ int x= (low+high)/2; if(small(x,m,n,k)){ high=x;} else low=x+1; } return low; } 0 vikashkumarhindu42 months ago public int KthSmallest(int m, int n, int k) { //Write your code here int low = 1, high = m*n; while(low < high){ int mid = low + (high-low)/2; int capacity = count(mid, m,n); if(capacity >= k) high = mid; else low = mid + 1; } return low; } public int count(int mid, int n, int m){ int count = 0; for(int i =1 ; i <=m; i++){ int temp = Math.min(mid/i, n); count += temp; } return count; } } +1 amanpandey30073 months ago Median in a row wise sorted matrix. int KthSmallest(int m, int n, int k) { int low=1; int high=m*n; while(low<=high) { int mid=low+(high-low)/2; int count=0; for(int i=1;i<=m;i++) count+=min(n,mid/i); if(count>=k) { high=mid-1; } else { low=mid+1; } } return low; } 0 oox7hxhe09xezluq19rsahkk2egq06mi7bimb4ug3 months ago 136417965 0 anutiger3 months ago int l = 1; int h = m * n; while(l <= h){ if(l == h) return l; int mid = (l + h) / 2; int cnt = 0; for(int i = 1; i <= m ; i ++){ if(mid >= i * n) cnt += n; else cnt += mid / i; } if(cnt < k) l = mid + 1; else h = mid; } return l; +1 sbh698405 months ago class Solution(object): def findKthNumber(self, m, n, k): #Write your code here lo,hi = 0,m*n+1 while lo<hi: mid = (lo+hi)//2 val = 0 for i in range(m): val+=min(n,(mid//(i+1))) if val>=k: hi = mid else: lo = mid+1 return hi +2 ramussq5 months ago Java code class Solution {public int getLowerNum(int m, int n, int target){int row = m - 1, col = 0;int res = 0;while(row >= 0 && col < n){if((row + 1) * (col + 1) > target) row--;else{res += row + 1;col++;}}return res;}public int KthSmallest(int m, int n, int k) {//Write your code hereint low = 1, high = m * n;while(low <= high){int mid = low + (high - low) / 2;int count = getLowerNum(m, n, mid);if(count < k) low = mid + 1;else high = mid - 1;}return low;}} +3 udaytyagi01235 months ago int KthSmallest(int m, int n, int k) { int low=1; int high=m*n; int ans; while(low<=high) { int count=0; int mid=(low+high)/2; for(int i=1;i<=m;i++)//find the number of smaller element than mid in each row { count=count+min(mid/i,n); } if(count>=k) { high=mid-1; ans=mid; } else low=mid+1; } return ans; } +3 anshumanj955 months ago class Solution { public int KthSmallest(int m, int n, int k) { //Write your code here int low=1,high=m*n; while(low<high){ int mid=(low+high)/2; if(smaller(mid,m,n,k)) high=mid; else low=mid+1; } return low; } public boolean smaller(int num,int m,int n,int k){ int count=0; for(int i=1;i<=m;i++) count+=Math.min(num/i,n); return count>=k; } } 0 grvb15155 months ago Funny part is that Python Code TLEs, and C++ code runs (both have the same logic). 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": 410, "s": 226, "text": "Given three integers M, N and K. Consider a grid of M * N, where mat[i][j] = i * j (1 based index). The task is to return the Kth smallest element in the M * N multiplication table.\n " }, { "code": null, "e": 421, "s": 410, "text": "Example 1:" }, { "code": null, "e": 507, "s": 421, "text": "Input:\nM = 3, N = 3\nK = 5\nOutput: 3\nExplanation: \n\nThe 5th smallest element is 3. \n\n\n" }, { "code": null, "e": 518, "s": 507, "text": "Example 2:" }, { "code": null, "e": 557, "s": 518, "text": "Input:\nM = 2, N = 3\nK = 6\nOutput: 6 \n\n" }, { "code": null, "e": 742, "s": 559, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function KthSmallest() which takes three integers as input and returns an integer as output." }, { "code": null, "e": 817, "s": 742, "text": "Expected Time Complexity: O(M * log(M * N))\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 869, "s": 819, "text": "Constraints:\n1 <= M, N <= 3 * 104\n1 <= K <= M * N" }, { "code": null, "e": 872, "s": 869, "text": "+1" }, { "code": null, "e": 925, "s": 872, "text": "0ehxmsy49h3ayafg2srpmc30s5h21xtq6mdt7g472 months ago" }, { "code": null, "e": 1335, "s": 925, "text": "bool small(int x,int m,int n, int k){ int co=0; for(int i=1;i<=m;i++){ co+=min(x/i,n); } return co>=k; } int KthSmallest(int m, int n, int k) { //Write your code here int low=1,high=m*n; while(low<high){ int x= (low+high)/2; if(small(x,m,n,k)){ high=x;} else low=x+1; } return low; }" }, { "code": null, "e": 1337, "s": 1335, "text": "0" }, { "code": null, "e": 1367, "s": 1337, "text": "vikashkumarhindu42 months ago" }, { "code": null, "e": 1967, "s": 1367, "text": "public int KthSmallest(int m, int n, int k) {\n //Write your code here\n int low = 1, high = m*n;\n while(low < high){\n int mid = low + (high-low)/2;\n int capacity = count(mid, m,n);\n if(capacity >= k) high = mid;\n else \n low = mid + 1;\n \n \n }\n return low;\n }\n public int count(int mid, int n, int m){\n int count = 0;\n for(int i =1 ; i <=m; i++){\n int temp = Math.min(mid/i, n);\n count += temp;\n }\n return count;\n }\n}\n" }, { "code": null, "e": 1970, "s": 1967, "text": "+1" }, { "code": null, "e": 1997, "s": 1970, "text": "amanpandey30073 months ago" }, { "code": null, "e": 2033, "s": 1997, "text": "Median in a row wise sorted matrix." }, { "code": null, "e": 2490, "s": 2035, "text": "int KthSmallest(int m, int n, int k) { int low=1; int high=m*n; while(low<=high) { int mid=low+(high-low)/2; int count=0; for(int i=1;i<=m;i++) count+=min(n,mid/i); if(count>=k) { high=mid-1; } else { low=mid+1; } } return low; }" }, { "code": null, "e": 2492, "s": 2490, "text": "0" }, { "code": null, "e": 2545, "s": 2492, "text": "oox7hxhe09xezluq19rsahkk2egq06mi7bimb4ug3 months ago" }, { "code": null, "e": 2555, "s": 2545, "text": "136417965" }, { "code": null, "e": 2557, "s": 2555, "text": "0" }, { "code": null, "e": 2578, "s": 2557, "text": "anutiger3 months ago" }, { "code": null, "e": 2999, "s": 2578, "text": "int l = 1;\n int h = m * n;\n while(l <= h){\n if(l == h) return l;\n int mid = (l + h) / 2; \n int cnt = 0;\n for(int i = 1; i <= m ; i ++){\n if(mid >= i * n)\n cnt += n;\n else \n cnt += mid / i;\n }\n if(cnt < k) l = mid + 1;\n else h = mid;\n }\n return l;" }, { "code": null, "e": 3002, "s": 2999, "text": "+1" }, { "code": null, "e": 3023, "s": 3002, "text": "sbh698405 months ago" }, { "code": null, "e": 3392, "s": 3023, "text": "class Solution(object):\n def findKthNumber(self, m, n, k):\n #Write your code here\n lo,hi = 0,m*n+1\n while lo<hi:\n mid = (lo+hi)//2\n val = 0\n for i in range(m):\n val+=min(n,(mid//(i+1)))\n if val>=k:\n hi = mid\n else:\n lo = mid+1\n return hi" }, { "code": null, "e": 3395, "s": 3392, "text": "+2" }, { "code": null, "e": 3415, "s": 3395, "text": "ramussq5 months ago" }, { "code": null, "e": 3426, "s": 3415, "text": "Java code " }, { "code": null, "e": 3879, "s": 3426, "text": "class Solution {public int getLowerNum(int m, int n, int target){int row = m - 1, col = 0;int res = 0;while(row >= 0 && col < n){if((row + 1) * (col + 1) > target) row--;else{res += row + 1;col++;}}return res;}public int KthSmallest(int m, int n, int k) {//Write your code hereint low = 1, high = m * n;while(low <= high){int mid = low + (high - low) / 2;int count = getLowerNum(m, n, mid);if(count < k) low = mid + 1;else high = mid - 1;}return low;}}" }, { "code": null, "e": 3882, "s": 3879, "text": "+3" }, { "code": null, "e": 3908, "s": 3882, "text": "udaytyagi01235 months ago" }, { "code": null, "e": 4405, "s": 3910, "text": "int KthSmallest(int m, int n, int k) { int low=1; int high=m*n; int ans; while(low<=high) { int count=0; int mid=(low+high)/2; for(int i=1;i<=m;i++)//find the number of smaller element than mid in each row { count=count+min(mid/i,n); } if(count>=k) { high=mid-1; ans=mid; } else low=mid+1; } return ans; }" }, { "code": null, "e": 4408, "s": 4405, "text": "+3" }, { "code": null, "e": 4432, "s": 4408, "text": "anshumanj955 months ago" }, { "code": null, "e": 4939, "s": 4432, "text": "class Solution {\n public int KthSmallest(int m, int n, int k) {\n //Write your code here\n int low=1,high=m*n;\n while(low<high){\n int mid=(low+high)/2;\n if(smaller(mid,m,n,k))\n high=mid;\n else\n low=mid+1;\n }\n return low;\n }\n public boolean smaller(int num,int m,int n,int k){\n int count=0;\n for(int i=1;i<=m;i++)\n count+=Math.min(num/i,n);\n return count>=k;\n }\n \n}" }, { "code": null, "e": 4941, "s": 4939, "text": "0" }, { "code": null, "e": 4962, "s": 4941, "text": "grvb15155 months ago" }, { "code": null, "e": 5047, "s": 4962, "text": "Funny part is that Python Code TLEs, and C++ code runs (both have the same logic). " }, { "code": null, "e": 5193, "s": 5047, "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": 5229, "s": 5193, "text": " Login to access your submissions. " }, { "code": null, "e": 5239, "s": 5229, "text": "\nProblem\n" }, { "code": null, "e": 5249, "s": 5239, "text": "\nContest\n" }, { "code": null, "e": 5312, "s": 5249, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5460, "s": 5312, "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": 5668, "s": 5460, "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": 5774, "s": 5668, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Extracting webpage information with Python for non-programmers | by Elye | Towards Data Science
Knowing how to extract data from the webpage using a script is helpful. The easiest way to do so that I found is using Python, with the help of lxml library. The nicest part is, you might not need to do it in your machine. You could put your script on the Python online compiler, and you get some data. For something simple, we just need a few lines of codes in a single file, then it will do pretty cool things. Several examples below. medium.com medium.com To make learning more relevant, we’ll take the Wordometer Coronavirus webpage as our source. If you visit the page, you’ll see something similar to below. I separate the learning into 4 sections, which I called as Exercise each as below. I have provided the code script (just 70 lines) whereby copy-paste and running it (in the online compiler), you’ll see the below And select each of the numbers to execute it. This should make learning easier. All webpage is constructed using HTML. Let’s get to the most basic structure of HTML, as that’s the basic pattern we need to recognize to extract the information we need. The most basic structure I could provide is as below. All of them consist of tag that is wrap with < and >. And it usually with a compliment of it i.e. </tag> ` or it just ends with /> in the tag itself.Within the <tag> it might have one or more attribute with a name given to it. That helps to differentiate tag of the same type.Around the <tag> pair, we could have one (or more) tag that is wrapped within, which I name as <sub-tag> above. You could imaging, sub-tag could have sub-sub-tag and so on.... , which makes up the majority part of the HTML.At times, the tag could wrap a text around it, which normally form the core of the information we are looking for. All of them consist of tag that is wrap with < and >. And it usually with a compliment of it i.e. </tag> ` or it just ends with /> in the tag itself. Within the <tag> it might have one or more attribute with a name given to it. That helps to differentiate tag of the same type. Around the <tag> pair, we could have one (or more) tag that is wrapped within, which I name as <sub-tag> above. You could imaging, sub-tag could have sub-sub-tag and so on.... , which makes up the majority part of the HTML. At times, the tag could wrap a text around it, which normally form the core of the information we are looking for. That’s it! Give a pat to yourself. You have mastered HTML (and also XML) structure 🎉 Before we could extract the HTML information, we need to get our script to read the HTML first. There are 2 ways of doing so. We’re using the request library of Python. Don’t worry, that’s as simple as the line below, then it’s done. import requests After that, try getting the website content using the code below. response = requests.get(url) To be more robust, in case the url is wrong or the website is down, I add the following try: response = requests.get(url)except: print ('Sorry bad url') sys.exit(2)if response.status_code != 200: print ('Sorry invalid response ' + str(response.status_code)) sys.exit(2) If the request is loaded successfully, then you could get Html content, using the below code, and extract it into a tree. tree = html.fromstring(response.text) The reason it is called a tree because if we draw the tags relationship, they look like one. Sometimes this is needed, as some webpages require credentials to log in, and hence to access it from the script would be more complicated as you need to supply the needed credential along the way. But since you just need to extract some data from the HTML, you could save it as a .html file and get the script to read from it. After that, in your python script, you just need to Open the file and read it as a String (set of letters).Read out the HTML content to form a tree Open the file and read it as a String (set of letters). Read out the HTML content to form a tree inputFile = open(inputfile,"r") fileContent = str(inputFile.readlines())tree = html.fromstring(fileContent) 1 Extracting single tag wrap text. Just to recap, for exercise 1, we want to extract the names of the countries as shown below. If we check the HTML code for it, we’ll see the below pattern. <a class=”mt_a” href=”country/spain/”>Spain</a> To extract the Spain, we’ll just need to identify a tag that has attribute class of "mt_a". To extract, we just use xpath function for the tree. extracteditems = tree.xpath(‘//a[@class=”mt_a”]/text()’)print("\n".join(extracteditems)) We’ll get a list of the, where we separate them by a newline (i.e. "\n") and print them out. We’ll get USASpainRussiaUKItaly... and many more ... Easy! 2 Extracting tag and sub-tag wrap text. Just to recap, for exercise 2, we want to extract the population information of each country. If we check the HTML code for it, we’ll see the below pattern. <td style=”font-weight: bold; text-align:right”> <a href=”/world-population/spain-population/”>46,752,556</a> </td><td style=”font-weight: bold; text-align:right”>2,467,761</td><td style=”font-weight: bold; text-align:right”>52,783</td> We cannot capture <a href=”/world-population/spain-population/”> as the href for each country will be different. We also cannot capture <td style=”font-weight: bold; text-align:right”>, as there are a lot of other numbers as shown above (e.g. 2,467,761) that we don’t want. Hence the best is to capture <td style=”font-weight: bold; text-align:right”> that follow by <a> tag. To extract, we just use xpath function as well for the tree. extracteditems = tree.xpath( '//td[@style="font-weight: bold; text-align:right"]//a/text()')print("\n".join(extracteditems)) We’ll get a list of the, where we separate them by a newline (i.e. "\n") and print them out. 330,758,78446,752,556145,926,78167,841,32460,472,650... and many more ... Easy! 3 Extracting attrib value from a tag. Just to recap, for exercise 3, we want to extract the image URL that the website has. In HTML, the images URL store as the src attribute of the img tag. <img src="/img/alert-plus.png" style="height:16px; width:16px" /> To extract it, we first need to extract the img element first, then use a special extraction below i.e. list(map(lambda ...)) to extract each src attribute out i.e. x.attrib.get(‘src’). The x is a single item of each elements within. elements = tree.xpath(‘//img’)extracteditems = list(map(lambda x: x.attrib.get(‘src’), elements))print(“\n”.join(extracteditems)) From this, we can now get /img/worldometers-logo.gif/images/alert.png/img/alert-plus.png... and a few others ... A little complicated on the list(map(lambda ...)) but it’s an approach that extracts individual items of the elements list. 4Iterate through each tag to extract the sub-tags. Just to recap, for exercise 4, we want to extract the high-level numbers for each continent To be more specific, as we enter one of the continents, the value is as shown below, that’s what we want to extract. If we look into the HTML, each of the continents data is grouped with tr that has class attribute of "total_row_world row_continnet". <tr class="total_row_world row_continent" data-continent="Europe" style="display: none"> <td></td> <td style="text-align:left;"><nobr>Europe</nobr></td> <td>1,741,129</td> <td></td> <td>160,482</td> <td></td> <td>739,811</td> <td>840,836</td> <td>12,196</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td style="display:none;" data-continent="Europe">Europe</td></tr> Let’s extract the "total_row_world row_continnet" as sections of information. To further extract each item within each section, we create a separate function name extractElements as shown below. We send in x which is each section from the sections. sections = tree.xpath( '//tr[@class="total_row_world row_continent"]')extracteditems = list(map(lambda x: '\"' + str(extractElements(x)) + '\"', sections))print("\n".join(extracteditems)) Now in the function extractElements, we use findall to extract out all the td tag, and again use the list(map(lambda ...)) to separately extract it’s text. def extractElements(element): return list(map(lambda x: x.text, element.findall('.//td'))) The output as shown below. That’s it! To further illustrate how element.findall(‘.//td’) work, I use a for-loop to individually print out each extracted def extractElements(element): for item in element.findall('.//td'): print(' EXTRACTED: ' + str(item.text))return list(map(lambda x: x.text, element.findall('.//td'))) The output as below EXTRACTED: 1,741,129EXTRACTED: +22,456EXTRACTED: 160,482EXTRACTED: +1,414EXTRACTED: 739,811... and more ...EXTRACTED: EuropeEXTRACTED: NoneEXTRACTED: Having learned all these four ways, you now have the basic essential to explore some website of your interest and extract relevant info for your further processing. 🛠 Cheers. Thanks for reading. You can check out my other topics here. You could follow me on Medium, Twitter, Facebook, or Reddit for little tips and learning on mobile development, medium writing, etc related topics. ~Elye~
[ { "code": null, "e": 330, "s": 172, "text": "Knowing how to extract data from the webpage using a script is helpful. The easiest way to do so that I found is using Python, with the help of lxml library." }, { "code": null, "e": 475, "s": 330, "text": "The nicest part is, you might not need to do it in your machine. You could put your script on the Python online compiler, and you get some data." }, { "code": null, "e": 585, "s": 475, "text": "For something simple, we just need a few lines of codes in a single file, then it will do pretty cool things." }, { "code": null, "e": 609, "s": 585, "text": "Several examples below." }, { "code": null, "e": 620, "s": 609, "text": "medium.com" }, { "code": null, "e": 631, "s": 620, "text": "medium.com" }, { "code": null, "e": 724, "s": 631, "text": "To make learning more relevant, we’ll take the Wordometer Coronavirus webpage as our source." }, { "code": null, "e": 869, "s": 724, "text": "If you visit the page, you’ll see something similar to below. I separate the learning into 4 sections, which I called as Exercise each as below." }, { "code": null, "e": 998, "s": 869, "text": "I have provided the code script (just 70 lines) whereby copy-paste and running it (in the online compiler), you’ll see the below" }, { "code": null, "e": 1078, "s": 998, "text": "And select each of the numbers to execute it. This should make learning easier." }, { "code": null, "e": 1117, "s": 1078, "text": "All webpage is constructed using HTML." }, { "code": null, "e": 1249, "s": 1117, "text": "Let’s get to the most basic structure of HTML, as that’s the basic pattern we need to recognize to extract the information we need." }, { "code": null, "e": 1303, "s": 1249, "text": "The most basic structure I could provide is as below." }, { "code": null, "e": 1917, "s": 1303, "text": "All of them consist of tag that is wrap with < and >. And it usually with a compliment of it i.e. </tag> ` or it just ends with /> in the tag itself.Within the <tag> it might have one or more attribute with a name given to it. That helps to differentiate tag of the same type.Around the <tag> pair, we could have one (or more) tag that is wrapped within, which I name as <sub-tag> above. You could imaging, sub-tag could have sub-sub-tag and so on.... , which makes up the majority part of the HTML.At times, the tag could wrap a text around it, which normally form the core of the information we are looking for." }, { "code": null, "e": 2067, "s": 1917, "text": "All of them consist of tag that is wrap with < and >. And it usually with a compliment of it i.e. </tag> ` or it just ends with /> in the tag itself." }, { "code": null, "e": 2195, "s": 2067, "text": "Within the <tag> it might have one or more attribute with a name given to it. That helps to differentiate tag of the same type." }, { "code": null, "e": 2419, "s": 2195, "text": "Around the <tag> pair, we could have one (or more) tag that is wrapped within, which I name as <sub-tag> above. You could imaging, sub-tag could have sub-sub-tag and so on.... , which makes up the majority part of the HTML." }, { "code": null, "e": 2534, "s": 2419, "text": "At times, the tag could wrap a text around it, which normally form the core of the information we are looking for." }, { "code": null, "e": 2619, "s": 2534, "text": "That’s it! Give a pat to yourself. You have mastered HTML (and also XML) structure 🎉" }, { "code": null, "e": 2745, "s": 2619, "text": "Before we could extract the HTML information, we need to get our script to read the HTML first. There are 2 ways of doing so." }, { "code": null, "e": 2853, "s": 2745, "text": "We’re using the request library of Python. Don’t worry, that’s as simple as the line below, then it’s done." }, { "code": null, "e": 2869, "s": 2853, "text": "import requests" }, { "code": null, "e": 2935, "s": 2869, "text": "After that, try getting the website content using the code below." }, { "code": null, "e": 2964, "s": 2935, "text": "response = requests.get(url)" }, { "code": null, "e": 3052, "s": 2964, "text": "To be more robust, in case the url is wrong or the website is down, I add the following" }, { "code": null, "e": 3240, "s": 3052, "text": "try: response = requests.get(url)except: print ('Sorry bad url') sys.exit(2)if response.status_code != 200: print ('Sorry invalid response ' + str(response.status_code)) sys.exit(2)" }, { "code": null, "e": 3362, "s": 3240, "text": "If the request is loaded successfully, then you could get Html content, using the below code, and extract it into a tree." }, { "code": null, "e": 3400, "s": 3362, "text": "tree = html.fromstring(response.text)" }, { "code": null, "e": 3493, "s": 3400, "text": "The reason it is called a tree because if we draw the tags relationship, they look like one." }, { "code": null, "e": 3691, "s": 3493, "text": "Sometimes this is needed, as some webpages require credentials to log in, and hence to access it from the script would be more complicated as you need to supply the needed credential along the way." }, { "code": null, "e": 3821, "s": 3691, "text": "But since you just need to extract some data from the HTML, you could save it as a .html file and get the script to read from it." }, { "code": null, "e": 3873, "s": 3821, "text": "After that, in your python script, you just need to" }, { "code": null, "e": 3969, "s": 3873, "text": "Open the file and read it as a String (set of letters).Read out the HTML content to form a tree" }, { "code": null, "e": 4025, "s": 3969, "text": "Open the file and read it as a String (set of letters)." }, { "code": null, "e": 4066, "s": 4025, "text": "Read out the HTML content to form a tree" }, { "code": null, "e": 4174, "s": 4066, "text": "inputFile = open(inputfile,\"r\") fileContent = str(inputFile.readlines())tree = html.fromstring(fileContent)" }, { "code": null, "e": 4302, "s": 4174, "text": "1 Extracting single tag wrap text. Just to recap, for exercise 1, we want to extract the names of the countries as shown below." }, { "code": null, "e": 4365, "s": 4302, "text": "If we check the HTML code for it, we’ll see the below pattern." }, { "code": null, "e": 4413, "s": 4365, "text": "<a class=”mt_a” href=”country/spain/”>Spain</a>" }, { "code": null, "e": 4505, "s": 4413, "text": "To extract the Spain, we’ll just need to identify a tag that has attribute class of \"mt_a\"." }, { "code": null, "e": 4558, "s": 4505, "text": "To extract, we just use xpath function for the tree." }, { "code": null, "e": 4647, "s": 4558, "text": "extracteditems = tree.xpath(‘//a[@class=”mt_a”]/text()’)print(\"\\n\".join(extracteditems))" }, { "code": null, "e": 4740, "s": 4647, "text": "We’ll get a list of the, where we separate them by a newline (i.e. \"\\n\") and print them out." }, { "code": null, "e": 4750, "s": 4740, "text": "We’ll get" }, { "code": null, "e": 4793, "s": 4750, "text": "USASpainRussiaUKItaly... and many more ..." }, { "code": null, "e": 4799, "s": 4793, "text": "Easy!" }, { "code": null, "e": 4933, "s": 4799, "text": "2 Extracting tag and sub-tag wrap text. Just to recap, for exercise 2, we want to extract the population information of each country." }, { "code": null, "e": 4996, "s": 4933, "text": "If we check the HTML code for it, we’ll see the below pattern." }, { "code": null, "e": 5235, "s": 4996, "text": "<td style=”font-weight: bold; text-align:right”> <a href=”/world-population/spain-population/”>46,752,556</a> </td><td style=”font-weight: bold; text-align:right”>2,467,761</td><td style=”font-weight: bold; text-align:right”>52,783</td>" }, { "code": null, "e": 5348, "s": 5235, "text": "We cannot capture <a href=”/world-population/spain-population/”> as the href for each country will be different." }, { "code": null, "e": 5509, "s": 5348, "text": "We also cannot capture <td style=”font-weight: bold; text-align:right”>, as there are a lot of other numbers as shown above (e.g. 2,467,761) that we don’t want." }, { "code": null, "e": 5611, "s": 5509, "text": "Hence the best is to capture <td style=”font-weight: bold; text-align:right”> that follow by <a> tag." }, { "code": null, "e": 5672, "s": 5611, "text": "To extract, we just use xpath function as well for the tree." }, { "code": null, "e": 5800, "s": 5672, "text": "extracteditems = tree.xpath( '//td[@style=\"font-weight: bold; text-align:right\"]//a/text()')print(\"\\n\".join(extracteditems))" }, { "code": null, "e": 5893, "s": 5800, "text": "We’ll get a list of the, where we separate them by a newline (i.e. \"\\n\") and print them out." }, { "code": null, "e": 5967, "s": 5893, "text": "330,758,78446,752,556145,926,78167,841,32460,472,650... and many more ..." }, { "code": null, "e": 5973, "s": 5967, "text": "Easy!" }, { "code": null, "e": 6097, "s": 5973, "text": "3 Extracting attrib value from a tag. Just to recap, for exercise 3, we want to extract the image URL that the website has." }, { "code": null, "e": 6164, "s": 6097, "text": "In HTML, the images URL store as the src attribute of the img tag." }, { "code": null, "e": 6230, "s": 6164, "text": "<img src=\"/img/alert-plus.png\" style=\"height:16px; width:16px\" />" }, { "code": null, "e": 6416, "s": 6230, "text": "To extract it, we first need to extract the img element first, then use a special extraction below i.e. list(map(lambda ...)) to extract each src attribute out i.e. x.attrib.get(‘src’)." }, { "code": null, "e": 6464, "s": 6416, "text": "The x is a single item of each elements within." }, { "code": null, "e": 6594, "s": 6464, "text": "elements = tree.xpath(‘//img’)extracteditems = list(map(lambda x: x.attrib.get(‘src’), elements))print(“\\n”.join(extracteditems))" }, { "code": null, "e": 6620, "s": 6594, "text": "From this, we can now get" }, { "code": null, "e": 6707, "s": 6620, "text": "/img/worldometers-logo.gif/images/alert.png/img/alert-plus.png... and a few others ..." }, { "code": null, "e": 6831, "s": 6707, "text": "A little complicated on the list(map(lambda ...)) but it’s an approach that extracts individual items of the elements list." }, { "code": null, "e": 6974, "s": 6831, "text": "4Iterate through each tag to extract the sub-tags. Just to recap, for exercise 4, we want to extract the high-level numbers for each continent" }, { "code": null, "e": 7091, "s": 6974, "text": "To be more specific, as we enter one of the continents, the value is as shown below, that’s what we want to extract." }, { "code": null, "e": 7225, "s": 7091, "text": "If we look into the HTML, each of the continents data is grouped with tr that has class attribute of \"total_row_world row_continnet\"." }, { "code": null, "e": 7620, "s": 7225, "text": "<tr class=\"total_row_world row_continent\" data-continent=\"Europe\" style=\"display: none\"> <td></td> <td style=\"text-align:left;\"><nobr>Europe</nobr></td> <td>1,741,129</td> <td></td> <td>160,482</td> <td></td> <td>739,811</td> <td>840,836</td> <td>12,196</td> <td></td> <td></td> <td></td> <td></td> <td></td> <td style=\"display:none;\" data-continent=\"Europe\">Europe</td></tr>" }, { "code": null, "e": 7698, "s": 7620, "text": "Let’s extract the \"total_row_world row_continnet\" as sections of information." }, { "code": null, "e": 7869, "s": 7698, "text": "To further extract each item within each section, we create a separate function name extractElements as shown below. We send in x which is each section from the sections." }, { "code": null, "e": 8064, "s": 7869, "text": "sections = tree.xpath( '//tr[@class=\"total_row_world row_continent\"]')extracteditems = list(map(lambda x: '\\\"' + str(extractElements(x)) + '\\\"', sections))print(\"\\n\".join(extracteditems))" }, { "code": null, "e": 8220, "s": 8064, "text": "Now in the function extractElements, we use findall to extract out all the td tag, and again use the list(map(lambda ...)) to separately extract it’s text." }, { "code": null, "e": 8314, "s": 8220, "text": "def extractElements(element): return list(map(lambda x: x.text, element.findall('.//td')))" }, { "code": null, "e": 8341, "s": 8314, "text": "The output as shown below." }, { "code": null, "e": 8352, "s": 8341, "text": "That’s it!" }, { "code": null, "e": 8467, "s": 8352, "text": "To further illustrate how element.findall(‘.//td’) work, I use a for-loop to individually print out each extracted" }, { "code": null, "e": 8639, "s": 8467, "text": "def extractElements(element): for item in element.findall('.//td'): print(' EXTRACTED: ' + str(item.text))return list(map(lambda x: x.text, element.findall('.//td')))" }, { "code": null, "e": 8659, "s": 8639, "text": "The output as below" }, { "code": null, "e": 8809, "s": 8659, "text": "EXTRACTED: 1,741,129EXTRACTED: +22,456EXTRACTED: 160,482EXTRACTED: +1,414EXTRACTED: 739,811... and more ...EXTRACTED: EuropeEXTRACTED: NoneEXTRACTED:" }, { "code": null, "e": 8976, "s": 8809, "text": "Having learned all these four ways, you now have the basic essential to explore some website of your interest and extract relevant info for your further processing. 🛠" }, { "code": null, "e": 8984, "s": 8976, "text": "Cheers." }, { "code": null, "e": 9044, "s": 8984, "text": "Thanks for reading. You can check out my other topics here." } ]
Learning SQL the Hard Way. By writing it | by Rahul Agarwal | Towards Data Science
A Data Scientist who doesn’t know SQL is not worth his salt. And that seems correct to me in every sense of the world. While we feel much more accomplished creating models and coming up with the different hypotheses, the role of data munging can’t be understated. And with the ubiquitousness of SQL when it comes to ETL and data preparation tasks, everyone should know a little bit of it to at least be useful. I still remember the first time I got my hands on SQL. It was the first language (if you can call it that) I learned. And it made an impact on me. I was able to automate things, and that was something I hadn’t thought of before. Before SQL, I used to work with Excel — VLOOKUPs and pivots. I was creating reporting systems, doing the same work again and again. SQL made it all go away. Now I could write a big script, and everything would be automated — all the crosstabs and analysis generated on the fly. That is the power of SQL. And though you could do anything that you do with SQL using Pandas, you still need to learn SQL to deal with systems like HIVE, Teradata and sometimes Spark too. This post is about installing SQL, explaining SQL and running SQL. Now the best way to learn SQL is to get your hands dirty with it(Same I can say for any other thing you want to learn) I will advise against using the web-based recipes like w3schools/tutorialspoint for SQL since you cannot use your data with those. Also, I will advise you to go with learning the MySQL flavour of SQL as it is Open Source, easy to set up in your laptop and has a great client named MySQL Workbench to make your life easier. As we have gotten these points out of the way, here is a step by step to get set up with MySQL: You can download MySQL for your particular system (MACOSX, Linux, Windows) from Download MySQL Community Server. In my case, I downloaded the DMG Archive. After that, double click and install the file. You might need to set up a password. Remember this password as it would be required to connect to the MySQL instance later. Create a file named my.cnf and put the following in it. This is needed to give Local file read permissions to your SQL database. [client]port= 3306[mysqld]port= 3306secure_file_priv=''local-infile=1 Open up System Preferences>MySQL. Go to Configuration and browse to the my.cnf file using the select button. Restart the server from Instances tab by clicking stop and start. Once you get that server running, download and install the MySQL Workbench: Download MySQL Workbench. The workbench gives you an editor to write your SQL Queries and get the results in a structured way. Open up the MySQL workbench now and connect to SQL through it. You will see something like below. You can see that the Local Instance connection has been set up for you beforehand. Now, you just need to click on that connection and get started using the password that we set up before for the MySQL server(You can also create a connection to an existing SQL server that might not be on your machine if you have the address, port number, username and password). And you get an editor to write your queries on the particular database. Check the Schemas tab on the top left to see the tables that are present. There is just a sys schema present with the table sys_config. Not an interesting data source to learn SQL. So let’s install some data to practice. If you have your own data to work. Then good and fine. You can create a new schema(database) and upload it into tables using these following commands. (You can run the commands by using Cmd+Enter or by clicking the ⚡️lightning button) In this tutorial, however, I am going to use the Sakila Movie database which you can install using the following steps: Go to MySQL Documentation and download the Sakila ZIP file. Unzip the file. Now go to MySQL Workbench and select File>Run SQL Script>select location sakila-db/sakila-schema.sql Go to MySQL Workbench and select File >Run SQL Script >select location sakila-db/sakila-data.sql Once you do that, you will see a new database added in the SCHEMA list. Now we have some data with us. Finally. Let’s start with writing some queries. You can try to understand the Schema of the Sakila Database in detail using the Sakila Sample Database document. Now the basic syntax of any SQL query is: SELECT col1, SUM(col2) as col2sum, AVG(col3) as col3avg FROM table_name WHERE col4 = 'some_value' GROUP BY col1 ORDER BY col2sum DESC; There are four elements in this query: SELECT: Which Columns to select? Here we choose col1 and do SUM aggregation on col2 and AVG aggregation on col3. We also give a new name to SUM(col2) by using the as keyword. This is known as aliasing.FROM: From which table should we SELECT?WHERE: We can filter data using WHERE statements.GROUP BY: All selected columns that are not in aggregation should be in GROUP BY.ORDER BY: Sort on col2sum SELECT: Which Columns to select? Here we choose col1 and do SUM aggregation on col2 and AVG aggregation on col3. We also give a new name to SUM(col2) by using the as keyword. This is known as aliasing. FROM: From which table should we SELECT? WHERE: We can filter data using WHERE statements. GROUP BY: All selected columns that are not in aggregation should be in GROUP BY. ORDER BY: Sort on col2sum The above query will help you with most of the simple things you want to find in a database. For example, we can find out how differently censored rated movies are timed differently using: SELECT rating, avg(length) as length_avg FROM sakila.film GROUP BY rating ORDER BY length_avg desc; You should now come up with some questions of your own. For Example, you can try to find out all the movies released in the year 2006. Or try to find all of the movies which have a rating of PG and length greater than 50 minutes. You can do this by running the following on MySQL Workbench: SELECT * FROM sakila.film WHERE release_year = 2006; SELECT * FROM sakila.film WHERE length>50 and rating="PG"; Till now, we have learned how we can work with single tables. But in reality, we need to work with multiple tables. So, the next thing we would want to learn is how to do joins. Now joins are an integral and an essential part of a MySQL Database and understanding them is necessary. The below visual talks about most of the joins that exist in SQL. I usually end up using just the LEFT JOIN, and INNER JOIN, so I will start with LEFT JOIN. The LEFT JOIN is used when you want to keep all the records in the left table(A) and merge B on the matching records. The records of A where B is not merged are kept as NULL in the resulting table. The MySQL Syntax is: SELECT A.col1, A.col2, B.col3, B.col4 FROM A LEFT JOIN B ON A.col2=B.col3 Here we select col1 and col2 from table A and col3 and col4 from table B. We also specify which common columns to join on using the ON statement. The INNER JOIN is used when you want to merge A and B and only to keep the common records in A and B. To give you a use case lets go back to our Sakila database. Suppose we wanted to find out how many copies of each movie we do have in our inventory. You can get that by using: SELECT film_id,count(film_id) as num_copies FROM sakila.inventory GROUP BY film_id ORDER BY num_copies DESC; Does this result look interesting? Not really. IDs don’t make sense to us humans, and if we can get the names of the movies, we would be able to process the information better. So we snoop around and see that the table film has got film_id as well as the title of the film. So we have all the data, but how do we get it in a single view? Come Joins to the rescue. We need to add the title to our inventory table information. We can do this using — SELECT A.*, B.title FROM sakila.inventory A LEFT JOIN sakila.film B ON A.film_id = B.film_id This will add another column to your inventory table information. As you might notice some films are in the film table that we don’t have in the inventory. We used a left join since we wanted to keep whatever is in the inventory table and join it with its corresponding counterpart in the film table and not everything in the film table. So now we have got the title as another field in the data. This is just what we wanted, but we haven’t solved the whole puzzle yet. We want title and num_copies of the title in the inventory. But before we can go any further, we should understand the concept of inner queries first. Now you have a query that can give you the above result. One thing you can do is create a new table using CREATE TABLE sakila.temp_table as SELECT A.*, B.title FROM sakila.inventory A LEFT JOIN sakila.film B ON A.film_id = B.film_id; And then use a simple group by operation using: SELECT title, count(title) as num_copies FROM sakila.temp_table GROUP BY title ORDER BY num_copies desc; But this is one step too many. And we have to create a temporary table that ends up taking space on the system. SQL provides us with the concept of the inner query just for these sort of issues. You can instead write all this in a single query using: SELECT temp.title, count(temp.title) as num_copies FROM (SELECT A.*, B.title FROM sakila.inventory A LEFT JOIN sakila.film B ON A.film_id = B.film_id) temp GROUP BY title ORDER BY num_copies DESC; What we did here was sandwich our first query in parenthesis and gave that table an alias temp. We then did the group by operations considering temp just as we would consider any table. It is because of the inner query concept that we can write SQL queries that span multiple pages at some times. HAVING is yet another SQL construct that is useful to understand. So we have got the results, and now we want to get the films whose number of copies are less than or equal to 2. We can do this by using the inner query concept and the WHERE clause. Here we nest one inner query inside another. Pretty neat. Or, we can use the HAVING Clause. The HAVING clause is used to filter on the final aggregated result. It is different from WHERE as where is used to filter the table that is used in the FROM statement. HAVING filters the final result after the GROUP BY happens. There are a lot of ways to do the same thing with SQL as you have already seen in the above example. We need to try to come up with the least verbose and thus HAVING makes sense in many cases. If you can follow this far, you already know more SQL than most people. Next thing to do: Practice. Try to come up with your questions on your dataset and try to find out the answers you have using SQL. Some questions I could provide for a start: Which Actor has the most distinct films in our inventory?Which Genre films are the most rented in our inventory? Which Actor has the most distinct films in our inventory? Which Genre films are the most rented in our inventory? This was just a simple tutorial on how to use SQL. If you want to learn more about SQL, I would like to call out an excellent course on SQL for Data Science from the University of California. Do check it out as it talks about other SQL concepts like UNION, String Manipulation, functions, Date Handling, etc. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz. Also, a small disclaimer — There might be some affiliate links in this post to relevant resources, as sharing knowledge is never a bad idea.
[ { "code": null, "e": 232, "s": 171, "text": "A Data Scientist who doesn’t know SQL is not worth his salt." }, { "code": null, "e": 435, "s": 232, "text": "And that seems correct to me in every sense of the world. While we feel much more accomplished creating models and coming up with the different hypotheses, the role of data munging can’t be understated." }, { "code": null, "e": 582, "s": 435, "text": "And with the ubiquitousness of SQL when it comes to ETL and data preparation tasks, everyone should know a little bit of it to at least be useful." }, { "code": null, "e": 811, "s": 582, "text": "I still remember the first time I got my hands on SQL. It was the first language (if you can call it that) I learned. And it made an impact on me. I was able to automate things, and that was something I hadn’t thought of before." }, { "code": null, "e": 1089, "s": 811, "text": "Before SQL, I used to work with Excel — VLOOKUPs and pivots. I was creating reporting systems, doing the same work again and again. SQL made it all go away. Now I could write a big script, and everything would be automated — all the crosstabs and analysis generated on the fly." }, { "code": null, "e": 1277, "s": 1089, "text": "That is the power of SQL. And though you could do anything that you do with SQL using Pandas, you still need to learn SQL to deal with systems like HIVE, Teradata and sometimes Spark too." }, { "code": null, "e": 1344, "s": 1277, "text": "This post is about installing SQL, explaining SQL and running SQL." }, { "code": null, "e": 1463, "s": 1344, "text": "Now the best way to learn SQL is to get your hands dirty with it(Same I can say for any other thing you want to learn)" }, { "code": null, "e": 1594, "s": 1463, "text": "I will advise against using the web-based recipes like w3schools/tutorialspoint for SQL since you cannot use your data with those." }, { "code": null, "e": 1786, "s": 1594, "text": "Also, I will advise you to go with learning the MySQL flavour of SQL as it is Open Source, easy to set up in your laptop and has a great client named MySQL Workbench to make your life easier." }, { "code": null, "e": 1882, "s": 1786, "text": "As we have gotten these points out of the way, here is a step by step to get set up with MySQL:" }, { "code": null, "e": 2208, "s": 1882, "text": "You can download MySQL for your particular system (MACOSX, Linux, Windows) from Download MySQL Community Server. In my case, I downloaded the DMG Archive. After that, double click and install the file. You might need to set up a password. Remember this password as it would be required to connect to the MySQL instance later." }, { "code": null, "e": 2337, "s": 2208, "text": "Create a file named my.cnf and put the following in it. This is needed to give Local file read permissions to your SQL database." }, { "code": null, "e": 2407, "s": 2337, "text": "[client]port= 3306[mysqld]port= 3306secure_file_priv=''local-infile=1" }, { "code": null, "e": 2516, "s": 2407, "text": "Open up System Preferences>MySQL. Go to Configuration and browse to the my.cnf file using the select button." }, { "code": null, "e": 2582, "s": 2516, "text": "Restart the server from Instances tab by clicking stop and start." }, { "code": null, "e": 2785, "s": 2582, "text": "Once you get that server running, download and install the MySQL Workbench: Download MySQL Workbench. The workbench gives you an editor to write your SQL Queries and get the results in a structured way." }, { "code": null, "e": 2883, "s": 2785, "text": "Open up the MySQL workbench now and connect to SQL through it. You will see something like below." }, { "code": null, "e": 3246, "s": 2883, "text": "You can see that the Local Instance connection has been set up for you beforehand. Now, you just need to click on that connection and get started using the password that we set up before for the MySQL server(You can also create a connection to an existing SQL server that might not be on your machine if you have the address, port number, username and password)." }, { "code": null, "e": 3318, "s": 3246, "text": "And you get an editor to write your queries on the particular database." }, { "code": null, "e": 3539, "s": 3318, "text": "Check the Schemas tab on the top left to see the tables that are present. There is just a sys schema present with the table sys_config. Not an interesting data source to learn SQL. So let’s install some data to practice." }, { "code": null, "e": 3774, "s": 3539, "text": "If you have your own data to work. Then good and fine. You can create a new schema(database) and upload it into tables using these following commands. (You can run the commands by using Cmd+Enter or by clicking the ⚡️lightning button)" }, { "code": null, "e": 3894, "s": 3774, "text": "In this tutorial, however, I am going to use the Sakila Movie database which you can install using the following steps:" }, { "code": null, "e": 3954, "s": 3894, "text": "Go to MySQL Documentation and download the Sakila ZIP file." }, { "code": null, "e": 3970, "s": 3954, "text": "Unzip the file." }, { "code": null, "e": 4071, "s": 3970, "text": "Now go to MySQL Workbench and select File>Run SQL Script>select location sakila-db/sakila-schema.sql" }, { "code": null, "e": 4168, "s": 4071, "text": "Go to MySQL Workbench and select File >Run SQL Script >select location sakila-db/sakila-data.sql" }, { "code": null, "e": 4240, "s": 4168, "text": "Once you do that, you will see a new database added in the SCHEMA list." }, { "code": null, "e": 4280, "s": 4240, "text": "Now we have some data with us. Finally." }, { "code": null, "e": 4319, "s": 4280, "text": "Let’s start with writing some queries." }, { "code": null, "e": 4432, "s": 4319, "text": "You can try to understand the Schema of the Sakila Database in detail using the Sakila Sample Database document." }, { "code": null, "e": 4474, "s": 4432, "text": "Now the basic syntax of any SQL query is:" }, { "code": null, "e": 4609, "s": 4474, "text": "SELECT col1, SUM(col2) as col2sum, AVG(col3) as col3avg FROM table_name WHERE col4 = 'some_value' GROUP BY col1 ORDER BY col2sum DESC;" }, { "code": null, "e": 4648, "s": 4609, "text": "There are four elements in this query:" }, { "code": null, "e": 5045, "s": 4648, "text": "SELECT: Which Columns to select? Here we choose col1 and do SUM aggregation on col2 and AVG aggregation on col3. We also give a new name to SUM(col2) by using the as keyword. This is known as aliasing.FROM: From which table should we SELECT?WHERE: We can filter data using WHERE statements.GROUP BY: All selected columns that are not in aggregation should be in GROUP BY.ORDER BY: Sort on col2sum" }, { "code": null, "e": 5247, "s": 5045, "text": "SELECT: Which Columns to select? Here we choose col1 and do SUM aggregation on col2 and AVG aggregation on col3. We also give a new name to SUM(col2) by using the as keyword. This is known as aliasing." }, { "code": null, "e": 5288, "s": 5247, "text": "FROM: From which table should we SELECT?" }, { "code": null, "e": 5338, "s": 5288, "text": "WHERE: We can filter data using WHERE statements." }, { "code": null, "e": 5420, "s": 5338, "text": "GROUP BY: All selected columns that are not in aggregation should be in GROUP BY." }, { "code": null, "e": 5446, "s": 5420, "text": "ORDER BY: Sort on col2sum" }, { "code": null, "e": 5539, "s": 5446, "text": "The above query will help you with most of the simple things you want to find in a database." }, { "code": null, "e": 5635, "s": 5539, "text": "For example, we can find out how differently censored rated movies are timed differently using:" }, { "code": null, "e": 5735, "s": 5635, "text": "SELECT rating, avg(length) as length_avg FROM sakila.film GROUP BY rating ORDER BY length_avg desc;" }, { "code": null, "e": 5791, "s": 5735, "text": "You should now come up with some questions of your own." }, { "code": null, "e": 5965, "s": 5791, "text": "For Example, you can try to find out all the movies released in the year 2006. Or try to find all of the movies which have a rating of PG and length greater than 50 minutes." }, { "code": null, "e": 6026, "s": 5965, "text": "You can do this by running the following on MySQL Workbench:" }, { "code": null, "e": 6138, "s": 6026, "text": "SELECT * FROM sakila.film WHERE release_year = 2006; SELECT * FROM sakila.film WHERE length>50 and rating=\"PG\";" }, { "code": null, "e": 6254, "s": 6138, "text": "Till now, we have learned how we can work with single tables. But in reality, we need to work with multiple tables." }, { "code": null, "e": 6316, "s": 6254, "text": "So, the next thing we would want to learn is how to do joins." }, { "code": null, "e": 6578, "s": 6316, "text": "Now joins are an integral and an essential part of a MySQL Database and understanding them is necessary. The below visual talks about most of the joins that exist in SQL. I usually end up using just the LEFT JOIN, and INNER JOIN, so I will start with LEFT JOIN." }, { "code": null, "e": 6797, "s": 6578, "text": "The LEFT JOIN is used when you want to keep all the records in the left table(A) and merge B on the matching records. The records of A where B is not merged are kept as NULL in the resulting table. The MySQL Syntax is:" }, { "code": null, "e": 6871, "s": 6797, "text": "SELECT A.col1, A.col2, B.col3, B.col4 FROM A LEFT JOIN B ON A.col2=B.col3" }, { "code": null, "e": 7017, "s": 6871, "text": "Here we select col1 and col2 from table A and col3 and col4 from table B. We also specify which common columns to join on using the ON statement." }, { "code": null, "e": 7119, "s": 7017, "text": "The INNER JOIN is used when you want to merge A and B and only to keep the common records in A and B." }, { "code": null, "e": 7295, "s": 7119, "text": "To give you a use case lets go back to our Sakila database. Suppose we wanted to find out how many copies of each movie we do have in our inventory. You can get that by using:" }, { "code": null, "e": 7404, "s": 7295, "text": "SELECT film_id,count(film_id) as num_copies FROM sakila.inventory GROUP BY film_id ORDER BY num_copies DESC;" }, { "code": null, "e": 7678, "s": 7404, "text": "Does this result look interesting? Not really. IDs don’t make sense to us humans, and if we can get the names of the movies, we would be able to process the information better. So we snoop around and see that the table film has got film_id as well as the title of the film." }, { "code": null, "e": 7742, "s": 7678, "text": "So we have all the data, but how do we get it in a single view?" }, { "code": null, "e": 7852, "s": 7742, "text": "Come Joins to the rescue. We need to add the title to our inventory table information. We can do this using —" }, { "code": null, "e": 7945, "s": 7852, "text": "SELECT A.*, B.title FROM sakila.inventory A LEFT JOIN sakila.film B ON A.film_id = B.film_id" }, { "code": null, "e": 8283, "s": 7945, "text": "This will add another column to your inventory table information. As you might notice some films are in the film table that we don’t have in the inventory. We used a left join since we wanted to keep whatever is in the inventory table and join it with its corresponding counterpart in the film table and not everything in the film table." }, { "code": null, "e": 8475, "s": 8283, "text": "So now we have got the title as another field in the data. This is just what we wanted, but we haven’t solved the whole puzzle yet. We want title and num_copies of the title in the inventory." }, { "code": null, "e": 8566, "s": 8475, "text": "But before we can go any further, we should understand the concept of inner queries first." }, { "code": null, "e": 8672, "s": 8566, "text": "Now you have a query that can give you the above result. One thing you can do is create a new table using" }, { "code": null, "e": 8800, "s": 8672, "text": "CREATE TABLE sakila.temp_table as SELECT A.*, B.title FROM sakila.inventory A LEFT JOIN sakila.film B ON A.film_id = B.film_id;" }, { "code": null, "e": 8848, "s": 8800, "text": "And then use a simple group by operation using:" }, { "code": null, "e": 8953, "s": 8848, "text": "SELECT title, count(title) as num_copies FROM sakila.temp_table GROUP BY title ORDER BY num_copies desc;" }, { "code": null, "e": 9065, "s": 8953, "text": "But this is one step too many. And we have to create a temporary table that ends up taking space on the system." }, { "code": null, "e": 9204, "s": 9065, "text": "SQL provides us with the concept of the inner query just for these sort of issues. You can instead write all this in a single query using:" }, { "code": null, "e": 9401, "s": 9204, "text": "SELECT temp.title, count(temp.title) as num_copies FROM (SELECT A.*, B.title FROM sakila.inventory A LEFT JOIN sakila.film B ON A.film_id = B.film_id) temp GROUP BY title ORDER BY num_copies DESC;" }, { "code": null, "e": 9698, "s": 9401, "text": "What we did here was sandwich our first query in parenthesis and gave that table an alias temp. We then did the group by operations considering temp just as we would consider any table. It is because of the inner query concept that we can write SQL queries that span multiple pages at some times." }, { "code": null, "e": 9877, "s": 9698, "text": "HAVING is yet another SQL construct that is useful to understand. So we have got the results, and now we want to get the films whose number of copies are less than or equal to 2." }, { "code": null, "e": 10005, "s": 9877, "text": "We can do this by using the inner query concept and the WHERE clause. Here we nest one inner query inside another. Pretty neat." }, { "code": null, "e": 10039, "s": 10005, "text": "Or, we can use the HAVING Clause." }, { "code": null, "e": 10267, "s": 10039, "text": "The HAVING clause is used to filter on the final aggregated result. It is different from WHERE as where is used to filter the table that is used in the FROM statement. HAVING filters the final result after the GROUP BY happens." }, { "code": null, "e": 10460, "s": 10267, "text": "There are a lot of ways to do the same thing with SQL as you have already seen in the above example. We need to try to come up with the least verbose and thus HAVING makes sense in many cases." }, { "code": null, "e": 10532, "s": 10460, "text": "If you can follow this far, you already know more SQL than most people." }, { "code": null, "e": 10560, "s": 10532, "text": "Next thing to do: Practice." }, { "code": null, "e": 10663, "s": 10560, "text": "Try to come up with your questions on your dataset and try to find out the answers you have using SQL." }, { "code": null, "e": 10707, "s": 10663, "text": "Some questions I could provide for a start:" }, { "code": null, "e": 10820, "s": 10707, "text": "Which Actor has the most distinct films in our inventory?Which Genre films are the most rented in our inventory?" }, { "code": null, "e": 10878, "s": 10820, "text": "Which Actor has the most distinct films in our inventory?" }, { "code": null, "e": 10934, "s": 10878, "text": "Which Genre films are the most rented in our inventory?" }, { "code": null, "e": 11243, "s": 10934, "text": "This was just a simple tutorial on how to use SQL. If you want to learn more about SQL, I would like to call out an excellent course on SQL for Data Science from the University of California. Do check it out as it talks about other SQL concepts like UNION, String Manipulation, functions, Date Handling, etc." }, { "code": null, "e": 11486, "s": 11243, "text": "I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz." } ]
UMAP Dimensionality Reduction - An Incredibly Robust Machine Learning Algorithm | by Saul Dobilas | Towards Data Science
Dimensionality reduction is not just for data visualization. It can also help you overcome the “curse of dimensionality” by identifying critical structures in the high-dimensional space and preserving them in the lower-dimensional embedding. This article will take you through the inner workings of an increasingly popular dimensionality reduction technique called Uniform Manifold Approximation and Projection (UMAP) and provide you with a Python example that can be used as a guide when working on your Data Science projects. UMAP’s place in the universe of Machine Learning algorithms An intuitive explanation of how UMAP works An example of using UMAP in Python The below sunburst chart is my attempt to categorize the most commonly used Machine Learning algorithms. I have created it to satisfy the need of Data Scientists like you and me to have a more structured and visual way of identifying how various algorithms fit together. This particular view of the Machine Learning universe enables us to see similarities and differences between algorithms, serving as a quick guide when looking for a suitable solution for a specific project. The graph is interactive so make sure to click👇 on different categories to enlarge and reveal more. If you enjoy Data Science and Machine Learning, please subscribe to get an email whenever I publish a new story. While UMAP is most commonly used for unsupervised learning, it can also perform supervised dimensionality reduction. You will find an example of that in the Python section at the end of this article. Let’s start by dissecting the UMAP name, which will give us a broad idea of what the algorithm is supposed to do. Note, the below statements are not official definitions but rather a set of descriptions that will help us understand key ideas behind UMAP. Projection — the process or technique of reproducing a spatial object upon a plane, a curved surface, or a line by projecting its points. You can also think of it as a mapping of an object from high-dimensional to low-dimensional space. Approximation — the algorithm assumes that we only have a finite set of data samples (points), not the entire set that makes up the manifold. Hence, we need to approximate the manifold based on the data available. Manifold — a manifold is a topological space that locally resembles Euclidean space near each point. One-dimensional manifolds include lines and circles, but not figure eights. Two-dimensional manifolds (a.k.a. surfaces) include planes, spheres, torus, and more. Uniform — the uniformity assumption tells us that our data samples are uniformly (evenly) distributed across the manifold. In the real world, however, this is rarely the case. Hence, this assumption leads to the notion that the distance varies across the manifold. i.e., the space itself is warping: stretching or shrinking according to where the data appear sparser or denser. Putting the above statements together, we can describe UMAP as: A dimensionality reduction technique that assumes the available data samples are evenly (uniformly) distributed across a topological space (manifold), which can be approximated from these finite data samples and mapped (projected) to a lower-dimensional space. The above description of the algorithm may help a little, but it is still vague on how UMAP does its magic. So, to answer the “how” question, let’s analyze the individual steps that UMAP performs. We can split UMAP into two major steps: learning the manifold structure in the high-dimensional space;finding a low-dimensional representation of said manifold. learning the manifold structure in the high-dimensional space; finding a low-dimensional representation of said manifold. We will, however, break this down into even smaller components to make our understanding of the algorithm deeper. The below map shows the order that we will go through in analyzing each piece. It will come as no surprise, but before we can map our data to lower dimensions, we first need to figure out what it looks like in the higher-dimensional space. 1.1. Finding nearest neighborsUMAP starts by finding the nearest neighbors using the Nearest-Neighbor-Descent algorithm of Dong et al. You will see in the Python section later on that we can specify how many nearest neighbors we want to use by adjusting UMAP’s n_neighbors hyperparameter. It is important to experiment with the number of n_neighbors because it controls how UMAP balances local versus global structure in the data. It does it by constraining the size of the local neighborhood when attempting to learn the manifold structure. Essentially, a small value for n_neighbors means that we want a very local interpretation that accurately captures the fine detail of the structure. In contrast, a large n_neighbors value means that our estimates will be based on larger regions, thus more broadly accurate across the manifold as a whole. 1.2. Constructing a graph Next, UMAP needs to construct a graph by connecting the previously identified nearest neighbors. To understand this process, we need to look at a few sub-components that explain how the neighborhood graph comes to be. 1.2.1. Varying distanceAs outlined in the analysis of the UMAP’s name, we assume a uniform distribution of points across the manifold, suggesting that space between them is stretching or shrinking according to where the data appears to be sparser or denser. It essentially means that the distance metric is not universal across the whole space, and instead, it varies between different regions. We can visualize it by drawing circles/spheres around each data point, which appear to be different in size because of the varying distance metric (see illustration below). 1.2.2. Local connectivityNext, we want to ensure that the manifold structure we are trying to learn does not result in many unconnected points. Luckily, we can use another hyperparameter called local_connectivity (default value = 1) to solve this potential problem. When we set local_connectivity=1, we tell the algorithm that every point in the higher-dimensional space is connected to at least one other point. You can see in the above illustration how each solid circle touches at least one data point. 1.2.3. Fuzzy areaYou must have noticed that the illustration above also contains fuzzy circles extending beyond the closest neighbor. This tells us that the certainty of connection with other points decreases as we get farther away from the point of interest. The easiest way to think about it is by viewing the two hyperparameters (local_connectivity and n_neighbors) as lower and upper bounds: local_connectivity (default=1) — there is 100% certainty that each point is connected to at least one other point (lower limit for a number of connections). n_neighbors (default=15) — there is a 0% chance that a point is directly connected to a 16th+ neighbor since it falls outside the local area used by UMAP when constructing a graph. neighbors 2 to 15 — there is some level of certainty (>0% but <100%) that a point is connected to its 2nd to 15th neighbor. 1.2.4. Merging of edgesFinally, we need to understand that the connection certainty discussed above is expressed through edge weights (w). Since we have employed a varying distance approach, we will unavoidably have cases where edge weights do not align when viewed from the perspective of each point. E.g., the edge weight for points A→ B will be different from the edge weight of B→ A. UMAP overcomes the problem of disagreeing edge weights we just described by taking a union of the two edges. Here is how UMAP documentation explains it: If we want to merge together two disagreeing edges with weight a and b then we should have a single edge with combined weight a+b−a⋅b. The way to think of this is that the weights are effectively the probabilities that an edge (1-simplex) exists. The combined weight is then the probability that at least one of the edges exists. In the end, we get a connected neighborhood graph that looks like this: After learning the approximate manifold from the higher-dimensional space, the next step for UMAP is to project it (map it) to a lower-dimensional space. 2.1. Minimum distanceUnlike the first step, we do not want varying distances in the lower-dimensional space representation. Instead, we want the distance on the manifold to be standard Euclidean distance with respect to the global coordinate system. The switch from varying to standard distances also impacts the proximity to nearest neighbors. Hence, we must pass another hyperparameter called min_dist (default=0.1) to define the minimum distance between embedded points. Essentially, we can control the minimum spread of points, avoiding scenarios with many points sitting on top of each other in the lower-dimensional embedding. 2.2. Minimizing the cost function (Cross-Entropy)With the minimum distance specified, the algorithm can start looking for a good low-dimensional manifold representation. UMAP does it by minimizing the following cost function, also known as Cross-Entropy (CE): As you can see, the ultimate goal is to find the optimal weights of edges in the low-dimensional representation. These optimal weights emerge as the above Cross-Entropy cost function is minimized following an iterative stochastic gradient descent process. And that is it! The UMAP’s job is now complete, and we are given an array containing the coordinates of each data point in a specified lower-dimensional space. Finally, we can use our newly acquired knowledge of UMAP to perform dimensionality reduction in Python. We will apply UMAP on the MNIST dataset (a collection of handwritten digits) to illustrate how we can successfully separate digits and display them in the low-dimensional space. We will use the following data and libraries: Scikit-learn library for1) MNIST digit data (load_digits);2) splitting data into train and test samples (train_test_split); UMAP library for performing dimensionality reduction; Plotly and Matplotlib for data visualizations; Pandas and Numpy for data manipulation. The first step is to import the libraries that we have listed above. Next, we load the MNIST data and display the images of the first ten handwritten digits. Next, we will create a function for drawing 3D scatter plots that we can reuse multiple times to display results from UMAP dimensionality reduction. Now, we take the MNIST digit data that we have previously loaded into an array X. The shape of X (1797,64) tells us that we have 1,797 digits, each made up of 64 dimensions. We will use UMAP to reduce the dimensionality from 64 down to 3. Please note that I have listed every hyperparameter available in UMAP with a short explanation of what they do. While, in this example, I am leaving most of the hyperparameters set to their default values, I encourage you to experiment with them to see how they affect the results. The above code applies UMAP to our MNIST data and prints the shape of the transformed array to confirm that we have successfully reduced dimensions from 64 to 3. We can now use the chart plotting function we created earlier to visualize our 3-dimensional digits data. We call the function with a simple line of code passing the arrays we want to visualize. chart(X_trans, y) The results look pretty great, with a clear separation between the digit clusters. Interestingly digit 1 formed three distinct clusters, which can be explained by different variations of how people write digit 1: Note how writing 1 with a base at the bottom makes it looks similar to digit 2. We can find these cases in a small red cluster of 1’s located very close to the green cluster of 2’s. As mentioned at the beginning of the article, we can also use UMAP in a supervised manner to help reduce the dimensions of our data. When performing supervised dimensionality reduction, in addition to image data (X_train array), we also need to pass labels data (y_train array) into a fit_transform method (see code below). Also, I want to bring your attention to the fact that I have made a couple of other minor changes to hyperparameters, setting min_dist=0.5 and local_connectivity=2 for nicer visualization and better results on a test sample. Now that we have successfully reduced dimensions using the supervised UMAP approach, we can plot 3D scatterplots to show the results. chart(X_train_res, y_train) We can see that UMAP has formed very tight clusters of each digit separated by a considerable distance. We now create the same 3D graph for the test data to see if UMAP could successfully place new data points into these clusters. chart(X_test_res, y_test) As you can see, the results are pretty good, with only a few digits placed in the wrong clusters. In particular, it looks like the algorithm struggled with digit 3, with a few examples located next to 7’s, 8’s, and 5’s. I appreciate you reading this long article, and I hope that every part of it has given you more insight into how this great algorithm operates. In general, UMAP has a solid mathematical foundation, and it can often do a better job than similar dimensionality reduction algorithms such as t-SNE. The secret lies in UMAP’s ability to infer both local and global structures while preserving relative global distances in the lower-dimensional space. These abilities enable us to unlock specific insights, such as finding similarities between the handwritten forms of digits 1 and 2. Please feel free to share your thoughts and feedback, which will help me write better articles in the future. Cheers 👏Saul Dobilas If you have already spent your learning budget for this month, please remember me next time. My personalized link to join Medium is: solclover.com Other articles you may find interesting:
[ { "code": null, "e": 414, "s": 172, "text": "Dimensionality reduction is not just for data visualization. It can also help you overcome the “curse of dimensionality” by identifying critical structures in the high-dimensional space and preserving them in the lower-dimensional embedding." }, { "code": null, "e": 700, "s": 414, "text": "This article will take you through the inner workings of an increasingly popular dimensionality reduction technique called Uniform Manifold Approximation and Projection (UMAP) and provide you with a Python example that can be used as a guide when working on your Data Science projects." }, { "code": null, "e": 760, "s": 700, "text": "UMAP’s place in the universe of Machine Learning algorithms" }, { "code": null, "e": 803, "s": 760, "text": "An intuitive explanation of how UMAP works" }, { "code": null, "e": 838, "s": 803, "text": "An example of using UMAP in Python" }, { "code": null, "e": 1109, "s": 838, "text": "The below sunburst chart is my attempt to categorize the most commonly used Machine Learning algorithms. I have created it to satisfy the need of Data Scientists like you and me to have a more structured and visual way of identifying how various algorithms fit together." }, { "code": null, "e": 1316, "s": 1109, "text": "This particular view of the Machine Learning universe enables us to see similarities and differences between algorithms, serving as a quick guide when looking for a suitable solution for a specific project." }, { "code": null, "e": 1416, "s": 1316, "text": "The graph is interactive so make sure to click👇 on different categories to enlarge and reveal more." }, { "code": null, "e": 1529, "s": 1416, "text": "If you enjoy Data Science and Machine Learning, please subscribe to get an email whenever I publish a new story." }, { "code": null, "e": 1729, "s": 1529, "text": "While UMAP is most commonly used for unsupervised learning, it can also perform supervised dimensionality reduction. You will find an example of that in the Python section at the end of this article." }, { "code": null, "e": 1843, "s": 1729, "text": "Let’s start by dissecting the UMAP name, which will give us a broad idea of what the algorithm is supposed to do." }, { "code": null, "e": 1984, "s": 1843, "text": "Note, the below statements are not official definitions but rather a set of descriptions that will help us understand key ideas behind UMAP." }, { "code": null, "e": 2221, "s": 1984, "text": "Projection — the process or technique of reproducing a spatial object upon a plane, a curved surface, or a line by projecting its points. You can also think of it as a mapping of an object from high-dimensional to low-dimensional space." }, { "code": null, "e": 2435, "s": 2221, "text": "Approximation — the algorithm assumes that we only have a finite set of data samples (points), not the entire set that makes up the manifold. Hence, we need to approximate the manifold based on the data available." }, { "code": null, "e": 2698, "s": 2435, "text": "Manifold — a manifold is a topological space that locally resembles Euclidean space near each point. One-dimensional manifolds include lines and circles, but not figure eights. Two-dimensional manifolds (a.k.a. surfaces) include planes, spheres, torus, and more." }, { "code": null, "e": 3076, "s": 2698, "text": "Uniform — the uniformity assumption tells us that our data samples are uniformly (evenly) distributed across the manifold. In the real world, however, this is rarely the case. Hence, this assumption leads to the notion that the distance varies across the manifold. i.e., the space itself is warping: stretching or shrinking according to where the data appear sparser or denser." }, { "code": null, "e": 3140, "s": 3076, "text": "Putting the above statements together, we can describe UMAP as:" }, { "code": null, "e": 3401, "s": 3140, "text": "A dimensionality reduction technique that assumes the available data samples are evenly (uniformly) distributed across a topological space (manifold), which can be approximated from these finite data samples and mapped (projected) to a lower-dimensional space." }, { "code": null, "e": 3598, "s": 3401, "text": "The above description of the algorithm may help a little, but it is still vague on how UMAP does its magic. So, to answer the “how” question, let’s analyze the individual steps that UMAP performs." }, { "code": null, "e": 3638, "s": 3598, "text": "We can split UMAP into two major steps:" }, { "code": null, "e": 3759, "s": 3638, "text": "learning the manifold structure in the high-dimensional space;finding a low-dimensional representation of said manifold." }, { "code": null, "e": 3822, "s": 3759, "text": "learning the manifold structure in the high-dimensional space;" }, { "code": null, "e": 3881, "s": 3822, "text": "finding a low-dimensional representation of said manifold." }, { "code": null, "e": 4074, "s": 3881, "text": "We will, however, break this down into even smaller components to make our understanding of the algorithm deeper. The below map shows the order that we will go through in analyzing each piece." }, { "code": null, "e": 4235, "s": 4074, "text": "It will come as no surprise, but before we can map our data to lower dimensions, we first need to figure out what it looks like in the higher-dimensional space." }, { "code": null, "e": 4524, "s": 4235, "text": "1.1. Finding nearest neighborsUMAP starts by finding the nearest neighbors using the Nearest-Neighbor-Descent algorithm of Dong et al. You will see in the Python section later on that we can specify how many nearest neighbors we want to use by adjusting UMAP’s n_neighbors hyperparameter." }, { "code": null, "e": 4777, "s": 4524, "text": "It is important to experiment with the number of n_neighbors because it controls how UMAP balances local versus global structure in the data. It does it by constraining the size of the local neighborhood when attempting to learn the manifold structure." }, { "code": null, "e": 5082, "s": 4777, "text": "Essentially, a small value for n_neighbors means that we want a very local interpretation that accurately captures the fine detail of the structure. In contrast, a large n_neighbors value means that our estimates will be based on larger regions, thus more broadly accurate across the manifold as a whole." }, { "code": null, "e": 5326, "s": 5082, "text": "1.2. Constructing a graph Next, UMAP needs to construct a graph by connecting the previously identified nearest neighbors. To understand this process, we need to look at a few sub-components that explain how the neighborhood graph comes to be." }, { "code": null, "e": 5584, "s": 5326, "text": "1.2.1. Varying distanceAs outlined in the analysis of the UMAP’s name, we assume a uniform distribution of points across the manifold, suggesting that space between them is stretching or shrinking according to where the data appears to be sparser or denser." }, { "code": null, "e": 5894, "s": 5584, "text": "It essentially means that the distance metric is not universal across the whole space, and instead, it varies between different regions. We can visualize it by drawing circles/spheres around each data point, which appear to be different in size because of the varying distance metric (see illustration below)." }, { "code": null, "e": 6160, "s": 5894, "text": "1.2.2. Local connectivityNext, we want to ensure that the manifold structure we are trying to learn does not result in many unconnected points. Luckily, we can use another hyperparameter called local_connectivity (default value = 1) to solve this potential problem." }, { "code": null, "e": 6400, "s": 6160, "text": "When we set local_connectivity=1, we tell the algorithm that every point in the higher-dimensional space is connected to at least one other point. You can see in the above illustration how each solid circle touches at least one data point." }, { "code": null, "e": 6660, "s": 6400, "text": "1.2.3. Fuzzy areaYou must have noticed that the illustration above also contains fuzzy circles extending beyond the closest neighbor. This tells us that the certainty of connection with other points decreases as we get farther away from the point of interest." }, { "code": null, "e": 6796, "s": 6660, "text": "The easiest way to think about it is by viewing the two hyperparameters (local_connectivity and n_neighbors) as lower and upper bounds:" }, { "code": null, "e": 6953, "s": 6796, "text": "local_connectivity (default=1) — there is 100% certainty that each point is connected to at least one other point (lower limit for a number of connections)." }, { "code": null, "e": 7134, "s": 6953, "text": "n_neighbors (default=15) — there is a 0% chance that a point is directly connected to a 16th+ neighbor since it falls outside the local area used by UMAP when constructing a graph." }, { "code": null, "e": 7258, "s": 7134, "text": "neighbors 2 to 15 — there is some level of certainty (>0% but <100%) that a point is connected to its 2nd to 15th neighbor." }, { "code": null, "e": 7397, "s": 7258, "text": "1.2.4. Merging of edgesFinally, we need to understand that the connection certainty discussed above is expressed through edge weights (w)." }, { "code": null, "e": 7646, "s": 7397, "text": "Since we have employed a varying distance approach, we will unavoidably have cases where edge weights do not align when viewed from the perspective of each point. E.g., the edge weight for points A→ B will be different from the edge weight of B→ A." }, { "code": null, "e": 7799, "s": 7646, "text": "UMAP overcomes the problem of disagreeing edge weights we just described by taking a union of the two edges. Here is how UMAP documentation explains it:" }, { "code": null, "e": 8129, "s": 7799, "text": "If we want to merge together two disagreeing edges with weight a and b then we should have a single edge with combined weight a+b−a⋅b. The way to think of this is that the weights are effectively the probabilities that an edge (1-simplex) exists. The combined weight is then the probability that at least one of the edges exists." }, { "code": null, "e": 8201, "s": 8129, "text": "In the end, we get a connected neighborhood graph that looks like this:" }, { "code": null, "e": 8355, "s": 8201, "text": "After learning the approximate manifold from the higher-dimensional space, the next step for UMAP is to project it (map it) to a lower-dimensional space." }, { "code": null, "e": 8605, "s": 8355, "text": "2.1. Minimum distanceUnlike the first step, we do not want varying distances in the lower-dimensional space representation. Instead, we want the distance on the manifold to be standard Euclidean distance with respect to the global coordinate system." }, { "code": null, "e": 8829, "s": 8605, "text": "The switch from varying to standard distances also impacts the proximity to nearest neighbors. Hence, we must pass another hyperparameter called min_dist (default=0.1) to define the minimum distance between embedded points." }, { "code": null, "e": 8988, "s": 8829, "text": "Essentially, we can control the minimum spread of points, avoiding scenarios with many points sitting on top of each other in the lower-dimensional embedding." }, { "code": null, "e": 9248, "s": 8988, "text": "2.2. Minimizing the cost function (Cross-Entropy)With the minimum distance specified, the algorithm can start looking for a good low-dimensional manifold representation. UMAP does it by minimizing the following cost function, also known as Cross-Entropy (CE):" }, { "code": null, "e": 9504, "s": 9248, "text": "As you can see, the ultimate goal is to find the optimal weights of edges in the low-dimensional representation. These optimal weights emerge as the above Cross-Entropy cost function is minimized following an iterative stochastic gradient descent process." }, { "code": null, "e": 9664, "s": 9504, "text": "And that is it! The UMAP’s job is now complete, and we are given an array containing the coordinates of each data point in a specified lower-dimensional space." }, { "code": null, "e": 9768, "s": 9664, "text": "Finally, we can use our newly acquired knowledge of UMAP to perform dimensionality reduction in Python." }, { "code": null, "e": 9946, "s": 9768, "text": "We will apply UMAP on the MNIST dataset (a collection of handwritten digits) to illustrate how we can successfully separate digits and display them in the low-dimensional space." }, { "code": null, "e": 9992, "s": 9946, "text": "We will use the following data and libraries:" }, { "code": null, "e": 10116, "s": 9992, "text": "Scikit-learn library for1) MNIST digit data (load_digits);2) splitting data into train and test samples (train_test_split);" }, { "code": null, "e": 10170, "s": 10116, "text": "UMAP library for performing dimensionality reduction;" }, { "code": null, "e": 10217, "s": 10170, "text": "Plotly and Matplotlib for data visualizations;" }, { "code": null, "e": 10257, "s": 10217, "text": "Pandas and Numpy for data manipulation." }, { "code": null, "e": 10326, "s": 10257, "text": "The first step is to import the libraries that we have listed above." }, { "code": null, "e": 10415, "s": 10326, "text": "Next, we load the MNIST data and display the images of the first ten handwritten digits." }, { "code": null, "e": 10564, "s": 10415, "text": "Next, we will create a function for drawing 3D scatter plots that we can reuse multiple times to display results from UMAP dimensionality reduction." }, { "code": null, "e": 10738, "s": 10564, "text": "Now, we take the MNIST digit data that we have previously loaded into an array X. The shape of X (1797,64) tells us that we have 1,797 digits, each made up of 64 dimensions." }, { "code": null, "e": 10915, "s": 10738, "text": "We will use UMAP to reduce the dimensionality from 64 down to 3. Please note that I have listed every hyperparameter available in UMAP with a short explanation of what they do." }, { "code": null, "e": 11085, "s": 10915, "text": "While, in this example, I am leaving most of the hyperparameters set to their default values, I encourage you to experiment with them to see how they affect the results." }, { "code": null, "e": 11247, "s": 11085, "text": "The above code applies UMAP to our MNIST data and prints the shape of the transformed array to confirm that we have successfully reduced dimensions from 64 to 3." }, { "code": null, "e": 11442, "s": 11247, "text": "We can now use the chart plotting function we created earlier to visualize our 3-dimensional digits data. We call the function with a simple line of code passing the arrays we want to visualize." }, { "code": null, "e": 11460, "s": 11442, "text": "chart(X_trans, y)" }, { "code": null, "e": 11673, "s": 11460, "text": "The results look pretty great, with a clear separation between the digit clusters. Interestingly digit 1 formed three distinct clusters, which can be explained by different variations of how people write digit 1:" }, { "code": null, "e": 11855, "s": 11673, "text": "Note how writing 1 with a base at the bottom makes it looks similar to digit 2. We can find these cases in a small red cluster of 1’s located very close to the green cluster of 2’s." }, { "code": null, "e": 11988, "s": 11855, "text": "As mentioned at the beginning of the article, we can also use UMAP in a supervised manner to help reduce the dimensions of our data." }, { "code": null, "e": 12179, "s": 11988, "text": "When performing supervised dimensionality reduction, in addition to image data (X_train array), we also need to pass labels data (y_train array) into a fit_transform method (see code below)." }, { "code": null, "e": 12404, "s": 12179, "text": "Also, I want to bring your attention to the fact that I have made a couple of other minor changes to hyperparameters, setting min_dist=0.5 and local_connectivity=2 for nicer visualization and better results on a test sample." }, { "code": null, "e": 12538, "s": 12404, "text": "Now that we have successfully reduced dimensions using the supervised UMAP approach, we can plot 3D scatterplots to show the results." }, { "code": null, "e": 12566, "s": 12538, "text": "chart(X_train_res, y_train)" }, { "code": null, "e": 12670, "s": 12566, "text": "We can see that UMAP has formed very tight clusters of each digit separated by a considerable distance." }, { "code": null, "e": 12797, "s": 12670, "text": "We now create the same 3D graph for the test data to see if UMAP could successfully place new data points into these clusters." }, { "code": null, "e": 12823, "s": 12797, "text": "chart(X_test_res, y_test)" }, { "code": null, "e": 13043, "s": 12823, "text": "As you can see, the results are pretty good, with only a few digits placed in the wrong clusters. In particular, it looks like the algorithm struggled with digit 3, with a few examples located next to 7’s, 8’s, and 5’s." }, { "code": null, "e": 13187, "s": 13043, "text": "I appreciate you reading this long article, and I hope that every part of it has given you more insight into how this great algorithm operates." }, { "code": null, "e": 13338, "s": 13187, "text": "In general, UMAP has a solid mathematical foundation, and it can often do a better job than similar dimensionality reduction algorithms such as t-SNE." }, { "code": null, "e": 13622, "s": 13338, "text": "The secret lies in UMAP’s ability to infer both local and global structures while preserving relative global distances in the lower-dimensional space. These abilities enable us to unlock specific insights, such as finding similarities between the handwritten forms of digits 1 and 2." }, { "code": null, "e": 13732, "s": 13622, "text": "Please feel free to share your thoughts and feedback, which will help me write better articles in the future." }, { "code": null, "e": 13753, "s": 13732, "text": "Cheers 👏Saul Dobilas" }, { "code": null, "e": 13886, "s": 13753, "text": "If you have already spent your learning budget for this month, please remember me next time. My personalized link to join Medium is:" }, { "code": null, "e": 13900, "s": 13886, "text": "solclover.com" } ]
DataOps Automation — Creating Azure Data Factory with git integration using Bicep | by Wesley Camargo | Towards Data Science
An important feature available in Azure Data Factory is the git integration, which allows us to keep Azure Data Factory artifacts under Source Control. This is a mandatory step to achieve Continuous Integration and Delivery later on, so why not configure this using Infrastructure as Code with Bicep in a fully automated way? In the official Microsoft documentation there is a good topic explaining how to integrate Azure Data Factory with git, but through the Azure Portal. In this post, I will explain how to do that using Bicep, the new IaC language for Azure, to make it possible to include this step into your CI/CD process, and also how to deploy only on needed environments. Okay, but why do I need to use git on my ADF? To explain this, I’ll list some advantages that the git integration offers, taken from Microsoft’s documentation: As your data factory workloads become crucial, you would want to integrate your factory with Git to leverage several source control benefits like the following: Ability to track/audit changes. Ability to revert changes that introduced bugs. When authoring against the data factory service, you can’t save changes as a draft and all publish must pass data factory validation. Whether your pipelines are not finished or you simply don’t want to lose changes if your computer crashes, git integration allows for incremental changes of data factory resources regardless of what state they are in. Configuring a git repository allows you to save changes, letting you only publish when you have tested your changes to your satisfaction. If you have multiple team members contributing to the same factory, you may want to let your teammates collaborate with each other via a code review process. You can also set up your factory such that not every contributor has equal permissions. Some team members may only be allowed to make changes via Git and only certain people in the team are allowed to publish the changes to the factory. If you are deploying to multiple environments with a continuous delivery process, git integration makes certain actions easier. Some of these actions include: Configure your release pipeline to trigger automatically as soon as there are any changes made to your ‘dev’ factory. Customize the properties in your factory that are available as parameters in the Resource Manager template. It can be useful to keep only the required set of properties as parameters and have everything else hardcoded. An average factory with git integration loads 10 times faster than one authoring against the data factory service. This performance improvement is because resources are downloaded via Git. There are two flows recommended by Microsoft to perform CI/CD on ADF, (you can check it on this post), in both cases the development happens in the Development Data Factory workspace only, and the artifacts are promoted through CI/CD deployments. It means that we should not create this integration for non-dev environments like UAT or Production. I will also cover how to identify the environment and create the integration only for your development environment :) To keep the explanation simple, I’ll show each stage of the bicep file. Each stage is a deployable file that you can execute individually with the command az deployment group create -f <your file>.bicep -g <your resource group> In the end, we will have the complete file ready to use. In the first stage, we are creating only the workspace with the most basic configurations. You can see that for the location we are using the location of the Resource Group where we are executing this deployment. In this stage we achieve the first goal of this post: create the git integration. I include the parameters necessary to connect with a GitHub repo, and then a section into “properties”. Now lets check the parameters: accountName - This is your GitHub/Azure DevOps account name.repositoryName - Name of your repository, pay attention that you don’t need your account name at the beginning.collaborationBranc - The branch that will be used to integrate your feature branches. It will depend on your branch stratety. For git flow, it should be developed branch, for GitHub Flow, master/main.rootFolder - The folder in your repo where the databricks artifacts will be versioned.projectName - This parameter is only used for Azure DevOps. It’s the Team Project name of your repo.type - This parameter defines if your repo is hosted on GitHub or Azure DevOps. For GitHub, the value must be: accountName - This is your GitHub/Azure DevOps account name. repositoryName - Name of your repository, pay attention that you don’t need your account name at the beginning. collaborationBranc - The branch that will be used to integrate your feature branches. It will depend on your branch stratety. For git flow, it should be developed branch, for GitHub Flow, master/main. rootFolder - The folder in your repo where the databricks artifacts will be versioned. projectName - This parameter is only used for Azure DevOps. It’s the Team Project name of your repo. type - This parameter defines if your repo is hosted on GitHub or Azure DevOps. For GitHub, the value must be: FactoryGitHubConfiguration For Azure Devops the value is: FactoryVSTSConfiguration As was explained above, we must create git integration in the development environment only. If you are using only GitHub or only Azure DevOps, this stage should be enough for your scenario. To check that, we need the following steps: An environment parameter.Extract the content of repoConfiguration to an external variable.Use a ternary if to check if the environment provided is development. If it is, then use the variable, if not, use an empty group. An environment parameter. Extract the content of repoConfiguration to an external variable. Use a ternary if to check if the environment provided is development. If it is, then use the variable, if not, use an empty group. The bicep file of this stage: In case that in your scenario you have both Azure DevOps and GitHub, you can prepare your template to support that. This template is more flexible and can be used in more situations. Let’s check the differences from the previous one: Included a “User Friendly” parameter to indicate the type of the repo.Check the type parameter and create a variable with the expected value.Create two configurations, one for GitHub and one for Azure DevOps.Include another ternary if nested into the first one Included a “User Friendly” parameter to indicate the type of the repo. Check the type parameter and create a variable with the expected value. Create two configurations, one for GitHub and one for Azure DevOps. Include another ternary if nested into the first one Below you can check the final bicep template: To check these examples in more realistic situations, I have been working in a repository in GitHub with examples of pipelines configured and working. You can check that in the DevOps Nights GitHub here: devopsnights/azuredevops-yaml-quickstart-templates (github.com) In this post, I am showing how to consume this Bicep Template into an Azure DevOps Pipeline. I hope this post can help you to create your ADF in a more automated way, and see you in the next post! Source control — Azure Data Factory | Microsoft Docs Factories — Configure Factory Repo — REST API (Azure Data Factory) | Microsoft Docs Microsoft.DataFactory/factories 2018–06–01 — ARM template reference | Microsoft Docs
[ { "code": null, "e": 498, "s": 172, "text": "An important feature available in Azure Data Factory is the git integration, which allows us to keep Azure Data Factory artifacts under Source Control. This is a mandatory step to achieve Continuous Integration and Delivery later on, so why not configure this using Infrastructure as Code with Bicep in a fully automated way?" }, { "code": null, "e": 854, "s": 498, "text": "In the official Microsoft documentation there is a good topic explaining how to integrate Azure Data Factory with git, but through the Azure Portal. In this post, I will explain how to do that using Bicep, the new IaC language for Azure, to make it possible to include this step into your CI/CD process, and also how to deploy only on needed environments." }, { "code": null, "e": 1014, "s": 854, "text": "Okay, but why do I need to use git on my ADF? To explain this, I’ll list some advantages that the git integration offers, taken from Microsoft’s documentation:" }, { "code": null, "e": 1175, "s": 1014, "text": "As your data factory workloads become crucial, you would want to integrate your factory with Git to leverage several source control benefits like the following:" }, { "code": null, "e": 1207, "s": 1175, "text": "Ability to track/audit changes." }, { "code": null, "e": 1255, "s": 1207, "text": "Ability to revert changes that introduced bugs." }, { "code": null, "e": 1745, "s": 1255, "text": "When authoring against the data factory service, you can’t save changes as a draft and all publish must pass data factory validation. Whether your pipelines are not finished or you simply don’t want to lose changes if your computer crashes, git integration allows for incremental changes of data factory resources regardless of what state they are in. Configuring a git repository allows you to save changes, letting you only publish when you have tested your changes to your satisfaction." }, { "code": null, "e": 2140, "s": 1745, "text": "If you have multiple team members contributing to the same factory, you may want to let your teammates collaborate with each other via a code review process. You can also set up your factory such that not every contributor has equal permissions. Some team members may only be allowed to make changes via Git and only certain people in the team are allowed to publish the changes to the factory." }, { "code": null, "e": 2299, "s": 2140, "text": "If you are deploying to multiple environments with a continuous delivery process, git integration makes certain actions easier. Some of these actions include:" }, { "code": null, "e": 2417, "s": 2299, "text": "Configure your release pipeline to trigger automatically as soon as there are any changes made to your ‘dev’ factory." }, { "code": null, "e": 2636, "s": 2417, "text": "Customize the properties in your factory that are available as parameters in the Resource Manager template. It can be useful to keep only the required set of properties as parameters and have everything else hardcoded." }, { "code": null, "e": 2825, "s": 2636, "text": "An average factory with git integration loads 10 times faster than one authoring against the data factory service. This performance improvement is because resources are downloaded via Git." }, { "code": null, "e": 3291, "s": 2825, "text": "There are two flows recommended by Microsoft to perform CI/CD on ADF, (you can check it on this post), in both cases the development happens in the Development Data Factory workspace only, and the artifacts are promoted through CI/CD deployments. It means that we should not create this integration for non-dev environments like UAT or Production. I will also cover how to identify the environment and create the integration only for your development environment :)" }, { "code": null, "e": 3446, "s": 3291, "text": "To keep the explanation simple, I’ll show each stage of the bicep file. Each stage is a deployable file that you can execute individually with the command" }, { "code": null, "e": 3519, "s": 3446, "text": "az deployment group create -f <your file>.bicep -g <your resource group>" }, { "code": null, "e": 3576, "s": 3519, "text": "In the end, we will have the complete file ready to use." }, { "code": null, "e": 3789, "s": 3576, "text": "In the first stage, we are creating only the workspace with the most basic configurations. You can see that for the location we are using the location of the Resource Group where we are executing this deployment." }, { "code": null, "e": 4006, "s": 3789, "text": "In this stage we achieve the first goal of this post: create the git integration. I include the parameters necessary to connect with a GitHub repo, and then a section into “properties”. Now lets check the parameters:" }, { "code": null, "e": 4674, "s": 4006, "text": "accountName - This is your GitHub/Azure DevOps account name.repositoryName - Name of your repository, pay attention that you don’t need your account name at the beginning.collaborationBranc - The branch that will be used to integrate your feature branches. It will depend on your branch stratety. For git flow, it should be developed branch, for GitHub Flow, master/main.rootFolder - The folder in your repo where the databricks artifacts will be versioned.projectName - This parameter is only used for Azure DevOps. It’s the Team Project name of your repo.type - This parameter defines if your repo is hosted on GitHub or Azure DevOps. For GitHub, the value must be:" }, { "code": null, "e": 4735, "s": 4674, "text": "accountName - This is your GitHub/Azure DevOps account name." }, { "code": null, "e": 4847, "s": 4735, "text": "repositoryName - Name of your repository, pay attention that you don’t need your account name at the beginning." }, { "code": null, "e": 5048, "s": 4847, "text": "collaborationBranc - The branch that will be used to integrate your feature branches. It will depend on your branch stratety. For git flow, it should be developed branch, for GitHub Flow, master/main." }, { "code": null, "e": 5135, "s": 5048, "text": "rootFolder - The folder in your repo where the databricks artifacts will be versioned." }, { "code": null, "e": 5236, "s": 5135, "text": "projectName - This parameter is only used for Azure DevOps. It’s the Team Project name of your repo." }, { "code": null, "e": 5347, "s": 5236, "text": "type - This parameter defines if your repo is hosted on GitHub or Azure DevOps. For GitHub, the value must be:" }, { "code": null, "e": 5374, "s": 5347, "text": "FactoryGitHubConfiguration" }, { "code": null, "e": 5405, "s": 5374, "text": "For Azure Devops the value is:" }, { "code": null, "e": 5430, "s": 5405, "text": "FactoryVSTSConfiguration" }, { "code": null, "e": 5664, "s": 5430, "text": "As was explained above, we must create git integration in the development environment only. If you are using only GitHub or only Azure DevOps, this stage should be enough for your scenario. To check that, we need the following steps:" }, { "code": null, "e": 5885, "s": 5664, "text": "An environment parameter.Extract the content of repoConfiguration to an external variable.Use a ternary if to check if the environment provided is development. If it is, then use the variable, if not, use an empty group." }, { "code": null, "e": 5911, "s": 5885, "text": "An environment parameter." }, { "code": null, "e": 5977, "s": 5911, "text": "Extract the content of repoConfiguration to an external variable." }, { "code": null, "e": 6108, "s": 5977, "text": "Use a ternary if to check if the environment provided is development. If it is, then use the variable, if not, use an empty group." }, { "code": null, "e": 6138, "s": 6108, "text": "The bicep file of this stage:" }, { "code": null, "e": 6372, "s": 6138, "text": "In case that in your scenario you have both Azure DevOps and GitHub, you can prepare your template to support that. This template is more flexible and can be used in more situations. Let’s check the differences from the previous one:" }, { "code": null, "e": 6633, "s": 6372, "text": "Included a “User Friendly” parameter to indicate the type of the repo.Check the type parameter and create a variable with the expected value.Create two configurations, one for GitHub and one for Azure DevOps.Include another ternary if nested into the first one" }, { "code": null, "e": 6704, "s": 6633, "text": "Included a “User Friendly” parameter to indicate the type of the repo." }, { "code": null, "e": 6776, "s": 6704, "text": "Check the type parameter and create a variable with the expected value." }, { "code": null, "e": 6844, "s": 6776, "text": "Create two configurations, one for GitHub and one for Azure DevOps." }, { "code": null, "e": 6897, "s": 6844, "text": "Include another ternary if nested into the first one" }, { "code": null, "e": 6943, "s": 6897, "text": "Below you can check the final bicep template:" }, { "code": null, "e": 7211, "s": 6943, "text": "To check these examples in more realistic situations, I have been working in a repository in GitHub with examples of pipelines configured and working. You can check that in the DevOps Nights GitHub here: devopsnights/azuredevops-yaml-quickstart-templates (github.com)" }, { "code": null, "e": 7304, "s": 7211, "text": "In this post, I am showing how to consume this Bicep Template into an Azure DevOps Pipeline." }, { "code": null, "e": 7408, "s": 7304, "text": "I hope this post can help you to create your ADF in a more automated way, and see you in the next post!" }, { "code": null, "e": 7461, "s": 7408, "text": "Source control — Azure Data Factory | Microsoft Docs" }, { "code": null, "e": 7545, "s": 7461, "text": "Factories — Configure Factory Repo — REST API (Azure Data Factory) | Microsoft Docs" } ]
A journey to Airflow on Kubernetes | by Marcelo Rabello Rossi | Towards Data Science
My humble opinion on Apache Airflow: basically, if you have more than a couple of automated tasks to schedule, and you are fiddling around with cron tasks that run even when some dependency of them fails, you should give it a try. But if you are not willing to just accept my words, feel free to check these posts.1 2 3 Delve into Airflow concepts and how it works is beyond the scope of this article. For that matter, please check these other posts.4 5 Long story short, its task definitions are code based, what means that they could be as dynamic as you wish. You can create tasks and define your task dependencies based on variables or conditionals. It has plenty of native operators (definitions of task types)6 that integrate your workflow with lots of other tools and allow you to run from the most basic shell scripts to parallel data processing with Apache Spark, and a plethora of other options. Contributor operators7 are also available for a great set of commercial tools and the list keeps growing every day. These operators are python classes, so they are extensible and could be modified to fit your needs. You can even create your own operators from scratch, inheriting from the BaseOperator class. Also, it makes your workflow scalable to hundreds or even thousands of tasks with little effort using its distributed executors such as Celery or Kubernetes. We are using Airflow in iFood since 2018. Our first implementation was really nice, based on docker containers to run each task in an isolated environment. It underwent a lot of changes since then, from a simple tool to serve our team’s workload to a task scheduling platform to serve the more than 200 people with a lot of abstractions on the top of it. At the end, it does not matter if you are a software engineer with years of experience or a business analyst with minimal SQL knowledge, you can schedule your task using our platform writing a yaml file with three simple fields: the ID of your task, the path of the file containing your queries and the name of its table dependencies (i.e. to run my task I depend on the tables orders and users), and voilà, you have your task scheduled to run daily. But this, unfortunately, is a topic for a future article. It was obvious that we would need to scale our application from an AWS t2.medium EC2 instance to something more powerful. Our first approaches were to scale vertically to an r4.large instance, and then to an r4.xlarge, but the memory usage was constantly increasing. Our company grows fast. There are dozens of tasks being created every day and suddenly we would be running on an r4.16xlarge instance. We needed a way to scale the application horizontally and, more than that, to upscale it considering the peak hours and to downscale it at dawn to minimize needless costs. At that point, we were migrating all our platforms to run on a Kubernetes cluster, so why not Airflow? I searched on the internet, from the official Apache Airflow documentation to Medium articles, digging for information on how to run a simple implementation of Airflow on Kubernetes with the KubernetesExecutor (I was aware of the CeleryExecutor existence, but it would not fit our needs, considering that you need to spin your workers upfront, with no native auto-scaling). I found a lot of people talking about the benefits of running Airflow on Kubernetes, the architecture behind it and a bunch of Helm charts, but little information on how to deploy it, piece by piece, in a logical way for a Kubernetes beginner. And that is the main point of this article. Assuming that you know Apache Airflow, and how its components work together, the idea is to show you how you can deploy it to run on Kubernetes leveraging the benefits of the KubernetesExecutor, with some extra information on the Kubernetes resources involved (yaml files). The examples will be AWS-based, but I am sure that with little research you can port the information to any cloud service you want or even run the code on-prem. To fully understand the sections below and get things running, I am assuming that you have: An AWS EKS cluster available, or another type of Kubernetes cluster, locally or in a cloud environment.Basic “hands-on” knowledge on Kubernetes and kubectl tool. At least on how to deploy resources and check their descriptions and logs.Solid knowledge on Apache Airflow, and their units (configuration, scheduler, webserver, database, DAGs and tasks) An AWS EKS cluster available, or another type of Kubernetes cluster, locally or in a cloud environment. Basic “hands-on” knowledge on Kubernetes and kubectl tool. At least on how to deploy resources and check their descriptions and logs. Solid knowledge on Apache Airflow, and their units (configuration, scheduler, webserver, database, DAGs and tasks) If you do not, I recommend that you play a little with Kubernetes and Airflow locally. You can find awesome tutorials in the internet, even at the official websites. For Kubernetes, you can start with the Katacoda tutorials.8 Regarding Apache Airflow, this was the first tutorial I ever tried.9 As a starting point, I found a way to get the Kubernetes resource yaml files from the official Helm chart available at the Airflow git repository.10 That brought me a lot of resources, some of them came empty (probably because I used the base values.yaml to fill the templates used by Helm) and some of them were useless to the KubernetesExecutor approach (i.e. I do not need a Redis cluster, or a Flower resource, or a result back-end, as these are specific to Celery). Removing those useless resources, I ended up with something around 15 resource files and some of them I did not even know at that time. Kinda overwhelming! I also removed all resources that were related to the PostgreSQL instance (i.e. pgbouncer), because I knew that I would use an AWS RDS instance, external to the Kubernetes cluster. Obs: I had these charts locally, so when I executed the helm template command, helm whined about not finding the PostgreSQL charts (it will not happen if you are using the Helm repositories). If that is your case, just create the path charts/ inside the folder containing your helm chart and put the postgresql/ helm chart folder inside of it (available at the official Helm charts github repository). It is also important to notice that the Apache Airflow helm chart available at https://github.com/helm/charts will bring you a different set of resources when compared to the chart I used.10 After all the cleaning, I ended up with these 12 resources: resources├── configmap.yaml├── dags-persistent-volume-claim.yaml├── rbac│ ├── pod-launcher-rolebinding.yaml│ └── pod-launcher-role.yaml├── scheduler│ ├── scheduler-deployment.yaml│ └── scheduler-serviceaccount.yaml├── secrets│ └── metadata-connection-secret.yaml├── statsd│ ├── statsd-deployment.yaml│ └── statsd-service.yaml├── webserver│ ├── webserver-deployment.yaml│ └── webserver-service.yaml└── workers └── worker-serviceaccount.yaml Most of the articles I found describe two ways to store DAG information: storing the DAGs on a persistent volume accessible from multiple AWS availability zones, such as the AWS Elastic File System (EFS), or syncing them from a git repository to an ephemeral volume mounted inside the cluster. If that pod dies, when another one is created, it will sync with the repository again to get the last modifications. Due to our present workflow, we need to build our DAGs dynamically from lots of tasks written in yaml files, meaning that our DAGs are not ready when the files are versioned on a git repository. A simple git-sync to bring information would not work for us, but it could be a starting point. Considering that we also needed some kind of persistence for our logs, we decided to go for the EFS approach too, using some kind of hybrid of what we found online: git-sync our yaml files to a PersistentVolume mounted on the top of an EFS, and to have another pod processing it and throwing the freshly-built DAGs into the folder that the scheduler and the webserver are constantly watching to fill the DagBag. As shown above, to mount the EFS inside the EKS cluster, I used the official AWS CSI driver,11 that must be installed in the cluster. And beyond the driver, this approach accounts for five Kubernetes resources: 2 PersistentVolume(s): DAGs, logs 2 PersistentVolumeClaim(s): DAGs, logs (analogous to the previous ones) 1 StorageClass These resources were not present in the initial list, as the original deployments used emptyDir volumes instead. Anyone that worked with Apache Airflow for some time knows that the airflow.cfg file (and maybe webserver_config.py file) is pretty important to set the things up. But throwing it inside the EFS volume did not seem wise, because of the sensitive information it contains (database passwords, fernet key). Then, I found out that the Kubernetes way to store configuration files is to use ConfigMap, a kind of "volume" that you mount inside the pods to expose a configuration file for them. And there is the Kubernetes Secret too, to store sensitive data. They work together, so I can reference a Secret inside a ConfigMap, or even pass a Secret to an environment variable. Mission accomplished! As you learn a little bit more about Kubernetes, you will notice that the “plain” secrets are somewhat unsafe to version in a repository. They contain base64 strings that can be readily “decrypted” in your terminal using the base64 -d command. Take a look on this ExternalSecrets API,12 to store your secrets on AWS Parameter Store and retrieve them from there. If you check the list of files above, you will notice that the ConfigMap is already there, you just have to customize it. My little experience with Kubernetes was enough at that point to make me think that I would need at least two deployments: one for the scheduler and one for the webserver. And they were there, lying inside the scheduler and webserver folders generated by the Helm Chart explosion. There was a third deployment, of a statsd application, that I found later to be related to metrics collection inside the application. Cool, one thing less to worry! Prometheus will be happy to scrape it. I opened the files and noticed that they have some familiar environment variables, related to the fernet key and the database connection string. I filled them with the data retrieved by the Kubernetes secrets. I needed to tweak the volume part a little bit, to match my EFS PersistentVolume and PersistentVolumeClaim. It is easy to notice these shell scripts being executed as init containers. They are related to the database migrations that happen when Airflow starts. The scheduler pod runs the migrations as soon as it starts, and the webserver pod keeps waiting for it to finish before starting the webserver container. The webserver deployment has a very similar structure, so I took the liberty of omitting it. There was. A Kubernetes service resource exposing the port 8080 of the container. Later I included an Ingress resource to give it an AWS Route53 friendly DNS. The statsd application also listens at an endpoint and has a service associated to it. Both the services were included in the files exported by the helm template command. I tried to apply those configurations to the cluster. Scheduler and webserver were up, both connected to my external RDS PostgreSQL database. I thought: “If I throw some DAGs into the dags folder, then it should work, right?” And it kinda did! I created a simple DAG with one task based on the KubernetesPodOperator, using a container image stored at the AWS Elastic Container Registry. I double checked if my pod would be allowed to access the ECR repository. Then, I triggered the DAG, but it failed (you really didn’t think it would be that easy, right?). Checking the logs I noticed that it happened due some kind of permission issue. My scheduler did not have the permission to spawn new pods. And then I understood the need for that ServiceAccount resources scattered among the folders, and the ClusterRole and ClusterRoleBinding stuff. These guys are there to allow your resources to spawn new resources. After all the configuration, I could make my task run successfully. The KubernetesPodOperator also has the service_account_name parameter, that should be filled with a ServiceAccount resource name able to spawn pods, because that is what it will do: spawn another pod with the image you passed as an argument to the image parameter. That pod will be in charge of running your task. If you want to run tasks directly from your webserver, clicking on that “Run” button inside the task menu, you must give your webserver ServiceAccount the permissions to watch and spawn pods too. If you forget that, your tasks will be triggered, but they will never run. If you are running your stuff on AWS, you need to make sure your pods will be able to access all AWS resources, such as S3, DynamoDB tables, EMR, and so on. To do so, you need to bind your ServiceAccount resource to an AWS IAM role with IAM policies attached, to grant you all the access you need. Just give your IAM role an assume role policy: The ServiceAccount for your worker and tasks should be linked to the IAM Role attached to the policy above. You can do it using annotations: If you are following this journey as a tutorial, after all the tweaking you can just create all the above resources in your cluster: kubectl apply -f resources/ --recursive But, wait! Do not apply them yet! If you are a watchful reader, you noticed that most of the resources above makes reference to the airflow-on-k8s namespace. A Namespace is a way to tell Kubernetes that all resources in the same namespace are somewhat related (i.e. they are part of the same project) and is a nice way to organize things inside the cluster. You should declare your Namespace resource inside the resources/ folder and apply it before applying everything else, otherwise you will get an error. FYI, not every resource on Kubernetes is namespaced (i.e. PersistentVolume, StorageClass and other low-level resources), and that is why some of them do not have any reference to a namespace. And that was a fast-forward take on my journey to deploy Airflow on Kubernetes. I tried to cover all kinds of resources generated by the helm chart export, but feel free to ask your questions in the comments section if you think I left something behind. These yaml resources above were taken from a functional deployment I made. Some of them I built from scratch, and others I adapted from the ones I exported. I suggest that you take your time understanding them and making changes for better organization and performance. There is a lot more you can do to get the most of this implementation. You can set the limits and requests fields for your containers inside the deployments, to make sure they will have the necessary resources available for them to work properly. Going further on the benefits of Kubernetes, you will see that the KubernetesPodOperator allows you to label your pods and pass a lot of Kubernetes configurations to it, such as affinities, tolerations and a bunch of other stuff. If you have tainted nodes, you can assure that just some specific pods will run on them, reserving the most powerful nodes to the most critical tasks. If you tried this setup and have something to add, something that worked like a charm or turned out to be a bad choice, please tell us in the comments. [1]: 10 Benefits to using Airflow: https://medium.com/analytics-and-data/10-benefits-to-using-airflow-33d312537bae [2]: Why we switched to Apache Airflow: https://www.solita.fi/en/blogs/why-we-switched-to-apache-airflow/ [3]: Why Robinhood uses Airflow: https://robinhood.engineering/why-robinhood-uses-airflow-aed13a9a90c8 [4]: Airflow: How and when to use it: https://towardsdatascience.com/airflow-how-and-when-to-use-it-2e07108ac9f5 [5]: Getting started with Apache Airflow: https://towardsdatascience.com/getting-started-with-apache-airflow-df1aa77d7b1b [6]: Airflow native operators: https://airflow.apache.org/docs/stable/_api/airflow/operators/index.html [7]: Airflow contrib operators: https://airflow.apache.org/docs/stable/_api/airflow/contrib/operators/index.html [8]: Kubernetes on Katacoda: https://www.katacoda.com/courses/kubernetes [9]: hgrif Airflow Tutorial: https://github.com/hgrif/airflow-tutorial [10]: Airflow Helm Chart: https://github.com/apache/airflow/tree/master/chart [11]: Amazon EFS CSI driver: https://github.com/kubernetes-sigs/aws-efs-csi-driver [12]: Go-daddy Kubernetes External Secrets: https://github.com/godaddy/kubernetes-external-secrets The Apache Airflow logo is either registered trademark or trademark of the Apache Software Foundation in the United States and/or other countries. No endorsement by The Apache Software Foundation is implied by the use of these marks. The Kubernetes logo files are licensed under a choice of either Apache-2.0 or CC-BY-4.0 (Creative Commons Attribution 4.0 International).
[ { "code": null, "e": 626, "s": 172, "text": "My humble opinion on Apache Airflow: basically, if you have more than a couple of automated tasks to schedule, and you are fiddling around with cron tasks that run even when some dependency of them fails, you should give it a try. But if you are not willing to just accept my words, feel free to check these posts.1 2 3 Delve into Airflow concepts and how it works is beyond the scope of this article. For that matter, please check these other posts.4 5" }, { "code": null, "e": 1545, "s": 626, "text": "Long story short, its task definitions are code based, what means that they could be as dynamic as you wish. You can create tasks and define your task dependencies based on variables or conditionals. It has plenty of native operators (definitions of task types)6 that integrate your workflow with lots of other tools and allow you to run from the most basic shell scripts to parallel data processing with Apache Spark, and a plethora of other options. Contributor operators7 are also available for a great set of commercial tools and the list keeps growing every day. These operators are python classes, so they are extensible and could be modified to fit your needs. You can even create your own operators from scratch, inheriting from the BaseOperator class. Also, it makes your workflow scalable to hundreds or even thousands of tasks with little effort using its distributed executors such as Celery or Kubernetes." }, { "code": null, "e": 2410, "s": 1545, "text": "We are using Airflow in iFood since 2018. Our first implementation was really nice, based on docker containers to run each task in an isolated environment. It underwent a lot of changes since then, from a simple tool to serve our team’s workload to a task scheduling platform to serve the more than 200 people with a lot of abstractions on the top of it. At the end, it does not matter if you are a software engineer with years of experience or a business analyst with minimal SQL knowledge, you can schedule your task using our platform writing a yaml file with three simple fields: the ID of your task, the path of the file containing your queries and the name of its table dependencies (i.e. to run my task I depend on the tables orders and users), and voilà, you have your task scheduled to run daily. But this, unfortunately, is a topic for a future article." }, { "code": null, "e": 2677, "s": 2410, "text": "It was obvious that we would need to scale our application from an AWS t2.medium EC2 instance to something more powerful. Our first approaches were to scale vertically to an r4.large instance, and then to an r4.xlarge, but the memory usage was constantly increasing." }, { "code": null, "e": 3087, "s": 2677, "text": "Our company grows fast. There are dozens of tasks being created every day and suddenly we would be running on an r4.16xlarge instance. We needed a way to scale the application horizontally and, more than that, to upscale it considering the peak hours and to downscale it at dawn to minimize needless costs. At that point, we were migrating all our platforms to run on a Kubernetes cluster, so why not Airflow?" }, { "code": null, "e": 4184, "s": 3087, "text": "I searched on the internet, from the official Apache Airflow documentation to Medium articles, digging for information on how to run a simple implementation of Airflow on Kubernetes with the KubernetesExecutor (I was aware of the CeleryExecutor existence, but it would not fit our needs, considering that you need to spin your workers upfront, with no native auto-scaling). I found a lot of people talking about the benefits of running Airflow on Kubernetes, the architecture behind it and a bunch of Helm charts, but little information on how to deploy it, piece by piece, in a logical way for a Kubernetes beginner. And that is the main point of this article. Assuming that you know Apache Airflow, and how its components work together, the idea is to show you how you can deploy it to run on Kubernetes leveraging the benefits of the KubernetesExecutor, with some extra information on the Kubernetes resources involved (yaml files). The examples will be AWS-based, but I am sure that with little research you can port the information to any cloud service you want or even run the code on-prem." }, { "code": null, "e": 4276, "s": 4184, "text": "To fully understand the sections below and get things running, I am assuming that you have:" }, { "code": null, "e": 4627, "s": 4276, "text": "An AWS EKS cluster available, or another type of Kubernetes cluster, locally or in a cloud environment.Basic “hands-on” knowledge on Kubernetes and kubectl tool. At least on how to deploy resources and check their descriptions and logs.Solid knowledge on Apache Airflow, and their units (configuration, scheduler, webserver, database, DAGs and tasks)" }, { "code": null, "e": 4731, "s": 4627, "text": "An AWS EKS cluster available, or another type of Kubernetes cluster, locally or in a cloud environment." }, { "code": null, "e": 4865, "s": 4731, "text": "Basic “hands-on” knowledge on Kubernetes and kubectl tool. At least on how to deploy resources and check their descriptions and logs." }, { "code": null, "e": 4980, "s": 4865, "text": "Solid knowledge on Apache Airflow, and their units (configuration, scheduler, webserver, database, DAGs and tasks)" }, { "code": null, "e": 5275, "s": 4980, "text": "If you do not, I recommend that you play a little with Kubernetes and Airflow locally. You can find awesome tutorials in the internet, even at the official websites. For Kubernetes, you can start with the Katacoda tutorials.8 Regarding Apache Airflow, this was the first tutorial I ever tried.9" }, { "code": null, "e": 6083, "s": 5275, "text": "As a starting point, I found a way to get the Kubernetes resource yaml files from the official Helm chart available at the Airflow git repository.10 That brought me a lot of resources, some of them came empty (probably because I used the base values.yaml to fill the templates used by Helm) and some of them were useless to the KubernetesExecutor approach (i.e. I do not need a Redis cluster, or a Flower resource, or a result back-end, as these are specific to Celery). Removing those useless resources, I ended up with something around 15 resource files and some of them I did not even know at that time. Kinda overwhelming! I also removed all resources that were related to the PostgreSQL instance (i.e. pgbouncer), because I knew that I would use an AWS RDS instance, external to the Kubernetes cluster." }, { "code": null, "e": 6676, "s": 6083, "text": "Obs: I had these charts locally, so when I executed the helm template command, helm whined about not finding the PostgreSQL charts (it will not happen if you are using the Helm repositories). If that is your case, just create the path charts/ inside the folder containing your helm chart and put the postgresql/ helm chart folder inside of it (available at the official Helm charts github repository). It is also important to notice that the Apache Airflow helm chart available at https://github.com/helm/charts will bring you a different set of resources when compared to the chart I used.10" }, { "code": null, "e": 6736, "s": 6676, "text": "After all the cleaning, I ended up with these 12 resources:" }, { "code": null, "e": 7197, "s": 6736, "text": "resources├── configmap.yaml├── dags-persistent-volume-claim.yaml├── rbac│ ├── pod-launcher-rolebinding.yaml│ └── pod-launcher-role.yaml├── scheduler│ ├── scheduler-deployment.yaml│ └── scheduler-serviceaccount.yaml├── secrets│ └── metadata-connection-secret.yaml├── statsd│ ├── statsd-deployment.yaml│ └── statsd-service.yaml├── webserver│ ├── webserver-deployment.yaml│ └── webserver-service.yaml└── workers └── worker-serviceaccount.yaml" }, { "code": null, "e": 7608, "s": 7197, "text": "Most of the articles I found describe two ways to store DAG information: storing the DAGs on a persistent volume accessible from multiple AWS availability zones, such as the AWS Elastic File System (EFS), or syncing them from a git repository to an ephemeral volume mounted inside the cluster. If that pod dies, when another one is created, it will sync with the repository again to get the last modifications." }, { "code": null, "e": 8311, "s": 7608, "text": "Due to our present workflow, we need to build our DAGs dynamically from lots of tasks written in yaml files, meaning that our DAGs are not ready when the files are versioned on a git repository. A simple git-sync to bring information would not work for us, but it could be a starting point. Considering that we also needed some kind of persistence for our logs, we decided to go for the EFS approach too, using some kind of hybrid of what we found online: git-sync our yaml files to a PersistentVolume mounted on the top of an EFS, and to have another pod processing it and throwing the freshly-built DAGs into the folder that the scheduler and the webserver are constantly watching to fill the DagBag." }, { "code": null, "e": 8522, "s": 8311, "text": "As shown above, to mount the EFS inside the EKS cluster, I used the official AWS CSI driver,11 that must be installed in the cluster. And beyond the driver, this approach accounts for five Kubernetes resources:" }, { "code": null, "e": 8556, "s": 8522, "text": "2 PersistentVolume(s): DAGs, logs" }, { "code": null, "e": 8628, "s": 8556, "text": "2 PersistentVolumeClaim(s): DAGs, logs (analogous to the previous ones)" }, { "code": null, "e": 8643, "s": 8628, "text": "1 StorageClass" }, { "code": null, "e": 8756, "s": 8643, "text": "These resources were not present in the initial list, as the original deployments used emptyDir volumes instead." }, { "code": null, "e": 9448, "s": 8756, "text": "Anyone that worked with Apache Airflow for some time knows that the airflow.cfg file (and maybe webserver_config.py file) is pretty important to set the things up. But throwing it inside the EFS volume did not seem wise, because of the sensitive information it contains (database passwords, fernet key). Then, I found out that the Kubernetes way to store configuration files is to use ConfigMap, a kind of \"volume\" that you mount inside the pods to expose a configuration file for them. And there is the Kubernetes Secret too, to store sensitive data. They work together, so I can reference a Secret inside a ConfigMap, or even pass a Secret to an environment variable. Mission accomplished!" }, { "code": null, "e": 9810, "s": 9448, "text": "As you learn a little bit more about Kubernetes, you will notice that the “plain” secrets are somewhat unsafe to version in a repository. They contain base64 strings that can be readily “decrypted” in your terminal using the base64 -d command. Take a look on this ExternalSecrets API,12 to store your secrets on AWS Parameter Store and retrieve them from there." }, { "code": null, "e": 9932, "s": 9810, "text": "If you check the list of files above, you will notice that the ConfigMap is already there, you just have to customize it." }, { "code": null, "e": 10417, "s": 9932, "text": "My little experience with Kubernetes was enough at that point to make me think that I would need at least two deployments: one for the scheduler and one for the webserver. And they were there, lying inside the scheduler and webserver folders generated by the Helm Chart explosion. There was a third deployment, of a statsd application, that I found later to be related to metrics collection inside the application. Cool, one thing less to worry! Prometheus will be happy to scrape it." }, { "code": null, "e": 10735, "s": 10417, "text": "I opened the files and noticed that they have some familiar environment variables, related to the fernet key and the database connection string. I filled them with the data retrieved by the Kubernetes secrets. I needed to tweak the volume part a little bit, to match my EFS PersistentVolume and PersistentVolumeClaim." }, { "code": null, "e": 11135, "s": 10735, "text": "It is easy to notice these shell scripts being executed as init containers. They are related to the database migrations that happen when Airflow starts. The scheduler pod runs the migrations as soon as it starts, and the webserver pod keeps waiting for it to finish before starting the webserver container. The webserver deployment has a very similar structure, so I took the liberty of omitting it." }, { "code": null, "e": 11294, "s": 11135, "text": "There was. A Kubernetes service resource exposing the port 8080 of the container. Later I included an Ingress resource to give it an AWS Route53 friendly DNS." }, { "code": null, "e": 11465, "s": 11294, "text": "The statsd application also listens at an endpoint and has a service associated to it. Both the services were included in the files exported by the helm template command." }, { "code": null, "e": 11926, "s": 11465, "text": "I tried to apply those configurations to the cluster. Scheduler and webserver were up, both connected to my external RDS PostgreSQL database. I thought: “If I throw some DAGs into the dags folder, then it should work, right?” And it kinda did! I created a simple DAG with one task based on the KubernetesPodOperator, using a container image stored at the AWS Elastic Container Registry. I double checked if my pod would be allowed to access the ECR repository." }, { "code": null, "e": 12759, "s": 11926, "text": "Then, I triggered the DAG, but it failed (you really didn’t think it would be that easy, right?). Checking the logs I noticed that it happened due some kind of permission issue. My scheduler did not have the permission to spawn new pods. And then I understood the need for that ServiceAccount resources scattered among the folders, and the ClusterRole and ClusterRoleBinding stuff. These guys are there to allow your resources to spawn new resources. After all the configuration, I could make my task run successfully. The KubernetesPodOperator also has the service_account_name parameter, that should be filled with a ServiceAccount resource name able to spawn pods, because that is what it will do: spawn another pod with the image you passed as an argument to the image parameter. That pod will be in charge of running your task." }, { "code": null, "e": 13030, "s": 12759, "text": "If you want to run tasks directly from your webserver, clicking on that “Run” button inside the task menu, you must give your webserver ServiceAccount the permissions to watch and spawn pods too. If you forget that, your tasks will be triggered, but they will never run." }, { "code": null, "e": 13375, "s": 13030, "text": "If you are running your stuff on AWS, you need to make sure your pods will be able to access all AWS resources, such as S3, DynamoDB tables, EMR, and so on. To do so, you need to bind your ServiceAccount resource to an AWS IAM role with IAM policies attached, to grant you all the access you need. Just give your IAM role an assume role policy:" }, { "code": null, "e": 13516, "s": 13375, "text": "The ServiceAccount for your worker and tasks should be linked to the IAM Role attached to the policy above. You can do it using annotations:" }, { "code": null, "e": 13649, "s": 13516, "text": "If you are following this journey as a tutorial, after all the tweaking you can just create all the above resources in your cluster:" }, { "code": null, "e": 13689, "s": 13649, "text": "kubectl apply -f resources/ --recursive" }, { "code": null, "e": 14198, "s": 13689, "text": "But, wait! Do not apply them yet! If you are a watchful reader, you noticed that most of the resources above makes reference to the airflow-on-k8s namespace. A Namespace is a way to tell Kubernetes that all resources in the same namespace are somewhat related (i.e. they are part of the same project) and is a nice way to organize things inside the cluster. You should declare your Namespace resource inside the resources/ folder and apply it before applying everything else, otherwise you will get an error." }, { "code": null, "e": 14390, "s": 14198, "text": "FYI, not every resource on Kubernetes is namespaced (i.e. PersistentVolume, StorageClass and other low-level resources), and that is why some of them do not have any reference to a namespace." }, { "code": null, "e": 14644, "s": 14390, "text": "And that was a fast-forward take on my journey to deploy Airflow on Kubernetes. I tried to cover all kinds of resources generated by the helm chart export, but feel free to ask your questions in the comments section if you think I left something behind." }, { "code": null, "e": 14914, "s": 14644, "text": "These yaml resources above were taken from a functional deployment I made. Some of them I built from scratch, and others I adapted from the ones I exported. I suggest that you take your time understanding them and making changes for better organization and performance." }, { "code": null, "e": 15542, "s": 14914, "text": "There is a lot more you can do to get the most of this implementation. You can set the limits and requests fields for your containers inside the deployments, to make sure they will have the necessary resources available for them to work properly. Going further on the benefits of Kubernetes, you will see that the KubernetesPodOperator allows you to label your pods and pass a lot of Kubernetes configurations to it, such as affinities, tolerations and a bunch of other stuff. If you have tainted nodes, you can assure that just some specific pods will run on them, reserving the most powerful nodes to the most critical tasks." }, { "code": null, "e": 15694, "s": 15542, "text": "If you tried this setup and have something to add, something that worked like a charm or turned out to be a bad choice, please tell us in the comments." }, { "code": null, "e": 15809, "s": 15694, "text": "[1]: 10 Benefits to using Airflow: https://medium.com/analytics-and-data/10-benefits-to-using-airflow-33d312537bae" }, { "code": null, "e": 15915, "s": 15809, "text": "[2]: Why we switched to Apache Airflow: https://www.solita.fi/en/blogs/why-we-switched-to-apache-airflow/" }, { "code": null, "e": 16018, "s": 15915, "text": "[3]: Why Robinhood uses Airflow: https://robinhood.engineering/why-robinhood-uses-airflow-aed13a9a90c8" }, { "code": null, "e": 16131, "s": 16018, "text": "[4]: Airflow: How and when to use it: https://towardsdatascience.com/airflow-how-and-when-to-use-it-2e07108ac9f5" }, { "code": null, "e": 16253, "s": 16131, "text": "[5]: Getting started with Apache Airflow: https://towardsdatascience.com/getting-started-with-apache-airflow-df1aa77d7b1b" }, { "code": null, "e": 16357, "s": 16253, "text": "[6]: Airflow native operators: https://airflow.apache.org/docs/stable/_api/airflow/operators/index.html" }, { "code": null, "e": 16470, "s": 16357, "text": "[7]: Airflow contrib operators: https://airflow.apache.org/docs/stable/_api/airflow/contrib/operators/index.html" }, { "code": null, "e": 16543, "s": 16470, "text": "[8]: Kubernetes on Katacoda: https://www.katacoda.com/courses/kubernetes" }, { "code": null, "e": 16614, "s": 16543, "text": "[9]: hgrif Airflow Tutorial: https://github.com/hgrif/airflow-tutorial" }, { "code": null, "e": 16692, "s": 16614, "text": "[10]: Airflow Helm Chart: https://github.com/apache/airflow/tree/master/chart" }, { "code": null, "e": 16775, "s": 16692, "text": "[11]: Amazon EFS CSI driver: https://github.com/kubernetes-sigs/aws-efs-csi-driver" }, { "code": null, "e": 16874, "s": 16775, "text": "[12]: Go-daddy Kubernetes External Secrets: https://github.com/godaddy/kubernetes-external-secrets" } ]
Overriding Methods in Python
You can always override your parent class methods. One reason for overriding parent's methods is because you may want special or different functionality in your subclass. Live Demo #!/usr/bin/python class Parent: # define parent class def myMethod(self): print 'Calling parent method' class Child(Parent): # define child class def myMethod(self): print 'Calling child method' c = Child() # instance of child c.myMethod() # child calls overridden method When the above code is executed, it produces the following result − Calling child method
[ { "code": null, "e": 1233, "s": 1062, "text": "You can always override your parent class methods. One reason for overriding parent's methods is because you may want special or different functionality in your subclass." }, { "code": null, "e": 1244, "s": 1233, "text": " Live Demo" }, { "code": null, "e": 1539, "s": 1244, "text": "#!/usr/bin/python\nclass Parent: # define parent class\n def myMethod(self):\n print 'Calling parent method'\nclass Child(Parent): # define child class\n def myMethod(self):\n print 'Calling child method'\nc = Child() # instance of child\nc.myMethod() # child calls overridden method" }, { "code": null, "e": 1607, "s": 1539, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 1628, "s": 1607, "text": "Calling child method" } ]
Possible edges of a tree for given diameter, height and vertices - GeeksforGeeks
14 May, 2021 Find a tree with the given values and print the edges of the tree. Print “-1”, if the tree is not possible. Given three integers n, d and h. n -> Number of vertices. [1, n] d -> Diameter of the tree (largest distance between two vertices). h -> Height of the tree (longest distance between vertex 1 and another vertex) Examples : Input : n = 5, d = 3, h = 2 Output : 1 2 2 3 1 4 1 5 Explanation : We can see that the height of the tree is 2 (1 -> 2 --> 5) and diameter is 3 ( 3 -> 2 -> 1 -> 5). So our conditions are satisfied. Input : n = 8, d = 4, h = 2 Output : 1 2 2 3 1 4 4 5 1 6 1 7 1 8 Explanation : Observe that when d = 1, we cannot construct a tree (if tree has more than 2 vertices). Also when d > 2*h, we cannot construct a tree.As we know that height is the longest path from vertex 1 to another vertex. So build that path from vertex 1 by adding edges up to h. Now, if d > h, we should add another path to satisfy diameter from vertex 1, with a length of d – h.Our conditions for height and diameter are satisfied. But still some vertices may be left. Add the remaining vertices at any vertex other than the end points. This step will not alter our diameter and height. Chose vertex 1 to add the remaining vertices (you can chose any).But when d == h, choose vertex 2 to add the remaining vertices. Observe that when d = 1, we cannot construct a tree (if tree has more than 2 vertices). Also when d > 2*h, we cannot construct a tree. As we know that height is the longest path from vertex 1 to another vertex. So build that path from vertex 1 by adding edges up to h. Now, if d > h, we should add another path to satisfy diameter from vertex 1, with a length of d – h. Our conditions for height and diameter are satisfied. But still some vertices may be left. Add the remaining vertices at any vertex other than the end points. This step will not alter our diameter and height. Chose vertex 1 to add the remaining vertices (you can chose any). But when d == h, choose vertex 2 to add the remaining vertices. C++ Java Python3 C# Javascript // C++ program to construct tree for given count// width and height.#include <bits/stdc++.h>using namespace std; // Function to construct the treevoid constructTree(int n, int d, int h){ if (d == 1) { // Special case when d == 2, only one edge if (n == 2 && h == 1) { cout << "1 2" << endl; return; } cout << "-1" << endl; // Tree is not possible return; } if (d > 2 * h) { cout << "-1" << endl; return; } // Satisfy the height condition by add // edges up to h for (int i = 1; i <= h; i++) cout << i << " " << i + 1 << endl; if (d > h) { // Add d - h edges from 1 to // satisfy diameter condition cout << "1" << " " << h + 2 << endl; for (int i = h + 2; i <= d; i++) { cout << i << " " << i + 1 << endl; } } // Remaining edges at vertex 1 or 2(d == h) for (int i = d + 1; i < n; i++) { int k = 1; if (d == h) k = 2; cout << k << " " << i + 1 << endl; }} // Driver Codeint main(){ int n = 5, d = 3, h = 2; constructTree(n, d, h); return 0;} // Java program to construct tree for given count// width and height.class GfG { // Function to construct the treestatic void constructTree(int n, int d, int h){ if (d == 1) { // Special case when d == 2, only one edge if (n == 2 && h == 1) { System.out.println("1 2"); return; } System.out.println("-1"); // Tree is not possible return; } if (d > 2 * h) { System.out.println("-1"); return; } // Satisfy the height condition by add // edges up to h for (int i = 1; i <= h; i++) System.out.println(i + " " + (i + 1)); if (d > h) { // Add d - h edges from 1 to // satisfy diameter condition System.out.println("1" + " " + (h + 2)); for (int i = h + 2; i <= d; i++) { System.out.println(i + " " + (i + 1)); } } // Remaining edges at vertex 1 or 2(d == h) for (int i = d + 1; i < n; i++) { int k = 1; if (d == h) k = 2; System.out.println(k + " " + (i + 1)); }} // Driver Codepublic static void main(String[] args){ int n = 5, d = 3, h = 2; constructTree(n, d, h);}} # Python3 code to construct tree for given count# width and height. # Function to construct the treedef constructTree(n, d, h): if d == 1: # Special case when d == 2, only one edge if n == 2 and h == 1: print("1 2") return 0 print("-1") # Tree is not possible return 0 if d > 2 * h: print("-1") return 0 # Satisfy the height condition by add # edges up to h for i in range(1, h+1): print(i," " , i + 1) if d > h: # Add d - h edges from 1 to # satisfy diameter condition print(1," ", h + 2) for i in range(h+2, d+1): print(i, " " , i + 1) # Remaining edges at vertex 1 or 2(d == h) for i in range(d+1, n): k = 1 if d == h: k = 2 print(k ," " , i + 1) # Driver Coden = 5d = 3h = 2constructTree(n, d, h) # This code is contributed by "Sharad_Bhardwaj". // C# program to construct tree for // given count width and height.using System; class GfG{ // Function to construct the tree static void constructTree(int n, int d, int h) { if (d == 1) { // Special case when d == 2, // only one edge if (n == 2 && h == 1) { Console.WriteLine("1 2"); return; } // Tree is not possible Console.WriteLine("-1"); return; } if (d > 2 * h) { Console.WriteLine("-1"); return; } // Satisfy the height condition // by add edges up to h for (int i = 1; i <= h; i++) Console.WriteLine(i + " " + (i + 1)); if (d > h) { // Add d - h edges from 1 to // satisfy diameter condition Console.WriteLine("1" + " " + (h + 2)); for (int i = h + 2; i <= d; i++) { Console.WriteLine(i + " " + (i + 1)); } } // Remaining edges at vertex 1 or 2(d == h) for (int i = d + 1; i < n; i++) { int k = 1; if (d == h) k = 2; Console.WriteLine(k + " " + (i + 1)); } } // Driver Code public static void Main(String[] args) { int n = 5, d = 3, h = 2; constructTree(n, d, h); }} // This code is contributed by 29AjayKumar <script> // Javascript program to construct tree for// given count width and height. // Function to construct the treefunction constructTree(n, d, h){ if (d == 1) { // Special case when d == 2, // only one edge if (n == 2 && h == 1) { document.write("1 2", "<br>"); return; } // Tree is not possible document.write("-1", "<br>"); return; } if (d > 2 * h) { document.write("-1", "<br>"); return; } // Satisfy the height condition // by add edges up to h for(var i = 1; i <= h; i++) document.write(i + " " + (i + 1), "<br>"); if (d > h) { // Add d - h edges from 1 to // satisfy diameter condition document.write("1" + " " + (h + 2), "<br>"); for(var i = h + 2; i <= d; i++) { document.write(i + " " + (i + 1), "<br>"); } } // Remaining edges at vertex 1 or 2(d == h) for(var i = d + 1; i < n; i++) { var k = 1; if (d == h) k = 2; document.write(k + " " + (i + 1), "<br>"); }} // Driver Codevar n = 5, d = 3, h = 2; constructTree(n, d, h); // This code is contributed by bunnyram19 </script> Output : 1 2 2 3 1 4 1 5 prerna saini 29AjayKumar bunnyram19 Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Inorder Tree Traversal without Recursion Binary Tree | Set 3 (Types of Binary Tree) Decision Tree Binary Tree | Set 2 (Properties) Complexity of different operations in Binary tree, Binary Search Tree and AVL tree A program to check if a binary tree is BST or not Construct Tree from given Inorder and Preorder traversals Introduction to Tree Data Structure Expression Tree Deletion in a Binary Tree
[ { "code": null, "e": 25358, "s": 25330, "text": "\n14 May, 2021" }, { "code": null, "e": 25466, "s": 25358, "text": "Find a tree with the given values and print the edges of the tree. Print “-1”, if the tree is not possible." }, { "code": null, "e": 25500, "s": 25466, "text": "Given three integers n, d and h. " }, { "code": null, "e": 25685, "s": 25500, "text": "n -> Number of vertices. [1, n]\nd -> Diameter of the tree (largest \n distance between two vertices).\nh -> Height of the tree (longest distance\n between vertex 1 and another vertex)" }, { "code": null, "e": 25697, "s": 25685, "text": "Examples : " }, { "code": null, "e": 25794, "s": 25697, "text": "Input : n = 5, d = 3, h = 2 \nOutput : 1 2\n 2 3\n 1 4\n 1 5\nExplanation : " }, { "code": null, "e": 26061, "s": 25794, "text": "We can see that the height of the tree is 2 (1 -> \n2 --> 5) and diameter is 3 ( 3 -> 2 -> 1 -> 5).\nSo our conditions are satisfied.\n\nInput : n = 8, d = 4, h = 2\nOutput : 1 2\n 2 3\n 1 4\n 4 5\n 1 6\n 1 7\n 1 8\nExplanation :" }, { "code": null, "e": 26767, "s": 26061, "text": "Observe that when d = 1, we cannot construct a tree (if tree has more than 2 vertices). Also when d > 2*h, we cannot construct a tree.As we know that height is the longest path from vertex 1 to another vertex. So build that path from vertex 1 by adding edges up to h. Now, if d > h, we should add another path to satisfy diameter from vertex 1, with a length of d – h.Our conditions for height and diameter are satisfied. But still some vertices may be left. Add the remaining vertices at any vertex other than the end points. This step will not alter our diameter and height. Chose vertex 1 to add the remaining vertices (you can chose any).But when d == h, choose vertex 2 to add the remaining vertices." }, { "code": null, "e": 26902, "s": 26767, "text": "Observe that when d = 1, we cannot construct a tree (if tree has more than 2 vertices). Also when d > 2*h, we cannot construct a tree." }, { "code": null, "e": 27137, "s": 26902, "text": "As we know that height is the longest path from vertex 1 to another vertex. So build that path from vertex 1 by adding edges up to h. Now, if d > h, we should add another path to satisfy diameter from vertex 1, with a length of d – h." }, { "code": null, "e": 27412, "s": 27137, "text": "Our conditions for height and diameter are satisfied. But still some vertices may be left. Add the remaining vertices at any vertex other than the end points. This step will not alter our diameter and height. Chose vertex 1 to add the remaining vertices (you can chose any)." }, { "code": null, "e": 27476, "s": 27412, "text": "But when d == h, choose vertex 2 to add the remaining vertices." }, { "code": null, "e": 27480, "s": 27476, "text": "C++" }, { "code": null, "e": 27485, "s": 27480, "text": "Java" }, { "code": null, "e": 27493, "s": 27485, "text": "Python3" }, { "code": null, "e": 27496, "s": 27493, "text": "C#" }, { "code": null, "e": 27507, "s": 27496, "text": "Javascript" }, { "code": "// C++ program to construct tree for given count// width and height.#include <bits/stdc++.h>using namespace std; // Function to construct the treevoid constructTree(int n, int d, int h){ if (d == 1) { // Special case when d == 2, only one edge if (n == 2 && h == 1) { cout << \"1 2\" << endl; return; } cout << \"-1\" << endl; // Tree is not possible return; } if (d > 2 * h) { cout << \"-1\" << endl; return; } // Satisfy the height condition by add // edges up to h for (int i = 1; i <= h; i++) cout << i << \" \" << i + 1 << endl; if (d > h) { // Add d - h edges from 1 to // satisfy diameter condition cout << \"1\" << \" \" << h + 2 << endl; for (int i = h + 2; i <= d; i++) { cout << i << \" \" << i + 1 << endl; } } // Remaining edges at vertex 1 or 2(d == h) for (int i = d + 1; i < n; i++) { int k = 1; if (d == h) k = 2; cout << k << \" \" << i + 1 << endl; }} // Driver Codeint main(){ int n = 5, d = 3, h = 2; constructTree(n, d, h); return 0;}", "e": 28677, "s": 27507, "text": null }, { "code": "// Java program to construct tree for given count// width and height.class GfG { // Function to construct the treestatic void constructTree(int n, int d, int h){ if (d == 1) { // Special case when d == 2, only one edge if (n == 2 && h == 1) { System.out.println(\"1 2\"); return; } System.out.println(\"-1\"); // Tree is not possible return; } if (d > 2 * h) { System.out.println(\"-1\"); return; } // Satisfy the height condition by add // edges up to h for (int i = 1; i <= h; i++) System.out.println(i + \" \" + (i + 1)); if (d > h) { // Add d - h edges from 1 to // satisfy diameter condition System.out.println(\"1\" + \" \" + (h + 2)); for (int i = h + 2; i <= d; i++) { System.out.println(i + \" \" + (i + 1)); } } // Remaining edges at vertex 1 or 2(d == h) for (int i = d + 1; i < n; i++) { int k = 1; if (d == h) k = 2; System.out.println(k + \" \" + (i + 1)); }} // Driver Codepublic static void main(String[] args){ int n = 5, d = 3, h = 2; constructTree(n, d, h);}}", "e": 29855, "s": 28677, "text": null }, { "code": "# Python3 code to construct tree for given count# width and height. # Function to construct the treedef constructTree(n, d, h): if d == 1: # Special case when d == 2, only one edge if n == 2 and h == 1: print(\"1 2\") return 0 print(\"-1\") # Tree is not possible return 0 if d > 2 * h: print(\"-1\") return 0 # Satisfy the height condition by add # edges up to h for i in range(1, h+1): print(i,\" \" , i + 1) if d > h: # Add d - h edges from 1 to # satisfy diameter condition print(1,\" \", h + 2) for i in range(h+2, d+1): print(i, \" \" , i + 1) # Remaining edges at vertex 1 or 2(d == h) for i in range(d+1, n): k = 1 if d == h: k = 2 print(k ,\" \" , i + 1) # Driver Coden = 5d = 3h = 2constructTree(n, d, h) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 30818, "s": 29855, "text": null }, { "code": "// C# program to construct tree for // given count width and height.using System; class GfG{ // Function to construct the tree static void constructTree(int n, int d, int h) { if (d == 1) { // Special case when d == 2, // only one edge if (n == 2 && h == 1) { Console.WriteLine(\"1 2\"); return; } // Tree is not possible Console.WriteLine(\"-1\"); return; } if (d > 2 * h) { Console.WriteLine(\"-1\"); return; } // Satisfy the height condition // by add edges up to h for (int i = 1; i <= h; i++) Console.WriteLine(i + \" \" + (i + 1)); if (d > h) { // Add d - h edges from 1 to // satisfy diameter condition Console.WriteLine(\"1\" + \" \" + (h + 2)); for (int i = h + 2; i <= d; i++) { Console.WriteLine(i + \" \" + (i + 1)); } } // Remaining edges at vertex 1 or 2(d == h) for (int i = d + 1; i < n; i++) { int k = 1; if (d == h) k = 2; Console.WriteLine(k + \" \" + (i + 1)); } } // Driver Code public static void Main(String[] args) { int n = 5, d = 3, h = 2; constructTree(n, d, h); }} // This code is contributed by 29AjayKumar", "e": 32289, "s": 30818, "text": null }, { "code": "<script> // Javascript program to construct tree for// given count width and height. // Function to construct the treefunction constructTree(n, d, h){ if (d == 1) { // Special case when d == 2, // only one edge if (n == 2 && h == 1) { document.write(\"1 2\", \"<br>\"); return; } // Tree is not possible document.write(\"-1\", \"<br>\"); return; } if (d > 2 * h) { document.write(\"-1\", \"<br>\"); return; } // Satisfy the height condition // by add edges up to h for(var i = 1; i <= h; i++) document.write(i + \" \" + (i + 1), \"<br>\"); if (d > h) { // Add d - h edges from 1 to // satisfy diameter condition document.write(\"1\" + \" \" + (h + 2), \"<br>\"); for(var i = h + 2; i <= d; i++) { document.write(i + \" \" + (i + 1), \"<br>\"); } } // Remaining edges at vertex 1 or 2(d == h) for(var i = d + 1; i < n; i++) { var k = 1; if (d == h) k = 2; document.write(k + \" \" + (i + 1), \"<br>\"); }} // Driver Codevar n = 5, d = 3, h = 2; constructTree(n, d, h); // This code is contributed by bunnyram19 </script>", "e": 33557, "s": 32289, "text": null }, { "code": null, "e": 33567, "s": 33557, "text": "Output : " }, { "code": null, "e": 33583, "s": 33567, "text": "1 2\n2 3\n1 4\n1 5" }, { "code": null, "e": 33598, "s": 33585, "text": "prerna saini" }, { "code": null, "e": 33610, "s": 33598, "text": "29AjayKumar" }, { "code": null, "e": 33621, "s": 33610, "text": "bunnyram19" }, { "code": null, "e": 33626, "s": 33621, "text": "Tree" }, { "code": null, "e": 33631, "s": 33626, "text": "Tree" }, { "code": null, "e": 33729, "s": 33631, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33738, "s": 33729, "text": "Comments" }, { "code": null, "e": 33751, "s": 33738, "text": "Old Comments" }, { "code": null, "e": 33792, "s": 33751, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 33835, "s": 33792, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 33849, "s": 33835, "text": "Decision Tree" }, { "code": null, "e": 33882, "s": 33849, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 33965, "s": 33882, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 34015, "s": 33965, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 34073, "s": 34015, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 34109, "s": 34073, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 34125, "s": 34109, "text": "Expression Tree" } ]
Develop, Train and Deploy TensorFlow Models using Google Cloud AI Platform | by MA Raza, Ph.D. | Towards Data Science
The TensorFlow ecosystem has become very popular for developing applications involving deep learning. One of the reasons is that it has a strong community and a lot of tools have been developed around the core library to support developers. In this tutorial, I will guide you through how to prototype models in google colab, train it on Google Cloud AI Platform, and deploy the finalized model on Google Cloud AI Platform for production. I will include the working Google colab notebooks to recreate the work. Google colab is a free resource for prototyping models in TensorFlow and comes with various runtime. Preparing a machine with GPU or TPU could be costly to start with however users can start with free GPU with google colab. Bear in mind, colab has limited resources and might not be suitable for properly training models requiring large compute resources. Nonetheless, colab is a perfect tool for prototyping your models and some initial experimentation. Once you are satisfied with your model pipeline, it is time to train the model with the proper number of EPOCHS and full datasets. As you might know, training deep learning models requires a long time and a large cluster of CPU’s GPUs or TPU’s. One option is that users set up their own computing cluster which is costly and time-consuming most of the time. Another option is to use cloud computing to training the model and pay as you go. TensorFlow team has released a package called Tensorflow Cloud to let users train the models on the Google Cloud platform without any hassle. I have followed steps from Train your TensorFlow model on Google Cloud using TensorFlow Cloud blog and will share some issues I have faced to make it work. Some of the pre-requisites are ad defined in the project guidelines for submitting a training job to the GCP platform. Python >= 3.5 A Google Cloud project An authenticated GCP account Google AI platform APIs enabled for your GCP account. We use the AI platform for deploying docker images on GCP. Either a functioning version of docker if you want to use a local docker process for your build, or create a cloud storage bucket to use with Google Cloud build for docker image build and publishing. After creating the GCP project, follow the below steps to config the environment with Google cloud authentication. # Authenticate from google.colab import authauth.authenticate_user() Set PROJECT_ID in the environment os.environ['PROJECT_ID']='gcpessentials-rz'!gcloud config set project $PROJECT_ID Create the Service Account and set some permissions needed for tensorflow-cloud the package. Download the service account key and add as an environment variable as GOOGLE_APPLICATION_CREDENTIALS. These credentials will be needed to submit the job to the google cloud platform. os.environ['PROJECT_ID']='gcpessentials-rz'!gcloud config set project $PROJECT_IDos.environ['SA_NAME']='gcpessentials-rz'!gcloud iam service-accounts create $SA_NAME!gcloud projects add-iam-policy-binding $PROJECT_ID \--member serviceAccount:$SA_NAME@$PROJECT_ID.iam.gserviceaccount.com \--role 'roles/editor'!gcloud iam service-accounts keys create key.json --iam-account $SA_NAME@$PROJECT_ID.iam.gserviceaccount.comos.environ['GOOGLE_APPLICATION_CREDENTIALS']='key.json' Even after following the above steps, I have to enable service Accounts and cloud_build Status under Cloud Build settings. Below is the snapshot of my project settings. The next step is to create GCP_BUCKET to store the data needed for submitting the job to Google Cloud. BUCKET = 'tf2-model-training'!gsutil mb gs://$BUCKET Once we have set up the environment in our google colab and created the GCP_BUCKET, we have to prepare the notebook with training the model. Below are some key points to consider while preparing a notebook. Test the code in a notebook using google colab for a small number of EPOCHSMake sure, there are no errors in the notebook and remove any unnecessary codePrepare the requirements.txt and upload to google colab environment.Save the trained model in GCP_BUCKET (will be used for Deployment) Test the code in a notebook using google colab for a small number of EPOCHS Make sure, there are no errors in the notebook and remove any unnecessary code Prepare the requirements.txt and upload to google colab environment. Save the trained model in GCP_BUCKET (will be used for Deployment) Once we are ready with the notebook, we submit the training on Google Cloud platform using tensorflow-cloud package. import tensorflow_cloud as tfcBUCKET = 'tf2-model-training'labels= {'phase': 'test','owner': 'raza',}tfc.run(requirements_txt="requirements.txt",distribution_strategy="auto",chief_config='auto',docker_image_bucket_name=BUCKET,job_labels=labels,) The above code will convert the notebook into identifier-Fg45-a.py and submit the training on the Google Cloud platform in the docker form. After you submit the job, you can see the message like the below figure. Wait for a few minutes before the job starts actually training By clicking on the provided link, you will see a page like below figure You can see the logs by clicking the view logs and will look like the below figure. Logs are helpful to see what sort of Exceptions happened in your code. Before submitting the huge job, test your pipeline submission script for few EPOCHS and then submit the complete job If all goes well, your model will be trained using the Google AI platform and saved in GCP_BUCKET along with other resources. Below is the working notebook to run the training on Google AI Platform using the TensorFlow-Cloud package. # Install tensorflow # !pip install tensorflow==2.3.0 # !pip install tensorflow_cloud # Import libraries # from __future__ import absolute_import, division, print_function, unicode_literals import pandas as pd from sklearn.preprocessing import MinMaxScaler import os import numpy as np from datetime import datetime import tensorflow as tf from tensorflow.keras.layers import Dense, Flatten, Conv2D from tensorflow.keras import Model from tensorflow.keras.models import Sequential, load_model import tensorflow_cloud as tfc #Load the tensorboard extension # Load tensorboard # %load_ext tensorboard # Upload requirements.txt file # from google.colab import files # uploaded = files.upload() Saving requirements.txt to requirements (1).txt BUCKET = 'tf2-model-training' labels= { 'phase': 'test', 'owner': 'User', } tfc.run( requirements_txt="requirements.txt", distribution_strategy="auto", chief_config='auto', docker_image_bucket_name=BUCKET, job_labels=labels, ) INFO:tensorflow_cloud.core.containerize:Uploading files to GCS. INFO:tensorflow_cloud.core.containerize:Building and publishing docker image using Google Cloud Build: gcr.io/gcpessentials-rz/tf_cloud_train:f96196a6_a0c1_44f1_a9f4_ec99a6880da6 INFO:googleapiclient.discovery:URL being requested: GET https://www.googleapis.com/discovery/v1/apis/cloudbuild/v1/rest INFO:googleapiclient.discovery:URL being requested: POST https://cloudbuild.googleapis.com/v1/projects/gcpessentials-rz/builds?alt=json INFO:googleapiclient.discovery:URL being requested: GET https://cloudbuild.googleapis.com/v1/projects/gcpessentials-rz/builds/f6f3e56d-e615-4ee1-b5d2-4c3108470858?alt=json INFO:googleapiclient.discovery:URL being requested: GET https://cloudbuild.googleapis.com/v1/projects/gcpessentials-rz/builds/f6f3e56d-e615-4ee1-b5d2-4c3108470858?alt=json INFO:googleapiclient.discovery:URL being requested: GET https://cloudbuild.googleapis.com/v1/projects/gcpessentials-rz/builds/f6f3e56d-e615-4ee1-b5d2-4c3108470858?alt=json INFO:googleapiclient.discovery:URL being requested: GET https://cloudbuild.googleapis.com/v1/projects/gcpessentials-rz/builds/f6f3e56d-e615-4ee1-b5d2-4c3108470858?alt=json INFO:googleapiclient.discovery:URL being requested: GET https://cloudbuild.googleapis.com/v1/projects/gcpessentials-rz/builds/f6f3e56d-e615-4ee1-b5d2-4c3108470858?alt=json INFO:googleapiclient.discovery:URL being requested: GET https://cloudbuild.googleapis.com/v1/projects/gcpessentials-rz/builds/f6f3e56d-e615-4ee1-b5d2-4c3108470858?alt=json INFO:googleapiclient.discovery:URL being requested: GET https://cloudbuild.googleapis.com/v1/projects/gcpessentials-rz/builds/f6f3e56d-e615-4ee1-b5d2-4c3108470858?alt=json INFO:googleapiclient.discovery:URL being requested: GET https://cloudbuild.googleapis.com/v1/projects/gcpessentials-rz/builds/f6f3e56d-e615-4ee1-b5d2-4c3108470858?alt=json INFO:googleapiclient.discovery:URL being requested: GET https://cloudbuild.googleapis.com/v1/projects/gcpessentials-rz/builds/f6f3e56d-e615-4ee1-b5d2-4c3108470858?alt=json INFO:googleapiclient.discovery:URL being requested: GET https://www.googleapis.com/discovery/v1/apis/ml/v1/rest INFO:googleapiclient.discovery:URL being requested: POST https://ml.googleapis.com/v1/projects/gcpessentials-rz/jobs?alt=json Job submitted successfully. Your job ID is: tf_cloud_train_28b2567c_c6e8_4e63_b86d_1cddc2a4a5bd Please access your job logs at the following URL: https://console.cloud.google.com/mlengine/jobs/tf_cloud_train_28b2567c_c6e8_4e63_b86d_1cddc2a4a5bd?project=gcpessentials-rz # Traing and Test data from github data_path= 'https://raw.githubusercontent.com/amjadraza/blogs-data/master/deep_leraning_tensorflow/' output_dir = 'tensorflow_out/' os.makedirs(output_dir, exist_ok=True) # Reading the traing and test data print('Loading the training data') training_data_df = pd.read_csv(data_path + 'sales_data_training.csv') test_data_df = pd.read_csv(data_path + 'sales_data_test.csv') scalar = MinMaxScaler(feature_range=(0,1)) scaled_training = scalar.fit_transform(training_data_df) scaled_test = scalar.fit_transform(test_data_df) scaled_training_df = pd.DataFrame(data = scaled_training, columns=training_data_df.columns) scaled_test_df = pd.DataFrame(data = scaled_test, columns=training_data_df.columns) # Splitting the feature and target columns. Using this dataset, we aim to predict total_earnings X = scaled_training_df.drop('total_earnings', axis=1).values Y = scaled_training_df['total_earnings'].values # Define the Model print('Building the Model') model = Sequential() model.add(Dense(50, input_dim=9, activation = 'relu')) model.add(Dense(100, activation = 'relu')) model.add(Dense(50, activation = 'relu')) model.add(Dense(1, activation = 'linear')) model.compile(loss = 'mean_squared_error', optimizer = 'adam') X_test = scaled_test_df.drop('total_earnings', axis=1).values Y_test = scaled_test_df['total_earnings'].values # if not tfc.remote(): # from google.colab import auth # auth.authenticate_user() # # GCP project name # os.environ['PROJECT_ID']='gcpessentials-rz' # !gcloud config set project $PROJECT_ID # os.environ['SA_NAME']='gcpessentials-rz' # !gcloud iam service-accounts create $SA_NAME # !gcloud projects add-iam-policy-binding $PROJECT_ID \ # --member serviceAccount:$SA_NAME@$PROJECT_ID.iam.gserviceaccount.com \ # --role 'roles/editor' # !gcloud iam service-accounts keys create key.json --iam-account $SA_NAME@$PROJECT_ID.iam.gserviceaccount.com # os.environ['GOOGLE_APPLICATION_CREDENTIALS']='key.json' # # Create the storage bucket for tf2 Models # # !gsutil mb $BUCKET # # !gcloud auth login # # os.environ['PROJECT_ID']='gcpessentials-rz' # # !gcloud config set project $PROJECT_ID # !gsutil mb gs://$BUCKET if tfc.remote(): # Collecting the logs in Google Cloud Storage MODEL_PATH = "TF" checkpoint_path = os.path.join("gs://", BUCKET, MODEL_PATH, "save_at_{epoch}") tensorboard_path = os.path.join( "gs://", BUCKET, "logs", datetime.now().strftime("%Y%m%d-%H%M%S") ) gcp_callbacks = [ tf.keras.callbacks.ModelCheckpoint(checkpoint_path), tf.keras.callbacks.TensorBoard(log_dir=tensorboard_path, histogram_freq=1), tf.keras.callbacks.EarlyStopping(monitor="val_loss", patience=3), ] epochs = 50 callbacks = gcp_callbacks else: # Setup for tensorboard tensorboard_path="logs/scalars/" + datetime.now().strftime("%Y%m%d-%H%M%S") checkpoint_path = os.path.join("logs","ckp", "save_at_{epoch}") tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=tensorboard_path) local_callbacks = [ tf.keras.callbacks.ModelCheckpoint(checkpoint_path), tf.keras.callbacks.TensorBoard(log_dir=tensorboard_path, histogram_freq=1), tf.keras.callbacks.EarlyStopping(monitor="val_loss", patience=3), ] epochs = 1 callbacks = local_callbacks training_history = model.fit(X, Y, epochs = epochs, shuffle=True, verbose=1, validation_data=(X_test, Y_test), callbacks=[callbacks]) print("Average test loss: ", np.average(training_history.history['loss'])) if tfc.remote(): MODEL = 'earnings-prediction' MODEL_SAVE_BUCKET = 'gs://gcpessentials-rz-tf2-models-serving' model.save(MODEL_SAVE_BUCKET + f'/{MODEL}', save_format='tf') 1/32 [..............................] - ETA: 0s - loss: 0.0078WARNING:tensorflow:Callbacks method `on_train_batch_end` is slow compared to the batch time (batch time: 0.0044s vs `on_train_batch_end` time: 0.0181s). Check your callbacks. WARNING:tensorflow:Callbacks method `on_train_batch_end` is slow compared to the batch time (batch time: 0.0044s vs `on_train_batch_end` time: 0.0181s). Check your callbacks. 12/32 [==========>...................] - ETA: 0s - loss: 0.0081WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/training/tracking/tracking.py:111: Model.state_updates (from tensorflow.python.keras.engine.training) is deprecated and will be removed in a future version. Instructions for updating: This property should not be used in TensorFlow 2.0, as updates are applied automatically. WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/training/tracking/tracking.py:111: Model.state_updates (from tensorflow.python.keras.engine.training) is deprecated and will be removed in a future version. Instructions for updating: This property should not be used in TensorFlow 2.0, as updates are applied automatically. WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/training/tracking/tracking.py:111: Layer.updates (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version. Instructions for updating: This property should not be used in TensorFlow 2.0, as updates are applied automatically. WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/training/tracking/tracking.py:111: Layer.updates (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version. Instructions for updating: This property should not be used in TensorFlow 2.0, as updates are applied automatically. INFO:tensorflow:Assets written to: logs/ckp/save_at_1/assets INFO:tensorflow:Assets written to: logs/ckp/save_at_1/assets 32/32 [==============================] - 1s 26ms/step - loss: 0.0056 - val_loss: 0.0048 Average test loss: 0.005643493961542845 Once the model is trained and finalized, users would like to deploy the model on a scale-able infrastructure. Google Cloud also provides the necessary infrastructure to deploy TensorFlow models on its platform without a lot of modifications. I will show you how to deploy the model on a google cloud platform. At the end of the training, we save the finalized model in Google Cloud Bucket. Below are the steps to deploy the model. Configure the models serving using AI Platform Perform the prediction on deployed model Use the below set of commands to configure the model for deployment withing Google colab. I have explained in detail how to deploy the model on Google Cloud in Model with TensorFlow and Serve on Google Cloud Platform. I have configured the model to serve as v2 following the same steps in the above tutorial. Once the model is deployed and you can see the green tick, it is time to test the model for predictions. Some important points to consider. Test the model prediction using Test & Use tab under your version or model tab. Input JSON data depends on how you define your model # [Reference](https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/ml_engine/online_prediction/predict.py)import googleapiclient.discoverydef predict_json(project, model, instances, version=None): service = googleapiclient.discovery.build('ml', 'v1') name = 'projects/{}/models/{}'.format(project, model) if version is not None: name += '/versions/{}'.format(version) response = service.projects().predict( name=name, body={'instances': instances} ).execute() if 'error' in response: raise RuntimeError(response['error']) return response['predictions'] Load the unseen data for predictions df_new_products = pd.read_csv(data_path + 'proposed_new_product.csv')tdata_instances = {'dense_input':df_new_products.values[0].tolist()}predictions_gcloud = predict_json(CLOUD_PROJECT, 'earnings_prediction', tdata_instances, version='v2')predictions_gcloud = predictions_gcloud[0]['dense_3'][0] + 0.1159predictions_gcloud = predictions_gcloud/0.0000036968print('Earnings predictions for Proposed product - ${}'.format(predictions_gcloud))Earnings predictions for Proposed product - $259671.15201209177 Below is the working notebook to perform prediction on the deployed model In this guide, we have learned about training the deep learning models with TensorFlow 2.3.0 using the Google Cloud AI platform with the help of tensorflow-cloud package and deployed the trained model on the Google Cloud AI platform too. Below are some key lessons Use Google Colab to Building TensorFlow models Train the Model on Google Cloud AI Platform using TensorFlow-Cloud Save the trained model in GCP Bucket after training Set up Model serving on GCP Make Prediction using deployed model in the cloud
[ { "code": null, "e": 682, "s": 172, "text": "The TensorFlow ecosystem has become very popular for developing applications involving deep learning. One of the reasons is that it has a strong community and a lot of tools have been developed around the core library to support developers. In this tutorial, I will guide you through how to prototype models in google colab, train it on Google Cloud AI Platform, and deploy the finalized model on Google Cloud AI Platform for production. I will include the working Google colab notebooks to recreate the work." }, { "code": null, "e": 1137, "s": 682, "text": "Google colab is a free resource for prototyping models in TensorFlow and comes with various runtime. Preparing a machine with GPU or TPU could be costly to start with however users can start with free GPU with google colab. Bear in mind, colab has limited resources and might not be suitable for properly training models requiring large compute resources. Nonetheless, colab is a perfect tool for prototyping your models and some initial experimentation." }, { "code": null, "e": 1994, "s": 1137, "text": "Once you are satisfied with your model pipeline, it is time to train the model with the proper number of EPOCHS and full datasets. As you might know, training deep learning models requires a long time and a large cluster of CPU’s GPUs or TPU’s. One option is that users set up their own computing cluster which is costly and time-consuming most of the time. Another option is to use cloud computing to training the model and pay as you go. TensorFlow team has released a package called Tensorflow Cloud to let users train the models on the Google Cloud platform without any hassle. I have followed steps from Train your TensorFlow model on Google Cloud using TensorFlow Cloud blog and will share some issues I have faced to make it work. Some of the pre-requisites are ad defined in the project guidelines for submitting a training job to the GCP platform." }, { "code": null, "e": 2008, "s": 1994, "text": "Python >= 3.5" }, { "code": null, "e": 2031, "s": 2008, "text": "A Google Cloud project" }, { "code": null, "e": 2060, "s": 2031, "text": "An authenticated GCP account" }, { "code": null, "e": 2173, "s": 2060, "text": "Google AI platform APIs enabled for your GCP account. We use the AI platform for deploying docker images on GCP." }, { "code": null, "e": 2373, "s": 2173, "text": "Either a functioning version of docker if you want to use a local docker process for your build, or create a cloud storage bucket to use with Google Cloud build for docker image build and publishing." }, { "code": null, "e": 2488, "s": 2373, "text": "After creating the GCP project, follow the below steps to config the environment with Google cloud authentication." }, { "code": null, "e": 2557, "s": 2488, "text": "# Authenticate from google.colab import authauth.authenticate_user()" }, { "code": null, "e": 2591, "s": 2557, "text": "Set PROJECT_ID in the environment" }, { "code": null, "e": 2673, "s": 2591, "text": "os.environ['PROJECT_ID']='gcpessentials-rz'!gcloud config set project $PROJECT_ID" }, { "code": null, "e": 2950, "s": 2673, "text": "Create the Service Account and set some permissions needed for tensorflow-cloud the package. Download the service account key and add as an environment variable as GOOGLE_APPLICATION_CREDENTIALS. These credentials will be needed to submit the job to the google cloud platform." }, { "code": null, "e": 3423, "s": 2950, "text": "os.environ['PROJECT_ID']='gcpessentials-rz'!gcloud config set project $PROJECT_IDos.environ['SA_NAME']='gcpessentials-rz'!gcloud iam service-accounts create $SA_NAME!gcloud projects add-iam-policy-binding $PROJECT_ID \\--member serviceAccount:$SA_NAME@$PROJECT_ID.iam.gserviceaccount.com \\--role 'roles/editor'!gcloud iam service-accounts keys create key.json --iam-account $SA_NAME@$PROJECT_ID.iam.gserviceaccount.comos.environ['GOOGLE_APPLICATION_CREDENTIALS']='key.json'" }, { "code": null, "e": 3592, "s": 3423, "text": "Even after following the above steps, I have to enable service Accounts and cloud_build Status under Cloud Build settings. Below is the snapshot of my project settings." }, { "code": null, "e": 3695, "s": 3592, "text": "The next step is to create GCP_BUCKET to store the data needed for submitting the job to Google Cloud." }, { "code": null, "e": 3748, "s": 3695, "text": "BUCKET = 'tf2-model-training'!gsutil mb gs://$BUCKET" }, { "code": null, "e": 3955, "s": 3748, "text": "Once we have set up the environment in our google colab and created the GCP_BUCKET, we have to prepare the notebook with training the model. Below are some key points to consider while preparing a notebook." }, { "code": null, "e": 4243, "s": 3955, "text": "Test the code in a notebook using google colab for a small number of EPOCHSMake sure, there are no errors in the notebook and remove any unnecessary codePrepare the requirements.txt and upload to google colab environment.Save the trained model in GCP_BUCKET (will be used for Deployment)" }, { "code": null, "e": 4319, "s": 4243, "text": "Test the code in a notebook using google colab for a small number of EPOCHS" }, { "code": null, "e": 4398, "s": 4319, "text": "Make sure, there are no errors in the notebook and remove any unnecessary code" }, { "code": null, "e": 4467, "s": 4398, "text": "Prepare the requirements.txt and upload to google colab environment." }, { "code": null, "e": 4534, "s": 4467, "text": "Save the trained model in GCP_BUCKET (will be used for Deployment)" }, { "code": null, "e": 4651, "s": 4534, "text": "Once we are ready with the notebook, we submit the training on Google Cloud platform using tensorflow-cloud package." }, { "code": null, "e": 4897, "s": 4651, "text": "import tensorflow_cloud as tfcBUCKET = 'tf2-model-training'labels= {'phase': 'test','owner': 'raza',}tfc.run(requirements_txt=\"requirements.txt\",distribution_strategy=\"auto\",chief_config='auto',docker_image_bucket_name=BUCKET,job_labels=labels,)" }, { "code": null, "e": 5110, "s": 4897, "text": "The above code will convert the notebook into identifier-Fg45-a.py and submit the training on the Google Cloud platform in the docker form. After you submit the job, you can see the message like the below figure." }, { "code": null, "e": 5173, "s": 5110, "text": "Wait for a few minutes before the job starts actually training" }, { "code": null, "e": 5245, "s": 5173, "text": "By clicking on the provided link, you will see a page like below figure" }, { "code": null, "e": 5400, "s": 5245, "text": "You can see the logs by clicking the view logs and will look like the below figure. Logs are helpful to see what sort of Exceptions happened in your code." }, { "code": null, "e": 5517, "s": 5400, "text": "Before submitting the huge job, test your pipeline submission script for few EPOCHS and then submit the complete job" }, { "code": null, "e": 5643, "s": 5517, "text": "If all goes well, your model will be trained using the Google AI platform and saved in GCP_BUCKET along with other resources." }, { "code": null, "e": 5751, "s": 5643, "text": "Below is the working notebook to run the training on Google AI Platform using the TensorFlow-Cloud package." }, { "code": null, "e": 5838, "s": 5751, "text": "# Install tensorflow\n# !pip install tensorflow==2.3.0\n# !pip install tensorflow_cloud\n" }, { "code": null, "e": 6354, "s": 5838, "text": "# Import libraries\n# from __future__ import absolute_import, division, print_function, unicode_literals\nimport pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\nimport os\nimport numpy as np\nfrom datetime import datetime\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.models import Sequential, load_model\nimport tensorflow_cloud as tfc\n\n#Load the tensorboard extension\n# Load tensorboard \n# %load_ext tensorboard\n" }, { "code": null, "e": 6447, "s": 6354, "text": "# Upload requirements.txt file\n# from google.colab import files\n# uploaded = files.upload()\n" }, { "code": null, "e": 6496, "s": 6447, "text": "Saving requirements.txt to requirements (1).txt\n" }, { "code": null, "e": 6762, "s": 6496, "text": "BUCKET = 'tf2-model-training'\nlabels= {\n 'phase': 'test',\n 'owner': 'User',\n }\ntfc.run(\n requirements_txt=\"requirements.txt\",\n distribution_strategy=\"auto\",\n chief_config='auto',\n docker_image_bucket_name=BUCKET,\n job_labels=labels,\n)\n" }, { "code": null, "e": 9048, "s": 6762, "text": "INFO:tensorflow_cloud.core.containerize:Uploading files to GCS.\nINFO:tensorflow_cloud.core.containerize:Building and publishing docker image using Google Cloud Build: gcr.io/gcpessentials-rz/tf_cloud_train:f96196a6_a0c1_44f1_a9f4_ec99a6880da6\nINFO:googleapiclient.discovery:URL being requested: GET https://www.googleapis.com/discovery/v1/apis/cloudbuild/v1/rest\nINFO:googleapiclient.discovery:URL being requested: POST https://cloudbuild.googleapis.com/v1/projects/gcpessentials-rz/builds?alt=json\nINFO:googleapiclient.discovery:URL being requested: GET https://cloudbuild.googleapis.com/v1/projects/gcpessentials-rz/builds/f6f3e56d-e615-4ee1-b5d2-4c3108470858?alt=json\nINFO:googleapiclient.discovery:URL being requested: GET https://cloudbuild.googleapis.com/v1/projects/gcpessentials-rz/builds/f6f3e56d-e615-4ee1-b5d2-4c3108470858?alt=json\nINFO:googleapiclient.discovery:URL being requested: GET https://cloudbuild.googleapis.com/v1/projects/gcpessentials-rz/builds/f6f3e56d-e615-4ee1-b5d2-4c3108470858?alt=json\nINFO:googleapiclient.discovery:URL being requested: GET https://cloudbuild.googleapis.com/v1/projects/gcpessentials-rz/builds/f6f3e56d-e615-4ee1-b5d2-4c3108470858?alt=json\nINFO:googleapiclient.discovery:URL being requested: GET https://cloudbuild.googleapis.com/v1/projects/gcpessentials-rz/builds/f6f3e56d-e615-4ee1-b5d2-4c3108470858?alt=json\nINFO:googleapiclient.discovery:URL being requested: GET https://cloudbuild.googleapis.com/v1/projects/gcpessentials-rz/builds/f6f3e56d-e615-4ee1-b5d2-4c3108470858?alt=json\nINFO:googleapiclient.discovery:URL being requested: GET https://cloudbuild.googleapis.com/v1/projects/gcpessentials-rz/builds/f6f3e56d-e615-4ee1-b5d2-4c3108470858?alt=json\nINFO:googleapiclient.discovery:URL being requested: GET https://cloudbuild.googleapis.com/v1/projects/gcpessentials-rz/builds/f6f3e56d-e615-4ee1-b5d2-4c3108470858?alt=json\nINFO:googleapiclient.discovery:URL being requested: GET https://cloudbuild.googleapis.com/v1/projects/gcpessentials-rz/builds/f6f3e56d-e615-4ee1-b5d2-4c3108470858?alt=json\nINFO:googleapiclient.discovery:URL being requested: GET https://www.googleapis.com/discovery/v1/apis/ml/v1/rest\nINFO:googleapiclient.discovery:URL being requested: POST https://ml.googleapis.com/v1/projects/gcpessentials-rz/jobs?alt=json\n" }, { "code": null, "e": 9320, "s": 9048, "text": "Job submitted successfully.\nYour job ID is: tf_cloud_train_28b2567c_c6e8_4e63_b86d_1cddc2a4a5bd\nPlease access your job logs at the following URL:\nhttps://console.cloud.google.com/mlengine/jobs/tf_cloud_train_28b2567c_c6e8_4e63_b86d_1cddc2a4a5bd?project=gcpessentials-rz\n" }, { "code": null, "e": 9730, "s": 9320, "text": "# Traing and Test data from github\ndata_path= 'https://raw.githubusercontent.com/amjadraza/blogs-data/master/deep_leraning_tensorflow/'\noutput_dir = 'tensorflow_out/'\nos.makedirs(output_dir, exist_ok=True)\n# Reading the traing and test data\nprint('Loading the training data')\ntraining_data_df = pd.read_csv(data_path + 'sales_data_training.csv')\ntest_data_df = pd.read_csv(data_path + 'sales_data_test.csv')\n" }, { "code": null, "e": 10263, "s": 9730, "text": "scalar = MinMaxScaler(feature_range=(0,1))\nscaled_training = scalar.fit_transform(training_data_df)\nscaled_test = scalar.fit_transform(test_data_df)\n\nscaled_training_df = pd.DataFrame(data = scaled_training, columns=training_data_df.columns)\nscaled_test_df = pd.DataFrame(data = scaled_test, columns=training_data_df.columns)\n# Splitting the feature and target columns. Using this dataset, we aim to predict total_earnings\nX = scaled_training_df.drop('total_earnings', axis=1).values\nY = scaled_training_df['total_earnings'].values\n" }, { "code": null, "e": 10583, "s": 10263, "text": "# Define the Model\nprint('Building the Model')\nmodel = Sequential()\n\nmodel.add(Dense(50, input_dim=9, activation = 'relu'))\n\nmodel.add(Dense(100, activation = 'relu'))\n\nmodel.add(Dense(50, activation = 'relu'))\n\nmodel.add(Dense(1, activation = 'linear'))\n\nmodel.compile(loss = 'mean_squared_error', optimizer = 'adam')\n" }, { "code": null, "e": 10695, "s": 10583, "text": "X_test = scaled_test_df.drop('total_earnings', axis=1).values\nY_test = scaled_test_df['total_earnings'].values\n" }, { "code": null, "e": 11546, "s": 10695, "text": "# if not tfc.remote():\n# from google.colab import auth\n# auth.authenticate_user()\n# # GCP project name\n# os.environ['PROJECT_ID']='gcpessentials-rz'\n# !gcloud config set project $PROJECT_ID\n# os.environ['SA_NAME']='gcpessentials-rz'\n# !gcloud iam service-accounts create $SA_NAME\n# !gcloud projects add-iam-policy-binding $PROJECT_ID \\\n# --member serviceAccount:$SA_NAME@$PROJECT_ID.iam.gserviceaccount.com \\\n# --role 'roles/editor'\n# !gcloud iam service-accounts keys create key.json --iam-account $SA_NAME@$PROJECT_ID.iam.gserviceaccount.com\n# os.environ['GOOGLE_APPLICATION_CREDENTIALS']='key.json'\n# # Create the storage bucket for tf2 Models\n# # !gsutil mb $BUCKET\n# # !gcloud auth login\n# # os.environ['PROJECT_ID']='gcpessentials-rz'\n# # !gcloud config set project $PROJECT_ID\n# !gsutil mb gs://$BUCKET\n" }, { "code": null, "e": 13182, "s": 11546, "text": "if tfc.remote():\n # Collecting the logs in Google Cloud Storage\n MODEL_PATH = \"TF\"\n checkpoint_path = os.path.join(\"gs://\", BUCKET, MODEL_PATH, \"save_at_{epoch}\")\n tensorboard_path = os.path.join(\n \"gs://\", BUCKET, \"logs\", datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n )\n gcp_callbacks = [\n tf.keras.callbacks.ModelCheckpoint(checkpoint_path),\n tf.keras.callbacks.TensorBoard(log_dir=tensorboard_path, histogram_freq=1),\n tf.keras.callbacks.EarlyStopping(monitor=\"val_loss\", patience=3),\n ]\n epochs = 50\n callbacks = gcp_callbacks\nelse:\n # Setup for tensorboard\n tensorboard_path=\"logs/scalars/\" + datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n checkpoint_path = os.path.join(\"logs\",\"ckp\", \"save_at_{epoch}\")\n tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=tensorboard_path)\n\n local_callbacks = [\n tf.keras.callbacks.ModelCheckpoint(checkpoint_path),\n tf.keras.callbacks.TensorBoard(log_dir=tensorboard_path, histogram_freq=1),\n tf.keras.callbacks.EarlyStopping(monitor=\"val_loss\", patience=3),\n ]\n epochs = 1\n callbacks = local_callbacks\n \ntraining_history = model.fit(X, Y,\n epochs = epochs,\n shuffle=True,\n verbose=1,\n validation_data=(X_test, Y_test),\n callbacks=[callbacks])\nprint(\"Average test loss: \", np.average(training_history.history['loss']))\n\nif tfc.remote():\n MODEL = 'earnings-prediction'\n MODEL_SAVE_BUCKET = 'gs://gcpessentials-rz-tf2-models-serving'\n model.save(MODEL_SAVE_BUCKET + f'/{MODEL}', save_format='tf')\n" }, { "code": null, "e": 13421, "s": 13182, "text": " 1/32 [..............................] - ETA: 0s - loss: 0.0078WARNING:tensorflow:Callbacks method `on_train_batch_end` is slow compared to the batch time (batch time: 0.0044s vs `on_train_batch_end` time: 0.0181s). Check your callbacks.\n" }, { "code": null, "e": 13597, "s": 13421, "text": "WARNING:tensorflow:Callbacks method `on_train_batch_end` is slow compared to the batch time (batch time: 0.0044s vs `on_train_batch_end` time: 0.0181s). Check your callbacks.\n" }, { "code": null, "e": 14016, "s": 13597, "text": "12/32 [==========>...................] - ETA: 0s - loss: 0.0081WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/training/tracking/tracking.py:111: Model.state_updates (from tensorflow.python.keras.engine.training) is deprecated and will be removed in a future version.\nInstructions for updating:\nThis property should not be used in TensorFlow 2.0, as updates are applied automatically.\n" }, { "code": null, "e": 14372, "s": 14016, "text": "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/training/tracking/tracking.py:111: Model.state_updates (from tensorflow.python.keras.engine.training) is deprecated and will be removed in a future version.\nInstructions for updating:\nThis property should not be used in TensorFlow 2.0, as updates are applied automatically.\n" }, { "code": null, "e": 14724, "s": 14372, "text": "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/training/tracking/tracking.py:111: Layer.updates (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\nInstructions for updating:\nThis property should not be used in TensorFlow 2.0, as updates are applied automatically.\n" }, { "code": null, "e": 15076, "s": 14724, "text": "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/training/tracking/tracking.py:111: Layer.updates (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\nInstructions for updating:\nThis property should not be used in TensorFlow 2.0, as updates are applied automatically.\n" }, { "code": null, "e": 15138, "s": 15076, "text": "INFO:tensorflow:Assets written to: logs/ckp/save_at_1/assets\n" }, { "code": null, "e": 15200, "s": 15138, "text": "INFO:tensorflow:Assets written to: logs/ckp/save_at_1/assets\n" }, { "code": null, "e": 15330, "s": 15200, "text": "32/32 [==============================] - 1s 26ms/step - loss: 0.0056 - val_loss: 0.0048\nAverage test loss: 0.005643493961542845\n" }, { "code": null, "e": 15761, "s": 15330, "text": "Once the model is trained and finalized, users would like to deploy the model on a scale-able infrastructure. Google Cloud also provides the necessary infrastructure to deploy TensorFlow models on its platform without a lot of modifications. I will show you how to deploy the model on a google cloud platform. At the end of the training, we save the finalized model in Google Cloud Bucket. Below are the steps to deploy the model." }, { "code": null, "e": 15808, "s": 15761, "text": "Configure the models serving using AI Platform" }, { "code": null, "e": 15849, "s": 15808, "text": "Perform the prediction on deployed model" }, { "code": null, "e": 16067, "s": 15849, "text": "Use the below set of commands to configure the model for deployment withing Google colab. I have explained in detail how to deploy the model on Google Cloud in Model with TensorFlow and Serve on Google Cloud Platform." }, { "code": null, "e": 16158, "s": 16067, "text": "I have configured the model to serve as v2 following the same steps in the above tutorial." }, { "code": null, "e": 16298, "s": 16158, "text": "Once the model is deployed and you can see the green tick, it is time to test the model for predictions. Some important points to consider." }, { "code": null, "e": 16378, "s": 16298, "text": "Test the model prediction using Test & Use tab under your version or model tab." }, { "code": null, "e": 16431, "s": 16378, "text": "Input JSON data depends on how you define your model" }, { "code": null, "e": 17051, "s": 16431, "text": "# [Reference](https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/ml_engine/online_prediction/predict.py)import googleapiclient.discoverydef predict_json(project, model, instances, version=None): service = googleapiclient.discovery.build('ml', 'v1') name = 'projects/{}/models/{}'.format(project, model) if version is not None: name += '/versions/{}'.format(version) response = service.projects().predict( name=name, body={'instances': instances} ).execute() if 'error' in response: raise RuntimeError(response['error']) return response['predictions']" }, { "code": null, "e": 17088, "s": 17051, "text": "Load the unseen data for predictions" }, { "code": null, "e": 17591, "s": 17088, "text": "df_new_products = pd.read_csv(data_path + 'proposed_new_product.csv')tdata_instances = {'dense_input':df_new_products.values[0].tolist()}predictions_gcloud = predict_json(CLOUD_PROJECT, 'earnings_prediction', tdata_instances, version='v2')predictions_gcloud = predictions_gcloud[0]['dense_3'][0] + 0.1159predictions_gcloud = predictions_gcloud/0.0000036968print('Earnings predictions for Proposed product - ${}'.format(predictions_gcloud))Earnings predictions for Proposed product - $259671.15201209177" }, { "code": null, "e": 17665, "s": 17591, "text": "Below is the working notebook to perform prediction on the deployed model" }, { "code": null, "e": 17930, "s": 17665, "text": "In this guide, we have learned about training the deep learning models with TensorFlow 2.3.0 using the Google Cloud AI platform with the help of tensorflow-cloud package and deployed the trained model on the Google Cloud AI platform too. Below are some key lessons" }, { "code": null, "e": 17977, "s": 17930, "text": "Use Google Colab to Building TensorFlow models" }, { "code": null, "e": 18044, "s": 17977, "text": "Train the Model on Google Cloud AI Platform using TensorFlow-Cloud" }, { "code": null, "e": 18096, "s": 18044, "text": "Save the trained model in GCP Bucket after training" }, { "code": null, "e": 18124, "s": 18096, "text": "Set up Model serving on GCP" } ]
An intuitive real life example of a binomial distribution and how to simulate it in R | by Serdar Korur | Towards Data Science
Learn. It is all about success and failure. What are binomial distributions and why are they so useful? When we repeat a set of events like 10 times coin flipping and each single event in a set has two possible outcomes (head or tails) think about Binomial distributions. Each single event here is known as a Bernoulli Trial. Bi- in binomial distributions refers to the two outcomes usually described as Success or no Success. A “yes” or “no”. Probability distributions in general are used to predict future events and often based on nasty looking mathematical formulas. But, there is also a beautiful thing here. For example the specific binomial distribution mathematical function can be used to predict the outcomes of any real life event which has two outcomes. Let’s start with a simple example. For example, playing with the coins, the two possibilities are getting heads (success) or tails (no success). And let’s say you have a of e.g. 50 times coin flipping. We can repeat this set as many times as we like and record how many times we got heads (success) in each repetition. And if plot the results we will have a probability distribution plot. And if you make enough repetitions you will approach a binomial probability distribution curve. We will do this in a minute. But, first generate data to draw our plot. We can use R to generate the data. We will generate random data from repeating set of 50-times coin flipping 100000 times and record the number of successes in each repetition. rbinom() function can generate a given number of repeated (here 100.000) sets (50 times of coin flipping) of experiments. It requires 3 arguments. rbinom(n = number of repetitions = 100.000, size = sample size = 50, p = the probability of success (chance of throwing heads is 0.5)) How can we use this probability distribution plot? Binomial probability distributions help us to understand the likelihood of rare events and to set probable expected ranges. The above plot illustrates if we randomly flip a coin 50 times, we will most likely get between 20 to 30 successes (heads) and events such as having more more than 35 successes (heads) out of 50 trials are very unlikely. The bars in red represents the sets which had 35 or more heads. R code can be used to find the exact probabilities. Let’s compare the probabilities of getting more than 25, 35 or even 49 heads. You can combine rbinom with mean function to find the percentage of the events with a chosen outcome. # Probability of getting 25 or more headsmean(rbinom(100000, 50, .5) >= 25)0.5555# Probability of getting 35 or more headsmean(rbinom(100000, 50, .5) >= 35)0.00341# Probability of getting 49 or more headsmean(rbinom(100000, 50, .5) >= 49)0 We found the probability of throwing 49 or more heads to be 0. But to be technically precise it is one in 375 trillion times (= 1/((1/249)+(1/250))). You can impress your friends with your ability to use binomial distributions to predict coin flipping outcomes, but let’s look at other real life applications of them. The performance of a machine learning model. You built a machine learning model with a binary outcome. Let’s say pathological image recognition algorithm for liver cancer that is 90% accurate. You tested 100 patients and you want to know your 95% confidence interval? Or your new results showed that your model detected less than 70 patients correctly. Is it possible? Or you should start optimizing your parameters again? Number of patients responding to a treatment. Let’s say you have a new therapy for cancer which has 10% probability to cure a patient. You have 500 patients which took the drug. The expected number of recovering patients is 50. But in your trial 75 patients responded. Is this due to chance or a significant effect? Or you should start looking underlying factors if there is something about the therapy or the patient group? Think about a hospital emergency station. You are a hospital manager and you want to organize the staff numbers correctly for different weekdays. You know total number of patients came in to a emergency station because of alcohol poisoning in a given time period. You can analyse the distribution of patient numbers for each day of the week. Most likely you will have more such cases in the weekends and you need larger staff. This will be also true for other businesses. They can use binomial distributions to calculate changes in demand and plan accordingly. If you are running a Webserver. You can allocate your resources better by identifying times when traffic will be higher. Some other questions we can answer by binomial distributions are: Number of people who answered ‘yes’ to a survey question.How many games a team will win in one season?Vote counts for a candidate in an election.Number of defective products in a production run. Binomial distributions are common and they have many real life applications. We can expand binomial distributions to multinomial distributions when instead there are more than two outcomes for the single event. Such as there are 6 outcomes when rolling a die, or analyzing distributions of eye color types (Black, blue, green etc) in a population. When it is about distributions for events with multiple categories think about multinomial distributions. If the number of observations(n) are large we can think of a multinomial draw as being a series of binomial draws (Gentle, 2003, pp. 198–199). For example, when rolling a die the 6 categories can be thought of a combination of 6 different binomial trials (getting 1, 2 ,3 and so on). If you are not convinced just by reading this, I will simulate how the shape of a multinomial event changes by increasing the number of trials. Let’s use some real life data to apply our knowledge so far. The data come from TidyTuesday — a weekly social data project in R organized by the R for Data Science community. It contains data about Horror Movies released since 2012. And what I asked was whether horror movies are more likely be released at the 13th each month? If you are in the right mindset anything feels better and if you are not in the mood nothing will make us happy. The mindset we have prior to an event influences what we will feel about an event. This is at least what behavioral scientist Robert Cialdini’s research says. Imagine you are a horror movie fan and you went to the cinema. On the screen couple of ads are running just before the movie starts. You approach your mobile to turn off the voice and the date catches your attention, it is the 13th. And usually with the number 13 we associate cursed events. Do you think it will influence your impression about the movie? We don’t know if this is true but I wanted to test whether movie makers have similar ideas and selected 13th as the release date more often than other days. So, I explored Horror movies data and calculated number of releases in different days of the month. In the data, there were 2782 movies associated with a release date. So expected movie release per day is 92 (2782 / 32) This is a good example of a multinomial probability distribution with 30 categories, and since the number of samples are large it will approximate a binomial distribution. Thus, we can apply binomial probability distributions for calculating the probabilities in our multinomial data. We saw above that in some days more movies are released than the expected value. What we want to know is, which days are in the range of random chance and which days there is a significant preference or an aversion to release a movie. I will define an interval which contains 95% of probabilities in our simulated distributions. And the values outside will be the ones which were not due to random chance. To do this I need 2.5th and 97.5th quantiles of the distribution. We can do this by the qbinom() function in R. For example qbinom(0.975, size, p) will return the value which will define the cut off which contains 0.975 of the probabilities. And our confidence interval will be the interval between: qbinom(0.025, size, p) < Confidence Interval < qbinom(0.975, size, p) lower <- qbinom(0.975, 2782, 1/30)75upper <- qbinom(0.025, 2782, 1/30)11275 < Confidence Interval < 112 95% of the time, a specific day of month will have between 75 and 112 movie releases. Higher or lower values than this range can not happen due to random chance according to our probability distribution. 124 movies released at the 13th of any month. This value is above the 97.5th quantile. So it is significant. But what is the exact p value? Let’s define p value first. For example in coin flipping, probability of heads is (0.5). If we follow our definition p value is the sum of the probability of that event (0.5) and similar events which is equally or less likely i.e. tails (0.5). So our p value is 0.5 + 0.5 = 1. Similarly, in our horror movie data this will be the sum of the probabilities of getting 124 movie releases or events that are equally probable or rarer. In R, pbinom function defines the cumulative probabilities. For example, pbinom(124, 2782, 1/30) will give us the cumulative probabilities of any number of movie releases up to 124. By using 1-pbinom(124, 2782, 1/30) we can find the sum of the probabilities with equal or lower chance than having 124. Thus, p value for getting at least 124 movie release is; p_val_binom <- 2 * (1 — pbinom(124, 2782, 1/30))0.00133 We multiplied by two because same rare events can happen in the left side of our confidence interval as well. Let’s put those p values on our horror movie plot to highlight the significant days. We tested our hypothesis about movie makers and calculated the p value and used the pbinom() function and found couple of other days where movies are more or less likely to be released. However, another widely used way to calculate p values is to calculate the mean of the distribution and its standard deviation and to verify how many standard deviations the observed value is away from the mean (the z score). When the sample size is large, binomial distributions can be approximated by a normal distribution. To build the normal distribution, I need mean and standard deviation. I can calculate this from the horror movie data. sample_mean is 92.7 sample_sd is 89.64 I can calculate the z-score for our observation of 124 movies that are released on the 13th. Simply, z-score is: how many standard deviations an observation is away from the mean. Since 95% of the observations will fall within 1.96 standard deviations from the mean in a normal distribution, a higher z-score will show that our p value is indeed significant. z_score <- (observation — sample_mean) / sample_sd3.302 I can calculate the exact p value by using a normal distribution function pnorm() and the z score we found. p_val_nor <- 2 * pnorm(3.302, lower.tail = FALSE)p_val_nor0.00095 As expected, I found similar values (Normal: 0.00095, Binomial: 0.00133) by using an approximation of a normal distribution and by using binomial distributions. Both methods proves that Horror movies are more likely to be released at the 13th. Many events in real life can be explained by binomial probability distributions, and they allow us to calculate whether or not the events happened due to random chance and test our hypotheses. It can be a fun data analysis such as in horror movies, or more serious subjects like testing of new medicines or predicting accuracy of machine learning algorithms detecting diseases. Until next time!
[ { "code": null, "e": 215, "s": 171, "text": "Learn. It is all about success and failure." }, { "code": null, "e": 275, "s": 215, "text": "What are binomial distributions and why are they so useful?" }, { "code": null, "e": 497, "s": 275, "text": "When we repeat a set of events like 10 times coin flipping and each single event in a set has two possible outcomes (head or tails) think about Binomial distributions. Each single event here is known as a Bernoulli Trial." }, { "code": null, "e": 615, "s": 497, "text": "Bi- in binomial distributions refers to the two outcomes usually described as Success or no Success. A “yes” or “no”." }, { "code": null, "e": 937, "s": 615, "text": "Probability distributions in general are used to predict future events and often based on nasty looking mathematical formulas. But, there is also a beautiful thing here. For example the specific binomial distribution mathematical function can be used to predict the outcomes of any real life event which has two outcomes." }, { "code": null, "e": 972, "s": 937, "text": "Let’s start with a simple example." }, { "code": null, "e": 1256, "s": 972, "text": "For example, playing with the coins, the two possibilities are getting heads (success) or tails (no success). And let’s say you have a of e.g. 50 times coin flipping. We can repeat this set as many times as we like and record how many times we got heads (success) in each repetition." }, { "code": null, "e": 1494, "s": 1256, "text": "And if plot the results we will have a probability distribution plot. And if you make enough repetitions you will approach a binomial probability distribution curve. We will do this in a minute. But, first generate data to draw our plot." }, { "code": null, "e": 1671, "s": 1494, "text": "We can use R to generate the data. We will generate random data from repeating set of 50-times coin flipping 100000 times and record the number of successes in each repetition." }, { "code": null, "e": 1818, "s": 1671, "text": "rbinom() function can generate a given number of repeated (here 100.000) sets (50 times of coin flipping) of experiments. It requires 3 arguments." }, { "code": null, "e": 1972, "s": 1818, "text": "rbinom(n = number of repetitions = 100.000, size = sample size = 50, p = the probability of success (chance of throwing heads is 0.5))" }, { "code": null, "e": 2023, "s": 1972, "text": "How can we use this probability distribution plot?" }, { "code": null, "e": 2147, "s": 2023, "text": "Binomial probability distributions help us to understand the likelihood of rare events and to set probable expected ranges." }, { "code": null, "e": 2432, "s": 2147, "text": "The above plot illustrates if we randomly flip a coin 50 times, we will most likely get between 20 to 30 successes (heads) and events such as having more more than 35 successes (heads) out of 50 trials are very unlikely. The bars in red represents the sets which had 35 or more heads." }, { "code": null, "e": 2664, "s": 2432, "text": "R code can be used to find the exact probabilities. Let’s compare the probabilities of getting more than 25, 35 or even 49 heads. You can combine rbinom with mean function to find the percentage of the events with a chosen outcome." }, { "code": null, "e": 2904, "s": 2664, "text": "# Probability of getting 25 or more headsmean(rbinom(100000, 50, .5) >= 25)0.5555# Probability of getting 35 or more headsmean(rbinom(100000, 50, .5) >= 35)0.00341# Probability of getting 49 or more headsmean(rbinom(100000, 50, .5) >= 49)0" }, { "code": null, "e": 3054, "s": 2904, "text": "We found the probability of throwing 49 or more heads to be 0. But to be technically precise it is one in 375 trillion times (= 1/((1/249)+(1/250)))." }, { "code": null, "e": 3222, "s": 3054, "text": "You can impress your friends with your ability to use binomial distributions to predict coin flipping outcomes, but let’s look at other real life applications of them." }, { "code": null, "e": 3267, "s": 3222, "text": "The performance of a machine learning model." }, { "code": null, "e": 3645, "s": 3267, "text": "You built a machine learning model with a binary outcome. Let’s say pathological image recognition algorithm for liver cancer that is 90% accurate. You tested 100 patients and you want to know your 95% confidence interval? Or your new results showed that your model detected less than 70 patients correctly. Is it possible? Or you should start optimizing your parameters again?" }, { "code": null, "e": 3691, "s": 3645, "text": "Number of patients responding to a treatment." }, { "code": null, "e": 4070, "s": 3691, "text": "Let’s say you have a new therapy for cancer which has 10% probability to cure a patient. You have 500 patients which took the drug. The expected number of recovering patients is 50. But in your trial 75 patients responded. Is this due to chance or a significant effect? Or you should start looking underlying factors if there is something about the therapy or the patient group?" }, { "code": null, "e": 4112, "s": 4070, "text": "Think about a hospital emergency station." }, { "code": null, "e": 4497, "s": 4112, "text": "You are a hospital manager and you want to organize the staff numbers correctly for different weekdays. You know total number of patients came in to a emergency station because of alcohol poisoning in a given time period. You can analyse the distribution of patient numbers for each day of the week. Most likely you will have more such cases in the weekends and you need larger staff." }, { "code": null, "e": 4631, "s": 4497, "text": "This will be also true for other businesses. They can use binomial distributions to calculate changes in demand and plan accordingly." }, { "code": null, "e": 4663, "s": 4631, "text": "If you are running a Webserver." }, { "code": null, "e": 4752, "s": 4663, "text": "You can allocate your resources better by identifying times when traffic will be higher." }, { "code": null, "e": 4818, "s": 4752, "text": "Some other questions we can answer by binomial distributions are:" }, { "code": null, "e": 5013, "s": 4818, "text": "Number of people who answered ‘yes’ to a survey question.How many games a team will win in one season?Vote counts for a candidate in an election.Number of defective products in a production run." }, { "code": null, "e": 5090, "s": 5013, "text": "Binomial distributions are common and they have many real life applications." }, { "code": null, "e": 5224, "s": 5090, "text": "We can expand binomial distributions to multinomial distributions when instead there are more than two outcomes for the single event." }, { "code": null, "e": 5467, "s": 5224, "text": "Such as there are 6 outcomes when rolling a die, or analyzing distributions of eye color types (Black, blue, green etc) in a population. When it is about distributions for events with multiple categories think about multinomial distributions." }, { "code": null, "e": 5751, "s": 5467, "text": "If the number of observations(n) are large we can think of a multinomial draw as being a series of binomial draws (Gentle, 2003, pp. 198–199). For example, when rolling a die the 6 categories can be thought of a combination of 6 different binomial trials (getting 1, 2 ,3 and so on)." }, { "code": null, "e": 5895, "s": 5751, "text": "If you are not convinced just by reading this, I will simulate how the shape of a multinomial event changes by increasing the number of trials." }, { "code": null, "e": 6070, "s": 5895, "text": "Let’s use some real life data to apply our knowledge so far. The data come from TidyTuesday — a weekly social data project in R organized by the R for Data Science community." }, { "code": null, "e": 6223, "s": 6070, "text": "It contains data about Horror Movies released since 2012. And what I asked was whether horror movies are more likely be released at the 13th each month?" }, { "code": null, "e": 6495, "s": 6223, "text": "If you are in the right mindset anything feels better and if you are not in the mood nothing will make us happy. The mindset we have prior to an event influences what we will feel about an event. This is at least what behavioral scientist Robert Cialdini’s research says." }, { "code": null, "e": 6728, "s": 6495, "text": "Imagine you are a horror movie fan and you went to the cinema. On the screen couple of ads are running just before the movie starts. You approach your mobile to turn off the voice and the date catches your attention, it is the 13th." }, { "code": null, "e": 6851, "s": 6728, "text": "And usually with the number 13 we associate cursed events. Do you think it will influence your impression about the movie?" }, { "code": null, "e": 7108, "s": 6851, "text": "We don’t know if this is true but I wanted to test whether movie makers have similar ideas and selected 13th as the release date more often than other days. So, I explored Horror movies data and calculated number of releases in different days of the month." }, { "code": null, "e": 7228, "s": 7108, "text": "In the data, there were 2782 movies associated with a release date. So expected movie release per day is 92 (2782 / 32)" }, { "code": null, "e": 7400, "s": 7228, "text": "This is a good example of a multinomial probability distribution with 30 categories, and since the number of samples are large it will approximate a binomial distribution." }, { "code": null, "e": 7513, "s": 7400, "text": "Thus, we can apply binomial probability distributions for calculating the probabilities in our multinomial data." }, { "code": null, "e": 7748, "s": 7513, "text": "We saw above that in some days more movies are released than the expected value. What we want to know is, which days are in the range of random chance and which days there is a significant preference or an aversion to release a movie." }, { "code": null, "e": 7985, "s": 7748, "text": "I will define an interval which contains 95% of probabilities in our simulated distributions. And the values outside will be the ones which were not due to random chance. To do this I need 2.5th and 97.5th quantiles of the distribution." }, { "code": null, "e": 8219, "s": 7985, "text": "We can do this by the qbinom() function in R. For example qbinom(0.975, size, p) will return the value which will define the cut off which contains 0.975 of the probabilities. And our confidence interval will be the interval between:" }, { "code": null, "e": 8289, "s": 8219, "text": "qbinom(0.025, size, p) < Confidence Interval < qbinom(0.975, size, p)" }, { "code": null, "e": 8393, "s": 8289, "text": "lower <- qbinom(0.975, 2782, 1/30)75upper <- qbinom(0.025, 2782, 1/30)11275 < Confidence Interval < 112" }, { "code": null, "e": 8597, "s": 8393, "text": "95% of the time, a specific day of month will have between 75 and 112 movie releases. Higher or lower values than this range can not happen due to random chance according to our probability distribution." }, { "code": null, "e": 8765, "s": 8597, "text": "124 movies released at the 13th of any month. This value is above the 97.5th quantile. So it is significant. But what is the exact p value? Let’s define p value first." }, { "code": null, "e": 9014, "s": 8765, "text": "For example in coin flipping, probability of heads is (0.5). If we follow our definition p value is the sum of the probability of that event (0.5) and similar events which is equally or less likely i.e. tails (0.5). So our p value is 0.5 + 0.5 = 1." }, { "code": null, "e": 9168, "s": 9014, "text": "Similarly, in our horror movie data this will be the sum of the probabilities of getting 124 movie releases or events that are equally probable or rarer." }, { "code": null, "e": 9470, "s": 9168, "text": "In R, pbinom function defines the cumulative probabilities. For example, pbinom(124, 2782, 1/30) will give us the cumulative probabilities of any number of movie releases up to 124. By using 1-pbinom(124, 2782, 1/30) we can find the sum of the probabilities with equal or lower chance than having 124." }, { "code": null, "e": 9527, "s": 9470, "text": "Thus, p value for getting at least 124 movie release is;" }, { "code": null, "e": 9583, "s": 9527, "text": "p_val_binom <- 2 * (1 — pbinom(124, 2782, 1/30))0.00133" }, { "code": null, "e": 9693, "s": 9583, "text": "We multiplied by two because same rare events can happen in the left side of our confidence interval as well." }, { "code": null, "e": 9778, "s": 9693, "text": "Let’s put those p values on our horror movie plot to highlight the significant days." }, { "code": null, "e": 9964, "s": 9778, "text": "We tested our hypothesis about movie makers and calculated the p value and used the pbinom() function and found couple of other days where movies are more or less likely to be released." }, { "code": null, "e": 10190, "s": 9964, "text": "However, another widely used way to calculate p values is to calculate the mean of the distribution and its standard deviation and to verify how many standard deviations the observed value is away from the mean (the z score)." }, { "code": null, "e": 10409, "s": 10190, "text": "When the sample size is large, binomial distributions can be approximated by a normal distribution. To build the normal distribution, I need mean and standard deviation. I can calculate this from the horror movie data." }, { "code": null, "e": 10448, "s": 10409, "text": "sample_mean is 92.7 sample_sd is 89.64" }, { "code": null, "e": 10807, "s": 10448, "text": "I can calculate the z-score for our observation of 124 movies that are released on the 13th. Simply, z-score is: how many standard deviations an observation is away from the mean. Since 95% of the observations will fall within 1.96 standard deviations from the mean in a normal distribution, a higher z-score will show that our p value is indeed significant." }, { "code": null, "e": 10863, "s": 10807, "text": "z_score <- (observation — sample_mean) / sample_sd3.302" }, { "code": null, "e": 10971, "s": 10863, "text": "I can calculate the exact p value by using a normal distribution function pnorm() and the z score we found." }, { "code": null, "e": 11037, "s": 10971, "text": "p_val_nor <- 2 * pnorm(3.302, lower.tail = FALSE)p_val_nor0.00095" }, { "code": null, "e": 11281, "s": 11037, "text": "As expected, I found similar values (Normal: 0.00095, Binomial: 0.00133) by using an approximation of a normal distribution and by using binomial distributions. Both methods proves that Horror movies are more likely to be released at the 13th." }, { "code": null, "e": 11474, "s": 11281, "text": "Many events in real life can be explained by binomial probability distributions, and they allow us to calculate whether or not the events happened due to random chance and test our hypotheses." }, { "code": null, "e": 11659, "s": 11474, "text": "It can be a fun data analysis such as in horror movies, or more serious subjects like testing of new medicines or predicting accuracy of machine learning algorithms detecting diseases." } ]
String Concatenation in R Programming - GeeksforGeeks
01 Jun, 2020 String concatenation is a way of appending two or more strings into a single string whether it is character by character or using some special character end to end. There are many ways to perform string concatenation. Example: Input: str1 = 'Geeks' str2 = 'for' str3 = 'Geeks' Output: 'GeeksforGeeks' To perform concatenation in R we use the paste() function which can combine two or more strings together. It takes different types of arguments as follows: Syntax:paste(string1, string2, ....stringn, sep = “”, collapse=NULL) Parameters:string1, string2...string3: Strings provided for concatenation.sep: the type of separator we use.collapse: defines how to separate the result element-wise in the vector of string. # create 2 different strings.string1 <- "Geeks" # first stringstring2 <- "forGeeks" # second string. # use cbind method to bind the strings into a vector.vec <- cbind(string1, string2) # combined vector. # use paste() function to perform string concatenation.S <- paste(string1, string2, sep ="") print(S)# print the output string # collapse will determine how different# elements are joined together.M <- paste(vec, collapse = "#")print(M) # print the output string using the collapse Output: "GeeksforGeeks" "Geeks#forGeeks" With the help of paste() function to we can perform concatenation by using different types of separators like whitespace or some special characters. # create 2 strings.string1 <- "Hello" # first stringstring2 <- "World" # second string # concatenate by using whitespace as a separator.S <- paste(string1, string2, sep =" ")print(S) M <- paste(string1, string2, sep =", ")print(M)# concatenate by using ', ' character. Output: Hello World Hello, World With the help of paste() function we can concatenate more than two strings. # create 3 different stringsstring1 <- "I" # first stringstring2 <- "Love" # second stringstring3 <- "Programming" # third string. # perform concatenation on multiple strings.S <- paste(string1, string2, string3, sep =" ")print(S) # print the output string. Output: I Love Programming Similarly, we can perform concatenation using cat() function with the help of which we can perform character-wise concatenation and it also gives us the flexibility to save the result in a file. Syntax:cat(string1, string2, ...string, sep = ”, file, append) Parameters: string1, string2...string3: Strings provided for concatenation.sep: the type of separator we use.file: used to save the result in a file with a specified name.append: logical argument to specify if you want to append the result in an existing file or create a new file. We can perform concatenation by inserting the variable name of the string and specifying the separator.we can insert more than two variables also and specify different types of parameter. # create 2 string variablesa <- 'Competitive'b <- 'Coding'c <- 'is difficult'cat(a, b, c, sep = ' ') Output: Competitive Coding is difficult To save the result of the concatenated output we can specify the name of the file in the argument. By default the append is false, but if you want to append the result into an existing file then specify append as TRUE.The result will be saved into the specified file format. # create a list of 10 numbers and # save it into file named temp.csvcat(11:20, sep = '\n', file = 'temp.csv')readLines('temp.csv') # read the file temp.csv Output: Picked R String-Functions R-strings R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Replace specific values in column in R DataFrame ? How to change Row Names of DataFrame in R ? Filter data by multiple conditions in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R Loops in R (for, while, repeat) How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? K-Means Clustering in R Programming Remove rows with NA in one column of R DataFrame
[ { "code": null, "e": 24027, "s": 23999, "text": "\n01 Jun, 2020" }, { "code": null, "e": 24245, "s": 24027, "text": "String concatenation is a way of appending two or more strings into a single string whether it is character by character or using some special character end to end. There are many ways to perform string concatenation." }, { "code": null, "e": 24254, "s": 24245, "text": "Example:" }, { "code": null, "e": 24330, "s": 24254, "text": "Input: str1 = 'Geeks'\nstr2 = 'for'\nstr3 = 'Geeks' \nOutput: 'GeeksforGeeks'\n" }, { "code": null, "e": 24486, "s": 24330, "text": "To perform concatenation in R we use the paste() function which can combine two or more strings together. It takes different types of arguments as follows:" }, { "code": null, "e": 24555, "s": 24486, "text": "Syntax:paste(string1, string2, ....stringn, sep = “”, collapse=NULL)" }, { "code": null, "e": 24746, "s": 24555, "text": "Parameters:string1, string2...string3: Strings provided for concatenation.sep: the type of separator we use.collapse: defines how to separate the result element-wise in the vector of string." }, { "code": "# create 2 different strings.string1 <- \"Geeks\" # first stringstring2 <- \"forGeeks\" # second string. # use cbind method to bind the strings into a vector.vec <- cbind(string1, string2) # combined vector. # use paste() function to perform string concatenation.S <- paste(string1, string2, sep =\"\") print(S)# print the output string # collapse will determine how different# elements are joined together.M <- paste(vec, collapse = \"#\")print(M) # print the output string using the collapse", "e": 25236, "s": 24746, "text": null }, { "code": null, "e": 25244, "s": 25236, "text": "Output:" }, { "code": null, "e": 25277, "s": 25244, "text": "\"GeeksforGeeks\"\n\"Geeks#forGeeks\"" }, { "code": null, "e": 25426, "s": 25277, "text": "With the help of paste() function to we can perform concatenation by using different types of separators like whitespace or some special characters." }, { "code": "# create 2 strings.string1 <- \"Hello\" # first stringstring2 <- \"World\" # second string # concatenate by using whitespace as a separator.S <- paste(string1, string2, sep =\" \")print(S) M <- paste(string1, string2, sep =\", \")print(M)# concatenate by using ', ' character.", "e": 25697, "s": 25426, "text": null }, { "code": null, "e": 25705, "s": 25697, "text": "Output:" }, { "code": null, "e": 25730, "s": 25705, "text": "Hello World\nHello, World" }, { "code": null, "e": 25806, "s": 25730, "text": "With the help of paste() function we can concatenate more than two strings." }, { "code": "# create 3 different stringsstring1 <- \"I\" # first stringstring2 <- \"Love\" # second stringstring3 <- \"Programming\" # third string. # perform concatenation on multiple strings.S <- paste(string1, string2, string3, sep =\" \")print(S) # print the output string.", "e": 26065, "s": 25806, "text": null }, { "code": null, "e": 26073, "s": 26065, "text": "Output:" }, { "code": null, "e": 26092, "s": 26073, "text": "I Love Programming" }, { "code": null, "e": 26287, "s": 26092, "text": "Similarly, we can perform concatenation using cat() function with the help of which we can perform character-wise concatenation and it also gives us the flexibility to save the result in a file." }, { "code": null, "e": 26350, "s": 26287, "text": "Syntax:cat(string1, string2, ...string, sep = ”, file, append)" }, { "code": null, "e": 26362, "s": 26350, "text": "Parameters:" }, { "code": null, "e": 26632, "s": 26362, "text": "string1, string2...string3: Strings provided for concatenation.sep: the type of separator we use.file: used to save the result in a file with a specified name.append: logical argument to specify if you want to append the result in an existing file or create a new file." }, { "code": null, "e": 26820, "s": 26632, "text": "We can perform concatenation by inserting the variable name of the string and specifying the separator.we can insert more than two variables also and specify different types of parameter." }, { "code": "# create 2 string variablesa <- 'Competitive'b <- 'Coding'c <- 'is difficult'cat(a, b, c, sep = ' ')", "e": 26921, "s": 26820, "text": null }, { "code": null, "e": 26929, "s": 26921, "text": "Output:" }, { "code": null, "e": 26961, "s": 26929, "text": "Competitive Coding is difficult" }, { "code": null, "e": 27236, "s": 26961, "text": "To save the result of the concatenated output we can specify the name of the file in the argument. By default the append is false, but if you want to append the result into an existing file then specify append as TRUE.The result will be saved into the specified file format." }, { "code": "# create a list of 10 numbers and # save it into file named temp.csvcat(11:20, sep = '\\n', file = 'temp.csv')readLines('temp.csv') # read the file temp.csv", "e": 27392, "s": 27236, "text": null }, { "code": null, "e": 27400, "s": 27392, "text": "Output:" }, { "code": null, "e": 27407, "s": 27400, "text": "Picked" }, { "code": null, "e": 27426, "s": 27407, "text": "R String-Functions" }, { "code": null, "e": 27436, "s": 27426, "text": "R-strings" }, { "code": null, "e": 27447, "s": 27436, "text": "R Language" }, { "code": null, "e": 27545, "s": 27447, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27554, "s": 27545, "text": "Comments" }, { "code": null, "e": 27567, "s": 27554, "text": "Old Comments" }, { "code": null, "e": 27625, "s": 27567, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 27669, "s": 27625, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 27721, "s": 27669, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 27773, "s": 27721, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27805, "s": 27773, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 27843, "s": 27805, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27878, "s": 27843, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27936, "s": 27878, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27972, "s": 27936, "text": "K-Means Clustering in R Programming" } ]
Abstract Classes in Python - GeeksforGeeks
19 Mar, 2021 An abstract class can be considered as a blueprint for other classes. It allows you to create a set of methods that must be created within any child classes built from the abstract class. A class which contains one or more abstract methods is called an abstract class. An abstract method is a method that has a declaration but does not have an implementation. While we are designing large functional units we use an abstract class. When we want to provide a common interface for different implementations of a component, we use an abstract class. Why use Abstract Base Classes : By defining an abstract base class, you can define a common Application Program Interface(API) for a set of subclasses. This capability is especially useful in situations where a third-party is going to provide implementations, such as with plugins, but can also help you when working in a large team or with a large code-base where keeping all classes in your mind is difficult or not possible. How Abstract Base classes work : By default, Python does not provide abstract classes. Python comes with a module that provides the base for defining Abstract Base classes(ABC) and that module name is ABC. ABC works by decorating methods of the base class as abstract and then registering concrete classes as implementations of the abstract base. A method becomes abstract when decorated with the keyword @abstractmethod. For Example – Code 1: Python3 # Python program showing# abstract base class work from abc import ABC, abstractmethod class Polygon(ABC): @abstractmethod def noofsides(self): pass class Triangle(Polygon): # overriding abstract method def noofsides(self): print("I have 3 sides") class Pentagon(Polygon): # overriding abstract method def noofsides(self): print("I have 5 sides") class Hexagon(Polygon): # overriding abstract method def noofsides(self): print("I have 6 sides") class Quadrilateral(Polygon): # overriding abstract method def noofsides(self): print("I have 4 sides") # Driver codeR = Triangle()R.noofsides() K = Quadrilateral()K.noofsides() R = Pentagon()R.noofsides() K = Hexagon()K.noofsides() Output: I have 3 sides I have 4 sides I have 5 sides I have 6 sides Code 2: Python3 # Python program showing# abstract base class work from abc import ABC, abstractmethodclass Animal(ABC): def move(self): pass class Human(Animal): def move(self): print("I can walk and run") class Snake(Animal): def move(self): print("I can crawl") class Dog(Animal): def move(self): print("I can bark") class Lion(Animal): def move(self): print("I can roar") # Driver codeR = Human()R.move() K = Snake()K.move() R = Dog()R.move() K = Lion()K.move() Output: I can walk and run I can crawl I can bark I can roar Implementation Through Subclassing : By subclassing directly from the base, we can avoid the need to register the class explicitly. In this case, the Python class management is used to recognize PluginImplementation as implementing the abstract PluginBase. Python3 # Python program showing# implementation of abstract# class through subclassing import abc class parent: def geeks(self): pass class child(parent): def geeks(self): print("child class") # Driver codeprint( issubclass(child, parent))print( isinstance(child(), parent)) Output: True True A side-effect of using direct subclassing is, it is possible to find all the implementations of your plugin by asking the base class for the list of known classes derived from it. Concrete Methods in Abstract Base Classes : Concrete classes contain only concrete (normal)methods whereas abstract classes may contain both concrete methods and abstract methods. The concrete class provides an implementation of abstract methods, the abstract base class can also provide an implementation by invoking the methods via super(). Let look over the example to invoke the method using super(): Python3 # Python program invoking a# method using super() import abcfrom abc import ABC, abstractmethod class R(ABC): def rk(self): print("Abstract Base Class") class K(R): def rk(self): super().rk() print("subclass ") # Driver coder = K()r.rk() Output: Abstract Base Class subclass In the above program, we can invoke the methods in abstract classes by using super(). Abstract Properties : Abstract classes include attributes in addition to methods, you can require the attributes in concrete classes by defining them with @abstractproperty. Python3 # Python program showing# abstract properties import abcfrom abc import ABC, abstractmethod class parent(ABC): @abc.abstractproperty def geeks(self): return "parent class"class child(parent): @property def geeks(self): return "child class" try: r =parent() print( r.geeks)except Exception as err: print (err) r = child()print (r.geeks) Output: Can't instantiate abstract class parent with abstract methods geeks child class In the above example, the Base class cannot be instantiated because it has only an abstract version of the property getter method. Abstract Class Instantiation : Abstract classes are incomplete because they have methods that have nobody. If python allows creating an object for abstract classes then using that object if anyone calls the abstract method, but there is no actual implementation to invoke. So we use an abstract class as a template and according to the need, we extend it and build on it before we can use it. Due to the fact, an abstract class is not a concrete class, it cannot be instantiated. When we create an object for the abstract class it raises an error. Python3 # Python program showing# abstract class cannot# be an instantiationfrom abc import ABC,abstractmethod class Animal(ABC): @abstractmethod def move(self): passclass Human(Animal): def move(self): print("I can walk and run") class Snake(Animal): def move(self): print("I can crawl") class Dog(Animal): def move(self): print("I can bark") class Lion(Animal): def move(self): print("I can roar") c=Animal() Output: Traceback (most recent call last): File "/home/ffe4267d930f204512b7f501bb1bc489.py", line 19, in c=Animal() TypeError: Can't instantiate abstract class Animal with abstract methods move OmriLevin zack_aayush Picked python-oop-concepts Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Adding new column to existing DataFrame in Pandas Python map() function Read JSON file using Python How to get column names in Pandas dataframe Enumerate() in Python How to Install PIP on Windows ? Read a file line by line in Python Python OOPs Concepts Iterate over a list in Python Different ways to create Pandas Dataframe
[ { "code": null, "e": 41161, "s": 41133, "text": "\n19 Mar, 2021" }, { "code": null, "e": 42577, "s": 41161, "text": "An abstract class can be considered as a blueprint for other classes. It allows you to create a set of methods that must be created within any child classes built from the abstract class. A class which contains one or more abstract methods is called an abstract class. An abstract method is a method that has a declaration but does not have an implementation. While we are designing large functional units we use an abstract class. When we want to provide a common interface for different implementations of a component, we use an abstract class. Why use Abstract Base Classes : By defining an abstract base class, you can define a common Application Program Interface(API) for a set of subclasses. This capability is especially useful in situations where a third-party is going to provide implementations, such as with plugins, but can also help you when working in a large team or with a large code-base where keeping all classes in your mind is difficult or not possible. How Abstract Base classes work : By default, Python does not provide abstract classes. Python comes with a module that provides the base for defining Abstract Base classes(ABC) and that module name is ABC. ABC works by decorating methods of the base class as abstract and then registering concrete classes as implementations of the abstract base. A method becomes abstract when decorated with the keyword @abstractmethod. For Example – " }, { "code": null, "e": 42585, "s": 42577, "text": "Code 1:" }, { "code": null, "e": 42593, "s": 42585, "text": "Python3" }, { "code": "# Python program showing# abstract base class work from abc import ABC, abstractmethod class Polygon(ABC): @abstractmethod def noofsides(self): pass class Triangle(Polygon): # overriding abstract method def noofsides(self): print(\"I have 3 sides\") class Pentagon(Polygon): # overriding abstract method def noofsides(self): print(\"I have 5 sides\") class Hexagon(Polygon): # overriding abstract method def noofsides(self): print(\"I have 6 sides\") class Quadrilateral(Polygon): # overriding abstract method def noofsides(self): print(\"I have 4 sides\") # Driver codeR = Triangle()R.noofsides() K = Quadrilateral()K.noofsides() R = Pentagon()R.noofsides() K = Hexagon()K.noofsides()", "e": 43341, "s": 42593, "text": null }, { "code": null, "e": 43351, "s": 43341, "text": "Output: " }, { "code": null, "e": 43411, "s": 43351, "text": "I have 3 sides\nI have 4 sides\nI have 5 sides\nI have 6 sides" }, { "code": null, "e": 43422, "s": 43411, "text": " Code 2: " }, { "code": null, "e": 43430, "s": 43422, "text": "Python3" }, { "code": "# Python program showing# abstract base class work from abc import ABC, abstractmethodclass Animal(ABC): def move(self): pass class Human(Animal): def move(self): print(\"I can walk and run\") class Snake(Animal): def move(self): print(\"I can crawl\") class Dog(Animal): def move(self): print(\"I can bark\") class Lion(Animal): def move(self): print(\"I can roar\") # Driver codeR = Human()R.move() K = Snake()K.move() R = Dog()R.move() K = Lion()K.move()", "e": 43943, "s": 43430, "text": null }, { "code": null, "e": 43953, "s": 43943, "text": "Output: " }, { "code": null, "e": 44006, "s": 43953, "text": "I can walk and run\nI can crawl\nI can bark\nI can roar" }, { "code": null, "e": 44267, "s": 44006, "text": " Implementation Through Subclassing : By subclassing directly from the base, we can avoid the need to register the class explicitly. In this case, the Python class management is used to recognize PluginImplementation as implementing the abstract PluginBase. " }, { "code": null, "e": 44275, "s": 44267, "text": "Python3" }, { "code": "# Python program showing# implementation of abstract# class through subclassing import abc class parent: def geeks(self): pass class child(parent): def geeks(self): print(\"child class\") # Driver codeprint( issubclass(child, parent))print( isinstance(child(), parent))", "e": 44569, "s": 44275, "text": null }, { "code": null, "e": 44579, "s": 44569, "text": "Output: " }, { "code": null, "e": 44589, "s": 44579, "text": "True\nTrue" }, { "code": null, "e": 45116, "s": 44589, "text": "A side-effect of using direct subclassing is, it is possible to find all the implementations of your plugin by asking the base class for the list of known classes derived from it. Concrete Methods in Abstract Base Classes : Concrete classes contain only concrete (normal)methods whereas abstract classes may contain both concrete methods and abstract methods. The concrete class provides an implementation of abstract methods, the abstract base class can also provide an implementation by invoking the methods via super(). " }, { "code": null, "e": 45180, "s": 45116, "text": "Let look over the example to invoke the method using super(): " }, { "code": null, "e": 45188, "s": 45180, "text": "Python3" }, { "code": "# Python program invoking a# method using super() import abcfrom abc import ABC, abstractmethod class R(ABC): def rk(self): print(\"Abstract Base Class\") class K(R): def rk(self): super().rk() print(\"subclass \") # Driver coder = K()r.rk()", "e": 45453, "s": 45188, "text": null }, { "code": null, "e": 45463, "s": 45453, "text": "Output: " }, { "code": null, "e": 45492, "s": 45463, "text": "Abstract Base Class\nsubclass" }, { "code": null, "e": 45756, "s": 45492, "text": "In the above program, we can invoke the methods in abstract classes by using super(). Abstract Properties : Abstract classes include attributes in addition to methods, you can require the attributes in concrete classes by defining them with @abstractproperty. " }, { "code": null, "e": 45764, "s": 45756, "text": "Python3" }, { "code": "# Python program showing# abstract properties import abcfrom abc import ABC, abstractmethod class parent(ABC): @abc.abstractproperty def geeks(self): return \"parent class\"class child(parent): @property def geeks(self): return \"child class\" try: r =parent() print( r.geeks)except Exception as err: print (err) r = child()print (r.geeks)", "e": 46145, "s": 45764, "text": null }, { "code": null, "e": 46155, "s": 46145, "text": "Output: " }, { "code": null, "e": 46235, "s": 46155, "text": "Can't instantiate abstract class parent with abstract methods geeks\nchild class" }, { "code": null, "e": 46918, "s": 46235, "text": "In the above example, the Base class cannot be instantiated because it has only an abstract version of the property getter method. Abstract Class Instantiation : Abstract classes are incomplete because they have methods that have nobody. If python allows creating an object for abstract classes then using that object if anyone calls the abstract method, but there is no actual implementation to invoke. So we use an abstract class as a template and according to the need, we extend it and build on it before we can use it. Due to the fact, an abstract class is not a concrete class, it cannot be instantiated. When we create an object for the abstract class it raises an error. " }, { "code": null, "e": 46926, "s": 46918, "text": "Python3" }, { "code": "# Python program showing# abstract class cannot# be an instantiationfrom abc import ABC,abstractmethod class Animal(ABC): @abstractmethod def move(self): passclass Human(Animal): def move(self): print(\"I can walk and run\") class Snake(Animal): def move(self): print(\"I can crawl\") class Dog(Animal): def move(self): print(\"I can bark\") class Lion(Animal): def move(self): print(\"I can roar\") c=Animal()", "e": 47382, "s": 46926, "text": null }, { "code": null, "e": 47392, "s": 47382, "text": "Output: " }, { "code": null, "e": 47585, "s": 47392, "text": "Traceback (most recent call last):\n File \"/home/ffe4267d930f204512b7f501bb1bc489.py\", line 19, in \n c=Animal()\nTypeError: Can't instantiate abstract class Animal with abstract methods move" }, { "code": null, "e": 47597, "s": 47587, "text": "OmriLevin" }, { "code": null, "e": 47609, "s": 47597, "text": "zack_aayush" }, { "code": null, "e": 47616, "s": 47609, "text": "Picked" }, { "code": null, "e": 47636, "s": 47616, "text": "python-oop-concepts" }, { "code": null, "e": 47643, "s": 47636, "text": "Python" }, { "code": null, "e": 47741, "s": 47643, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47750, "s": 47741, "text": "Comments" }, { "code": null, "e": 47763, "s": 47750, "text": "Old Comments" }, { "code": null, "e": 47813, "s": 47763, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 47835, "s": 47813, "text": "Python map() function" }, { "code": null, "e": 47863, "s": 47835, "text": "Read JSON file using Python" }, { "code": null, "e": 47907, "s": 47863, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 47929, "s": 47907, "text": "Enumerate() in Python" }, { "code": null, "e": 47961, "s": 47929, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 47996, "s": 47961, "text": "Read a file line by line in Python" }, { "code": null, "e": 48017, "s": 47996, "text": "Python OOPs Concepts" }, { "code": null, "e": 48047, "s": 48017, "text": "Iterate over a list in Python" } ]
ArrayList and LinkedList remove() methods in Java with Examples - GeeksforGeeks
19 Jan, 2022 List interface in Java (which is implemented by ArrayList and LinkedList) provides two versions of remove method. boolean remove(Object obj) : It accepts object to be removed. It returns true if it finds and removes the element. It returns false if the element to be removed is not present. Removes the first occurrence of the specified element from given list, if the element is present. If the element is not present, the given list is not changed. After removing, it shifts subsequent elements(if any) to left and decreases their indexes by 1. It throws following exceptions ClassCastException – if the type of the specified element is incompatible with this collection (optional). NullPointerException – if the specified element is null and this collection does not permit null elements(optional). UnsupportedOperationException – if the remove operation is not supported by this collection Java // A Java program to demonstrate working of list remove// when Object to be removed is passed.import java.util.*; public class GFG{ public static void main(String[] args) { // Demonstrating remove on ArrayList List<String> myAlist = new ArrayList<String>(); myAlist.add("Geeks"); myAlist.add("Practice"); myAlist.add("Quiz"); System.out.println("Original ArrayList : " + myAlist); myAlist.remove("Quiz"); System.out.println("Modified ArrayList : " + myAlist); // Demonstrating remove on LinkedList List<String> myLlist = new LinkedList<String>(); myLlist.add("Geeks"); myLlist.add("Practice"); myLlist.add("Quiz"); System.out.println("Original LinkedList : " + myLlist); myLlist.remove("Quiz"); System.out.println("Modified LinkedList : " + myLlist); }} Original ArrayList : [Geeks, Practice, Quiz] Modified ArrayList : [Geeks, Practice] Original LinkedList : [Geeks, Practice, Quiz] Modified LinkedList : [Geeks, Practice] object remove(int index) : It removes the element at given index. It returns the object that is removed. After removing, it shifts subsequent elements(if any) to left and decreases their indexes by 1. If the list contains int types, then this method is called when an int is passed (Please refer this for details) It throws IndexOutOfBoundsException if index is out of bound, Java // A Java program to demonstrate working of list remove// when index is passed.import java.util.*; public class GFG{ public static void main(String[] args) { // Demonstrating remove on ArrayList List<String> myAlist = new ArrayList<String>(); myAlist.add("Geeks"); myAlist.add("Practice"); myAlist.add("Quiz"); System.out.println("Original ArrayList : " + myAlist); myAlist.remove("Quiz"); System.out.println("Modified ArrayList : " + myAlist); // Demonstrating remove on LinkedList List<String> myLlist = new LinkedList<String>(); myLlist.add("Geeks"); myLlist.add("Practice"); myLlist.add("Quiz"); System.out.println("Original LinkedList : " + myLlist); myLlist.remove(2); System.out.println("Modified LinkedList : " + myLlist); }} Original ArrayList : [Geeks, Practice, Quiz] Modified ArrayList : [Geeks, Practice] Original LinkedList : [Geeks, Practice, Quiz] Modified LinkedList : [Geeks, Practice] Important Points: Note that there is no direct way to remove elements in array as size of array is fixed. So there are no methods like add(), remove(), delete(). But in Collection like ArrayList and Hashset, we have these methods. So it’s better to either convert array to ArrayList or Use Arraylist from first place when we need these methods. It is not recommended to use remove() of list interface when iterating over elements. This may lead to ConcurrentModificationException (Refer this for a sample program with this exception). When iterating over elements, it is recommended to use Iterator.remove() method. Please see this for details. This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. dhruvagni95 anandsharma1905736 anikakapoor sagar0719kumar Java - util package Java-ArrayList Java-Collections Java-Functions java-LinkedList Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multithreading in Java
[ { "code": null, "e": 26450, "s": 26422, "text": "\n19 Jan, 2022" }, { "code": null, "e": 26742, "s": 26450, "text": "List interface in Java (which is implemented by ArrayList and LinkedList) provides two versions of remove method. boolean remove(Object obj) : It accepts object to be removed. It returns true if it finds and removes the element. It returns false if the element to be removed is not present. " }, { "code": null, "e": 26902, "s": 26742, "text": "Removes the first occurrence of the specified element from given list, if the element is present. If the element is not present, the given list is not changed." }, { "code": null, "e": 26998, "s": 26902, "text": "After removing, it shifts subsequent elements(if any) to left and decreases their indexes by 1." }, { "code": null, "e": 27345, "s": 26998, "text": "It throws following exceptions ClassCastException – if the type of the specified element is incompatible with this collection (optional). NullPointerException – if the specified element is null and this collection does not permit null elements(optional). UnsupportedOperationException – if the remove operation is not supported by this collection" }, { "code": null, "e": 27350, "s": 27345, "text": "Java" }, { "code": "// A Java program to demonstrate working of list remove// when Object to be removed is passed.import java.util.*; public class GFG{ public static void main(String[] args) { // Demonstrating remove on ArrayList List<String> myAlist = new ArrayList<String>(); myAlist.add(\"Geeks\"); myAlist.add(\"Practice\"); myAlist.add(\"Quiz\"); System.out.println(\"Original ArrayList : \" + myAlist); myAlist.remove(\"Quiz\"); System.out.println(\"Modified ArrayList : \" + myAlist); // Demonstrating remove on LinkedList List<String> myLlist = new LinkedList<String>(); myLlist.add(\"Geeks\"); myLlist.add(\"Practice\"); myLlist.add(\"Quiz\"); System.out.println(\"Original LinkedList : \" + myLlist); myLlist.remove(\"Quiz\"); System.out.println(\"Modified LinkedList : \" + myLlist); }}", "e": 28228, "s": 27350, "text": null }, { "code": null, "e": 28398, "s": 28228, "text": "Original ArrayList : [Geeks, Practice, Quiz]\nModified ArrayList : [Geeks, Practice]\nOriginal LinkedList : [Geeks, Practice, Quiz]\nModified LinkedList : [Geeks, Practice]" }, { "code": null, "e": 28504, "s": 28398, "text": "object remove(int index) : It removes the element at given index. It returns the object that is removed. " }, { "code": null, "e": 28600, "s": 28504, "text": "After removing, it shifts subsequent elements(if any) to left and decreases their indexes by 1." }, { "code": null, "e": 28713, "s": 28600, "text": "If the list contains int types, then this method is called when an int is passed (Please refer this for details)" }, { "code": null, "e": 28776, "s": 28713, "text": "It throws IndexOutOfBoundsException if index is out of bound, " }, { "code": null, "e": 28781, "s": 28776, "text": "Java" }, { "code": "// A Java program to demonstrate working of list remove// when index is passed.import java.util.*; public class GFG{ public static void main(String[] args) { // Demonstrating remove on ArrayList List<String> myAlist = new ArrayList<String>(); myAlist.add(\"Geeks\"); myAlist.add(\"Practice\"); myAlist.add(\"Quiz\"); System.out.println(\"Original ArrayList : \" + myAlist); myAlist.remove(\"Quiz\"); System.out.println(\"Modified ArrayList : \" + myAlist); // Demonstrating remove on LinkedList List<String> myLlist = new LinkedList<String>(); myLlist.add(\"Geeks\"); myLlist.add(\"Practice\"); myLlist.add(\"Quiz\"); System.out.println(\"Original LinkedList : \" + myLlist); myLlist.remove(2); System.out.println(\"Modified LinkedList : \" + myLlist); }}", "e": 29637, "s": 28781, "text": null }, { "code": null, "e": 29807, "s": 29637, "text": "Original ArrayList : [Geeks, Practice, Quiz]\nModified ArrayList : [Geeks, Practice]\nOriginal LinkedList : [Geeks, Practice, Quiz]\nModified LinkedList : [Geeks, Practice]" }, { "code": null, "e": 29826, "s": 29807, "text": "Important Points: " }, { "code": null, "e": 30153, "s": 29826, "text": "Note that there is no direct way to remove elements in array as size of array is fixed. So there are no methods like add(), remove(), delete(). But in Collection like ArrayList and Hashset, we have these methods. So it’s better to either convert array to ArrayList or Use Arraylist from first place when we need these methods." }, { "code": null, "e": 30453, "s": 30153, "text": "It is not recommended to use remove() of list interface when iterating over elements. This may lead to ConcurrentModificationException (Refer this for a sample program with this exception). When iterating over elements, it is recommended to use Iterator.remove() method. Please see this for details." }, { "code": null, "e": 30748, "s": 30453, "text": "This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 30760, "s": 30748, "text": "dhruvagni95" }, { "code": null, "e": 30779, "s": 30760, "text": "anandsharma1905736" }, { "code": null, "e": 30791, "s": 30779, "text": "anikakapoor" }, { "code": null, "e": 30806, "s": 30791, "text": "sagar0719kumar" }, { "code": null, "e": 30826, "s": 30806, "text": "Java - util package" }, { "code": null, "e": 30841, "s": 30826, "text": "Java-ArrayList" }, { "code": null, "e": 30858, "s": 30841, "text": "Java-Collections" }, { "code": null, "e": 30873, "s": 30858, "text": "Java-Functions" }, { "code": null, "e": 30889, "s": 30873, "text": "java-LinkedList" }, { "code": null, "e": 30894, "s": 30889, "text": "Java" }, { "code": null, "e": 30899, "s": 30894, "text": "Java" }, { "code": null, "e": 30916, "s": 30899, "text": "Java-Collections" }, { "code": null, "e": 31014, "s": 30916, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31029, "s": 31014, "text": "Stream In Java" }, { "code": null, "e": 31080, "s": 31029, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 31110, "s": 31080, "text": "HashMap in Java with Examples" }, { "code": null, "e": 31129, "s": 31110, "text": "Interfaces in Java" }, { "code": null, "e": 31160, "s": 31129, "text": "How to iterate any Map in Java" }, { "code": null, "e": 31178, "s": 31160, "text": "ArrayList in Java" }, { "code": null, "e": 31210, "s": 31178, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 31230, "s": 31210, "text": "Stack Class in Java" }, { "code": null, "e": 31254, "s": 31230, "text": "Singleton Class in Java" } ]
Program for Arrow Star Pattern - GeeksforGeeks
29 Apr, 2021 Given the value of n, print the pattern.Examples : Input : 5 Output : ***** **** *** ** * ** *** **** ***** Input : 7 Output : ******* ****** ***** **** *** ** * ** *** **** ***** ****** ******* Below is the implementation to print the above pattern : C++ Java Python3 C# PHP Javascript // C++ Implementation to print the pattern #include <bits/stdc++.h>using namespace std; // arrow functionint arrow(int n){ // Prints the upper part of the arrow for (int i = 1; i <= n; i++) { // for the spacing to form // the point of the arrow for (int j = i; j < n; j++) { printf(" "); } // for printing the star(*) for (int j = i; j <= n; j++) { cout << "*"; } cout << endl; } // Prints lower part of the arrow for (int i = 2; i <= n; i++) { // for the spacing to form // the point of the arrow for (int j = 1; j < i; j++) { printf(" "); } // for printing the star(*) for (int j = 1; j <= i; j++) { cout << "*"; } cout << endl; }} // driver codeint main(){ // get the value from user int n = 5; // function calling arrow(n); return 0;} // Java Implementation to// print the above patternimport java.io.*; class GFG { // arrow functionstatic void arrow(int n){ // Prints the upper part of the arrow for (int i = 1; i <= n; i++) { // for the spacing to form // the point of the arrow for (int j = i; j < n; j++) { System.out.print(" "); } // for printing the star(*) for (int j = i; j <= n; j++) { System.out.print("*"); } System.out.println(); } // Prints lower part of the arrow for (int i = 2; i <= n; i++) { // for the spacing to form // the point of the arrow for (int j = 1; j < i; j++) { System.out.print(" "); } // for printing the star(*) for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.print('\n'); }} // driver codepublic static void main(String[] Argv) { // get the value from user int n = 5; // function calling arrow(n);}} // this code is contributed by 'vt_m' # Python Implementation to# print the pattern # arrow functiondef arrow(n): # Prints the upper part of the arrow for i in range(1, n+1): # for the spacing to form # the point of the arrow for j in range(i, n): print(" ", end="") # for printing the star(*) for j in range(i, n+1): print("*", end="") print() # Prints lower part of the arrow for i in range(2, n+1): # for the spacing to form # the point of the arrow for j in range(1, i): print(" ", end="") # for printing the star(*) for j in range(1, i+1): print("*", end="") print() # driver code# get the value from the usern = 5 # function callingarrow(n) # This code is contributed# by Anant Agarwal. // C# Implementation to// print the above patternusing System; class GFG { // arrow functionstatic void arrow(int n){ // Prints the upper part of the arrow for (int i = 1; i <= n; i++) { // for the spacing to form // the point of the arrow for (int j = i; j < n; j++) { Console.Write(" "); } // for printing the star(*) for (int j = i; j <= n; j++) { Console.Write("*"); } Console.WriteLine(); } // Prints lower part of the arrow for (int i = 2; i <= n; i++) { // for the spacing to form // the point of the arrow for (int j = 1; j < i; j++) { Console.Write(" "); } // for printing the star(*) for (int j = 1; j <= i; j++) { Console.Write("*"); } Console.WriteLine(); }} // driver codepublic static void Main() { // get the value from user int n = 5; // function calling arrow(n);}} // this code is contributed by 'vt_m' <?php// PHP Implementation to print// the pattern function arrow($n){ // Prints the upper part of // the arrow for ($i = 1; $i <= $n; $i++) { // for the spacing to form // the point of the arrow for ($j = $i; $j < $n; $j++) { echo " "; } // for printing the star(*) for ($j = $i; $j <= $n; $j++) { echo "*"; } echo "\n"; } // Prints lower part of the arrow for ($i = 2; $i <= $n; $i++) { // for the spacing to form // the point of the arrow for ($j = 1; $j < $i; $j++) { echo " "; } // for printing the star(*) for ($j = 1; $j <= $i; $j++) { echo "*"; } echo "\n"; }} // Driver code$n = 5;arrow($n); // This code is contributed by mits?> <script> // JavaScript Implementation // to print the pattern // arrow function function arrow(n) { // Prints the upper part of the arrow for (var i = 1; i <= n; i++) { // for the spacing to form // the point of the arrow for (var j = i; j < n; j++) { document.write(" "); } // for printing the star(*) for (var j = i; j <= n; j++) { document.write("*"); } document.write("<br>"); } // Prints lower part of the arrow for (var i = 2; i <= n; i++) { // for the spacing to form // the point of the arrow for (var j = 1; j < i; j++) { document.write(" "); } // for printing the star(*) for (var j = 1; j <= i; j++) { document.write("*"); } document.write("<br>"); } } // driver code // get the value from user var n = 5; // function calling arrow(n);</script> Output : ***** **** *** ** * ** *** **** ***** Mithun Kumar rdtank pattern-printing School Programming pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C++ Classes and Objects Interfaces in Java Constructors in C++ Operator Overloading in C++ Polymorphism in C++ Copy Constructor in C++ Friend class and function in C++ C++ Data Types Types of Operating Systems Introduction To PYTHON
[ { "code": null, "e": 25837, "s": 25809, "text": "\n29 Apr, 2021" }, { "code": null, "e": 25890, "s": 25837, "text": "Given the value of n, print the pattern.Examples : " }, { "code": null, "e": 26098, "s": 25890, "text": "Input : 5\nOutput :\n *****\n ****\n ***\n **\n*\n **\n ***\n ****\n *****\n\nInput : 7\nOutput : \n *******\n ******\n *****\n ****\n ***\n **\n*\n **\n ***\n ****\n *****\n ******\n *******" }, { "code": null, "e": 26159, "s": 26100, "text": "Below is the implementation to print the above pattern : " }, { "code": null, "e": 26163, "s": 26159, "text": "C++" }, { "code": null, "e": 26168, "s": 26163, "text": "Java" }, { "code": null, "e": 26176, "s": 26168, "text": "Python3" }, { "code": null, "e": 26179, "s": 26176, "text": "C#" }, { "code": null, "e": 26183, "s": 26179, "text": "PHP" }, { "code": null, "e": 26194, "s": 26183, "text": "Javascript" }, { "code": "// C++ Implementation to print the pattern #include <bits/stdc++.h>using namespace std; // arrow functionint arrow(int n){ // Prints the upper part of the arrow for (int i = 1; i <= n; i++) { // for the spacing to form // the point of the arrow for (int j = i; j < n; j++) { printf(\" \"); } // for printing the star(*) for (int j = i; j <= n; j++) { cout << \"*\"; } cout << endl; } // Prints lower part of the arrow for (int i = 2; i <= n; i++) { // for the spacing to form // the point of the arrow for (int j = 1; j < i; j++) { printf(\" \"); } // for printing the star(*) for (int j = 1; j <= i; j++) { cout << \"*\"; } cout << endl; }} // driver codeint main(){ // get the value from user int n = 5; // function calling arrow(n); return 0;}", "e": 27185, "s": 26194, "text": null }, { "code": "// Java Implementation to// print the above patternimport java.io.*; class GFG { // arrow functionstatic void arrow(int n){ // Prints the upper part of the arrow for (int i = 1; i <= n; i++) { // for the spacing to form // the point of the arrow for (int j = i; j < n; j++) { System.out.print(\" \"); } // for printing the star(*) for (int j = i; j <= n; j++) { System.out.print(\"*\"); } System.out.println(); } // Prints lower part of the arrow for (int i = 2; i <= n; i++) { // for the spacing to form // the point of the arrow for (int j = 1; j < i; j++) { System.out.print(\" \"); } // for printing the star(*) for (int j = 1; j <= i; j++) { System.out.print(\"*\"); } System.out.print('\\n'); }} // driver codepublic static void main(String[] Argv) { // get the value from user int n = 5; // function calling arrow(n);}} // this code is contributed by 'vt_m'", "e": 28299, "s": 27185, "text": null }, { "code": "# Python Implementation to# print the pattern # arrow functiondef arrow(n): # Prints the upper part of the arrow for i in range(1, n+1): # for the spacing to form # the point of the arrow for j in range(i, n): print(\" \", end=\"\") # for printing the star(*) for j in range(i, n+1): print(\"*\", end=\"\") print() # Prints lower part of the arrow for i in range(2, n+1): # for the spacing to form # the point of the arrow for j in range(1, i): print(\" \", end=\"\") # for printing the star(*) for j in range(1, i+1): print(\"*\", end=\"\") print() # driver code# get the value from the usern = 5 # function callingarrow(n) # This code is contributed# by Anant Agarwal.", "e": 29190, "s": 28299, "text": null }, { "code": "// C# Implementation to// print the above patternusing System; class GFG { // arrow functionstatic void arrow(int n){ // Prints the upper part of the arrow for (int i = 1; i <= n; i++) { // for the spacing to form // the point of the arrow for (int j = i; j < n; j++) { Console.Write(\" \"); } // for printing the star(*) for (int j = i; j <= n; j++) { Console.Write(\"*\"); } Console.WriteLine(); } // Prints lower part of the arrow for (int i = 2; i <= n; i++) { // for the spacing to form // the point of the arrow for (int j = 1; j < i; j++) { Console.Write(\" \"); } // for printing the star(*) for (int j = 1; j <= i; j++) { Console.Write(\"*\"); } Console.WriteLine(); }} // driver codepublic static void Main() { // get the value from user int n = 5; // function calling arrow(n);}} // this code is contributed by 'vt_m'", "e": 30281, "s": 29190, "text": null }, { "code": "<?php// PHP Implementation to print// the pattern function arrow($n){ // Prints the upper part of // the arrow for ($i = 1; $i <= $n; $i++) { // for the spacing to form // the point of the arrow for ($j = $i; $j < $n; $j++) { echo \" \"; } // for printing the star(*) for ($j = $i; $j <= $n; $j++) { echo \"*\"; } echo \"\\n\"; } // Prints lower part of the arrow for ($i = 2; $i <= $n; $i++) { // for the spacing to form // the point of the arrow for ($j = 1; $j < $i; $j++) { echo \" \"; } // for printing the star(*) for ($j = 1; $j <= $i; $j++) { echo \"*\"; } echo \"\\n\"; }} // Driver code$n = 5;arrow($n); // This code is contributed by mits?>", "e": 31153, "s": 30281, "text": null }, { "code": "<script> // JavaScript Implementation // to print the pattern // arrow function function arrow(n) { // Prints the upper part of the arrow for (var i = 1; i <= n; i++) { // for the spacing to form // the point of the arrow for (var j = i; j < n; j++) { document.write(\" \"); } // for printing the star(*) for (var j = i; j <= n; j++) { document.write(\"*\"); } document.write(\"<br>\"); } // Prints lower part of the arrow for (var i = 2; i <= n; i++) { // for the spacing to form // the point of the arrow for (var j = 1; j < i; j++) { document.write(\" \"); } // for printing the star(*) for (var j = 1; j <= i; j++) { document.write(\"*\"); } document.write(\"<br>\"); } } // driver code // get the value from user var n = 5; // function calling arrow(n);</script>", "e": 32257, "s": 31153, "text": null }, { "code": null, "e": 32268, "s": 32257, "text": "Output : " }, { "code": null, "e": 32326, "s": 32268, "text": " *****\n ****\n ***\n **\n*\n **\n ***\n ****\n *****" }, { "code": null, "e": 32341, "s": 32328, "text": "Mithun Kumar" }, { "code": null, "e": 32348, "s": 32341, "text": "rdtank" }, { "code": null, "e": 32365, "s": 32348, "text": "pattern-printing" }, { "code": null, "e": 32384, "s": 32365, "text": "School Programming" }, { "code": null, "e": 32401, "s": 32384, "text": "pattern-printing" }, { "code": null, "e": 32499, "s": 32401, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32523, "s": 32499, "text": "C++ Classes and Objects" }, { "code": null, "e": 32542, "s": 32523, "text": "Interfaces in Java" }, { "code": null, "e": 32562, "s": 32542, "text": "Constructors in C++" }, { "code": null, "e": 32590, "s": 32562, "text": "Operator Overloading in C++" }, { "code": null, "e": 32610, "s": 32590, "text": "Polymorphism in C++" }, { "code": null, "e": 32634, "s": 32610, "text": "Copy Constructor in C++" }, { "code": null, "e": 32667, "s": 32634, "text": "Friend class and function in C++" }, { "code": null, "e": 32682, "s": 32667, "text": "C++ Data Types" }, { "code": null, "e": 32709, "s": 32682, "text": "Types of Operating Systems" } ]
Fibonacci series program in Java without using recursion.
Following is the required program. Live Demo public class Tester { public static void main(String args[]) { int n1 = 0, n2 = 1, n3, i, max = 5; System.out.print(n1 + " " + n2); for (i = 2; i < max; ++i) { n3 = n1 + n2; System.out.print(" " + n3); n1 = n2; n2 = n3; } } } 0 1 1 2 3
[ { "code": null, "e": 1097, "s": 1062, "text": "Following is the required program." }, { "code": null, "e": 1107, "s": 1097, "text": "Live Demo" }, { "code": null, "e": 1409, "s": 1107, "text": "public class Tester {\n public static void main(String args[]) {\n int n1 = 0, n2 = 1, n3, i, max = 5;\n System.out.print(n1 + \" \" + n2);\n for (i = 2; i < max; ++i) {\n n3 = n1 + n2;\n System.out.print(\" \" + n3);\n n1 = n2;\n n2 = n3;\n }\n }\n }" }, { "code": null, "e": 1419, "s": 1409, "text": "0 1 1 2 3" } ]
Python | sympy.Mul() method - GeeksforGeeks
11 Jul, 2019 With the help of sympy.Mul() method, we can multiply two variables and can form a mathematical expression. Syntax : sympy.Mul()Return : Return the product of two variables. Example #1 :In this example we can see that by using sympy.Mul() method, we are able two multiply the two variables and we can also form mathematical expression. # import sympyfrom sympy import * x, y = symbols('x y') # Use sympy.Mul() methodmul = Mul(x, y) print(mul) Output : x*y Example #2 : # import sympyfrom sympy import * x, y = symbols('x y') # Use sympy.Mul() method mul = Mul(x, y) + Mul(x, x) print(mul) Output : x**2 + x*y SymPy 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 Defaultdict in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n11 Jul, 2019" }, { "code": null, "e": 25754, "s": 25647, "text": "With the help of sympy.Mul() method, we can multiply two variables and can form a mathematical expression." }, { "code": null, "e": 25820, "s": 25754, "text": "Syntax : sympy.Mul()Return : Return the product of two variables." }, { "code": null, "e": 25982, "s": 25820, "text": "Example #1 :In this example we can see that by using sympy.Mul() method, we are able two multiply the two variables and we can also form mathematical expression." }, { "code": "# import sympyfrom sympy import * x, y = symbols('x y') # Use sympy.Mul() methodmul = Mul(x, y) print(mul)", "e": 26093, "s": 25982, "text": null }, { "code": null, "e": 26102, "s": 26093, "text": "Output :" }, { "code": null, "e": 26106, "s": 26102, "text": "x*y" }, { "code": null, "e": 26119, "s": 26106, "text": "Example #2 :" }, { "code": "# import sympyfrom sympy import * x, y = symbols('x y') # Use sympy.Mul() method mul = Mul(x, y) + Mul(x, x) print(mul)", "e": 26243, "s": 26119, "text": null }, { "code": null, "e": 26252, "s": 26243, "text": "Output :" }, { "code": null, "e": 26263, "s": 26252, "text": "x**2 + x*y" }, { "code": null, "e": 26269, "s": 26263, "text": "SymPy" }, { "code": null, "e": 26276, "s": 26269, "text": "Python" }, { "code": null, "e": 26374, "s": 26276, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26406, "s": 26374, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26448, "s": 26406, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26490, "s": 26448, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26546, "s": 26490, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26573, "s": 26546, "text": "Python Classes and Objects" }, { "code": null, "e": 26604, "s": 26573, "text": "Python | os.path.join() method" }, { "code": null, "e": 26633, "s": 26604, "text": "Create a directory in Python" }, { "code": null, "e": 26655, "s": 26633, "text": "Defaultdict in Python" }, { "code": null, "e": 26691, "s": 26655, "text": "Python | Pandas dataframe.groupby()" } ]
PostgreSQL - Installing PostgreSQL Without Admin Rights on Windows - GeeksforGeeks
21 Jun, 2021 If you are a part of a corporation, it is highly unlikely that you have the admin privileges to install any external software. But the curious souls that all software developers are, in this article, we will see the detailed process of installation of PostgreSQL without having administrator rights on our Windows machine. Follow the below steps to install PostgreSQL: Step 1: For setting up PostgreSQL, we need to download the PostgreSQL Binaries. To download the binaries, visit this link. Choose the appropriate binary file as per the required PostgreSQL version and download them. Step 2: Now create a new folder at a place where you have full access rights to this folder and extract these binary zip files there. (You can preferably extract these binary files at locations such as D:\ drive or E:\ drive). Step 3: After extraction, the folder structure will look as shown below. PostgreSQL zip binaries after extraction Step 4: Now add this location of your extraction in the Path variable in the User Environment Variables of your computer. Configuring User Environment Path Variable Well, Congratulations!!. At this point, we have successfully configured PostgreSQL in your windows system. To verify if it is installed properly, use the following commands. The below command checks the PostgreSQL server version: postgres -V Check PostgreSQL Server Version The below command checks the PostgreSQL client version: psql -V Check PostgreSQL Client Version Now it is time to initialize the database and associate a user to this. The database will be initialized at the location given by us (data folder in this case). The command for this is as follows: initdb -D D:\PostgreSQL\pgsql\data -U postgres -E utf8 The following are the references for the command line arguments which will help for better understanding – -D path/to/db/server/ – This option instructs the initdb to initialize the database at a particular location specified by user. After specifying the location a new directory will implicitly be created and all the PostgreSQL files and their related data will be kept here. -U name – This option is used to create a user with the specified name and with all the superuser privileges. -W – It is used to explicitly prompt a password for superuser. -E – It specifies the encoding to be used for the database. -A – It is used to specify the encrypting of the superuser password. PostgreSQL initdb Step 1: Start the database by running the following command. pg_ctl -D D:\PostgreSQL\pgsql\data -l logfile start Start Database Server Step 2: Now navigate to the location of your PostgreSQL binary folder and traverse to the following path as shown in the figure. Step 3: Double click on pgAdmin4 application. Now a pgAdmin4 instance will load into the system’s default browser. pgAdmin4 Home Page Step 4: Set a master password to secure the server. Step 5: Now click on Servers on the right-hand side to create a new server for your database. Fill in the required details. Step 6: Click on the Database section to create a new database for your work purpose and begin using it. Step 7: To stop the database, use the same command used for start database as used in Step 7 and replace start by stop. pg_ctl -D D:\PostgreSQL\pgsql\data -l logfile stop Your basic setup of PostgreSQL is now done. However, if you want to use additional PGSQL functions like vacuuming, upgrade, restore etc then you might need to setup the binary paths for it . For this, go to File -> Preferences. Now scroll down to Paths and click Binary Paths. Specify all the three paths as the directory of PgSQL installation bin folder. Refer to the below figure for setting up the binary paths. chinmay_bhide Picked postgreSQL-administration PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. PostgreSQL - CREATE PROCEDURE PostgreSQL - GROUP BY clause PostgreSQL - DROP INDEX PostgreSQL - Copy Table PostgreSQL - REPLACE Function PostgreSQL - TIME Data Type PostgreSQL - CREATE SCHEMA PostgreSQL - Cursor PostgreSQL - ROW_NUMBER Function PostgreSQL - SELECT
[ { "code": null, "e": 25479, "s": 25451, "text": "\n21 Jun, 2021" }, { "code": null, "e": 25803, "s": 25479, "text": " If you are a part of a corporation, it is highly unlikely that you have the admin privileges to install any external software. But the curious souls that all software developers are, in this article, we will see the detailed process of installation of PostgreSQL without having administrator rights on our Windows machine." }, { "code": null, "e": 25849, "s": 25803, "text": "Follow the below steps to install PostgreSQL:" }, { "code": null, "e": 26065, "s": 25849, "text": "Step 1: For setting up PostgreSQL, we need to download the PostgreSQL Binaries. To download the binaries, visit this link. Choose the appropriate binary file as per the required PostgreSQL version and download them." }, { "code": null, "e": 26292, "s": 26065, "text": "Step 2: Now create a new folder at a place where you have full access rights to this folder and extract these binary zip files there. (You can preferably extract these binary files at locations such as D:\\ drive or E:\\ drive)." }, { "code": null, "e": 26365, "s": 26292, "text": "Step 3: After extraction, the folder structure will look as shown below." }, { "code": null, "e": 26406, "s": 26365, "text": "PostgreSQL zip binaries after extraction" }, { "code": null, "e": 26528, "s": 26406, "text": "Step 4: Now add this location of your extraction in the Path variable in the User Environment Variables of your computer." }, { "code": null, "e": 26571, "s": 26528, "text": "Configuring User Environment Path Variable" }, { "code": null, "e": 26679, "s": 26571, "text": "Well, Congratulations!!. At this point, we have successfully configured PostgreSQL in your windows system. " }, { "code": null, "e": 26747, "s": 26679, "text": "To verify if it is installed properly, use the following commands. " }, { "code": null, "e": 26803, "s": 26747, "text": "The below command checks the PostgreSQL server version:" }, { "code": null, "e": 26815, "s": 26803, "text": "postgres -V" }, { "code": null, "e": 26847, "s": 26815, "text": "Check PostgreSQL Server Version" }, { "code": null, "e": 26903, "s": 26847, "text": "The below command checks the PostgreSQL client version:" }, { "code": null, "e": 26911, "s": 26903, "text": "psql -V" }, { "code": null, "e": 26943, "s": 26911, "text": "Check PostgreSQL Client Version" }, { "code": null, "e": 27140, "s": 26943, "text": "Now it is time to initialize the database and associate a user to this. The database will be initialized at the location given by us (data folder in this case). The command for this is as follows:" }, { "code": null, "e": 27195, "s": 27140, "text": "initdb -D D:\\PostgreSQL\\pgsql\\data -U postgres -E utf8" }, { "code": null, "e": 27302, "s": 27195, "text": "The following are the references for the command line arguments which will help for better understanding –" }, { "code": null, "e": 27574, "s": 27302, "text": "-D path/to/db/server/ – This option instructs the initdb to initialize the database at a particular location specified by user. After specifying the location a new directory will implicitly be created and all the PostgreSQL files and their related data will be kept here." }, { "code": null, "e": 27684, "s": 27574, "text": "-U name – This option is used to create a user with the specified name and with all the superuser privileges." }, { "code": null, "e": 27747, "s": 27684, "text": "-W – It is used to explicitly prompt a password for superuser." }, { "code": null, "e": 27807, "s": 27747, "text": "-E – It specifies the encoding to be used for the database." }, { "code": null, "e": 27876, "s": 27807, "text": "-A – It is used to specify the encrypting of the superuser password." }, { "code": null, "e": 27894, "s": 27876, "text": "PostgreSQL initdb" }, { "code": null, "e": 27955, "s": 27894, "text": "Step 1: Start the database by running the following command." }, { "code": null, "e": 28007, "s": 27955, "text": "pg_ctl -D D:\\PostgreSQL\\pgsql\\data -l logfile start" }, { "code": null, "e": 28029, "s": 28007, "text": "Start Database Server" }, { "code": null, "e": 28158, "s": 28029, "text": "Step 2: Now navigate to the location of your PostgreSQL binary folder and traverse to the following path as shown in the figure." }, { "code": null, "e": 28273, "s": 28158, "text": "Step 3: Double click on pgAdmin4 application. Now a pgAdmin4 instance will load into the system’s default browser." }, { "code": null, "e": 28292, "s": 28273, "text": "pgAdmin4 Home Page" }, { "code": null, "e": 28344, "s": 28292, "text": "Step 4: Set a master password to secure the server." }, { "code": null, "e": 28468, "s": 28344, "text": "Step 5: Now click on Servers on the right-hand side to create a new server for your database. Fill in the required details." }, { "code": null, "e": 28573, "s": 28468, "text": "Step 6: Click on the Database section to create a new database for your work purpose and begin using it." }, { "code": null, "e": 28694, "s": 28573, "text": "Step 7: To stop the database, use the same command used for start database as used in Step 7 and replace start by stop. " }, { "code": null, "e": 28745, "s": 28694, "text": "pg_ctl -D D:\\PostgreSQL\\pgsql\\data -l logfile stop" }, { "code": null, "e": 29160, "s": 28745, "text": "Your basic setup of PostgreSQL is now done. However, if you want to use additional PGSQL functions like vacuuming, upgrade, restore etc then you might need to setup the binary paths for it . For this, go to File -> Preferences. Now scroll down to Paths and click Binary Paths. Specify all the three paths as the directory of PgSQL installation bin folder. Refer to the below figure for setting up the binary paths." }, { "code": null, "e": 29174, "s": 29160, "text": "chinmay_bhide" }, { "code": null, "e": 29181, "s": 29174, "text": "Picked" }, { "code": null, "e": 29207, "s": 29181, "text": "postgreSQL-administration" }, { "code": null, "e": 29218, "s": 29207, "text": "PostgreSQL" }, { "code": null, "e": 29316, "s": 29218, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29346, "s": 29316, "text": "PostgreSQL - CREATE PROCEDURE" }, { "code": null, "e": 29375, "s": 29346, "text": "PostgreSQL - GROUP BY clause" }, { "code": null, "e": 29399, "s": 29375, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 29423, "s": 29399, "text": "PostgreSQL - Copy Table" }, { "code": null, "e": 29453, "s": 29423, "text": "PostgreSQL - REPLACE Function" }, { "code": null, "e": 29481, "s": 29453, "text": "PostgreSQL - TIME Data Type" }, { "code": null, "e": 29508, "s": 29481, "text": "PostgreSQL - CREATE SCHEMA" }, { "code": null, "e": 29528, "s": 29508, "text": "PostgreSQL - Cursor" }, { "code": null, "e": 29561, "s": 29528, "text": "PostgreSQL - ROW_NUMBER Function" } ]
Add Background Image in Python Arcade - GeeksforGeeks
26 Oct, 2021 In this article, we will learn how to add background images to arcade games in Python. We are going to use the below image as our background image. So to add this image as our background image we are going to use load_texture() and draw_texture_rectangle() function. load_texture function is used to import texture from file in arcade. Syntax: arcade.load_texture(name, x, y, width, height) Parameters: name: Name of the file to that holds the texture. x: X position of the crop area of the texture y: Y position of the crop area of the texture width: width of the texture height: height of the texture draw_texture_rectangle function used to import texture with specific coordinated. Syntax: arcade.draw_texture_rectangle(x, y, width, height, texture, angle, alpha) x: x coordinate of rectangle center. y: y coordinate of rectangle center. width: width of texture height: height of the texture texture: identifier of texture returned from load_texture() call angle: rotation of the rectangle alpha: Transparency of image Below is the implementation: Python3 # Importing arcade moduleimport arcade # Creating MainGame classclass MainGame(arcade.Window): def __init__(self): super().__init__(600, 600, title = "Background Image") # Loading the background image self.background = arcade.load_texture("BACKGROUND.png") # Creating on_draw() function to draw on the screen def on_draw(self): arcade.start_render() # Drawing the background image arcade.draw_texture_rectangle(300, 300, 600, 600, self.background) # Calling MainGame classMainGame()arcade.run() Output: surinderdawra388 Python-Arcade Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Pandas dataframe.groupby() Create a directory in Python Defaultdict in Python Python | Get unique values from a list
[ { "code": null, "e": 25671, "s": 25643, "text": "\n26 Oct, 2021" }, { "code": null, "e": 25758, "s": 25671, "text": "In this article, we will learn how to add background images to arcade games in Python." }, { "code": null, "e": 25819, "s": 25758, "text": "We are going to use the below image as our background image." }, { "code": null, "e": 25938, "s": 25819, "text": "So to add this image as our background image we are going to use load_texture() and draw_texture_rectangle() function." }, { "code": null, "e": 26007, "s": 25938, "text": "load_texture function is used to import texture from file in arcade." }, { "code": null, "e": 26062, "s": 26007, "text": "Syntax: arcade.load_texture(name, x, y, width, height)" }, { "code": null, "e": 26074, "s": 26062, "text": "Parameters:" }, { "code": null, "e": 26124, "s": 26074, "text": "name: Name of the file to that holds the texture." }, { "code": null, "e": 26170, "s": 26124, "text": "x: X position of the crop area of the texture" }, { "code": null, "e": 26216, "s": 26170, "text": "y: Y position of the crop area of the texture" }, { "code": null, "e": 26244, "s": 26216, "text": "width: width of the texture" }, { "code": null, "e": 26274, "s": 26244, "text": "height: height of the texture" }, { "code": null, "e": 26356, "s": 26274, "text": "draw_texture_rectangle function used to import texture with specific coordinated." }, { "code": null, "e": 26438, "s": 26356, "text": "Syntax: arcade.draw_texture_rectangle(x, y, width, height, texture, angle, alpha)" }, { "code": null, "e": 26476, "s": 26438, "text": "x: x coordinate of rectangle center." }, { "code": null, "e": 26514, "s": 26476, "text": "y: y coordinate of rectangle center." }, { "code": null, "e": 26539, "s": 26514, "text": "width: width of texture" }, { "code": null, "e": 26569, "s": 26539, "text": "height: height of the texture" }, { "code": null, "e": 26634, "s": 26569, "text": "texture: identifier of texture returned from load_texture() call" }, { "code": null, "e": 26668, "s": 26634, "text": "angle: rotation of the rectangle" }, { "code": null, "e": 26697, "s": 26668, "text": "alpha: Transparency of image" }, { "code": null, "e": 26726, "s": 26697, "text": "Below is the implementation:" }, { "code": null, "e": 26734, "s": 26726, "text": "Python3" }, { "code": "# Importing arcade moduleimport arcade # Creating MainGame classclass MainGame(arcade.Window): def __init__(self): super().__init__(600, 600, title = \"Background Image\") # Loading the background image self.background = arcade.load_texture(\"BACKGROUND.png\") # Creating on_draw() function to draw on the screen def on_draw(self): arcade.start_render() # Drawing the background image arcade.draw_texture_rectangle(300, 300, 600, 600, self.background) # Calling MainGame classMainGame()arcade.run()", "e": 27328, "s": 26734, "text": null }, { "code": null, "e": 27336, "s": 27328, "text": "Output:" }, { "code": null, "e": 27353, "s": 27336, "text": "surinderdawra388" }, { "code": null, "e": 27367, "s": 27353, "text": "Python-Arcade" }, { "code": null, "e": 27374, "s": 27367, "text": "Python" }, { "code": null, "e": 27472, "s": 27374, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27504, "s": 27472, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27546, "s": 27504, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27588, "s": 27546, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27644, "s": 27588, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27671, "s": 27644, "text": "Python Classes and Objects" }, { "code": null, "e": 27702, "s": 27671, "text": "Python | os.path.join() method" }, { "code": null, "e": 27738, "s": 27702, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 27767, "s": 27738, "text": "Create a directory in Python" }, { "code": null, "e": 27789, "s": 27767, "text": "Defaultdict in Python" } ]
NavigableMap Interface in Java with Example
NavigableMap is an extension of the SortedMap collection framework. It is used to arrange the elements in a uniform fashion. NavigableMap has different methods to iterate over the elements in the Map. Following is an example − Live Demo import java.util.NavigableMap; import java.util.TreeMap; public class Demo { public static void main(String[] args) { NavigableMap<String, Integer> my_map = new TreeMap<String, Integer>(); my_map.put("A", 856); my_map.put("M", 349); my_map.put("Z", 567); System.out.printf("The descending set is : %s%n", my_map.descendingKeySet()); System.out.printf("The floor entry is : %s%n", my_map.floorEntry("A")); System.out.printf("The first key : %s%n", my_map.firstKey()); System.out.printf("The reversed map : %s%n", my_map.descendingMap()); } } The descending set is : [Z, M, A] The floor entry is : A=856 The first key : A The reversed map : {Z=567, M=349, A=856} A class named Demo contains the main function. An instance of the NavigableMap is created, and elements are added to the map with the help of the ‘put’ function. The relevant function are used to display the map in descending order, the first element of the map, the first key of the map, and the reversed version of the map.
[ { "code": null, "e": 1263, "s": 1062, "text": "NavigableMap is an extension of the SortedMap collection framework. It is used to arrange the elements in a uniform fashion. NavigableMap has different methods to iterate over the elements in the Map." }, { "code": null, "e": 1289, "s": 1263, "text": "Following is an example −" }, { "code": null, "e": 1300, "s": 1289, "text": " Live Demo" }, { "code": null, "e": 1895, "s": 1300, "text": "import java.util.NavigableMap;\nimport java.util.TreeMap;\npublic class Demo {\n public static void main(String[] args) {\n NavigableMap<String, Integer> my_map = new TreeMap<String, Integer>();\n my_map.put(\"A\", 856);\n my_map.put(\"M\", 349);\n my_map.put(\"Z\", 567);\n System.out.printf(\"The descending set is : %s%n\", my_map.descendingKeySet());\n System.out.printf(\"The floor entry is : %s%n\", my_map.floorEntry(\"A\"));\n System.out.printf(\"The first key : %s%n\", my_map.firstKey());\n System.out.printf(\"The reversed map : %s%n\", my_map.descendingMap());\n }\n}" }, { "code": null, "e": 2015, "s": 1895, "text": "The descending set is : [Z, M, A]\nThe floor entry is : A=856\nThe first key : A\nThe reversed map : {Z=567, M=349, A=856}" }, { "code": null, "e": 2341, "s": 2015, "text": "A class named Demo contains the main function. An instance of the NavigableMap is created, and elements are added to the map with the help of the ‘put’ function. The relevant function are used to display the map in descending order, the first element of the map, the first key of the map, and the reversed version of the map." } ]
Train a GPT-2 Transformer to write Harry Potter Books! | by Priya Dwivedi | Towards Data Science
Natural Language Processing is a field widely growing in popularity these days. A large number of companies worldwide are leveraging the power of Natural language processing and the innovations in the field to extract meaningful insights from text and to generate text. In the past couple of years, with Google Brain’s Attention is All You Need paper, the transformers architecture has revolutionized this field even further. In almost all the classic NLP tasks like Machine translation, Question Answering, Reading Comprehension, Common Sense Reasoning and Summarization, a Transformer-based architecture beat the State-of-the-art. Since then, all tech giants like Google, Facebook, OpenAI, Microsoft have been experimenting with transformers in various applications. One such application that made headlines was the Language Generation task, wherein Transformers were able to generate meaningful text given a prompt. One of the first headliners was HuggingFace with their Talk to Transformers web page, where anyone could generate their own AI-generated text by giving a prompt. Here, we will explore how transformers are used in Language generation. Also later in the blog, we will share code for how to train a transformer language model on your own corpus. We trained a GPT-2 model on Harry Potter books. The trained model is able to generate text like Harry Potter books when presented with an input. See the example below. Full code is available on my Github. Interesting observations: 1. Model has learnt that Hagrid has large feet!, 2. Gilderoy Lockhart writes books, 3. New books can appear in Hogwarts bookshelves. Original full story published on my website here. A language model is a model which learns to predict the probability of a sequence of words. In simpler words, language models essentially predict the next word given some text. By training language models on specific texts, it is possible to make the model learn the writing style of that text. Although various kinds of language models existed in the past, they became much more powerful after the introduction of Transformers by the Google Brain team(“Attention is All You Need”). With the advent of transformers, multiple groups were able to create and train custom architectures for language models. One such group was the Open AI community who introduced GPT(short for Generative Pre-training Transformer). The GPT model was released in 2018, but unfortunately, soon after it’s release, it was knocked off the GLUE leaderboard by BERT. But, in February, 2019, OpenAI scaled up their model by training on a whopping 1.5 billion parameters which in turn gave it human-like writing capabilities. It was named “OpenAI’s GPT-2”. Transformers is the basic architecture behind the language models. A transformer mainly consists of two basic components: encoders and decoders. As seen in the diagram above, both Encoder and Decoders have modules that can be stacked together, as represented by Nx. Mainly, both Encoders and Decoders have the Feed-forward and Multi-Head attention components. The inputs and outputs are embedded into an n-dimensional space before passing them on to the components. One important step in the input and output components is the Positional Encoding wherein we provide information regarding the position of the word to the transformer. These encodings are added to the embeddings of each word and the resulting embeddings are passed to the transformer. An encoder block has multiple encoder blocks and the decoder block has the same number of decoder blocks. The number of blocks is a hyperparameter which can be tuned while training. The working of the encoder-decoder stack is described as follows: The input embeddings are passed to the first encoder. The embeddings are transformed after passing through the feed-forward and self-attention layers of the encoder. The transformed output is passed to the next encoder. The last encoder passes the output to all the decoders in the stack. The self-attention layer in the encoder and decoders play a very important role in the processing of the words. It enables the model to look at other words in the input sequence to get a better understanding of the context of the current word. Apart from the Feed-forward and Attention component, decoders also have another attention layer (Masked multi-head attention) which helps the decoder focus on specific parts of the input sequence. OpenAI extended the Transformers concept for the Language generation task in two iterations: GPT and GPT-2. GPT architecture used 12-layer decoders with masked self-attention heads and trained for 100 epochs. With GPT-2 model, the vocabulary was expanded to 50,257 words. There was also an increase in the context size from 512 to 1024 tokens and a larger batchsize of 512 was used. In this blog, we will leverage the awesome HuggingFace’s transformer repository to train our own GPT-2 model on text from Harry Potter books. We will provide a sentence prompt to the model and the model will complete the text. In order to train the model, we will feed all Harry Potter books for the model to learn from them. We have cloned the huggingface repo and updated the code to correctly perform language model training and inference. Please follow along on my Github repo. The first step is downloading all the harry potter books and preprocessing the text. We scraped the text from the first 4books and merged it together. Then we wrote a short piece of code to remove unnecessary text like the page numbers from the merged text. Finally the GPT-2 model needs both train and validation text. So we take first 90% of the data as training sample and the remaining as validation sample. The preprocessing code is here. To train the model we use the script — run_lm_finetuning.py. The script takes as input the model type and its size, as well as the preprocessed text. The script also provides a bunch of hyperparameters that can be tweaked in order to customize the training process. The code snippet for training is: cd examples ## Move to examples directorypython run_lm_finetuning.py \ --output_dir=output \ --model_type=gpt2 \ --model_name_or_path=gpt2-medium \ --do_train \ --train_data_file='input_data/train_harry.txt' \ --do_eval \ --eval_data_file='input_data/val_harry.txt'\ --overwrite_output_dir\ --block_size=200\ --per_gpu_train_batch_size=1\ --save_steps 5000\ --num_train_epochs=2 The parameters used in the code is as follows: The parameters used here are explained as follows: Output_dir is the name of the folder where the model weights are stored. Model_type is the name of the model. In our case we are training on the gpt-2 architecture, we use ‘gpt-2’. Model_name_or_path is where we define the model size to be used.(’gpt2’ for small, ‘gpt2-medium’ for a medium model and ‘gpt2-large’ for a large model) Do_train is essentially a flag which we define to train the model. train_data_file is used to specify the training file name. Do_eval is a flag which we define whether to evaluate the model or not, if we don’t define this, there would not be a perplexity score calculated. Eval_data_file is used to specify the test file name. gradient_accumulation_steps is a parameter used to define the number of updates steps to accumulate before performing a backward/update pass. Overwrite_output_dir is a parameter which when specified overwrites the output directory with new weights. block_size is a parameter according to which the training dataset will be truncated in block of this size for training. Per_gpu_train_batch_size is the batch size per GPU/CPU for training. Save steps — allows you to periodically save weights before the final set of weights num_epochs — Determines how many epochs are run. We trained a medium GPT-2 model on the text of 4harry potter books. This model took only 10 min to train on a GTX 1080 Ti. The perplexity score of the trained model was 12.71. Read this blog to learn more about Perplexity score. But remember, lower the score, the better the model is. Once the model is trained, we can run inference using it. The inference script is run_generation.py For doing inference, the input text is first encoded through the tokenizer , then the result is passed through a generate function where the generation of text happens based on parameters like temperature, top-p and k values. The code snippet for doing inference is: cd examplespython run_generation.py --model_type gpt2 --model_name_or_path output --length 300 --prompt "Malfoy hadn’t noticed anything." These parameters are explained below: model_name_or_path : This is the folder path where the weights of the trained model are stored. Prompt: This is the input prompt based on which the rest of the text will be generated. Length: This parameter controls the length of characters to be generated in the output. Some additional parameters that can be tweaked are: Temperature: This parameter decides how adventurous the model gets with its word selection. p : This parameter controls how broad a range of continuations are considered. Set it high to consider all continuations. Set it low to just consider likely continuations. The overall effect is similar to temperature, but more subtle. k: This parameter controls the number of beams or parallel searches through the sequence of probabilities. Higher the value, better the accuracy , but slower the speed. Seed: This parameter helps in setting the seed. Repetition_penalty: This parameter penalizes the model for repeating the words chosen. One more example of model output is below. Very interesting to see the story around the cloaked figure that this model is creating. The advent of transformers has truly revolutionized many Natural language processing tasks, and language generation is one of them. The potential of a language generation model is huge and can be leveraged in many applications like chatbots, long answer generation, writing automated reports and many more. In this blog, we understood the working of transformers, how they are used in language generation and some examples of how anyone can leverage these architectures to train their own language model and generate text. I am extremely passionate about NLP, Transformers and deep learning in general. I have my own deep learning consultancy and love to work on interesting problems. I have helped many startups deploy innovative AI based solutions. Check us out at — http://deeplearninganalytics.org/. You can also see my other writings at: https://medium.com/@priya.dwivedi If you have a project that we can collaborate on, then please contact me through my website or at [email protected] Transformers — Attention is all you need. This is the paper that started it all BERT GPT-2 model Hugging Face Repo
[ { "code": null, "e": 940, "s": 171, "text": "Natural Language Processing is a field widely growing in popularity these days. A large number of companies worldwide are leveraging the power of Natural language processing and the innovations in the field to extract meaningful insights from text and to generate text. In the past couple of years, with Google Brain’s Attention is All You Need paper, the transformers architecture has revolutionized this field even further. In almost all the classic NLP tasks like Machine translation, Question Answering, Reading Comprehension, Common Sense Reasoning and Summarization, a Transformer-based architecture beat the State-of-the-art. Since then, all tech giants like Google, Facebook, OpenAI, Microsoft have been experimenting with transformers in various applications." }, { "code": null, "e": 1638, "s": 940, "text": "One such application that made headlines was the Language Generation task, wherein Transformers were able to generate meaningful text given a prompt. One of the first headliners was HuggingFace with their Talk to Transformers web page, where anyone could generate their own AI-generated text by giving a prompt. Here, we will explore how transformers are used in Language generation. Also later in the blog, we will share code for how to train a transformer language model on your own corpus. We trained a GPT-2 model on Harry Potter books. The trained model is able to generate text like Harry Potter books when presented with an input. See the example below. Full code is available on my Github." }, { "code": null, "e": 1797, "s": 1638, "text": "Interesting observations: 1. Model has learnt that Hagrid has large feet!, 2. Gilderoy Lockhart writes books, 3. New books can appear in Hogwarts bookshelves." }, { "code": null, "e": 1847, "s": 1797, "text": "Original full story published on my website here." }, { "code": null, "e": 2330, "s": 1847, "text": "A language model is a model which learns to predict the probability of a sequence of words. In simpler words, language models essentially predict the next word given some text. By training language models on specific texts, it is possible to make the model learn the writing style of that text. Although various kinds of language models existed in the past, they became much more powerful after the introduction of Transformers by the Google Brain team(“Attention is All You Need”)." }, { "code": null, "e": 2876, "s": 2330, "text": "With the advent of transformers, multiple groups were able to create and train custom architectures for language models. One such group was the Open AI community who introduced GPT(short for Generative Pre-training Transformer). The GPT model was released in 2018, but unfortunately, soon after it’s release, it was knocked off the GLUE leaderboard by BERT. But, in February, 2019, OpenAI scaled up their model by training on a whopping 1.5 billion parameters which in turn gave it human-like writing capabilities. It was named “OpenAI’s GPT-2”." }, { "code": null, "e": 3021, "s": 2876, "text": "Transformers is the basic architecture behind the language models. A transformer mainly consists of two basic components: encoders and decoders." }, { "code": null, "e": 3236, "s": 3021, "text": "As seen in the diagram above, both Encoder and Decoders have modules that can be stacked together, as represented by Nx. Mainly, both Encoders and Decoders have the Feed-forward and Multi-Head attention components." }, { "code": null, "e": 3626, "s": 3236, "text": "The inputs and outputs are embedded into an n-dimensional space before passing them on to the components. One important step in the input and output components is the Positional Encoding wherein we provide information regarding the position of the word to the transformer. These encodings are added to the embeddings of each word and the resulting embeddings are passed to the transformer." }, { "code": null, "e": 3808, "s": 3626, "text": "An encoder block has multiple encoder blocks and the decoder block has the same number of decoder blocks. The number of blocks is a hyperparameter which can be tuned while training." }, { "code": null, "e": 3874, "s": 3808, "text": "The working of the encoder-decoder stack is described as follows:" }, { "code": null, "e": 3928, "s": 3874, "text": "The input embeddings are passed to the first encoder." }, { "code": null, "e": 4040, "s": 3928, "text": "The embeddings are transformed after passing through the feed-forward and self-attention layers of the encoder." }, { "code": null, "e": 4094, "s": 4040, "text": "The transformed output is passed to the next encoder." }, { "code": null, "e": 4163, "s": 4094, "text": "The last encoder passes the output to all the decoders in the stack." }, { "code": null, "e": 4407, "s": 4163, "text": "The self-attention layer in the encoder and decoders play a very important role in the processing of the words. It enables the model to look at other words in the input sequence to get a better understanding of the context of the current word." }, { "code": null, "e": 4604, "s": 4407, "text": "Apart from the Feed-forward and Attention component, decoders also have another attention layer (Masked multi-head attention) which helps the decoder focus on specific parts of the input sequence." }, { "code": null, "e": 4987, "s": 4604, "text": "OpenAI extended the Transformers concept for the Language generation task in two iterations: GPT and GPT-2. GPT architecture used 12-layer decoders with masked self-attention heads and trained for 100 epochs. With GPT-2 model, the vocabulary was expanded to 50,257 words. There was also an increase in the context size from 512 to 1024 tokens and a larger batchsize of 512 was used." }, { "code": null, "e": 5313, "s": 4987, "text": "In this blog, we will leverage the awesome HuggingFace’s transformer repository to train our own GPT-2 model on text from Harry Potter books. We will provide a sentence prompt to the model and the model will complete the text. In order to train the model, we will feed all Harry Potter books for the model to learn from them." }, { "code": null, "e": 5469, "s": 5313, "text": "We have cloned the huggingface repo and updated the code to correctly perform language model training and inference. Please follow along on my Github repo." }, { "code": null, "e": 5913, "s": 5469, "text": "The first step is downloading all the harry potter books and preprocessing the text. We scraped the text from the first 4books and merged it together. Then we wrote a short piece of code to remove unnecessary text like the page numbers from the merged text. Finally the GPT-2 model needs both train and validation text. So we take first 90% of the data as training sample and the remaining as validation sample. The preprocessing code is here." }, { "code": null, "e": 6213, "s": 5913, "text": "To train the model we use the script — run_lm_finetuning.py. The script takes as input the model type and its size, as well as the preprocessed text. The script also provides a bunch of hyperparameters that can be tweaked in order to customize the training process. The code snippet for training is:" }, { "code": null, "e": 6629, "s": 6213, "text": "cd examples ## Move to examples directorypython run_lm_finetuning.py \\ --output_dir=output \\ --model_type=gpt2 \\ --model_name_or_path=gpt2-medium \\ --do_train \\ --train_data_file='input_data/train_harry.txt' \\ --do_eval \\ --eval_data_file='input_data/val_harry.txt'\\ --overwrite_output_dir\\ --block_size=200\\ --per_gpu_train_batch_size=1\\ --save_steps 5000\\ --num_train_epochs=2" }, { "code": null, "e": 6676, "s": 6629, "text": "The parameters used in the code is as follows:" }, { "code": null, "e": 6727, "s": 6676, "text": "The parameters used here are explained as follows:" }, { "code": null, "e": 6800, "s": 6727, "text": "Output_dir is the name of the folder where the model weights are stored." }, { "code": null, "e": 6908, "s": 6800, "text": "Model_type is the name of the model. In our case we are training on the gpt-2 architecture, we use ‘gpt-2’." }, { "code": null, "e": 7060, "s": 6908, "text": "Model_name_or_path is where we define the model size to be used.(’gpt2’ for small, ‘gpt2-medium’ for a medium model and ‘gpt2-large’ for a large model)" }, { "code": null, "e": 7127, "s": 7060, "text": "Do_train is essentially a flag which we define to train the model." }, { "code": null, "e": 7186, "s": 7127, "text": "train_data_file is used to specify the training file name." }, { "code": null, "e": 7333, "s": 7186, "text": "Do_eval is a flag which we define whether to evaluate the model or not, if we don’t define this, there would not be a perplexity score calculated." }, { "code": null, "e": 7387, "s": 7333, "text": "Eval_data_file is used to specify the test file name." }, { "code": null, "e": 7529, "s": 7387, "text": "gradient_accumulation_steps is a parameter used to define the number of updates steps to accumulate before performing a backward/update pass." }, { "code": null, "e": 7636, "s": 7529, "text": "Overwrite_output_dir is a parameter which when specified overwrites the output directory with new weights." }, { "code": null, "e": 7756, "s": 7636, "text": "block_size is a parameter according to which the training dataset will be truncated in block of this size for training." }, { "code": null, "e": 7825, "s": 7756, "text": "Per_gpu_train_batch_size is the batch size per GPU/CPU for training." }, { "code": null, "e": 7910, "s": 7825, "text": "Save steps — allows you to periodically save weights before the final set of weights" }, { "code": null, "e": 7959, "s": 7910, "text": "num_epochs — Determines how many epochs are run." }, { "code": null, "e": 8244, "s": 7959, "text": "We trained a medium GPT-2 model on the text of 4harry potter books. This model took only 10 min to train on a GTX 1080 Ti. The perplexity score of the trained model was 12.71. Read this blog to learn more about Perplexity score. But remember, lower the score, the better the model is." }, { "code": null, "e": 8344, "s": 8244, "text": "Once the model is trained, we can run inference using it. The inference script is run_generation.py" }, { "code": null, "e": 8570, "s": 8344, "text": "For doing inference, the input text is first encoded through the tokenizer , then the result is passed through a generate function where the generation of text happens based on parameters like temperature, top-p and k values." }, { "code": null, "e": 8611, "s": 8570, "text": "The code snippet for doing inference is:" }, { "code": null, "e": 8749, "s": 8611, "text": "cd examplespython run_generation.py --model_type gpt2 --model_name_or_path output --length 300 --prompt \"Malfoy hadn’t noticed anything.\"" }, { "code": null, "e": 8787, "s": 8749, "text": "These parameters are explained below:" }, { "code": null, "e": 8883, "s": 8787, "text": "model_name_or_path : This is the folder path where the weights of the trained model are stored." }, { "code": null, "e": 8971, "s": 8883, "text": "Prompt: This is the input prompt based on which the rest of the text will be generated." }, { "code": null, "e": 9059, "s": 8971, "text": "Length: This parameter controls the length of characters to be generated in the output." }, { "code": null, "e": 9111, "s": 9059, "text": "Some additional parameters that can be tweaked are:" }, { "code": null, "e": 9203, "s": 9111, "text": "Temperature: This parameter decides how adventurous the model gets with its word selection." }, { "code": null, "e": 9438, "s": 9203, "text": "p : This parameter controls how broad a range of continuations are considered. Set it high to consider all continuations. Set it low to just consider likely continuations. The overall effect is similar to temperature, but more subtle." }, { "code": null, "e": 9607, "s": 9438, "text": "k: This parameter controls the number of beams or parallel searches through the sequence of probabilities. Higher the value, better the accuracy , but slower the speed." }, { "code": null, "e": 9655, "s": 9607, "text": "Seed: This parameter helps in setting the seed." }, { "code": null, "e": 9742, "s": 9655, "text": "Repetition_penalty: This parameter penalizes the model for repeating the words chosen." }, { "code": null, "e": 9874, "s": 9742, "text": "One more example of model output is below. Very interesting to see the story around the cloaked figure that this model is creating." }, { "code": null, "e": 10397, "s": 9874, "text": "The advent of transformers has truly revolutionized many Natural language processing tasks, and language generation is one of them. The potential of a language generation model is huge and can be leveraged in many applications like chatbots, long answer generation, writing automated reports and many more. In this blog, we understood the working of transformers, how they are used in language generation and some examples of how anyone can leverage these architectures to train their own language model and generate text." }, { "code": null, "e": 10678, "s": 10397, "text": "I am extremely passionate about NLP, Transformers and deep learning in general. I have my own deep learning consultancy and love to work on interesting problems. I have helped many startups deploy innovative AI based solutions. Check us out at — http://deeplearninganalytics.org/." }, { "code": null, "e": 10751, "s": 10678, "text": "You can also see my other writings at: https://medium.com/@priya.dwivedi" }, { "code": null, "e": 10880, "s": 10751, "text": "If you have a project that we can collaborate on, then please contact me through my website or at [email protected]" }, { "code": null, "e": 10960, "s": 10880, "text": "Transformers — Attention is all you need. This is the paper that started it all" }, { "code": null, "e": 10965, "s": 10960, "text": "BERT" }, { "code": null, "e": 10977, "s": 10965, "text": "GPT-2 model" } ]